tods-competition-factory 3.4.0 → 3.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +2 -2
- package/dist/tods-competition-factory.development.cjs.js +8 -8
- 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 +10 -9
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var _W=Object.defineProperty;var Gt=(t,e)=>{for(var r in e)_W(t,r,{get:e[r],enumerable:!0})};var tw="3.4.0";function cs(){return tw}var oD={};Gt(oD,{competitionGovernor:()=>ob,drawsGovernor:()=>hv,entriesGovernor:()=>Uv,eventGovernor:()=>Vv,generationGovernor:()=>jv,matchUpFormatGovernor:()=>eN,matchUpGovernor:()=>mO,mocksGovernor:()=>xh,officiatingGovernor:()=>hx,participantGovernor:()=>WO,policyGovernor:()=>qM,publishingGovernor:()=>XO,queryGovernor:()=>Iv,rankingGovernor:()=>wh,reportGovernor:()=>o_,scheduleGovernor:()=>h_,scoreGovernor:()=>nh,temporalGovernor:()=>ax,tieFormatGovernor:()=>b_,tournamentGovernor:()=>q_,venueGovernor:()=>Cx});var ob={};Gt(ob,{getCompetitionLeaderboard:()=>Yy,getCompetitionParticipantState:()=>Hy,getCompetitionPolicy:()=>Ao,getCompetitionState:()=>Wo,getLinkedTournamentIds:()=>bp,getTournamentIds:()=>Xm,initializeCompetitionState:()=>XR,linkTournaments:()=>FR,mutate:()=>rb,processCompetitionMatchUp:()=>Jm,processCompetitionRound:()=>tb,query:()=>nb,resetCompetitionState:()=>eb,unlinkTournament:()=>GR,unlinkTournaments:()=>kR});var rb={};Gt(rb,{initializeCompetitionState:()=>XR,linkTournaments:()=>FR,processCompetitionMatchUp:()=>Jm,processCompetitionRound:()=>tb,resetCompetitionState:()=>eb,unlinkTournament:()=>GR,unlinkTournaments:()=>kR});var Os="SINGLES",Ct="SINGLES",ei="DOUBLES",Rt="DOUBLES",Ir="TEAM",xt="TEAM",wW="HYBRID",Mm="HYBRID",ew={SINGLES_MATCHUP:Os,SINGLES:Ct,DOUBLES_MATCHUP:ei,DOUBLES:Rt,TEAM_MATCHUP:Ir,TEAM:xt,HYBRID_MATCHUP:wW,HYBRID:Mm};var CT={[Ct]:[Ct,"S"],[Rt]:[Rt,"D"],[xt]:[xt,"T"],[Mm]:[Mm,"H"],S:[Ct,"S"],D:[Rt,"D"],T:[xt,"T"],H:[Mm,"H"]};function Zt(t,e){return(t??0)-(e??0)}function st(t){return typeof t=="number"?parseInt(t.toString()):typeof t=="string"?parseInt(t):0}function Br(t){return typeof t=="function"}function wt(t){return typeof t=="string"}function Tt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function rw(t,e){if(!Tt(t)||!Tt(e))return!1;let r=Object.keys(t),n=Object.keys(e);if(r.length!==n.length)return!1;for(let o of r)if(t[o]!==e[o])return!1;return!0}function vT(t,e){return Array.isArray(t)?Object.assign({},...(t??[]).filter(Tt).map(r=>r[e]&&{[r[e]]:r}).filter(Boolean)):{}}var nw=t=>e=>Object.keys(t).every(r=>e[r]===t[r]);function MT(t,e){if(t===void 0)return null;if(!Tt(t)||t===null)return t;let r=Object.keys(t),n=o=>o===void 0?null:o;return Object.assign({},...r.map(o=>Array.isArray(t[o])?{[o]:e?t[o]:t[o].map(i=>MT(i))}:{[o]:e?n(t[o]):MT(t[o])}))}function AD(t){return Array.isArray(t)?t.length+t.map(AD).reduce((e,r)=>e+r,0):Tt(t)&&t!==null?Object.keys(t).length+Object.keys(t).map(e=>AD(t[e])).reduce((e,r)=>e+r,0):0}function ow(t){if(t===null||typeof t!="object")return;let e=JSON.stringify(t),r=AD(t),n=e.split("").reduce((o,i)=>o+i.charCodeAt(0),0);return[e.length,r,n].map(o=>o.toString(36)).join("")}function en(t){return Number.isNaN(Number(t))?!1:t>0&&(t&t-1)===0}function iw(t){if(!t.length)return;let e=[...t].sort(Zt),r=Math.floor(e.length/2);return e.length%2?e[r]:(e[r-1]+e[r])/2}function sw(t){if(t===1||Number.isNaN(Number(t))||!en(t))return!1;let e=t,r=1;for(;e!==2;)r+=1,e=e/2;return r}function el(t){return Number.isNaN(Number(t))?0:t%2&&t+1||t}function rl(t){return Math.pow(2,Math.round(Math.log(t)/Math.log(2)))}function Le(t){return!Number.isNaN(Number.parseFloat(t))}function OT(t){let e=st(t);if(!Number.isNaN(e))return e===0?!1:(e&-e)===1}function Pi(t){if(Number.isNaN(Number(t)))return!1;for(;!en(t);)t++;return t}function pn(t,e,r){return t=Math.ceil(t),e=Math.floor(e),Math.floor((r??Math.random)()*(e-t+1))+t}function yt(t){return wt(t)&&!t.trim().length?!1:Number.isSafeInteger(typeof t=="string"?+t:t)}function aw(t=1,e=3,r=!0,n){let o=n??Math.random,i=0;for(let s=0;s<e;s++)i+=o()*(t/e);return r&&t>1?Math.round(i):i}function LW(t,e){e||(e=1);let r=1/e;return Math.round(t*r)/r}function PD(t,e,r,n,o=2,i){let s=i??Math.random,a=1-s(),c=1-s(),u=Math.sqrt(-2*Math.log(a))*Math.cos(2*Math.PI*c);return u=u/10+.5,u>1||u<0?u=PD(t,e,r,void 0,2,i):(u=Math.pow(u,r),u*=e-t,u+=t),n&&(u=LW(u,n)),Number.parseFloat(u.toFixed(o))}function xg(t,e=2){return Number.parseFloat(Number(Math.round(t*1e3)/1e3).toFixed(e))}function pt(t){return Array.isArray(t)?t?.filter((e,r,n)=>n.lastIndexOf(e)===r):[]}function cw(t){return Array.isArray(t)?t?.map(e=>e===null?void 0:e):t}function ar(t,e){if(!Array.isArray(t))return[];let r=e??Math.random;return t.map(n=>[r(),n]).sort((n,o)=>n[0]-o[0]).map(n=>n[1])}function Wc(t){return yt(t)?t:1/0}function mn(t){return Array.isArray(t)?t.reduce((e,r)=>(e[r]||(e[r]=0),e[r]++,e),{}):{}}function uw(t){return ND(mn(t))}function ND(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return e[n]?e[n].push(r):e[n]=[r],e},{})}function FW(t,e,r){return r.indexOf(t)===e}function _T(t){return t.filter(FW)}function Sr(t,e){return Array.isArray(t)&&t.length?t.splice(Math.floor((e??Math.random)()*t.length),1)[0]:void 0}function Pn(t,e){let r=Math.floor((e??Math.random)()*t.length);return t[r]}function Q(t,e){return Array.from({length:e-t},(r,n)=>n+t)}function us(t,e){return e.reduce((r,n,o)=>(n===t&&r.push(o),r),[])}function Yt(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(r=>e.indexOf(r)!==-1).filter((r,n,o)=>o.indexOf(r)===n)}function DD(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(r=>!e.includes(r))}function Re(t,e){return!Array.isArray(t)||!Array.isArray(e)?!1:t.some(r=>e.includes(r))}function pw(t,e){return Array.isArray(e)&&e.reduce((r,n)=>(r[n]=1+r[n]||1,r),{})[t]||0}function mw(t,e,r,n){return Array.isArray(t)?[].concat(...t.slice(0,e),...t.slice(e,e+r).sort(n),...t.slice(e+r,t.length)):[]}function he(t,e){return Array.isArray(t)?t.reduce((r,n,o)=>{let i=Math.floor(o/e);return r[i]=[].concat(r[i]??[],n),r},[]):[]}function UD(t,[e,...r]){return t.length?[t.slice(0,e),...UD(t.slice(e),[...r,e])]:[]}function dw(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 xT(t){return Array.isArray(t)?t.reduce((e,r)=>!isNaN(parseInt(r))&&e,!0):!1}function wT(t){return Array.isArray(t)?t.reduce((e,r)=>isNaN(parseInt(r))&&e,!0):!1}function wg(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 lw(t,e=1){if(!Array.isArray(t)||!t.every(yt))return[];let r=Math.min(...t,e),n=Math.max(...t);return Q(r,n+1).filter(o=>!t.includes(o))}function _s(t,e){return!Array.isArray(t)||!wt(e)?!1:Yt(t,CT[e]).length}var P={success:!0},RD="error",fw={SUCCESS:P,ERROR:RD};function LT({collectionValueProfiles:t,matchUpCount:e}){let r=[];if(!Array.isArray(t))return r.push(`collectionValueProfiles is not an array: ${t}`),{errors:r};if(t.length&&t.length!==e)return r.push("collectionValueProfiles do not align with matchUpsCount"),{errors:r};for(let o of t){if(typeof o!="object")return r.push(`valueProfile is not type object: ${o}`),{errors:r};let{matchUpValue:i,collectionPosition:s}=o;if(typeof i!="number"||typeof s!="number"||s>e||s<1)return r.push("Invalid value profile: value and collectionPosition must be numeric. collectionPosition cannot be greater than matchUpCount"),{errors:r}}let n=t.map(o=>o.collectionPosition);return n.length!==pt(n).length?(r.push("collectionPositions are not unique"),{errors:r}):{...P}}var bw={};Gt(bw,{addNotice:()=>at,callListener:()=>cl,createInstanceState:()=>$U,cycleMutationStatus:()=>pI,deepCopyEnabled:()=>uI,deleteNotice:()=>zT,deleteNotices:()=>ms,disableNotifications:()=>KU,enableNotifications:()=>cI,getDevContext:()=>je,getMethods:()=>mI,getNotices:()=>KT,getProvider:()=>QT,getTopics:()=>vr,getTournamentId:()=>Fs,getTournamentRecord:()=>dI,getTournamentRecords:()=>oi,globalLog:()=>XU,handleCaughtError:()=>km,hasTopic:()=>tu,removeTournamentRecord:()=>QU,setDeepCopy:()=>pp,setDevContext:()=>up,setGlobalLog:()=>Dw,setGlobalMethods:()=>Uw,setGlobalSubscriptions:()=>fH,setMethods:()=>Rw,setStateMethods:()=>JU,setStateProvider:()=>dH,setSubscriptions:()=>gH,setTournamentId:()=>Fm,setTournamentRecord:()=>zU,setTournamentRecords:()=>ul,timeKeeper:()=>lH});var FT={message:"Chronological error; time violation.",code:"ANACHRONISM"},nl={message:"Duplicate entry",code:"DUPLICATE_ENTRY"},bD={message:"Cannot remove main structure",code:"ERR_CANNOT_REMOVE_MAIN_STRUCTURE"},kT={message:"records must be an object with tournamentId keys",code:"ERR_INVALID_TOURNAMENTS"},kt={message:"Missing tournamentRecords",code:"ERR_MISSING_TOURNAMENTS"},j={message:"Missing tournamentRecord",code:"ERR_MISSING_TOURNAMENT"},Hc={message:"Invalid tournamentRecord",code:"ERR_INVALID_TOURNAMENT"},ac={message:"Missing tournamentId",code:"ERR_MISSING_TOURNAMENT_ID"},ha={message:"Invalid drawDefinition",code:"ERR_INVALID_DRAWDEF"},$={message:"Missing drawDefinition",code:"ERR_MISSING_DRAWDEF"},CD={message:"Existing drawDefinition(s)",code:"ERR_EXISTING_DRAWDEFS"},Mr={message:"drawDefinition not found",code:"ERR_NOT_FOUND_DRAWDEF"},Co={message:"Invalid structure",code:"ERR_INVALID_STRUCTURE"},Lg={message:"Incomplete source structure",code:"ERR_INCOMPLETE_STRUCTURE"},Fg={message:"Invalid drawPosition for seedAssignment",code:"ERR_INVALID_SEEDING_POSITION"},Yc={message:"drawPosition already assigned",code:"ERR_EXISTING_POSITION_ASSIGNMENT"},MD={message:"Schedule not cleared",code:"ERR_UNCHANGED_SCHEDULE_NOT_CLEARED"},vD={message:"Schedule conflict: court slot already occupied",code:"ERR_SCHEDULE_CONFLICT_DOUBLE_BOOKING"},OD={message:"Schedule conflict: matchUps scheduled outside court availability",code:"ERR_SCHEDULE_CONFLICT_COURT_UNAVAILABLE"},_D={message:"drawPosition not cleared",code:"ERR_FAILURE_POSITION_NOT_CLEARED"},kW={message:"drawPosition not found",code:"ERR_NOT_FOUND_DRAW_POSITION"},rp={message:"Unrecognized drawType",code:"ERR_UNRECOGNIZED_DRAW_TYPE"},jc={message:"Missing drawPositions",code:"ERR_MISSING_DRAW_POSITIONS"},qc={message:"drawPosition is active",code:"ERR_ACTIVE_DRAW_POSITION"},gw={message:"drawPosition is occupied",code:"ERR_OCCUPIED_DRAW_POSITION"},ps={message:"Invlid drawPosition",code:"ERR_INVALID_DRAW_POSITION"},Ta={message:"Missing drawPosition",code:"ERR_MISSING_DRAW_POSITION"},ol={message:"Invalid drawType",code:"ERR_INVALID_DRAW_TYPE"},vm={message:"Invalid drawSize",code:"ERR_INVALID_DRAW_SIZE"},GW={message:"Cannot set drawSize to be less than existing entries",code:"ERR_INVALID_DRAW_SIZE_MISMATCH"},$c={message:"Missing drawSize",code:"ERR_MISSING_DRAW_SIZE"},Nn={message:"Missing drawId",code:"ERR_MISSING_DRAW_ID"},xD={message:"drawId exists",code:"ERR_EXISTING_DRAW_ID"},wD={message:"participantId cannot be assigned to multiple seedNumbers",code:"INVALID_PARTICIPANT_SEEDING"},LD={message:"seedsCount greater than drawSize",code:"ERR_INVALID_SEED_COUNT"},FD={message:"Missing seedCountThresholds",code:"ERR_MISSING_SEED_COUNT_THRESHOLD"},kD={message:"Invalid action",code:"ERR_INVALID_ACTION"},GT={message:"Invalid assignment",code:"ERR_INVALID_ASSIGNMENT"},GD={message:"Missing seedAssignments",code:"ERR_MISSING_SEED_ASSIGNMENTS"},VD={message:"Invalid seedNumber",code:"ERR_INVALID_SEED_NUMBER"},BD={message:"Invalid seedPosition",code:"ERR_INVALID_SEED_POSITION"},kg={message:"Missing targetLink",code:"ERR_MISSING_LINK_TARGET"},WD={message:"Existing round",code:"ERR_EXISTING_ROUND"},VW={message:"Missing roundNumber",code:"ERR_MISSING_ROUND_NUMBER"},dn={message:"Missing structureId",code:"ERR_MISSING_STRUCTURE_ID"},Nt={message:"structure not found",code:"ERR_NOT_FOUND_STRUCTURE"},Gg={message:"Missing structures",code:"ERR_MISSING_STRUCTURES"},_i={message:"Missing structure",code:"ERR_MISSING_STRUCTURE"},Vg={message:"Missing MAIN structure",code:"ERR_MISSING_MAIN_STRUCTURE"},HD={message:"drawDefinition contains unlinked structures",code:"ERR_MISSING_STRUCTURE_LINKS"},zn={message:"Invalid eventType",code:"ERR_INVALID_EVENT_TYPE"};var le={message:"Missing event / eventId",code:"ERR_MISSING_EVENT_ID"},Wr={message:"Event not found",code:"ERR_NOT_FOUND_EVENT"},YD={message:"Event exists",code:"ERR_EXISTING_EVENT"},jD={message:"Missing entries",code:"ERR_MISSING_ENTRIES"},qD={message:"Invalid entries",code:"ERR_INVALID_ENTRIES"},Bg={message:"Missing assignments",code:"ERR_MISSING_ASSIGNMENTS"},Wg={message:"Missing stage",code:"ERR_MISSING_STAGE"},cc={message:"Invalid stage",code:"ERR_INVALID_STAGE"},$D={message:"stageSequence limit",code:"ERR_LIMIT_STAGE_SEQUENCE"},KD={message:"Missing positionAssignments",code:"ERR_MISSING_POSITION_ASSIGNMENTS"},zD={message:"Cannot Assign BYE status if no assignment: { bye: true }",code:"ERR_UNCHANGED_CANNOT_ASSIGN_BYE"},QD={message:"Lucky draw first round allows at most one BYE",code:"ERR_LUCKY_DRAW_BYE_LIMIT"},VT={message:"Unrecognized matchUpStatus",code:"ERR_UNRECOGNIZED_MATCHUP_STATUS"},Kc={message:"Unrecognized matchUpFormat",code:"ERR_UNRECOGNIZED_MATCHUP_FORMAT"},Hg={message:"Incompatible matchUpStatus",code:"ERR_INCOMPATIBLE_MATCHUP_STATUS"},Iw={message:"Propagated exits downstream",code:"ERR_PROPAGATED_EXITS_DOWNSTREAM"},uc={message:"Invalid matchUpStatus",code:"ERR_INVALID_MATCHUP_STATUS"},ri={message:"Invalid tieFormat",code:"ERR_INVALID_TIE_FORMAT"},XD={message:"Invalid matchUpFormat",code:"ERR_INVALID_MATCHUP_FORMAT"},JD={message:"Missing matchUpFormat",code:"ERR_MISSING_MATCHUP_FORMAT"},ZD={message:"Missing collectionDefinition",code:"ERR_MISSING_COLLECTION_DEFINITION"},ya={message:"Missing tieFormat",code:"ERR_MISSING_TIE_FORMAT"},mr={message:"Missing matchUpId",code:"ERR_MISSING_MATCHUP_ID"},xs={message:"Missing matchUpIds",code:"ERR_MISSING_MATCHUP_IDS"},Be={message:"matchUp not found",code:"ERR_NOT_FOUND_MATCHUP"},Bn={message:"Missing matchUps",code:"ERR_MISSING_MATCHUPS"},Xe={message:"Missing matchUp",code:"ERR_MISSING_MATCHUP"},cr={message:"Invalid matchUp",code:"ERR_INVALID_MATCHUP"},BT={message:"Missing policyType",code:"ERR_MISSING_POLICY_TYPE"},Ea={message:"Missing policyDefinitions",code:"ERR_MISSING_POLICY_DEFINITIONS"},BW={message:"Missing seeding policy",code:"ERR_MISSING_POLICY_SEEDING"},tU={message:"Missing avoidance policy",code:"ERR_MISSING_POLICY_AVOIDANCE"},WT={message:"Missing policy attributes",code:"ERR_MISSING_POLICY_ATTRIBUTES"},eU={message:"Invalid policyDefinitions",code:"ERR_INVALID_POLICY_DEFINITIONS"},HT={message:"existing policyType",code:"ERR_EXISTING_POLICY_TYPE"},WW={message:"Policy not attached",code:"ERR_FAILURE_POLICY_NOT_ATTACHED"},np={message:"Policy not found",code:"ERR_NOT_FOUND_POLICY"},HW={message:"Missing scoring policy / matchUpFormats",code:"ERR_MISSING_POLICY_SCORING_MATCHUP_FORMATS"},rU={message:"Invalid sideNumber",code:"ERR_INVALID_SIDE_NUMBER"},YW={message:"Invalid setNumber",code:"ERR_INVALID_SET_NUMBER"},Yg={message:"Missing setObject",code:"ERR_MISSING_SET_ATTRIBUTE"},jW={message:"Missing setNumber",code:"ERR_MISSING_SET_NUMBER"},qW={message:"Missing sideNumber",code:"ERR_MISSING_SIDE_NUMBER"},jg={message:"Missing courtId",code:"ERR_MISSING_COURT_ID"},nt={message:"Missing value",code:"ERR_MISSING_VALUE"},nU={message:"Missing birthdate",code:"ERR_MISSING_BIRTH_DATE"},oU={message:"Missing date",code:"ERR_MISSING_DATE"},qg={message:"No valid dates",code:"ERR_NO_VALID_DATES"},il={message:"Invalid bookings",code:"ERR_INVALID_BOOKINGS"},$g={message:"Invalid dateAvailability",code:"ERR_INVALID_DATE_AVAILABILITY"},iU={message:"Missing dateAvailability",code:"ERR_MISSING_DATE_AVAILABILITY"},ae={message:"Invalid Date",code:"ERR_INVALID_DATE"},ws={message:"Invalid time",code:"ERR_INVALID_TIME"},sU={message:"Invalid tournament dates",code:"ERR_INVALID_DATES_TOURNAMENT"},Sw={message:"Missing date range",info:"Event or tournament must have start and end dates",code:"ERR_MISSING_DATE_RANGE"},op={message:"Invalid Time Zone",code:"ERR_INVALID_TIME_ZONE"},ip={message:"Invalid embargo: must be an ISO 8601 datetime with timezone (Z or \xB1HH:MM offset)",code:"ERR_INVALID_EMBARGO"},YT={message:"Invalid game scores",code:"ERR_INVALID_SCORES_GAME"},aU={message:"Invalid score",code:"ERR_INVALID_SCORE"},sl={message:"Invalid winningSide",code:"ERR_INVALID_WINNING_SIDE"};var hw={message:"No participants generated",code:"ERR_NO_PARTICIPANTS_GENERATED"},Kg={message:"Cannot modify tieFormat",code:"ERR_UNCHANGED_CANNOT_MODIFY_TIEFORMAT"},cU={message:"Cannot modify participantType",code:"ERR_UNCHANGED_CANNOT_MODIFY_PARTICIPANT_TYPE"},Om={message:"Cannot remove participants",code:"ERR_UNCHANGED_CANNOT_REMOVE_PARTICIPANTS"},uU={message:"Participant category mismatch",code:"ERR_CATEGORY_MISMATCH"},al={message:"Cannot change winningSide",code:"ERR_UNCHANGED_CANNOT_CHANGE_WINNING_SIDE"},xi={message:"Invalid participant",code:"ERR_INVALID_PARTICIPANT"},Hr={message:"Invalid participantId",code:"ERR_INVALID_PARTICIPANT_ID"},_r={message:"Invalid participantIds",code:"ERR_INVALID_PARTICIPANT_IDS"},pU={message:"Invalid participantRole",code:"ERR_INVALID_PARTICIPANT_ROLE"},Dn={message:"Invalid participantType",code:"ERR_INVALID_PARTICIPANT_TYPE"},mU={message:"Missing participantRole",code:"ERR_MISSING_PARTICIPANT_ROLE"},Aa={message:"Missing participant",code:"ERR_MISSING_PARTICIPANT"},zc={message:"Missing participants",code:"ERR_MISSING_PARTICIPANTS"},We={message:"Missing participantId",code:"ERR_MISSING_PARTICIPANT_ID"},dU={message:"Missing qualified participants",code:"ERR_MISSING_QUALIFIED_PARTICIPANTS"},ee={message:"Participant Not Found",code:"ERR_NOT_FOUND_PARTICIPANT"},lU={message:"participantId exists",code:"ERR_EXISTING_PARTICIPANT_ID"},$W={message:"participant pair exists",code:"ERR_EXISTING_PARTICIPANT_PAIR"},fU={message:"No participant removed",code:"ERR_UNCHANGED_NO_PARTICIPANT_REMOVED"},Mo={message:"Missing participantIds",code:"ERR_MISSING_PARTICIPANT_IDS"},gU={message:"Missing participantsCount",code:"ERR_MISSING_PARTICIPANT_COUNT"},IU={message:"Participant not checked in",code:"ERR_UNCHANGED_PARTICIPANT_NOT_CHECKED_IN"},SU={message:"Missing person details",code:"ERR_MISSING_PERSON_DETAILS"},Pa={message:"Existing participant drawPosition assignment",code:"ERR_EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT"},_m={message:"Existing participant",code:"ERR_EXISTING_PARTICIPANT"},zg={message:"participantsCount exceeds drawSize",code:"ERR_INVALID_PARTICIPANT_COUNT"},Qg={message:"Invalid entry status",code:"ERR_INVALID_ENTRY_STATUS"},jT={message:"Participant Entry Not Found",code:"ERR_NOT_FOUND_PARTICIPANT_ENTRY"},Tw={message:"Participant not entered in stage",code:"ERR_UNCHANGED_PARTICIPANT_NOT_ENTERED"},yw={message:"Participant not found in stageSequence",code:"ERR_NOT_FOUND_PARTICIPANT_IN_STAGE"},hU={message:"entryStatus not allowed in stage",code:"ERR_INVALID_ENTRY_STATUS_IN_STAGE"},TU={message:"entryStatus not allowed for event",code:"ERR_INVALID_ENTRY_STATUS_IN_EVENT"},Xg={message:"No stage space available for entryStatus",code:"ERR_UNCHANGED_NO_AVAILABLE_STAGE_SPACE"},Jg={message:"Insufficient drawPositions to accommodate qualifiers",code:"ERR_UNCHANGED_NO_DRAW_POSITIONS_FOR_QUALIFIERS"},Zg={message:"Insufficient drawPositions to accommodate entries",code:"ERR_INSUFFICIENT_DRAW_POSITIONS"},yU={message:"Missing penaltyType",code:"ERR_MISSING_PENALTY_TYPE"},EU={message:"Missing penaltyId",code:"ERR_MISSING_PENALTY_ID"},sp={message:"Penalty not found",code:"ERR_NOT_FOUND_PENALTY"},AU={message:"Missing courtsCount/courtNames",code:"ERR_MISSING_COURTS_INFO"},vo={message:"Court not found",code:"ERR_NOT_FOUND_COURT"},PU={message:"Court exists",code:"ERR_EXISTING_COURT"},qT={message:"Booking not found",code:"ERR_NOT_FOUND_BOOKING"},NU={message:"An active draft already exists for this draw",code:"ERR_EXISTING_DRAFT"},DU={message:"Existing matchUps conflict with booking",code:"ERR_EXISTING_MATCHUPS"},UU={message:"Venue exists",code:"ERR_EXISTING_VENUE"},wi={message:"Venue not found",code:"ERR_NOT_FOUND_VENUE"},Ls={message:"Missing venueId",code:"ERR_MISSING_VENUE_ID"},RU={message:"Invalid endTime",code:"ERR_INVALID_END_TIME"},bU={message:"Existing endTime",code:"ERR_EXISTING_END_TIME"},CU={message:"Invalid stopTime",code:"ERR_INVALID_STOP_TIME"},MU={message:"Invalid startTime",code:"ERR_INVALID_START_TIME"},Ew={message:"Invalid resumeTime",code:"ERR_INVALID_RESUME_TIME"},tI={message:"Invalid timeItem",code:"ERR_INVALID_TIME_ITEMS"},vU={message:"Missing async state provider",code:"ERR_MISSING_ASYNC_STATE_PROVIDER"},eI={message:"Missing timeItem",code:"ERR_MISSING_TIME_ITEM"},rI={message:"Missing timeItems",code:"ERR_MISSING_TIME_ITEMS"},ap={message:"Missing context",code:"ERR_MISSING_CONTEXT"},OU={message:"Missing schedule",code:"ERR_MISSING_SCHEDULE"},Qc={message:"Invalid scaleItem",code:"ERR_INVALID_SCALE_ITEM"},_U={message:"Modifications failed",code:"ERR_FAILURE_MODIFICATIONS"},Na={message:"No modifications applied",code:"ERR_UNCHANGED_NO_MODIFICATIONS_APPLIED"},xU={message:"Unable to assign court",code:"ERR_UNCHANGED_COURT_NOT_ASSIGNED"},xm={message:"No Candidates",code:"ERR_UNCHANGED_NO_CANDIDATES"},ni={message:"Invalid configuration",code:"ERR_INVALID_CONFIG"},wU={message:"Invalid collectionDefinition",code:"ERR_INVALID_COLLECTION_DEFINITION"},yo={message:"Invalid object",code:"ERR_INVALID_OBJECT"},wm={message:"Invalid gender",code:"ERR_INVALID_GENDER"},cp={message:"Invalid category",code:"ERR_INVALID_CATEGORY"},O={message:"Invalid values",code:"ERR_INVALID_VALUES"},LU={message:"Duplicate value",code:"ERR_DUPLICATE_VALUE"},nI={message:"Team not found",code:"ERR_NOT_FOUND_TEAM"},FU={message:"No valid actions",code:"ERR_NO_VALID_ACTIONS"},Xc={message:"No valid attributes",code:"ERR_NO_VALID_ATTRIBUTES"},oI={message:"Value unchanged",code:"ABORT_UNCHANGED"},fe={message:"Not found",code:"ERR_NOT_FOUND"},iI={message:"Not implemented",code:"ERR_NOT_IMPLEMENTED"},kU={message:"Existing flight",code:"ERR_EXISTING_FLIGHT"},sI={message:"Existing flight profile",code:"ERR_EXISTING_FLIGHT_PROFILE"},GU={message:"Existing outcome",code:"ERR_EXISTING_OUTCOME"},VU={message:"Existing matchUpId",code:"ERR_EXISTING_MATCHUP_ID"},$T={message:"Existing stage",code:"ERR_EXISTING_STAGE"},aI={message:"Existing structure",code:"ERR_EXISTING_STRUCTURE"},Jc={message:"Method not found",code:"ERR_NOT_FOUND_METHOD"},BU={message:"Mutation blocked by active lock",code:"ERR_MUTATION_LOCKED"},WU={message:"Active mutation lock already exists for scope",code:"ERR_EXISTING_MUTATION_LOCK"},HU={message:"Mutation lock not found",code:"ERR_NOT_FOUND_MUTATION_LOCK"},YU={message:"Lock token does not match",code:"ERR_UNAUTHORIZED_LOCK_OPERATION"},jU={message:"Scheduled matchUps",code:"ERR_SCHEDULED_MATCHUPS"},Zc={message:"Scores present",code:"ERR_SCORES_PRESENT"},Aw={ANACHRONISM:FT,BOOKING_NOT_FOUND:qT,CANNOT_CHANGE_WINNING_SIDE:al,CANNOT_MODIFY_TIEFORMAT:Kg,CANNOT_MODIFY_PARTICIPANT_TYPE:cU,CANNOT_REMOVE_MAIN_STRUCTURE:bD,CANNOT_REMOVE_PARTICIPANTS:Om,CATEGORY_MISMATCH:uU,COURT_EXISTS:PU,COURT_NOT_FOUND:vo,EXISTING_DRAFT:NU,EXISTING_MATCHUPS:DU,DRAW_DEFINITION_NOT_FOUND:Mr,DRAW_ID_EXISTS:xD,DRAW_POSITION_ACTIVE:qc,DRAW_POSITION_ASSIGNED:Yc,DRAW_POSITION_NOT_CLEARED:_D,DRAW_POSITION_NOT_FOUND:kW,DRAW_SIZE_MISMATCH:GW,DUPLICATE_ENTRY:nl,DUPLICATE_VALUE:LU,ENTRY_STATUS_NOT_ALLOWED_FOR_EVENT:TU,ENTRY_STATUS_NOT_ALLOWED_IN_STAGE:hU,EVENT_EXISTS:YD,EVENT_NOT_FOUND:Wr,EXISTING_DRAW_DEFINITIONS:CD,EXISTING_END_TIME:bU,EXISTING_FLIGHT:kU,EXISTING_MATCHUP_ID:VU,EXISTING_OUTCOME:GU,EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT:Pa,EXISTING_PARTICIPANT:_m,EXISTING_POLICY_TYPE:HT,EXISTING_PROFILE:sI,EXISTING_ROUND:WD,EXISTING_STAGE:$T,EXISTING_STRUCTURE:aI,INCOMPATIBLE_MATCHUP_STATUS:Hg,INCOMPLETE_SOURCE_STRUCTURE:Lg,INSUFFICIENT_DRAW_POSITIONS:Zg,INVALID_ACTION:kD,INVALID_ASSIGNMENT:GT,INVALID_BOOKINGS:il,INVALID_CATEGORY:cp,INVALID_COLLECTION_DEFINITION:wU,INVALID_CONFIGURATION:ni,INVALID_DATE_AVAILABILITY:$g,INVALID_DATE:ae,INVALID_DRAW_DEFINITION:ha,INVALID_DRAW_POSITION_FOR_SEEDING:Fg,INVALID_DRAW_POSITION:ps,INVALID_DRAW_SIZE:vm,INVALID_END_TIME:RU,INVALID_ENTRIES:qD,INVALID_EVENT_TYPE:zn,INVALID_GAME_SCORES:YT,INVALID_GENDER:wm,INVALID_MATCHUP_FORMAT:XD,INVALID_MATCHUP_STATUS:uc,INVALID_MATCHUP_STATUS_BYE:zD,INVALID_MATCHUP:cr,INVALID_OBJECT:yo,INVALID_PARTICIPANT_ID:Hr,INVALID_PARTICIPANT_IDS:_r,INVALID_PARTICIPANT_ROLE:pU,INVALID_PARTICIPANT_SEEDING:wD,INVALID_PARTICIPANT_TYPE:Dn,INVALID_PARTICIPANT:xi,INVALID_POLICY_DEFINITION:eU,INVALID_RECORDS:kT,INVALID_SCALE_ITEM:Qc,INVALID_SEED_NUMBER:VD,INVALID_SEED_POSITION:BD,INVALID_SET_NUMBER:YW,INVALID_SIDE_NUMBER:rU,INVALID_SCORE:aU,INVALID_STAGE:cc,INVALID_START_TIME:MU,INVALID_STRUCTURE:Co,INVALID_STOP_TIME:CU,INVALID_TIE_FORMAT:ri,INVALID_TIME:ws,INVALID_TIME_ITEM:tI,INVALID_TOURNAMENT_DATES:sU,INVALID_TOURNAMENT_RECORD:Hc,INVALID_VALUES:O,INVALID_WINNING_SIDE:sl,LUCKY_DRAW_BYE_LIMIT:QD,MATCHUP_NOT_FOUND:Be,METHOD_NOT_FOUND:Jc,MUTATION_LOCKED:BU,MUTATION_LOCK_EXISTS:WU,MUTATION_LOCK_NOT_FOUND:HU,MISSING_ASSIGNMENTS:Bg,MISSING_ASYNC_STATE_PROVIDER:vU,MISSING_AVOIDANCE_POLICY:tU,MISSING_BIRTH_DATE:nU,MISSING_COLLECTION_DEFINITION:ZD,MISSING_COURT_ID:jg,MISSING_COURTS_INFO:AU,MISSING_DATE_AVAILABILITY:iU,MISSING_DATE:oU,MISSING_DRAW_DEFINITION:$,MISSING_DRAW_ID:Nn,MISSING_DRAW_POSITION:Ta,MISSING_DRAW_POSITIONS:jc,MISSING_DRAW_SIZE:$c,MISSING_ENTRIES:jD,MISSING_EVENT:le,MISSING_QUALIFIED_PARTICIPANTS:dU,MISSING_MATCHUP_FORMAT:JD,MISSING_MATCHUP_ID:mr,MISSING_MATCHUP_IDS:xs,MISSING_MATCHUP:Xe,MISSING_MATCHUPS:Bn,MISSING_PARTICIPANT_COUNT:gU,MISSING_PARTICIPANT_ID:We,MISSING_PARTICIPANT_IDS:Mo,MISSING_PARTICIPANT_ROLE:mU,MISSING_PARTICIPANT:Aa,MISSING_PARTICIPANTS:zc,MISSING_PENALTY_ID:EU,MISSING_PENALTY_TYPE:yU,MISSING_PERSON_DETAILS:SU,MISSING_POLICY_ATTRIBUTES:WT,MISSING_POLICY_DEFINITION:Ea,MISSING_POLICY_TYPE:BT,MISSING_POSITION_ASSIGNMENTS:KD,MISSING_ROUND_NUMBER:VW,MISSING_SCHEDULE:OU,MISSING_SCORING_POLICY:HW,MISSING_SEED_ASSIGNMENTS:GD,MISSING_SEEDCOUNT_THRESHOLDS:FD,MISSING_SEEDING_POLICY:BW,MISSING_SET_NUMBER:jW,MISSING_SET_OBJECT:Yg,MISSING_SIDE_NUMBER:qW,MISSING_STAGE:Wg,MISSING_STRUCTURE_ID:dn,MISSING_STRUCTURE:_i,MISSING_MAIN_STRUCTURE:Vg,MISSING_STRUCTURES:Gg,MISSING_TARGET_LINK:kg,MISSING_TIE_FORMAT:ya,MISSING_TIME_ITEM:eI,MISSING_TIME_ITEMS:rI,MISSING_TOURNAMENT_ID:ac,MISSING_TOURNAMENT_RECORD:j,MISSING_TOURNAMENT_RECORDS:kt,MISSING_VALUE:nt,MISSING_VENUE_ID:Ls,MODIFICATIONS_FAILED:_U,NO_CANDIDATES:xm,NO_DRAW_POSITIONS_AVAILABLE_FOR_QUALIFIERS:Jg,NO_MODIFICATIONS_APPLIED:Na,NO_STAGE_SPACE_AVAILABLE_FOR_ENTRY_STATUS:Xg,NO_PARTICIPANT_REMOVED:fU,NO_VALID_ACTIONS:FU,NO_VALID_ATTRIBUTES:Xc,NO_VALID_DATES:qg,NOT_FOUND:fe,NOT_IMPLEMENTED:iI,PARTICIPANT_COUNT_EXCEEDS_DRAW_SIZE:zg,PARTICIPANT_ID_EXISTS:lU,PARTICIPANT_NOT_CHECKED_IN:IU,PARTICIPANT_NOT_FOUND:ee,PARTICIPANT_PAIR_EXISTS:$W,PENALTY_NOT_FOUND:sp,POLICY_NOT_ATTACHED:WW,POLICY_NOT_FOUND:np,SCHEDULE_NOT_CLEARED:MD,SCHEDULE_CONFLICT_DOUBLE_BOOKING:vD,SCHEDULE_CONFLICT_COURT_UNAVAILABLE:OD,SCHEDULED_MATCHUPS:jU,SCORES_PRESENT:Zc,SEEDSCOUNT_GREATER_THAN_DRAW_SIZE:LD,STAGE_SEQUENCE_LIMIT:$D,STRUCTURE_NOT_FOUND:Nt,TEAM_NOT_FOUND:nI,UNABLE_TO_ASSIGN_COURT:xU,UNAUTHORIZED_LOCK_OPERATION:YU,UNLINKED_STRUCTURES:HD,UNRECOGNIZED_DRAW_TYPE:rp,UNRECOGNIZED_MATCHUP_FORMAT:Kc,UNRECOGNIZED_MATCHUP_STATUS:VT,VALUE_UNCHANGED:oI,VENUE_EXISTS:UU};var Qe={disableNotifications:!1,tournamentId:void 0,tournamentRecords:{},subscriptions:{},modified:!1,methods:{},notices:[]},qU={addNotice:iH,callListener:pH,cycleMutationStatus:oH,deleteNotice:cH,deleteNotices:aH,disableNotifications:KW,enableNotifications:zW,getMethods:Lm,getNotices:sH,getTopics:uH,getTournamentId:Pw,getTournamentRecord:QW,getTournamentRecords:XW,removeTournamentRecord:eH,setMethods:nH,setSubscriptions:rH,setTournamentId:ZW,setTournamentRecord:JW,setTournamentRecords:tH,handleCaughtError:mH};function KW(){Qe.disableNotifications=!0}function zW(){Qe.disableNotifications=!1}function Pw(){return Qe.tournamentId}function QW(t){return Qe.tournamentRecords[t]}function XW(){return Qe.tournamentRecords}function JW(t){let e=t?.tournamentId;return e?(Qe.tournamentRecords[e]=t,{success:!0}):{error:Hc}}function ZW(t){return t?Qe.tournamentRecords[t]?(Qe.tournamentId=t,{success:!0}):{error:j}:(Qe.tournamentId=void 0,{success:!0})}function tH(t){Qe.tournamentRecords=t;let e=Object.keys(t);e.length===1?Qe.tournamentId=e[0]:e.length||(Qe.tournamentId=void 0)}function eH(t){if(typeof t!="string")return{error:O};if(!Qe.tournamentRecords[t])return{error:fe};delete Qe.tournamentRecords[t];let e=Object.keys(Qe.tournamentRecords);return e.length===1?Qe.tournamentId=e[0]:e.length||(Qe.tournamentId=void 0),{success:!0}}function rH(t){return t.subscriptions===null||Object.keys(t.subscriptions).length===0?(Qe.subscriptions={},{...P}):typeof t.subscriptions!="object"?{error:O}:(Object.keys(t.subscriptions).forEach(e=>{typeof t.subscriptions[e]=="function"?Qe.subscriptions[e]=t.subscriptions[e]:delete Qe.subscriptions[e]}),{...P})}function nH(t){return typeof t!="object"?{error:O}:(Object.keys(t).forEach(e=>{typeof t[e]=="function"&&(Qe.methods[e]=t[e])}),{...P})}function oH(){let t=Qe.modified;return Qe.modified=!1,t}function iH({topic:t,payload:e,key:r},n){if(!(typeof t!="string"||typeof e!="object")&&(Qe.disableNotifications||(Qe.modified=!0),!(Qe.disableNotifications||!Qe.subscriptions[t]&&!n)))return r&&(Qe.notices=Qe.notices.filter(o=>!(o.topic===t&&o.key===r))),Qe.notices.push({topic:t,payload:e,key:r}),{...P}}function Lm(){return Qe.methods??{}}function sH({topic:t}){return Qe.notices.filter(e=>e.topic===t).map(e=>e.payload)}function aH(){Qe.notices=[]}function cH({topic:t,key:e}){Qe.notices=Qe.notices.filter(r=>(!t||r.topic===t)&&r.key!==e)}function uH(){return{topics:Object.keys(Qe.subscriptions)}}function pH({topic:t,notices:e},r){let n=Qe.subscriptions[t];n&&typeof n=="function"&&n(e);let o=r?.[t];o&&typeof o=="function"&&o(e)}function mH({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:Pw(),params:JSON.stringify(r),engine:t,methodName:e,error:o}),{error:o}}var be={timers:{default:{elapsedTime:0}},globalSubscriptions:{},deepCopyAttributes:{stringify:[],ignore:[],toJSON:[]},globalMethods:[],deepCopy:!0},rn=qU,Nw=["addNotice","callListener","cycleMutationStatus","deleteNotice","deleteNotices","disableNotifications","enableNotifications","getMethods","getNotices","getTopics","getTournamentId","getTournamentRecord","getTournamentRecords","removeTournamentRecord","setSubscriptions","setTournamentId","setTournamentRecord","setTournamentRecords"];function dH(t){if(typeof t!="object")throw new Error("Global state provider can not be undefined or null");if(Yt(Object.keys(t),Nw).length!==Nw.length)throw new Error("Global state provider is missing required methods");return rn=t,{success:!0}}function $U(){if(rn.createInstanceState){try{rn.createInstanceState()}catch(t){return{error:t}}return{success:!0}}else return{error:vU}}function je(t){return!t||typeof t!="object"?be.devContext??!1:typeof be.devContext!="object"?!1:Object.keys(t).every(e=>be.devContext?.[e]===t[e])&&be.devContext}function lH(t="reset",e="default"){let r=Date.now();if(t==="report"){if(e==="allTimers")return Object.keys(be.timers).filter(o=>o!=="default"||be.timers[o].startTime).map(o=>{let i=be.timers[o],s=i.state==="stopped"?0:(r-(i?.startTime??0))/1e3,a=i.elapsedTime+s;return{state:be.timers[o].state,elapsedTime:a.toFixed(2),timer:o}});{let n=be.timers[e].state==="stopped"?0:(r-(be.timers[e]?.startTime??0))/1e3,o=be.timers[e].elapsedTime+n;return{state:be.timers[e].state,elapsedTime:o.toFixed(2),timer:e}}}if(!be.timers[e]||t==="reset"){if(e==="allTimers")return be.timers={default:{elapsedTime:0}},!0;be.timers[e]={startTime:r,state:"active",elapsedTime:0}}return be.timers[e].elapsedTime||(be.timers[e].elapsedTime=0),t==="stop"&&be.timers[e].state!=="stopped"&&(be.timers[e].state="stopped")&&(be.timers[e].elapsedTime+=(r-(be.timers[e]?.startTime??0))/1e3),t==="start"&&(be.timers[e].startTime=r)&&(be.timers[e].state="active"),be.timers[e]}function Dw(t){Br(t)?be.globalLog=t:delete be.globalLog}function up(t){be.devContext=t}function KU(){rn.disableNotifications()}function cI(){rn.enableNotifications()}function pp(t,e){typeof t=="boolean"&&(be.deepCopy=t),typeof e=="object"&&(Array.isArray(e.ignore)&&(be.deepCopyAttributes.ignore=e.ignore),Array.isArray(e.toJSON)&&(be.deepCopyAttributes.toJSON=e.toJSON),Array.isArray(e.stringify)&&(be.deepCopyAttributes.stringify=e.stringify),e.threshold&&(be.deepCopyAttributes.threshold=e.threshold))}function uI(){return{enabled:be.deepCopy,...be.deepCopyAttributes}}function fH(t){return t?.subscriptions?(Object.keys(t.subscriptions).forEach(e=>{be.globalSubscriptions[e]=t.subscriptions[e]}),{...P}):{error:nt,info:"missing subscriptions"}}function gH(t){return t?.subscriptions?rn.setSubscriptions({subscriptions:t.subscriptions}):{error:nt,info:"missing subscriptions"}}function Uw(t){return t?typeof t!="object"?{error:O}:(Object.keys(t).forEach(e=>{Br(t[e])&&(be.globalMethods[e]=t[e])}),{...P}):{error:nt,info:"missing method declarations"}}function Rw(t){return t?typeof t!="object"?{error:O}:rn.setMethods(t):{error:nt,info:"missing method declarations"}}function pI(){return rn.cycleMutationStatus()}function at(t){if(typeof t?.topic!="string")return;let e=be.globalSubscriptions[t.topic];return rn.addNotice(t,e)}function mI(){return{...be.globalMethods,...rn.getMethods()}}function KT(t){return rn.getNotices(t)}function zT({key:t,topic:e}){return rn.deleteNotice({key:t,topic:e})}function ms(){return rn.deleteNotices()}function vr(){return rn.getTopics()}function tu(t){return vr()?.topics?.includes(t)}async function cl(t){return rn.callListener(t,be.globalSubscriptions)}function Fs(){return rn.getTournamentId()}function dI(t){return rn.getTournamentRecord(t)}function oi(){return rn.getTournamentRecords()}function zU(t){return rn.setTournamentRecord(t)}function ul(t){return rn.setTournamentRecords(t)}function Fm(t){return rn.setTournamentId(t)}function QU(t){return rn.removeTournamentRecord(t)}function QT(){return rn}function km({engineName:t,methodName:e,params:r,err:n}){let o=Br(rn.handleCaughtError)&&rn.handleCaughtError||qU.handleCaughtError,{tournamentRecord:i,...s}=r;return o({params:s,engineName:t,methodName:e,err:n})}function XU(t,e){if(be.globalLog)try{be.globalLog({log:t,engine:e})}catch(r){console.log("globalLog error",r),console.log(e,t),Dw()}else console.log(e,t)}function JU(t,e,r,n){if(!Tt(t))return{error:O};Le||(r=1);let o=Array.isArray(e)?e:[],i={},s=(a,c=0)=>{Object.keys(a).forEach(u=>{Br(a[u])?i[u]=a[u]:Tt(a[u])&&(e===!0||o?.includes(u))&&(r===void 0||c<r)&&s(a[u],c+1)})};return s(t),n?Uw(i):Rw(i),{methods:i}}function IH(t,e,r){return Object.keys(t).filter(n=>!e.includes(t[n])&&(!r||(Array.isArray(t[n])?t[n].length:!0)))}function et(t,e,r,n){if(typeof t!="object"||t===null)return t;uI()?.enabled||(n=!0);let i=["",void 0,null];e&&i.push(!1);let s=IH(t,i,r);return Object.assign({},...s.map(a=>Array.isArray(t[a])?{[a]:n?t[a]:t[a].map(c=>et(c))}:{[a]:n?t[a]:et(t[a])}))}function M({context:t,result:e,stack:r,info:n}){return e&&!Array.isArray(e?.stack)&&(e.stack=[]),e&&Array.isArray(e?.stack)&&typeof r=="string"&&e.stack.push(r),e&&n&&(e.info=n),e&&typeof t=="object"&&Object.keys(t).length&&(e.context??={},Object.assign(e.context,et(t))),e&&!e?.error&&!e?.success&&Object.assign(e,{...P}),e??{success:!0}}var Je="FEMALE",ii="OTHER",ds="MIXED",Ce="MALE";var pl={FEMALE_ABBR:"F",OTHER_ABBR:"O",MIXED_ABBR:"X",MALE_ABBR:"M",ANY_ABBR:"A",FEMALE:Je,MIXED:ds,OTHER:ii,MALE:Ce,ANY:"ANY"};function ls(t){return[Je,"F"].includes(t)}function Da(t){return[Ce,"M"].includes(t)}function nn(t){return[ds,"X"].includes(t)}function Oo(t){return["ANY","A"].includes(t)}function Ar(t){if(t){if(ls(t))return Je;if(nn(t))return ds;if(Da(t))return Ce;if(Oo(t))return"ANY"}return ii}function Un(t){return ls(t)||Da(t)}var EH="MIXED events can not contain mixed singles or { gender: ANY } collections",AH="events with { gender: ANY } can not contain MIXED singles collections";function ml(t){let e="tieFormatGenderValidityCheck",{referenceGender:r,matchUpType:n,gender:o}=t;return r&&o&&Un(r)&&Ar(r)!==Ar(o)?M({result:{valid:!1,error:wm},context:{gender:o},stack:e}):nn(r)&&(Oo(o)||nn(o)&&n!==Rt)?M({result:{error:wm,valid:!1},info:EH,stack:e}):Oo(r)&&nn(o)&&n!==Rt?M({result:{error:wm,valid:!1},info:AH,stack:e}):{valid:!0}}var PH="normal",ZU="timed",NH="final",lI="NOAD";var tR=["SET","HAL","QTR","PER","INN","RND","FRM","MAP","MAT"],XT="CONSECUTIVE",JT="TRADITIONAL",DH="game",UH="matchUp",Cw={S:PH,F:NH,G:DH,M:UH};function mp(t,e){if(Tt(t)&&(t?.bestOf||t?.exactly)&&t?.setFormat)return bH(t,e)}function fI(t){return!Number.isNaN(Number(t))&&Number(t)}function Ow(t){let e=`T${t.minutes}`;return t.based==="P"&&(e+="P"),t.tiebreakFormat?.tiebreakTo&&(e+=`/TB${t.tiebreakFormat.tiebreakTo}`),t.modifier&&(e+=`@${t.modifier}`),e}function RH(t){let e=t?.deuceAfter?`${t.deuceAfter}D`:"";if(t?.type===JT)return`TN${e}`;if(t?.type===XT&&Number.isInteger(t.count))return`${t.count}C${e}`}function bH(t,e){let r=fI(t.bestOf)||void 0,n=fI(t.exactly)||void 0,o=r||n;if(t.setFormat?.timed&&t.simplified&&o===1)return Ow(t.setFormat);let i=t.matchRoot||"SET",s=n&&n!==1?"X":"",a=t.aggregate?"A":"",c=o&&`${i}${o}${s}${a}`||"",u=Mw(t.setFormat,e),p=u&&`S:${u}`||"",m=Mw(t.finalSetFormat,e),d=o&&o>1&&m&&u!==m&&`F:${m}`||"",l=t.gameFormat?`G:${RH(t.gameFormat)}`:"",f=t.matchUpConstraint?.timed?`M:T${t.matchUpConstraint.minutes}`:"";if(c&&u)return[c,p,l,d,f].filter(Boolean).join("-")}function Mw(t,e){if(typeof t=="object"&&Object.keys(t).length){if(t.timed)return Ow(t);if(t.outs)return`O${t.outs}`;if(t.tiebreakSet)return vw(t.tiebreakSet);let r=fI(t.setTo);if(r){let n=t.NoAD&&lI||"",o=vw(t.tiebreakFormat),i=o&&`/${o}`||"",s=fI(t.tiebreakAt),a=s&&(s!==r||e)&&`@${s}`||"";if(o!==!1)return`${r}${n}${i}${a}`}}}function vw(t){if(t){if(typeof t=="object"&&!t.tiebreakTo)return"";if(typeof t=="object"&&fI(t.tiebreakTo)){let e=`TB${t.tiebreakTo}${t.NoAD?lI:""}`;return t.modifier&&(e+=`@${t.modifier}`),e}else return!1}}function oe(t){if(wt(t)){let e=t.startsWith("T")&&ZU||tR.some(r=>t.startsWith(r))&&"SET"||"";if(e===ZU){let r=Lw(t),n={simplified:!0,setFormat:r,bestOf:1};if(r)return n}if(e==="SET")return vH(t)}}function CH(t){let e=tR.find(u=>t.startsWith(u));if(!e)return;let r=t.slice(e.length),n=/^(\d+)([A-Z]*)$/.exec(r);if(!n)return;let o=Gm(n[1]);if(!o)return;let i=n[2],s=!1,a=!1,c=[];for(let u of i)u==="X"?s=!0:u==="A"?a=!0:c.push(u);return{matchRoot:e,count:o,exactly:s,aggregate:a,matchMods:c}}function MH(t){let e=/^(.+?)(\d+D)$/.exec(t),r=e?e[1]:t,n=e?Number(e[2].slice(0,-1)):void 0;if(n!==void 0&&(n<1||!Number.isInteger(n)))return;if(r==="TN"){let i={type:JT};return n&&(i.deuceAfter=n),i}let o=/^([1-9]\d*)C$/.exec(r);if(o){let i={type:XT,count:Number(o[1])};return n&&(i.deuceAfter=n),i}}function vH(t){let e=t.split("-"),r=CH(e[0]);if(!r)return;let{matchRoot:n,count:o,exactly:i,aggregate:s,matchMods:a}=r,c=i&&o!==1?void 0:o,u=i&&o!==1?o:void 0,p,m,d,l,h={setFormat:p,finalSetFormat:m,gameFormat:d,matchUpConstraint:l,sCount:0,fCount:0,gCount:0,mCount:0};for(let T=1;T<e.length;T++)if(!OH(e[T],h))return;return{setFormat:p,finalSetFormat:m,gameFormat:d,matchUpConstraint:l}=h,_H({setFormat:p,finalSetFormat:m,gameFormat:d,matchUpConstraint:l,matchRoot:n,aggregate:s,matchMods:a,bestOf:c,exactly:u})}function OH(t,e){let r=t.indexOf(":");if(r<0)return!1;let n=t.slice(0,r),o=t.slice(r+1);if(!(n in Cw))return!1;if(n==="S"){if(e.sCount++,e.sCount>1)return!1;e.setFormat=_w(t,o)}else if(n==="F"){if(e.fCount++,e.fCount>1)return!1;e.finalSetFormat=_w(t,o)}else if(n==="G"){if(e.gCount++,e.gCount>1||(e.gameFormat=MH(o),!e.gameFormat))return!1}else if(n==="M"&&(e.mCount++,e.mCount>1||(e.matchUpConstraint=GH(o),!e.matchUpConstraint)))return!1;return!0}function _H({setFormat:t,finalSetFormat:e,gameFormat:r,matchUpConstraint:n,matchRoot:o,aggregate:i,matchMods:s,bestOf:a,exactly:c}){let u=t&&t.timed||e&&e.timed;if(o==="SET"&&!(a&&a<6||u&&c)||!t||!(!e||e))return;let d=et({setFormat:t,exactly:c,bestOf:a});return o!=="SET"&&(d.matchRoot=o),i&&(d.aggregate=!0),s.length>0&&(d.matchMods=s),e&&(d.finalSetFormat=e),r&&(d.gameFormat=r),n&&(d.matchUpConstraint=n),d}function _w(t,e){return e.startsWith("TB")?xH(e):e.startsWith("O")?wH(e):e.startsWith("T")?Lw(e):LH(t,e)}function xH(t){let e=ww(t);return e===!1?!1:typeof e=="object"?{tiebreakSet:e}:void 0}function wH(t){let e=/^O([1-9]\d*)$/.exec(t);if(e)return{outs:Number(e[1])}}function LH(t,e){let r=/^[FS]:(\d+)([A-Za-z]*)/.exec(t),n=r&&Fw(r[2])||!1,o=!r?.[2]||n,i=r?Gm(r[1]):void 0,s=xw(e),a=s!==!1,c=a&&s||i,u=ww(e.split("/")[1]);return!i||!o||!(u!==!1)||!a?!1:FH(i,n,u,c)}function FH(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 xw(t,e=!0){let r=t?.indexOf("@")>0&&t.split("@");if(r)return(e?Gm(r[1]):r[1])||!1}function ww(t){if(t)return t.startsWith("TB")?kH(t):!1}function kH(t){let e=xw(t,!1),r=/^TB(\d+)([A-Za-z]*)/.exec(t),n=r?.[1],o=r&&Fw(r[2]),i=!r?.[2]||o,s=Gm(n);if(!s||!i)return!1;let a={tiebreakTo:s};return e&&typeof e=="string"&&!yt(e)&&(a.modifier=e),o&&(a.NoAD=!0),a}function Lw(t){let e=t.slice(1),r=/^(\d+)([PG])?(?:\/TB(\d+))?(@[A-Za-z]+)?$/.exec(e),n=Gm(r?.[1]);if(!n)return;let o={timed:!0,minutes:n},i=r?.[2];i==="P"?o.based="P":i==="G"&&(o.based="G");let s=r?.[3];if(s){let u=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 GH(t){let e=/^T(\d+)$/.exec(t);if(!e)return;let r=Gm(e[1]);if(r)return{timed:!0,minutes:r}}function Fw(t){return t?.includes(lI)}function Gm(t){let e=Number(t);return Number.isNaN(e)?0:e}function VH(t){return t.replaceAll(/T(\d+)G(?=\/TB|@|-|$)/g,"T$1")}function xr({matchUpFormat:t}){if(!wt(t)||t==="")return!1;let e=oe(t),r=/-S:(\d+)\/TB(\d{1,2})@?(\d?)/.exec(t),n=r?.[1],o=r?.[2],i=r?.[3],s=/-F:(\d+)\/TB(\d{1,2})@?(\d?)/.exec(t),a=s?.[1],c=s?.[2],u=s?.[3];return mp(e,!!(r&&o&&n===i||s&&c&&a===u))===VH(t)}var Vm=/^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2]\d|3[0-1])$/,ZT=/^((0\d|1\d|2[0-3]):[0-5]\d(:[0-5]\d)?)([.,]\d{3})?$/,_o=/^(\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?$/,ru=/^(\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 ll(t){let{scheduledDate:e}=t;if(!e&&t.scheduledTime&&(e=mt(t.scheduledTime)),!e)return;let r=$t(t.scheduledTime),n=mt(e);return n&&r&&(n+=`T${r}`),n}function kw(t){return typeof t!="object"||Array.isArray(t)?!1:Object.prototype.toString.call(t)==="[object Date]"}function Bm(t){let e=typeof t=="string"?t?.split(" "):[];if(t&&e?.length>1&&!["AM","PM"].includes(e[1].toUpperCase()))return!1;let r=dp(t,!0,!0);return!!(!t||r&&ru.test(r))}function Me(t){return fs(t)||Vm.test(t)}function BH(t){let e=new Date(t),r=e.getSeconds()+60*e.getMinutes()+3600*e.getHours();return WH(r,{displaySeconds:!1})}function WH(t,e){let r=Number.parseInt(t,10),n=Math.floor(r/3600),o=Math.floor((r-n*3600)/60),i=r-n*3600-o*60;return(!e||e?.displaySeconds?n+":"+o+":"+i:n+":"+o).split(":").map(co).join(":")}var SI=t=>{let e=gI(t)||fs(t)?new Date(t):new Date,r=e.getUTCMonth()+1,n=r<10?`0${r}`:`${r}`;return`${e.getUTCFullYear()}-${co(n)}-${co(e.getUTCDate())}`};function HH(t){let e=gI(t)||fs(t)?new Date(t):new Date;return Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())}function Qn(t,e="-",r="YMD"){if(!t)return"";typeof t=="string"&&!t.includes("T")&&(t=t+"T00:00");let n=new Date(t),o=""+(n.getMonth()+1),i=""+n.getDate(),s=n.getFullYear();return o.length<2&&(o="0"+o),i.length<2&&(i="0"+i),r==="DMY"?[i,o,s].join(e):r==="MDY"?[o,i,s].join(e):r==="YDM"?[s,i,o].join(e):r==="DYM"?[i,s,o].join(e):r==="MYD"?[o,s,i].join(e):[s,o,i].join(e)}function ty(t){let e=t?new Date(t):new Date,r=e.getTimezoneOffset();return new Date(e.getTime()-r*60*1e3)}function YH(t){return ty(t).getTime()}function gI(t){if(typeof t=="boolean")return!1;let e=t instanceof Date&&t||!Number.isNaN(Number(t))&&new Date(t)||!1;return e&&!Number.isNaN(Number(e.valueOf()))}function jH(t,e){return t<=e}function Ua(t,e){if(!Me(t)||!Me(e))return[];let r=mt(t)+"T00:00",n=mt(e)+"T00:00",o=new Date(r),i=new Date(n),s=gI(i)&&gI(o)&&jH(o,i),a=[],c=0;if(s){let u=o,p=u.getTime();for(;p<=i.getTime()&&c<300;)c+=1,a.push(new Date(u)),p=u.setDate(u.getDate()+1)}return a.map(u=>Qn(u))}var qH=/^([+-]?\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 fs(t){return typeof t!="string"?!1:qH.test(t)}function Ra(t){return typeof t!="string"||!fs(t)?!1:/([zZ]|[+-]\d{2}:?\d{2})$/.test(t)}function ry(t){if(typeof t!="string")return!1;let r=t.split("Z")[0].split(":"),n=r.every(i=>!Number.isNaN(Number.parseInt(i)));return!(r.length<2||!n||Number.parseInt(r[0])>23||Number.parseInt(r[1])>60)}function jt(t){let e=$t(t);if(!e)return 0;let[r,n]=e.split(":").map(o=>Number.parseInt(o));return r*60+n}function Gw(t){let e=Math.floor(t/60),r=t-e*60;return e>23&&(e=e%24),[co(e),co(r)].join(":")}function II(t){return ry(t)?t.split(":").slice(0,2).map(co).join(":"):void 0}function $t(t){return fs(t)&&t.indexOf("T")>0?II(t.split("T").reverse()[0]):II(t)}function mt(t){return fs(t)||_o.test(t)?t.split("T")[0]:""}function Wm(t,e){let r=new Date(t);return r.setUTCDate(r.getUTCDate()+e),mt(r.toISOString())}function ey(t){t=typeof t=="string"?t:"00:00";let e={},r={};return{0:e.time,1:e.ampm}=t.split(" ")??[],{0:r.hours,1:r.minutes}=e.time.split(":")??[],r.ampm=e.ampm,Number.isNaN(Number.parseInt(r.hours))||Number.isNaN(Number.parseInt(r.minutes))||r.ampm&&!["AM","PM"].includes(r.ampm.toUpperCase())?{}:r}function $H(t){let e=ey(t);return e.ampm&&e.hours&&(e.ampm.toLowerCase()==="pm"&&Number.parseInt(e.hours)<12&&(e.hours=(e.hours&&Number.parseInt(e.hours)||0)+12),e.ampm.toLowerCase()==="am"&&e.hours==="12"&&(e.hours="00")),`${e.hours||"12"}:${e.minutes||"00"}`.split(":").map(co).join(":")}function KH(t){let e=ey(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 dp(t,e,r){let n=mt(t),o=$t(t),i=n?o:t;return t?e&&(n&&r&&t||$H(i))||KH(i):void 0}function ny(t,e){let r=ey(t),n=ey(e);if(Number.parseInt(r.hours)<Number.parseInt(n.hours))return-1;if(Number.parseInt(r.hours)>Number.parseInt(n.hours))return 1;if(r.hours===n.hours){if(Number.parseInt(r.minutes)<Number.parseInt(n.minutes))return-1;if(Number.parseInt(r.minutes)>Number.parseInt(n.minutes))return 1}return 0}function oy(t,e=7){let r=mt(t)+"T00:00",n=new Date(r),o=new Date(n.setDate(n.getDate()+e));return Qn(o)}function zH(t){return oy(t)}function QH(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())),Qn(o,r)}function Vw(t,e,r){let n=new Date(t,0);return Qn(new Date(n.setDate(e)),r)}function ve(t,e=void 0){let[r,n]=(t||"00:00").split(":").map(co),o=ty(e).setHours(r,n,0,0);return ty(o)}function ks(t,e,r=!0){let n=new Date(t),i=(new Date(e).getTime()-n.getTime())/1e3/60;return r?Math.abs(Math.round(i)):Math.round(i)}function Yr(t,e){let r=$t(t);if(!r)return"00:00";let n=Number.isNaN(e)?0:e;return $t(hI(ve(r),n).toISOString())||"00:00"}function hI(t,e){let r=new Date(t);return new Date(r.getTime()+e*6e4)}function co(t){return t.toString()[1]?t:"0"+t}function Xn(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 iy={addDays:oy,addWeek:zH,addMinutesToTimeString:Yr,convertTime:dp,getIsoDateString:ll,getUTCdateString:SI,DateHHMM:BH,extractDate:mt,extractTime:$t,formatDate:Qn,getDateByWeek:QH,isISODateString:fs,isValidEmbargoDate:Ra,isDate:gI,isTimeString:ry,offsetDate:ty,offsetTime:YH,sameDay:Xn,timeStringMinutes:jt,timeToDate:ve,timeUTC:HH,validTimeValue:Bm,validDateString:Vm,timeValidation:ru,dateValidation:_o};var XH=(t,e)=>t.filter(Boolean).every(r=>typeof r===e),JH=t=>t.filter(Boolean).every(Le);function fl(t,e){return`${t}-${e}`}function gs(t){let e=t.category;if(typeof e!="object"||!e)return{error:cp};let{ageCategoryCode:r,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s}=e,a=e.categoryName,c;if(!(XH([r,n,o,a],"string")&&JH([i,s])&&[n,o].filter(Boolean).every(Me)))return{error:cp};let p=t.consideredDate??mt(new Date().toLocaleDateString("sv"));if(!p||!Me(p))return{error:ae};let[m]=p.split("-").slice(0,3).map(B=>Number.parseInt(B)),d=Wm(p,-1);if(!d)return{error:ae};let[l,f]=d.split("-").slice(1,3).map(B=>Number.parseInt(B)),g=`${co(l)}-${co(f)}`,I=Wm(p,1);if(!I)return{error:ae};let[S,h]=I.split("-").slice(1,3).map(B=>Number.parseInt(B)),T=`${co(S)}-${co(h)}`,y=s&&Wm(p,-1*365*s),E=i&&Wm(p,-1*365*i),A=[],N=B=>!A.includes(B)&&A.push(B);r=r??a;let D=/^([UO]?)(\d{1,2})([UO]?)$/,R=/^C(\d{1,2})-(\d{1,2})$/,U=r?.includes("-"),b=U&&r?.match(R),C=r?.match(D);function _(B){let z=m-B,H=fl(z,T);e.ageMinDate&&e.ageMinDate!==H&&N(`Invalid submitted ageMinDate: ${o}`),o=H,r&&(e.ageMax&&e.ageMax!==B-1&&(N(`Invalid submitted ageMax: ${i}`),E=void 0),i=B-1)}function v(B){let z=m-B-1,H=fl(z,T);e.ageMin&&e.ageMin>B&&N(`Invalid submitted ageMin: ${s}`),e.ageMax&&e.ageMax>B&&N(`Invalid submitted ageMax: ${i}`),e.ageMinDate&&e.ageMinDate!==H&&N(`Invalid submitted ageMinDate: ${o}`),o=H,r&&(e.ageMax&&e.ageMax!==B&&(N(`Invalid submitted ageMax: ${i}`),y=void 0),i=B)}function w(B){let z=m-B,H=fl(z,g);e.ageMaxDate&&e.ageMaxDate!==H&&N(`Invalid submitted ageMaxDate: ${n}`),n=H,r&&(e.ageMin&&e.ageMin!==B+1&&(N(`Invalid submitted ageMin: ${s}`),y=void 0),s=B+1)}function L(B){let z=m-B-1,H=fl(z,g);e.ageMaxDate&&e.ageMaxDate!==H&&N(`Invalid submitted ageMaxDate: ${n}`),n=H,r&&(e.ageMin&&e.ageMin!==B&&(N(`Invalid submitted ageMin: ${s}`),y=void 0),s=B)}function F(B){let z=D.exec(B)??[],[H,K,Y]=z.slice(1),J=Number.parseInt(K);H==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&N(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),_(J)):H==="O"&&w(J),Y==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&N(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),v(J)):Y==="O"&&L(J),n=(n??y)||void 0,o=(o??E)||void 0}function x(){if(n=void 0,o=void 0,i=void 0,s=void 0,e.ageMin){let H=m-e.ageMin;n=fl(H,g)}if(e.ageMax){let H=m-e.ageMax-1;o=fl(H,T)}let[B,z]=(r?.match(R)??[]).slice(1).map(H=>Number.parseInt(H));B<=z?(s=B,i=z,c=!0):N(`Invalid combined age range ${r}`)}function k(){s&&w(s),i&&v(i)}function G(){b?x():U?r?.split("-").forEach(F):C&&r?F(r):k()}G(),i&&e?.ageMin&&e?.ageMin>i&&(N(`Invalid submitted ageMin: ${e?.ageMin}`),s=void 0);let V=et({consideredDate:p,combinedAge:c,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s});return A.length&&(V.errors=A),V}function lp({category:t}){if(!Tt(t))return{error:O};let e=gs({category:t});if(e.error)return{error:e};let{ratingMax:r,ratingMin:n}=t;return r&&!Le(r)?M({result:{error:O},context:{ratingMax:r}}):n&&!Le(n)?M({result:{error:O},context:{ratingMin:n}}):{...e}}function fp({childCategory:t,withDetails:e,category:r}){let n=lp({category:r}),o=lp({category:t}),i=o.ageMin&&(n.ageMin&&o.ageMin<n.ageMin||n.ageMax&&o.ageMin>n.ageMax),s=o.ageMax&&(n.ageMax&&o.ageMax>n.ageMax||n.ageMin&&o.ageMax<n.ageMin),a=o.ageMinDate&&n.ageMaxDate&&new Date(o.ageMinDate)>new Date(n.ageMaxDate),c=o.ageMaxDate&&n.ageMinDate&&new Date(o.ageMaxDate)<new Date(n.ageMinDate),p=r?.ratingType&&t?.ratingType&&r.ratingType===t.ratingType&&(r.ratingMin&&t.ratingMin&&t.ratingMin<r.ratingMin||r.ratingMax&&t.ratingMax&&t.ratingMax>r.ratingMax||r.ratingMin&&t.ratingMax&&t.ratingMax<r.ratingMin||r.ratingMax&&t.ratingMin&&t.ratingMin>r.ratingMax),m=r?.ballType&&t?.ballType&&r.ballType!==t.ballType,f=et({invalidRatingRange:p,invalidAgeMinDate:a,invalidAgeMaxDate:c,invalidBallType:m,invalidAgeMax:s,invalidAgeMin:i,valid:!p&&!a&&!c&&!m&&!s&&!i},!0);return e&&Object.assign(f,{categoryDetails:n,childCategoryDetails:o}),f}function gp({checkCategory:t=!0,collectionDefinition:e,checkCollectionIds:r,checkGender:n=!0,referenceCategory:o,referenceGender:i,event:s}){i=i??s?.gender;let a="validateCollectionDefinition",c=[];if(typeof e!="object")return c.push(`collectionDefinition must be an object: ${e}`),M({result:{errors:c,error:yo},stack:a});let{collectionValueProfiles:u,collectionGroupNumber:p,collectionValue:m,collectionId:d,matchUpCount:l,matchUpFormat:f,matchUpValue:g,matchUpType:I,scoreValue:S,setValue:h,category:T,gender:y}=e;if(r&&typeof d!="string"&&c.push(`collectionId is not type string: ${d}`),typeof l!="number"&&c.push(`matchUpCount is not type number: ${l}`),I&&!_s([Ct,Rt,Mm],I)&&c.push(`matchUpType must be SINGLES, DOUBLES, or HYBRID: ${I}`),[!!u?.length].concat([g,m,S,h].map(yt)).filter(Boolean).length!==1&&c.push("Missing value definition for matchUps: matchUpValue, collectionValue, or collectionValueProfiles"),g&&typeof g!="number"&&c.push(`matchUpValue is not type number: ${g}`),m&&typeof m!="number"&&c.push(`collectionValue is not type number: ${m}`),u&&l){let A=LT({collectionValueProfiles:u,matchUpCount:l});A.errors&&c.push(...A.errors)}if(p&&typeof p!="number"&&c.push(`collectionGroupNumber is not type number: ${m}`),f&&!xr({matchUpFormat:f})&&c.push(`Invalid matchUpFormat: ${f}`),n){let A=ml({referenceGender:i,matchUpType:I,gender:y});if(A.error)return M({context:{referenceGender:i,gender:y},result:A,stack:a})}if(t&&o&&T){let A=fp({category:o,childCategory:T});if(!A.valid)return M({result:{error:cp},context:A,stack:a})}return c.length?M({result:{errors:c,error:wU},stack:a}):{valid:!0}}function or(t){let e=!!(t?.enforceCategory!==!1&&t?.category),r=!!(t?.enforceGender!==!1&&t?.gender),n=t?.checkCollectionIds,o=t?.tieFormat,i=t?.event,s="validateTieFormat",a=[],c=ZH({...t,stack:s});if(c?.error)return c;let u,p=o.collectionDefinitions.every(I=>{let{setValue:S,scoreValue:h,collectionValue:T}=I;(S||h)&&!T&&(u=!0);let{valid:y,errors:E}=gp({referenceCategory:t.category,referenceGender:t.gender,collectionDefinition:I,checkCollectionIds:n,checkCategory:e,checkGender:r,event:i});return y?!0:(Array.isArray(E)&&a.push(...E),!1)}),m=typeof o.winCriteria?.valueGoal=="number"&&o.winCriteria?.valueGoal>0&&!u||o.winCriteria?.aggregateValue;if(!(m||o.winCriteria?.aggregateValue))return u?a.push("aggregateValue is required"):a.push("Either non-zero valueGoal, or { aggregateValue: true } must be specified in winCriteria"),M({context:{tieFormat:o,errors:a,aggregateValueImperative:u},result:{error:ri},stack:s});let d=o.collectionDefinitions.map(({collectionId:I})=>I),l=!n||d.length===pt(d).length,f=p&&m&&l,g={valid:f,errors:a};return f?g:M({result:{error:ri},context:{tieFormat:o,errors:a},stack:s})}function ZH(t){let{tieFormat:e,stack:r}=t;return!t||!e||!Tt(e)?M({result:{error:ri},context:{tieFormat:e,message:"tieformat must be an object"},stack:r}):Tt(e.winCriteria)?Array.isArray(e.collectionDefinitions)?{...P}:M({result:{error:ri},context:{tieFormat:e,message:"collectionDefinitions must be an array"},stack:r}):M({result:{error:ri},context:{tieFormat:e,message:"tieformat.winCritiera must be an object"},stack:r})}var gl="resourceSubType",Il="resourceType",nu="identifier",sy="name",Bw={RESOURCE_SUB_TYPE:gl,RESOURCE_TYPE:Il,IDENTIFIER:nu,NAME:sy};function q(t,e,r,n,o=0){if(QT().makeDeepCopy)return QT().makeDeepCopy(t,e,r,n);let i=uI(),{stringify:s,toJSON:a,ignore:c,modulate:u}=i??{};if(!i?.enabled&&!r||typeof t!="object"||Br(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)||Br(c)&&!c(l)),d=(l,f)=>{p[l]=Br(f?.toString)?f.toString():JSON.stringify(f)};for(let l of m){let f=t[l],g=Br(u)?u(f):void 0;if(g!==void 0)p[l]=g;else if(e&&l==="extensions"&&Array.isArray(f)){let I=TI(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)&&Br(f?.toJSON)?p[l]=f.toJSON():f===null?p[l]=void 0:kw(f)?p[l]=new Date(f).toISOString():p[l]=q(f,e,r,n,o+1)}return p}function TI(t){return t?.map(e=>{let{name:r,value:n}=e;return r&&n&&{[`_${r}`]:n}}).filter(Boolean)}function ay(t=1,e,r){return Q(0,t).map(()=>it(e,r))}function it(t,e){let r=e??Math.random,n=[];for(let u=0;u<256;u++)n[u]=(u<16?"0":"")+u.toString(16);let o=Math.trunc(r()*4294967295),i=Math.trunc(r()*4294967295),s=Math.trunc(r()*4294967295),a=Math.trunc(r()*4294967295),c=n[o&255]+n[o>>8&255]+n[o>>16&255]+n[o>>24&255]+"-"+n[i&255]+n[i>>8&255]+"-"+n[i>>16&15|64]+n[i>>24&255]+"-"+n[s&63|128]+n[s>>8&255]+"-"+n[s>>16&255]+n[s>>24&255]+n[a&255]+n[a>>8&255]+n[a>>16&255]+n[a>>24&255];return typeof t=="string"?`${t}_${c.replaceAll("-","")}`:c}var cy={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 uy={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 py={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 my={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 dy={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 ly={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 fy={collectionDefinitions:[{category:{ageCategoryCode:"14U"},collectionName:"14U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"14U"},collectionName:"14U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],collectionGroups:[{groupNumber:1,groupName:"Doubles",groupValue:1,winCriteria:{valueGoal:2}}],tieFormatName:"Brewer Cup",winCriteria:{valueGoal:4}};var gy={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 xn="SET3-S:6/TB7",cY="SET3-S:6NOAD",eR="SET3-S:6NOAD/TB7-F:TB10",uY="SET3-S:4/TB7",pY="SET3-S:4/TB5@3",mY="SET5-S:6/TB7",dY="SET1-S:6/TB7",lY="SET1-S:TB10",fY="SET3-S:6/TB7-F:TB7",gY="SET1-S:T20",IY="SET1-S:8/TB7",SY="SET1-S:8/TB7@7",Ww={FORMAT_STANDARD:xn,FORMAT_STANDARD_NOAD:cY,FORMAT_ATP_DOUBLES:eR,FORMAT_SHORT_SETS:uY,FORMAT_FAST4:pY,FORMAT_GRAND_SLAM:mY,FORMAT_ONE_SET:dY,FORMAT_MATCH_TIEBREAK:lY,FORMAT_SET3_TB7:fY,FORMAT_PRO_SET:IY,FORMAT_COLLEGE_PRO_SET:SY,TIMED20:gY};var Iy={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 Sy={collectionDefinitions:[{collectionName:"Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",collectionValue:1},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"USTA Collegiate",winCriteria:{valueGoal:4}};var hy={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 Ty={collectionDefinitions:[{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Male Singles",matchUpCount:1,gender:"MALE",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Overtime",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"World Team Tennis ITT",winCriteria:{aggregateValue:!0}};var Hw={tieFormatName:"INTENNSE 2026",winCriteria:{aggregateValue:!0},collectionDefinitions:[{collectionId:"intennse-ms",collectionName:"Men's Singles",matchUpType:"SINGLES",matchUpCount:2,matchUpFormat:"SET2XA-S:T10",scoreValue:1,gender:"MALE",category:{categoryName:"MS"}},{collectionId:"intennse-ws",collectionName:"Women's Singles",matchUpType:"SINGLES",matchUpCount:2,matchUpFormat:"SET2XA-S:T10",scoreValue:1,gender:"FEMALE",category:{categoryName:"WS"}},{collectionId:"intennse-md",collectionName:"Men's Doubles",matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET1A-S:T10",scoreValue:1,gender:"MALE",category:{categoryName:"MD"}},{collectionId:"intennse-wd",collectionName:"Women's Doubles",matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET1A-S:T10",scoreValue:1,gender:"FEMALE",category:{categoryName:"WD"}},{collectionId:"intennse-xd",collectionName:"Mixed Doubles",matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET1A-S:T10",scoreValue:1,gender:"MIXED",category:{categoryName:"XD"}}]};var yy={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 Ey={collectionDefinitions:[{collectionGroupNumber:1,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6NOAD/TB7-F:TB10",matchUpValue:1},{collectionGroupNumber:1,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:1},{collectionGroupNumber:2,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6NOAD/TB7-F:TB10",matchUpValue:2},{collectionGroupNumber:2,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:2},{collectionGroupNumber:3,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6NOAD/TB7-F:TB10",matchUpValue:3},{collectionGroupNumber:3,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:3}],collectionGroups:[{groupNumber:1,groupName:"Day 1"},{groupNumber:2,groupName:"Day 2"},{groupNumber:3,groupName:"Day 3"}],tieFormatName:"Laver Cup",winCriteria:{valueGoal:13}};var Ay={collectionDefinitions:[{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Male Singles",matchUpCount:1,gender:"MALE",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Overtime",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"USTA Tennis on Campus",winCriteria:{aggregateValue:!0}};var yI="COLLEGE_DEFAULT",rR="COLLEGE_JUCO",nR="COLLEGE_D3",oR="DOMINANT_DUO",iR="DOMINANT_DUO_MIXED",sR="INTENNSE_2026",aR="LAVER_CUP",cR="TEAM_DOUBLES_3_AGGREGATION",uR="USTA_BREWER_CUP",pR="USTA_OZAKI_CUP",mR="USTA_COLLEGE",dR="USTA_GOLD_TEAM_CHALLENGE",lR="USTA_LEVEL_1",fR="USTA_INTERSECTIONAL",gR="USTA_SECTION_BATTLE",IR="USTA_SOUTHERN_LEVEL_5",SR="USTA_TOC",hR="USTA_WTT_ITT",TR="USTA_ZONAL",Yw={COLLEGE_D3:nR,COLLEGE_DEFAULT:yI,COLLEGE_JUCO:rR,DOMINANT_DUO:oR,DOMINANT_DUO_MIXED:iR,INTENNSE_2026:sR,LAVER_CUP:aR,TEAM_DOUBLES_3_AGGREGATION:cR,USTA_BREWER_CUP:uR,USTA_OZAKI_CUP:pR,USTA_COLLEGE:mR,USTA_GOLD_TEAM_CHALLENGE:dR,USTA_INTERSECTIONAL:fR,USTA_LEVEL_1:lR,USTA_SECTION_BATTLE:gR,USTA_SOUTHERN_LEVEL_5:IR,USTA_TOC:SR,USTA_WTT_ITT:hR,USTA_ZONAL:TR};var qw="STANDARD",jw={[qw]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1},singles:{matchUpCount:6,matchUpValue:1},valueGoal:5},[nR]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7@7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:xn,matchUpCount:6,matchUpValue:1},tieFormatName:"College D3",valueGoal:5},[yI]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:6/TB7",collectionValue:1,matchUpCount:3},singles:{matchUpFormat:xn,matchUpCount:6,matchUpValue:1},tieFormatName:"College Default",valueGoal:4},[rR]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:xn,matchUpCount:6,matchUpValue:1},tieFormatName:"College JUCO",valueGoal:5},[aR]:Ey,[oR]:Iy,[iR]:ly,[sR]:Hw,[cR]:uy,[uR]:fy,[pR]:gy,[mR]:Sy,[dR]:cy,[fR]:dy,[lR]:hy,[gR]:my,[IR]:py,[hR]:Ty,[SR]:Ay,[TR]:yy},UY=t=>{let e=t?.namedFormat&&Object.keys(jw).includes(t.namedFormat)?t.namedFormat:qw,r=Array.isArray(t?.uuids)?t?.uuids:[],n,{category:o,gender:i}=t?.event??{},s=q(jw[e],!1,!0),a=c=>{if(!t?.isMock&&!t?.event?.isMock||!t.event)return r?.pop()??it();let u=t?.event?.eventId;return r.pop()??`${u}-COL-${c+1}`};return s.hydrate?(n={winCriteria:{valueGoal:s.valueGoal},collectionDefinitions:[{collectionId:a(0),matchUpFormat:eR,collectionName:"Doubles",matchUpType:Rt,...s.doubles},{collectionId:a(1),matchUpFormat:xn,collectionName:"Singles",matchUpType:Ct,...s.singles}]},s.tieFormatName&&(n.tieFormatName=s.tieFormatName)):(s.collectionDefinitions.forEach((c,u)=>c.collectionId=a(u)),n=s),t?.hydrateCollections&&n.collectionDefinitions.forEach(c=>{o&&!c.category&&(c.category=o),i&&!c.gender&&(c.gender=i)}),n},uo=UY;var Dt="SINGLES",ba="SINGLES",Lt="DOUBLES",si="DOUBLES",Oe="TEAM",Ze="TEAM",Ip="HYBRID",EI="HYBRID";var RY="RATING",bY="BOTH",$w={AGE:"AGE",BOTH:bY,DOUBLES:Lt,DOUBLES_EVENT:si,HYBRID:Ip,HYBRID_EVENT:EI,RATING:RY,SINGLES:Dt,SINGLES_EVENT:ba,TEAM_EVENT:Ze,TEAM:Oe};var W="MAIN",Z="QUALIFYING",me="CONSOLATION",Fe="VOLUNTARY_CONSOLATION",Vt="PLAY_OFF",ou=[W,Z,me,Vt,Fe],Ca={[Z]:1,[W]:2,[Vt]:3,[me]:3,[Fe]:4},yR="finishingPositions",ER="aggregateEventStructures",AR={[W]:1,[Vt]:2,[me]:3,[Z]:4,[Fe]:5},Kw={[Vt]:1,[W]:2,[me]:3,[Z]:4,[Fe]:5},iu="CLUSTER",Hm="ADJACENT",PR="SEPARATE",Li="WATERFALL",su="ITEM",de="CONTAINER",ln="DRAW",Ym="RANDOM",qe="TOP_DOWN",Fi="BOTTOM_UP",fn="POSITION",Pr="WINNER",ir="LOSER",Wn="FIRST_MATCHUP",Ni="AD_HOC",CY="AD_HOC",pc="FEED_IN",xo="COMPASS",Sp="OLYMPIC",MY="SINGLE_ELIMINATION";var Nr="SINGLE_ELIMINATION",Gs="DOUBLE_ELIMINATION",wo="FIRST_MATCH_LOSER_CONSOLATION",Ma="FIRST_ROUND_LOSER_CONSOLATION",ai="LUCKY_DRAW",ki="ADAPTIVE",AI="CURTIS_CONSOLATION",PI="CURTIS_CONSOLATION",Py="FEED_IN_CHAMPIONSHIP_TO_SF",Is="FEED_IN_CHAMPIONSHIP_TO_SF",Ny="FEED_IN_CHAMPIONSHIP_TO_QF",va="FEED_IN_CHAMPIONSHIP_TO_QF",Dy="FEED_IN_CHAMPIONSHIP_TO_R16",au="FEED_IN_CHAMPIONSHIP_TO_R16",NR="MODIFIED_FEED_IN_CHAMPIONSHIP",Oa="MODIFIED_FEED_IN_CHAMPIONSHIP",Vs="FEED_IN_CHAMPIONSHIP",jm="PAGE_PLAYOFF",qm="PLAYOFF",Bs="SWISS",vY={0:{name:"Qualifier 1",abbreviation:"Q1"},"0-1":{name:"Eliminator",abbreviation:"EL"},"0-2":{name:"Final",abbreviation:"F"}},Uy="DOUBLE_ROUND_ROBIN",hr="ROUND_ROBIN",Tr="ROUND_ROBIN_WITH_PLAYOFF",DR="DECIDER",UR="BACKDRAW",NI={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"}},DI={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-1-1":{name:"South",abbreviation:"S"}},UI={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"}},po="WIN_RATIO",Ss="ROUND_OUTCOME",RR=[ki,xo,AI,va,au,Is,Vs,Ny,Dy,Py,wo,Ma,ai,Oa,Sp,jm,qm,Tr],OY=[Ni,ki,xo,AI,Gs,va,au,Is,Vs,pc,wo,Ma,ai,Oa,Sp,jm,qm,hr,Tr,Nr,Bs],bR={MAIN:W,QUALIFYING:Z,CONSOLATION:me,ITEM:su,CONTAINER:de,FIRST_MATCHUP:Wn,WINNER:Pr,LOSER:ir,AD_HOC:Ni,FEED_IN:pc,FLEX_ROUNDS:CY,COMPASS:xo,PLAY_OFF:Vt,PAGE_PLAYOFF:jm,PAGE_PLAYOFF_ATTRIBUTES:vY,PLAYOFF:qm,SWISS:Bs,OLYMPIC:Sp,KNOCKOUT:MY,SINGLE_ELIMINATION:Nr,DOUBLE_ELIMINATION:Gs,CURTIS:AI,FICSF:Py,FICQF:Ny,FICR16:Dy,MFIC:NR,VOLUNTARY_CONSOLATION:Fe,FIRST_MATCH_LOSER_CONSOLATION:wo,FIRST_ROUND_LOSER_CONSOLATION:Ma,MODIFIED_FEED_IN_CHAMPIONSHIP:Oa,FEED_IN_CHAMPIONSHIP_TO_R16:au,FEED_IN_CHAMPIONSHIP_TO_QF:va,FEED_IN_CHAMPIONSHIP_TO_SF:Is,FEED_IN_CHAMPIONSHIP:Vs,LUCKY_DRAW:ai,ADAPTIVE:ki,ROUND_ROBIN_WITH_PLAYOFF:Tr,ROUND_ROBIN:hr,DECIDER:DR,BACKDRAW:UR,COMPASS_ATTRIBUTES:NI,OLYMPIC_ATTRIBUTES:DI,ADAPTIVE_ATTRIBUTES:UI,DRAW:ln,RANDOM:Ym,TOP_DOWN:qe,BOTTOM_UP:Fi,CLUSTER:iu,ADJACENT:Hm,SEPARATE:PR,WATERFALL:Li,WIN_RATIO:po,ROUND_OUTCOME:Ss,MULTI_STRUCTURE_DRAWS:RR,generatedDrawTypes:OY,stageOrder:Ca,finishOrder:AR,AGGREGATE_EVENT_STRUCTURES:ER,FINISHING_POSITIONS:yR},zw=bR;var Ee="tournamentRecords",RI="policyDefinitions",rt="tournamentRecord",Ry="onlineResource",Kt="drawDefinition",by="tieFormatName",Sl="matchUpFormat",sr="participantId",hl="scheduleDates",Qw="tournamentId",Xw="scheduleDate",Jw="roundNumber",mo="structureId",$m="participant",cu="matchUpIds",Cy="entryStage",Zw="policyType",CR="structures",bI="eventType",wr="matchUpId",Tl="tieFormat",hp="inContext",mc="structure",Km="courtIds",tL="personId",zm="venueIds",CI="matchUps",Ws="courtId",My="eventId",Rn="matchUp",dc="drawId",jr="error",ce="event",Gi="param",MI="uuids",vy="penaltyType",yl="penaltyId",Tp="venueId",eL="stage",rL="averageMatchUpMinutes",nL="recoveryMinutes",oL="periodLength",iL="number";var qr="object",ke="array";var $e="_validate",Oy="_message",Lr="_invalid",Ge="_ofType",yp="_anyOf",_a="_oneOf";var sL={[Ry]:t=>Yt(Object.keys(t),[gl,Il,nu]).length===3,[by]:t=>t&&uo({namedFormat:t}),[MI]:t=>!t||Array.isArray(t)&&t.every(wt),[Tl]:t=>!or({tieFormat:t}).error,[bI]:t=>[Dt,Lt,Oe].includes(t),[Cy]:t=>ou.includes(t)},_Y={[Ee]:kt,[rt]:j,[RI]:Ea,[Kt]:$,[sr]:We,[Sl]:JD,[Qw]:ac,[mo]:dn,[cu]:xs,[$m]:Aa,[Ry]:yo,[bI]:zn,[CR]:Gg,[wr]:mr,[Tl]:ri,[mc]:_i,[Ws]:jg,[CI]:Bn,[My]:Wr,[Rn]:Xe,[Km]:nt,[zm]:nt,[vy]:yU,[yl]:EU,[Tp]:Ls,[dc]:Nn,[ce]:le,[eL]:Wg},xY={[Ee]:qr,[RI]:qr,[rt]:qr,[Kt]:qr,[Ry]:qr,[hl]:ke,[$m]:qr,[cu]:ke,[CR]:ke,[Tl]:qr,[mc]:qr,[Km]:ke,[zm]:ke,[CI]:ke,[Rn]:qr,[ce]:qr,[MI]:ke};function X(t,e,r){if(!t&&!Tt(t))return{error:O};if(!e?.length||t?._bypassParamCheck)return{valid:!0};if(!Array.isArray(e))return{error:O};let{paramError:n,errorParam:o}=FY(t,e);if(!n)return{valid:!0};let i=n[$e]&&(n[jr]||n[Lr])||t?.[o]==null&&(n[jr]||n[Lr]||_Y[o]||O)||O,s=o??(n[_a]&&Object.keys(n[_a]).join(", "));return M({info:{param:s,message:n[Oy]},result:{error:i},stack:r})}function aL(t,e){let r=Object.keys(t),n=Object.keys(e);return Yt(r,n)}function wY(t,e){if(!e)return;let r=aL(t,e);return r.length!==1?{error:O}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function LY(t,e){if(!e)return;let r=aL(t,e).filter(n=>t[n]);return r.length<1?{error:O}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function FY(t,e){let r,n;return{paramError:e.find(({_ofType:i,_oneOf:s,_anyOf:a,_validate:c,_info:u,...p})=>{let m=s&&wY(t,s);if(m?.error)return m.error;m&&Object.assign(p,m);let d=a&&LY(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&&!Br(c),S=t[g]!==void 0&&!c&&kY(t,g,i),h=p[g]&&t[g]==null,y=I||S||h||c&&t[g]!==void 0&&!GY(t[g],c)||sL[g]&&!sL[g](t[g]);return y&&(r=g,n=u),y});return!l.length||f}),errorParam:r,paramInfo:n}}function kY(t,e,r){return r=r||xY[e]||"string",r==="array"?!Array.isArray(t[e]):typeof t[e]!==r}function GY(t,e){return Br(e)?e(t):!0}var Ep="DYNAMIC",Jn="RANKING",Lo="RATING",ci="SCALE",Eo="SEEDING",cL={RANKING:Jn,RATING:Lo,SCALE:ci,SEEDING:Eo};function lc(t){let e=X(t,[{[$m]:!0}]);if(e.error)return e;let r=t.participant.timeItems?.filter(({itemType:o})=>o?.startsWith(ci)&&[Jn,Lo,Eo].includes(o.split(".")[1])),n={ratings:{},rankings:{},seedings:{}};if(r?.length){let o=s=>r.filter(a=>a?.itemType===s).sort((a,c)=>new Date(a.createdAt||void 0).getTime()-new Date(c.createdAt||void 0).getTime()).pop(),i=pt(r.map(({itemType:s})=>s));for(let s of i){let a=o(s);if(a){let[,c,u,p,m]=a.itemType.split("."),d=m?`${p}.${m}`:p,l=c===Eo&&"seedings"||c===Jn&&"rankings"||"ratings";n[l][u]||(n[l][u]=[]),n[l][u].push({scaleValue:a.itemValue,scaleDate:a.itemDate,scaleName:d})}}}return{...P,...n}}function hs(t){if(t===null)return{};let{source:e,template:r}=t??{};if(!r)return e;let n={};return o(e,r,n),n;function o(i,s,a){if(!i||!s)return;let c=Object.keys(i),u=Object.keys(s),p=Object.assign({},...u.filter(l=>l.indexOf("||")).map(l=>l.split("||").map(f=>({[f]:l}))).flat()),m=u.concat(...Object.keys(p)),d=m.includes("*");for(let l of c)if(m.indexOf(l)>=0||d){let f=p[l]||l,g=s[f]||d,I=i[l];if(typeof g=="object"&&typeof I!="function"&&!Array.isArray(g))if(Array.isArray(I)){let S=I.map(h=>{let T={};return o(h,g,T)!==!1?T:void 0}).filter(Boolean);a[l]=S}else I&&(a[l]={},o(I,g,a[l]));else{let S=i[l];if(Array.isArray(g)&&!g.includes(S))return!1;(s[l]||d&&s[l]!==!1)&&(a[l]=S)}}}}var _y="voluntaryConsolation",gn="competitiveBands",vI="roundRobinTally",Zn="positionActions",He="matchUpActions",gr="rankingPoints",Fo="roundNaming",xa="participant",Ap="progression",ko="scheduling",fc="avoidance",VY="participant",BY="display",Qr="scoring",Hn="seeding",uu="feedIn",WY="sanctioning",HY="audit",pu="competition",El="draws",MR="print",uL={POLICY_TYPE_VOLUNTARY_CONSOLATION:_y,POLICY_TYPE_COMPETITIVE_BANDS:gn,POLICY_TYPE_ROUND_ROBIN_TALLY:vI,POLICY_TYPE_POSITION_ACTIONS:Zn,POLICY_TYPE_MATCHUP_ACTIONS:He,POLICY_TYPE_RANKING_POINTS:gr,POLICY_TYPE_ROUND_NAMING:Fo,POLICY_TYPE_PARTICIPANT:xa,POLICY_TYPE_PROGRESSION:Ap,POLICY_TYPE_SCHEDULING:ko,POLICY_TYPE_AVOIDANCE:fc,POLICY_TYPE_COMPETITION:pu,POLICY_TYPE_DISPLAY:BY,POLICY_TYPE_PRIVACY:VY,POLICY_TYPE_FEED_IN:uu,POLICY_TYPE_SCORING:Qr,POLICY_TYPE_SEEDING:Hn,POLICY_TYPE_SANCTIONING:WY,POLICY_TYPE_AUDIT:HY,POLICY_TYPE_DRAWS:El,POLICY_TYPE_PRINT:MR};function ui({tournamentParticipants:t=[],policyDefinitions:e={},contextProfile:r,participantId:n,internalUse:o,personId:i}){let s=t.find(c=>n&&c.participantId===n||i&&c.person&&c.person.personId===i),a=q(s,!1,o);if(a){let c=e?.[xa];if(r?.withScaleValues){let{ratings:u,rankings:p}=lc({participant:a});a.rankings=p,a.ratings=u}if(c?.participant)return hs({template:c.participant,source:a})}return a}var pL="element required",mL="missing name";function dr(t){if(!t||typeof t!="object")return{error:nt};if(t.element&&typeof t?.element!="object")return{error:O};if(!t?.name)return{error:nt,info:mL};if(!t?.element){if(t.discover&&t.tournamentRecords){for(let e of Object.keys(t.tournamentRecords)){let r=t.tournamentRecords[e],n=dr({element:r,name:t.name});if(n.error)return M({result:n,stack:"removeExtension"})}return{...P}}return{error:nt,info:pL}}return t?.element.extensions?(t.element.extensions=t.element.extensions.filter(e=>e?.name!==t.name),{...P}):{...P,info:fe}}function Yn({requiredAttributes:t=["name","value"],extension:e}){if(!e||typeof e!="object"||typeof e.name!="string")return!1;let r=Object.keys(e);return t.filter(n=>r.includes(n)).length===t.length}function ut(t){if(typeof t!="object")return{error:nt};let e="addExtension";if(t?.element&&typeof t.element!="object")return M({result:{error:O},stack:e});if(!Yn({extension:t.extension}))return M({result:{error:O,info:"invalid extension"},stack:e});if(!t.element)if(t.discover&&!t.tournamentId&&t.tournamentRecords){for(let o of Object.values(t.tournamentRecords)){let i=ut({extension:t.extension,element:o});if(i.error)return M({result:i,stack:e})}return{...P}}else return M({result:{error:nt},stack:e});if(t.element.extensions||(t.element.extensions=[]),t?.creationTime??!0){let o=new Date().toISOString();Object.assign(t.extension,{createdAt:o})}let n=t.element.extensions.find(({name:o})=>o===t.extension.name);return n?n.value=t.extension.value:t.extension.value&&t.element.extensions.push(t.extension),{...P}}function OI(t){return!t||typeof t!="object"?{error:nt}:t.tournamentRecord?ut({creationTime:t.creationTime,element:t.tournamentRecord,extension:t.extension}):{error:j}}function _I(t){return!t||typeof t!="object"?{error:nt}:t.drawDefinition?ut({creationTime:t.creationTime,element:t.drawDefinition,extension:t.extension}):{error:Mr}}function Go(t){return!t||typeof t!="object"?{error:nt}:t.event?ut({creationTime:t.creationTime,extension:t.extension,element:t.event}):{error:Wr}}function vR(t){if(!t||typeof t!="object")return{error:nt};if(!t.participantId)return{error:We};let e=t.tournamentRecord?.participants??[],r=ui({participantId:t.participantId,tournamentParticipants:e});return r?ut({creationTime:t.creationTime,extension:t.extension,element:r}):{error:ee}}function xI(t){return!t||typeof t!="object"?{error:nt}:t.tournamentRecord?dr({element:t.tournamentRecord,name:t.name}):{error:j}}function OR(t){return!t||typeof t!="object"?{error:nt}:t.drawDefinition?dr({element:t.drawDefinition,name:t.name}):{error:Mr}}function Qm(t){return!t||typeof t!="object"?{error:nt}:t?.event?dr({element:t.event,name:t.name}):{error:Wr}}function _R(t){if(!t||typeof t!="object")return{error:nt};if(!t.participantId)return{error:We};let e=t.tournamentRecord?.participants??[],r=ui({participantId:t.participantId,tournamentParticipants:e});return r?dr({element:r,name:t.name}):{error:ee}}function Xm({tournamentRecords:t}){return{tournamentIds:Tt(t)?Object.keys(t):[],...P}}var YY="extensionQueries";function ot({discover:t,element:e,name:r,...n}){if(!e||!r){if(t&&n){let s=Object.keys(n).filter(p=>typeof t=="boolean"||Array.isArray(t)&&t.includes(p)).find(p=>Array.isArray(n[p]?.extensions)?n[p].extensions.find(m=>m?.name===r):!1),a=s&&n[s];!a&&n.tournamentRecords&&(a=Object.values(n.tournamentRecords).find(p=>p.extensions?.length));let c=a?.extensions?.find(p=>p?.name===r);return{extension:c,info:c?void 0:fe}}return M({result:{error:nt},stack:YY})}if(!Array.isArray(e.extensions))return{info:"no extensions"};let o=e.extensions.find(s=>s?.name===r);return{extension:o,info:o?void 0:fe}}var jY="activeSuspension",Pp="appliedPolicies",wa="competitionState",xR="context",Al="delegatedOutcome",lo="disabled",gc="disableAutoCalc",Pl="disableLinks",Nl="display",Vi="draftState",Ic="drawDeletions",qY="drawProfile",$Y="eventProfile",KY="eventWithdrawalRequests",zY="factory",on="flightProfile",xy="groupingAttribute",Vo="lineUps",La="linkedTournamentsIds",sn="mutationLocks",wy="participantRepresentatives",Sc="personRequests",mu="positionActions",QY="rankingPoints",XY="registration",bn="roundTarget",wR="sanctioningConstraints",Np="scheduleLimits",pi="scheduleTiming",hc="schedulingProfile",JY="statusDetail",du="subOrder",Bo="tally",Dl="tieFormatModification",Ly={ACTIVE_SUSPENSION:jY,APPLIED_POLICIES:Pp,COMPETITION_STATE:wa,CONTEXT:xR,DELEGATED_OUTCOME:Al,DISABLED:lo,DISABLE_LINKS:Pl,DISABLE_AUTO_CALC:gc,DISPLAY:Nl,DRAFT_STATE:Vi,DRAW_DELETIONS:Ic,DRAW_PROFILE:qY,EVENT_PROFILE:$Y,EVENT_WITHDRAWAL_REQUESTS:KY,FLIGHT_PROFILE:on,GROUPING_ATTRIBUTE:xy,LINEUPS:Vo,LINKED_TOURNAMENTS:La,MUTATION_LOCKS:sn,PARTICIPANT_REPRESENTATIVES:wy,PERSON_REQUESTS:Sc,POSITION_ACTIONS:mu,RANKING_POINTS:QY,REGISTRATION:XY,ROUND_TARGET:bn,SANCTIONING_CONSTRAINTS:wR,SCHEDULE_LIMITS:Np,SCHEDULE_TIMING:pi,SCHEDULING_PROFILE:hc,STATUS_DETAIL:JY,SUB_ORDER:du,TALLY:Bo,TIE_FORMAT_MODIFICATIONS:Dl,FACTORY:zY},LR=[Al,lo,gc,Pl,on,Vo,La,sn,wy,Sc,bn,Np,pi,hc,du,Bo,Dl];function FR({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:kt};let e=Xm({tournamentRecords:t}),{tournamentIds:r}=e;return r?.length>1?ut({tournamentRecords:t,discover:!0,extension:{name:La,value:{tournamentIds:r}}}):{...P}}function kR({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:kt};let e=dr({name:La,tournamentRecords:t,discover:!0});return M({result:e,stack:"unlinkTournaments"})}function GR({tournamentRecords:t,tournamentId:e}){if(typeof t!="object")return{error:O};if(!e)return{error:ac};let r=Xm({tournamentRecords:t}),{tournamentIds:n}=r;if(!n.includes(e))return{error:ac};let o;return n.every(i=>{let s=t[i],{extension:a}=ot({element:s,name:La});if(!a)return!0;let c=a?.value?.tournamentIds??[];if(!c?.length||c.length===1&&c.includes(e)||i===e){let m=xI({name:La,tournamentRecord:s});return m.error&&(o=m.error),m.success}let u=c.filter(m=>m!==e);a.value={tournamentIds:u};let p=OI({tournamentRecord:s,extension:a});return p.error&&(o=p.error),p.success}),o?{error:o}:{...P}}function ft({onlySpecifiedPolicyTypes:t=!1,policyTypes:e=[],tournamentRecord:r,drawDefinition:n,structure:o,event:i}){if(!Array.isArray(e))return{error:BT};let s={};return r&&a(r),i&&a(i),n&&a(n),o&&a(o),{appliedPolicies:s,...P};function a(c){let p=c?.extensions?.find(m=>m.name===Pp)?.value;if(p)for(let m of Object.keys(p))(t?e.includes(m):!e.length||e.includes(m))&&(s[m]=q(p[m],!1,!0))}}function fo({policyTypes:t=[],tournamentRecord:e,drawDefinition:r,structure:n,event:o}){if(!Array.isArray(t))return{error:BT};let{appliedPolicies:i}=ft({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:np.message}}function Ao(t){let{appliedPolicies:e}=ft({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,event:t.event});return{competitionPolicy:e?.[pu]}}function Bi({element:t,accessor:e}){if(typeof e!="string")return{values:[]};let r=q(t),n=e.split("."),o=[],i;a({targetElement:r,attributes:n});let s={value:i};return o.length&&(s.values=o),s;function a({targetElement:c,attributes:u=[],significantCharacters:p}){for(let[d,l]of u.entries())if(c?.[l]){let f=u.slice(d+1);f.length?Array.isArray(c[l])?c[l].forEach(I=>a({targetElement:I,attributes:f})):(c=c[l],m({targetElement:c,index:d})):(i||(i=c[l]),o.includes(c[l])||o.push(c[l]))}function m({targetElement:d,index:l}){if(d&&l===u.length-1&&["string","number"].includes(typeof d)){let f=p?d.slice(0,p):d;i?o.includes(f)||o.push(f):(i=f,o.push(f))}}}}function Po({requireTimeStamp:t,scaleAttributes:e,participant:r}){if(!r)return{error:Aa};if(!Tt(e))return{error:O};if(r.timeItems??=[],Array.isArray(r.timeItems)){let{accessor:n,scaleType:o,eventType:i,scaleName:s}=e,a=[ci,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!==ci)return{error:Qc};let f=n&&Bi({element:u.itemValue,accessor:n}),g=f?.value||u.itemValue,I={rawValue:f&&u.itemValue,eventType:d,scaleDate:u.itemDate,scaleValue:g,scaleName:l,scaleType:m};return{...P,scaleItem:I}}}return{...P,scaleItem:void 0}}function Dp({value:t,sourceRange:e,targetRange:r}){if(!Array.isArray(e)||e.length!==2)return 0;let n=Math.min(...e),o=Math.max(...e),i=Math.min(...r),s=Math.max(...r);return(t-n)*(s-i)/(o-n)+i}var VR="NTRP";var BR="DUPR",WR="UTR_P",HR="UTPR";var YR="SQUASH_LEVELS",jR="US_SQUASH",qR="USATT",$R="ITTF",KR="USAR";var dL={ELO:"ELO",NTRP:VR,TRN:"TRN",UTR:"UTR",WTN:"WTN",DUPR:BR,UTR_P:WR,UTPR:HR,PSA:"PSA",SQUASH_LEVELS:YR,US_SQUASH:jR,USATT:qR,ITTF:$R,USAR:KR,BWF:"BWF"};var rj={ELO:{defaultInitialization:1500,decimalsCount:0,range:[0,3e3],ascending:!1},[VR]:{accessors:["ntrpRating","dntrpRatingHundredths"],attributes:{ustaRatingType:""},accessor:"dntrpRatingHundredths",defaultInitialization:3,decimalsCount:1,ascending:!1,range:[1,7]},UTR:{defaultInitialization:6,accessors:["utrRating"],accessor:"utrRating",decimalsCount:2,ascending:!1,range:[1,16]},WTN:{attributes:{confidence:{generator:!0,range:[60,100]}},accessors:["wtnRating","confidence"],defaultInitialization:23,accessor:"wtnRating",ascending:!0,decimalsCount:2,range:[40,1]},[BR]:{defaultInitialization:3.5,accessors:["duprRating","reliabilityScore"],accessor:"duprRating",attributes:{reliabilityScore:{generator:!0,range:[0,100]}},decimalsCount:3,ascending:!1,range:[2,8]},[WR]:{defaultInitialization:5,accessors:["utrpRating","verified"],accessor:"utrpRating",attributes:{verified:{type:"boolean"},provisional:{type:"string"}},decimalsCount:1,ascending:!1,range:[1,10]},[HR]:{defaultInitialization:3.5,accessor:"utprRating",decimalsCount:1,ascending:!1,range:[2,5],deprecated:!0},PSA:{defaultInitialization:500,accessor:"psaPoints",decimalsCount:0,ascending:!1,range:[0,3e3],attributes:{tournaments:{generator:!0,range:[1,20]},divisor:{generator:!0,range:[10,20]}}},[YR]:{defaultInitialization:2e3,accessor:"squashLevel",decimalsCount:0,ascending:!1,range:[0,7e3]},[jR]:{defaultInitialization:3.5,accessor:"usSquashRating",decimalsCount:1,ascending:!1,range:[2,6]},[qR]:{defaultInitialization:1e3,accessor:"usattRating",decimalsCount:0,ascending:!1,range:[200,3e3]},[$R]:{defaultInitialization:500,accessor:"ittfPoints",decimalsCount:0,ascending:!1,range:[0,2e4]},[KR]:{defaultInitialization:1e4,accessor:"usarRanking",decimalsCount:0,ascending:!0,range:[1,25e3]},BWF:{defaultInitialization:5e3,accessor:"bwfPoints",decimalsCount:0,ascending:!0,range:[0,15e4],attributes:{tournaments:{generator:!0,range:[1,10]}}}},Ke=rj;function Up({sourceRatingType:t,sourceRating:e}){let r=Ke[t]?.range,n=r?.[0]>r?.[1],o=Ke["ELO"].range;return Dp({value:n?r[0]-e:e,sourceRange:r,targetRange:o})}function lL({targetRatingType:t,sourceRating:e}){let r=Ke[t]?.decimalsCount||0,n=Ke[t]?.range,o=n?.[0]>n?.[1],i=Math.max(...n),s=Ke["ELO"]?.range,a=Dp({targetRange:n,sourceRange:s,value:e}),c=Number.parseFloat(a?.toFixed(r))||0;return o?i-c:c}function Ul(t){let{tournamentRecord:e,participantIds:r,scaleName:n,eventType:o,convertToELO:i,adHocRatings:s={}}=t,a=t.scaleAccessor??Ke[n]?.accessor,c=e.participants??[];for(let u of r??[]){let p=c?.find(d=>d.participantId===u),m;i&&(m=QR({scaleName:`${"ELO"}.${Ep}`,participant:p,eventType:o})),m||(m=QR({scaleName:`${n}.${Ep}`,participant:p,eventType:o}),m&&i&&n!=="ELO"&&(m=Up({sourceRatingType:n,sourceRating:m}))),!m&&n&&(m=QR({scaleAccessor:a,participant:p,scaleName:n,eventType:o}),m&&i&&n!=="ELO"&&(m=Up({sourceRatingType:n,sourceRating:m}))),m&&!s[u]&&(s[u]=m)}return s}function QR({scaleType:t=Lo,scaleAccessor:e,participant:r,scaleName:n,eventType:o}){let a=(r&&Po({scaleAttributes:{eventType:o??ba,scaleType:t,scaleName:n},participant:r}))?.scaleItem?.scaleValue;return e&&Tt(a)?a[e]:a}function XR(t){let{tournamentRecord:e,drawDefinition:r,participantIds:n,event:o}=t;if(!r)return{error:$};if(!n?.length)return{error:nt};let{competitionPolicy:i}=Ao({tournamentRecord:e,drawDefinition:r,event:o});if(!i)return{...P};let s=i.ratingPolicy,a=s.baselineRating.scaleName,c=s.ratingAggregation??"AVERAGE",u=o?.eventType,p=a?Ul({tournamentRecord:e,participantIds:n,scaleName:a,eventType:u}):{},m={};for(let l of n){let f=nj({tournamentRecord:e,participantId:l,adHocRatings:p,aggregation:c,eventType:u});m[l]={participantId:l,baselineRating:f,dynamicFormRating:f,pressureRating:0,roundsPlayed:0,wins:0,losses:0,draws:0,totalPointsWon:0,totalPointsLost:0,ratingHistory:[]}}let d={participantStates:m,roundStates:{}};return ut({element:r,extension:{name:wa,value:d}}),{competitionState:d,...P}}function nj({tournamentRecord:t,participantId:e,adHocRatings:r,aggregation:n,eventType:o}){if(r[e]!==void 0)return r[e];if(o===Lt){let s=t.participants?.find(a=>a.participantId===e)?.individualParticipantIds;if(s?.length){let a=s.map(c=>r[c]??0);return oj(a,n)}}return 0}function oj(t,e){if(!t.length)return 0;switch(e){case"MIN":return Math.min(...t);case"MAX":return Math.max(...t);case"SUM":return t.reduce((r,n)=>r+n,0);default:return t.reduce((r,n)=>r+n,0)/t.length}}function Wo({drawDefinition:t}){let{extension:e}=ot({element:t,name:wa});return{competitionState:e?.value}}function gL(t){let e=t.score?.sets??[];if(!e.length)return fL(t);let r=0,n=0;for(let o of e){let i=o.side1Score??0,s=o.side2Score??0;if(o.side1TiebreakScore!==void 0||o.side2TiebreakScore!==void 0){let a=o.side1TiebreakScore??0,c=o.side2TiebreakScore??0,u=a+c;if(u>0){r+=i-(o.winningSide===1?1:0)+a/u,n+=s-(o.winningSide===2?1:0)+c/u;continue}}r+=i,n+=s}return r>0||n>0?{side1Count:r,side2Count:n}:fL(t)}function fL(t){let{winningSide:e}=t;return e===1?{side1Count:1,side2Count:0}:e===2?{side1Count:0,side2Count:1}:{side1Count:0,side2Count:0}}function JR({pointsWon:t,pointsLost:e,competitionPolicy:r}){let n=t+e;if(n===0)return .5;let o=t/n,i=r.ratingPolicy.pressureRating;if(!i||i.actualOutputMethod==="POINT_SHARE")return o;let s=i.weights??{pointShare:1},a=(t-e)/n,c=0,u=s.pointShare??1,p=s.pointDifferential??0,m=s.contextFactor??0,d=u+p+m;return d===0?o:(u*o+p*a+m*c)/d}function wI(t,e,r){return 1/(1+Math.pow(10,(e-t)/r))}function Jm(t){let{tournamentRecord:e,drawDefinition:r,matchUp:n,event:o}=t;if(!r)return{error:$};if(!n)return{error:Xe};let{competitionPolicy:i}=Ao({tournamentRecord:e,drawDefinition:r,event:o});if(!i)return{...P};let{competitionState:s}=Wo({drawDefinition:r});if(!s)return{...P};let a=n.sides??[],c=a[0]?.participantId,u=a[1]?.participantId;if(!c||!u)return{...P};let p=s.participantStates[c],m=s.participantStates[u];if(!p||!m)return{...P};let{winningSide:d}=n,{side1Count:l,side2Count:f}=gL(n),g=JR({pointsWon:l,pointsLost:f,competitionPolicy:i}),I=JR({pointsWon:f,pointsLost:l,competitionPolicy:i}),S=i.ratingPolicy.dynamicFormRating.logisticScale,h=i.ratingPolicy.dynamicFormRating.kFactor,T=wI(p.baselineRating,m.baselineRating,S),y=wI(m.baselineRating,p.baselineRating,S),E=wI(p.dynamicFormRating,m.dynamicFormRating,S),A=wI(m.dynamicFormRating,p.dynamicFormRating,S),N=i.ratingPolicy.pressureRating?.enabled,D=N?g-T:0,R=N?I-y:0,U=i.ratingPolicy.dynamicFormRating.enabled,b=U?p.dynamicFormRating+h*(g-E):p.dynamicFormRating,C=U?m.dynamicFormRating+h*(I-A):m.dynamicFormRating,_=n.roundNumber??0;return p.dynamicFormRating=b,p.pressureRating+=D,p.roundsPlayed+=1,p.wins+=d===1?1:0,p.losses+=d===2?1:0,p.draws+=d?0:1,p.totalPointsWon+=l,p.totalPointsLost+=f,p.ratingHistory.push({roundNumber:_,opponentParticipantId:u,dynamicFormRatingBefore:p.dynamicFormRating-h*(g-E),dynamicFormRatingAfter:b,pressureDelta:D,actualOutput:g,expectedOutput:T}),m.dynamicFormRating=C,m.pressureRating+=R,m.roundsPlayed+=1,m.wins+=d===2?1:0,m.losses+=d===1?1:0,m.draws+=d?0:1,m.totalPointsWon+=f,m.totalPointsLost+=l,m.ratingHistory.push({roundNumber:_,opponentParticipantId:c,dynamicFormRatingBefore:m.dynamicFormRating-h*(I-A),dynamicFormRatingAfter:C,pressureDelta:R,actualOutput:I,expectedOutput:y}),ut({element:r,extension:{name:wa,value:s}}),{...P}}var Fr="ABANDONED",lu="AWAITING_RESULT";var to="CANCELLED",ie="COMPLETED",Rp="DEAD_RUBBER",Mt="DEFAULTED",ge="DOUBLE_DEFAULT",Qt="DOUBLE_WALKOVER",Cn="IN_PROGRESS",Xr="INCOMPLETE",ZR="NOT_PLAYED",De="RETIRED",Wi="SUSPENDED",zt="TO_BE_PLAYED",vt="WALKOVER",IL=[lu,ie,Mt,Cn,Xr,De,Wi],Fy=[lu,ie,Mt,Qt,ge,Cn,Xr,De,Wi,vt],ky=[Fr,lu,"BYE",to,ie,Rp,Mt,Qt,ge,Cn,Xr,ZR,De,Wi,zt,vt],Gy=["BYE",Qt,ge,ie,Mt,De,vt],Vy=[Fr,lu,to,Rp,Cn,Xr,ZR,Wi,zt,void 0],Ot=[to,Fr,ie,Rp,Mt,Qt,ge,De,vt],Rl=[Fr,ie,Mt,Qt,ge,Cn,De,vt],By=[Cn,Xr,Wi,zt],Wy={ABANDONED:Fr,AWAITING_RESULT:lu,BYE:"BYE",CANCELLED:to,COMPLETED:ie,DEAD_RUBBER:Rp,DEFAULTED:Mt,DOUBLE_WALKOVER:Qt,DOUBLE_DEFAULT:ge,IN_PROGRESS:Cn,INCOMPLETE:Xr,NOT_PLAYED:ZR,RETIRED:De,SUSPENDED:Wi,TO_BE_PLAYED:zt,WALKOVER:vt};function tb(t){let{tournamentRecord:e,drawDefinition:r,roundNumber:n,matchUps:o,event:i}=t;if(!r)return{error:$};let{competitionPolicy:s}=Ao({tournamentRecord:e,drawDefinition:r,event:i});if(!s)return{...P};let{competitionState:a}=Wo({drawDefinition:r});if(!a)return{...P};if(a.roundStates[n]?.processed)return{...P};let c=o.filter(p=>p.roundNumber===n&&(p.winningSide||Ot.includes(p.matchUpStatus)));for(let p of c)Jm({tournamentRecord:e,drawDefinition:r,matchUp:p,event:i});let{competitionState:u}=Wo({drawDefinition:r});return u&&(u.roundStates[n]={roundNumber:n,processed:!0},ut({element:r,extension:{name:wa,value:u}})),{...P}}function eb({drawDefinition:t}){return t?(ut({element:t,extension:{name:wa,value:void 0}}),{...P}):{error:$}}var nb={};Gt(nb,{getCompetitionLeaderboard:()=>Yy,getCompetitionParticipantState:()=>Hy,getCompetitionPolicy:()=>Ao,getCompetitionState:()=>Wo,getLinkedTournamentIds:()=>bp,getTournamentIds:()=>Xm});function Hy({drawDefinition:t,participantId:e}){let{competitionState:r}=Wo({drawDefinition:t});return{participantState:r?.participantStates?.[e]}}function Yy(t){let{tournamentRecord:e,drawDefinition:r,event:n}=t,{competitionPolicy:o}=Ao({tournamentRecord:e,drawDefinition:r,event:n}),{competitionState:i}=Wo({drawDefinition:r});if(!i||!o)return{leaderboard:[]};let s=o.victoryPolicy.primaryRanking;return{leaderboard:[...Object.values(i.participantStates)].sort((p,m)=>{let d=SL(m,s)-SL(p,s);if(d!==0)return d;for(let l of o.victoryPolicy.tiebreakOrder??[]){let f=ij(p,m,l,i.participantStates);if(f!==0)return f}return 0}).map((p,m)=>({participantId:p.participantId,rank:m+1,baselineRating:p.baselineRating,dynamicFormRating:p.dynamicFormRating,pressureRating:p.pressureRating,wins:p.wins,losses:p.losses,draws:p.draws,pointsWon:p.totalPointsWon,pointsLost:p.totalPointsLost}))}}function SL(t,e){switch(e){case"PRESSURE_RATING":return t.pressureRating;case"DYNAMIC_FORM_RATING":return t.dynamicFormRating;case"WINS":return t.wins;case"POINTS":return t.totalPointsWon;default:return t.wins}}function ij(t,e,r,n){switch(r){case"POINT_DIFFERENTIAL":return t.totalPointsWon-t.totalPointsLost-(e.totalPointsWon-e.totalPointsLost);case"DYNAMIC_FORM_RATING":return t.dynamicFormRating-e.dynamicFormRating;case"PRESSURE_RATING":return t.pressureRating-e.pressureRating;case"HEAD_TO_HEAD":{let o=t.ratingHistory.filter(c=>c.opponentParticipantId===e.participantId),i=e.ratingHistory.filter(c=>c.opponentParticipantId===t.participantId),s=o.filter(c=>c.actualOutput>.5).length,a=i.filter(c=>c.actualOutput>.5).length;return s-a}case"HEAD_TO_HEAD_PRESSURE":{let o=t.ratingHistory.filter(c=>c.opponentParticipantId===e.participantId),i=e.ratingHistory.filter(c=>c.opponentParticipantId===t.participantId),s=o.reduce((c,u)=>c+u.pressureDelta,0),a=i.reduce((c,u)=>c+u.pressureDelta,0);return s-a}case"STRENGTH_OF_OPPOSITION":{let o=t.ratingHistory.map(c=>n[c.opponentParticipantId]?.baselineRating??0),i=e.ratingHistory.map(c=>n[c.opponentParticipantId]?.baselineRating??0),s=o.length?o.reduce((c,u)=>c+u,0)/o.length:0,a=i.length?i.reduce((c,u)=>c+u,0)/i.length:0;return s-a}default:return 0}}function bp({tournamentRecords:t}){return typeof t!="object"||!Object.keys(t).length?{error:kt}:{linkedTournamentIds:Object.assign({},...Object.keys(t).map(r=>{let n=t[r],o=n?.tournamentId,{extension:i}=ot({element:n,name:La}),s=(i?.value?.tournamentIds??[]).filter(a=>a!==o);return{[r]:s}}))}}var hv={};Gt(hv,{adHocPositionSwap:()=>OC,addAdHocMatchUps:()=>Jp,addDrawDefinitionTimeItem:()=>OS,addFinishingRounds:()=>Nc,addGoesTo:()=>Ps,addLinkedConsolationStructure:()=>uC,addPlayoffStructures:()=>GS,addQualifyingStructure:()=>MC,addVoluntaryConsolationStructure:()=>gS,allPlayoffPositionsFilled:()=>qE,alternateDrawPositionAssignment:()=>mC,assignDrawPosition:()=>FC,assignDrawPositionBye:()=>Or,attachConsolationStructures:()=>AS,attachPlayoffStructures:()=>PS,attachQualifyingStructure:()=>vS,attachStructures:()=>NS,autoSeeding:()=>$k,automatedPlayoffPositioning:()=>Ha,automatedPositioning:()=>Ou,buildDrawHierarchy:()=>qk,checkValidEntries:()=>Nf,deleteAdHocMatchUps:()=>GC,drawMatic:()=>im,findDrawDefinition:()=>pA,generateAdHocMatchUps:()=>Mc,generateAdHocRounds:()=>Lf,generateAndPopulatePlayoffStructures:()=>Sf,generateConsolationStructure:()=>cC,generateDrawDefinition:()=>xc,generateDrawMaticRound:()=>bf,generateDrawStructuresAndLinks:()=>Df,generateDrawTypeAndModifyDrawDefinition:()=>Uf,generateQualifyingStructure:()=>lf,generateSwissRound:()=>Yk,generateVoluntaryConsolation:()=>xA,getAssignedParticipantIds:()=>Ji,getAvailableMatchUpsCount:()=>hf,getAvailablePlayoffProfiles:()=>qp,getDraftState:()=>RA,getDrawDefinitionTimeItem:()=>Zy,getDrawParticipantRepresentativeIds:()=>sA,getDrawStructures:()=>Sn,getDrawTypeCoercion:()=>em,getEligibleVoluntaryConsolationParticipants:()=>iA,getLuckyDrawRoundStatus:()=>ff,getMatchUpsMap:()=>Ie,getParticipantIdFinishingPositions:()=>Ef,getPositionAssignments:()=>xu,getPositionsPlayedOff:()=>bu,getRandomQualifierList:()=>PA,getSeedingThresholds:()=>bE,getSeedsCount:()=>rm,getStructureSeedAssignments:()=>Ur,getSwissChart:()=>UA,getSwissStandings:()=>NA,getTeamLineUp:()=>Xs,getValidGroupSizes:()=>ud,hasLuckyRounds:()=>nS,initializeDraft:()=>kC,isAdHoc:()=>Ae,isCompletedStructure:()=>Ro,isValidForQualifying:()=>DA,luckyDrawAdvancement:()=>_C,luckyLoserDrawPositionAssignment:()=>rC,modifyDrawDefinition:()=>xC,modifyDrawName:()=>VS,modifySeedAssignment:()=>TC,mutate:()=>WC,positionActions:()=>AA,predictDrawCompetitiveBands:()=>Zp,pruneDrawDefinition:()=>LC,qualifierDrawPositionAssignment:()=>US,qualifierProgression:()=>dC,query:()=>nM,remapDrawDefinitionMatchUpIds:()=>DS,removeDrawPositionAssignment:()=>jp,removeRoundMatchUps:()=>VC,removeSeededParticipant:()=>CC,removeStructure:()=>NC,renameStructures:()=>EC,resetDrawDefinition:()=>wC,resetQualifyingStructure:()=>PC,resetVoluntaryConsolationStructure:()=>lb,resolveDraftPositions:()=>AC,seedWithdrawalCascade:()=>vC,setDrawParticipantRepresentativeIds:()=>ib,setDrawPositionPreferences:()=>pC,setPositionAssignments:()=>oC,setStructureOrder:()=>yC,setSubOrder:()=>BC,shiftAdHocRounds:()=>nC,swapAdHocRounds:()=>iC,swapDrawPositionAssignments:()=>bC,updateTeamLineUp:()=>Us,validatePlayoffGroups:()=>pf,withdrawParticipantAtDrawPosition:()=>tC});var WC={};Gt(WC,{adHocPositionSwap:()=>OC,addAdHocMatchUps:()=>Jp,addDrawDefinitionTimeItem:()=>OS,addLinkedConsolationStructure:()=>uC,addPlayoffStructures:()=>GS,addQualifyingStructure:()=>MC,addVoluntaryConsolationStructure:()=>gS,alternateDrawPositionAssignment:()=>mC,assignDrawPosition:()=>FC,assignDrawPositionBye:()=>Or,attachConsolationStructures:()=>AS,attachPlayoffStructures:()=>PS,attachQualifyingStructure:()=>vS,attachStructures:()=>NS,automatedPlayoffPositioning:()=>Ha,automatedPositioning:()=>Ou,deleteAdHocMatchUps:()=>GC,initializeDraft:()=>kC,luckyDrawAdvancement:()=>_C,luckyLoserDrawPositionAssignment:()=>rC,modifyDrawDefinition:()=>xC,modifyDrawName:()=>VS,modifySeedAssignment:()=>TC,pruneDrawDefinition:()=>LC,qualifierDrawPositionAssignment:()=>US,qualifierProgression:()=>dC,remapDrawDefinitionMatchUpIds:()=>DS,removeDrawPositionAssignment:()=>jp,removeRoundMatchUps:()=>VC,removeSeededParticipant:()=>CC,removeStructure:()=>NC,renameStructures:()=>EC,resetDrawDefinition:()=>wC,resetQualifyingStructure:()=>PC,resetVoluntaryConsolationStructure:()=>lb,resolveDraftPositions:()=>AC,seedWithdrawalCascade:()=>vC,setDrawParticipantRepresentativeIds:()=>ib,setDrawPositionPreferences:()=>pC,setPositionAssignments:()=>oC,setStructureOrder:()=>yC,setSubOrder:()=>BC,shiftAdHocRounds:()=>nC,swapAdHocRounds:()=>iC,swapDrawPositionAssignments:()=>bC,updateTeamLineUp:()=>Us,withdrawParticipantAtDrawPosition:()=>tC});var jy=t=>e=>t[e],bl=(t=[])=>t.map(Te).filter(Boolean),LI=(t=[])=>t.map(gt).filter(Boolean),gt=(t={})=>jy(t)("participantId"),hL=(t={})=>jy(t)("drawPosition");var Te=(t={})=>jy(t)("matchUpId"),Tc=(t={})=>jy(t)("drawId");function ib({representativeParticipantIds:t,drawDefinition:e}){if(!e)return{error:Mr};if(!Array.isArray(t))return{error:O};let r=LI(e?.entries??[]);return t.length&&Yt(t,r).length<t.length?{error:O}:_I({drawDefinition:e,extension:{name:wy,value:t}})}function Hi(t,e,r){let n=m=>ot({element:m,name:bn})?.extension?.value,o=r?.deprioritizeCompleted,i=r?.mode===ER&&Kw,s=r?.mode===yR&&AR,a=s||i||Ca,c=m=>m?.stage===W&&m?.stageSequence===1,u=m=>c(m)?-1:a[m?.stage],p=m=>m?.matchUps.every(({matchUpStatus:d})=>Ot.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)||(FI(t)||0)-(FI(e)||0)}function FI(t){return(t?.matchUps??[]).reduce((e,r)=>{let n=(r.finishingPositionRange?.winner??[]).reduce((o,i)=>o+i,0);return!e||n<e?n:e},void 0)}function tt(t){let e=X(t,[{[Kt]:!0,[mo]:!0}]);if(e.error)return e;let{drawDefinition:r,structureId:n}=t,{structures:o}=Sn({drawDefinition:r}),i=o?.flatMap(c=>c.structures?[...c.structures].concat(c):c),s=i?.find(c=>c.structureId===n);if(!s)return{error:Nt};let a=s.structureType===su?i?.find(c=>c.structures?.some(u=>u.structureId===n)):void 0;return{structure:s,containingStructure:a}}function Sn({withStageGrouping:t,drawDefinition:e,stageSequences:r,stageSequence:n,roundTarget:o,sortConfig:i,stages:s,stage:a}){let c=!e&&$||!e?.structures&&Gg||void 0;if(c)return{error:c,structures:[],stageStructures:{}};let u=f=>{let g=ot({element:f,name:bn})?.extension?.value;return!o||o===g},p=e?.structures?.filter(d).filter(l).filter(u).sort((f,g)=>Hi(f,g,i))??[],m=t?Object.assign({},...ou.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 qy({drawDefinition:t}){if(!t)return{error:$};let e={};return{allPositionedParticipantIds:(t.structures??[]).map(n=>{let o=n.stage;e[o]||(e[o]=[]);let{positionAssignments:i}=Pt({structure:n}),s=i?.map(gt).filter(Boolean)??[];return e[o].push(...s),s}).flat(),stagePositionedParticipantIds:e}}function Pt({drawDefinition:t,structureId:e,structure:r}){let n,o=[];if(!r){if(!t)return{positionAssignments:o,error:$};if({structure:r,error:n}=tt({drawDefinition:t,structureId:e}),n)return{positionAssignments:o,error:n}}return r.structures?o=[].concat(...r.structures.map(i=>Pt({structure:i}).positionAssignments)):r.positionAssignments?o=r.positionAssignments:n=KD,{positionAssignments:o,error:n}}function se({drawDefinition:t,structureId:e,structure:r}){let n=Pt({drawDefinition:t,structureId:e,structure:r})?.positionAssignments??[],o=n?.filter(u=>u.participantId??u.bye??u.qualifier),i=n&&n?.length===o?.length,s=n?.filter(u=>!u.participantId&&!u.bye&&!u.qualifier),a=n?.filter(u=>!u.participantId&&u.bye),c=n?.filter(u=>!u.participantId&&u.qualifier);return{allPositionsAssigned:i,positionAssignments:n,unassignedPositions:s,assignedPositions:o,qualifierPositions:c,byePositions:a}}function dt(t,e,r){let n=e.reduce((o,i)=>(o[i]=!0,o),{});return X(t,[n],r)}var kI="addDrawDefinition",Zm="addMatchUps",Di="addParticipants",GI="addScaleItems",sb="addEvent",$y="addVenue",Yi="audit",Ky="dataIssue",VI="deleteParticipants",BI="deleteVenue",WI="deletedDrawIds",HI="deletedMatchUpIds",YI="modifyDrawDefinition",ab="modifyDrawEntries",cb="modifyEventEntries",jI="modifyMatchUp",tr="modifyParticipants",qI="modifyPositionAssignments",$I="modifySeedAssignments",mi="modifyTournamentDetail",No="modifyVenue",Cl="mutations",zy="publishEvent",ub="publishEventSeeding",pb="publishOrderOfPlay",mb="publishParticipants",KI="unPublishEvent",zI="unPublishEventSeeding",QI="unPublishOrderOfPlay",db="unPublishParticipants",Ml="unPublishTournament",Cp="updateInContextMatchUp",TL={ADD_DRAW_DEFINITION:kI,ADD_MATCHUPS:Zm,ADD_PARTICIPANTS:Di,ADD_SCALE_ITEMS:GI,ADD_EVENT:sb,ADD_VENUE:$y,AUDIT:Yi,DATA_ISSUE:Ky,DELETE_PARTICIPANTS:VI,DELETE_VENUE:BI,DELETED_DRAW_IDS:WI,DELETED_MATCHUP_IDS:HI,MODIFY_DRAW_DEFINITION:YI,MODIFY_DRAW_ENTRIES:ab,MODIFY_EVENT_ENTRIES:cb,MODIFY_MATCHUP:jI,MODIFY_PARTICIPANTS:tr,MODIFY_POSITION_ASSIGNMENTS:qI,MODIFY_SEED_ASSIGNMENTS:$I,MODIFY_TOURNAMENT_DETAIL:mi,MODIFY_VENUE:No,MUTATIONS:Cl,PUBLISH_EVENT_SEEDING:ub,PUBLISH_EVENT:zy,PUBLISH_ORDER_OF_PLAY:pb,PUBLISH_PARTICIPANTS:mb,UNPUBLISH_EVENT_SEEDING:zI,UNPUBLISH_EVENT:KI,UNPUBLISH_ORDER_OF_PLAY:QI,UNPUBLISH_PARTICIPANTS:db,UNPUBLISH_TOURNAMENT:Ml,UPDATE_INCONTEXT_MATCHUP:Cp};function Qy(t,e){if(!t)return{error:$};let r=Date.now();t.updatedAt&&r===new Date(t.updatedAt).getTime()&&(r+=1);let n=new Date(r).toISOString(),o=e?.filter(Boolean);return t.updatedAt=n,t.structures?.filter(Boolean).forEach(i=>{(!o?.length||o?.includes(i.structureId))&&(i.updatedAt=n)}),{...P}}function yL(t){if(!t)return;let e=Date.now(),r=t.updatedAt;if(r){let n=typeof r=="string"?new Date(r).getTime():r.getTime();!Number.isNaN(n)&&e<=n&&(e=n+1)}t.updatedAt=new Date(e).toISOString()}function Ho({drawDefinition:t,tournamentId:e,matchUps:r,eventId:n}){if(t&&Qy(t),Array.isArray(r))for(let o of r)yL(o);return at({payload:{matchUps:r,tournamentId:e,eventId:n},topic:Zm}),{...P}}function wn({drawDefinition:t,tournamentId:e,matchUpIds:r,eventId:n,action:o}){t&&Qy(t),at({topic:HI,payload:{tournamentId:e,matchUpIds:r,eventId:n,action:o}});for(let i of r)zT({key:i});return{...P}}function It({drawDefinition:t,tournamentId:e,structureId:r,context:n,eventId:o,matchUp:i}){return i?(t&&Ft({drawDefinition:t,structureIds:r?[r]:void 0,tournamentId:e,eventId:o}),yL(i),at({topic:jI,payload:{matchUp:i,tournamentId:e,context:n},key:i.matchUpId}),{...P}):(console.log(Xe),{error:Xe})}function EL({tournamentId:t,inContextMatchUp:e}){return e?(at({payload:{inContextMatchUp:e,tournamentId:t},topic:Cp,key:e.matchUpId}),{...P}):{error:Xe}}function yc({tournamentId:t,eventId:e,drawDefinition:r}){return r?(Qy(r),at({payload:{drawDefinition:r,tournamentId:t,eventId:e},topic:kI,key:r.drawId}),{...P}):(console.log($),{error:$})}function AL({tournamentId:t,eventId:e,drawId:r}){return at({payload:{drawId:r,tournamentId:t,eventId:e},topic:WI,key:r}),zT({key:r}),{...P}}function Ft({drawDefinition:t,tournamentId:e,structureIds:r,eventId:n}){return t?(Qy(t,r),at({payload:{tournamentId:e,eventId:n,drawDefinition:t},topic:YI,key:t.drawId}),{...P}):{error:$}}function vl({drawDefinition:t,tournamentId:e,structure:r,eventId:n}){let o=dt({drawDefinition:t,structure:r},[Kt,mc]);if(o.error)return o;let i=r.seedAssignments,s=r.structureId,a=t.drawId;return at({payload:{tournamentId:e,eventId:n,drawId:a,structureId:s,seedAssignments:i},topic:$I,key:t.drawId}),Ft({structureIds:[s],drawDefinition:t,tournamentId:e,eventId:n}),{...P}}function hn({drawDefinition:t,tournamentId:e,structure:r,event:n}){let o=dt({drawDefinition:t,structure:r},[Kt,mc]);if(o.error)return o;let i=Pt({structure:r}),s=r.structureId,a=t.drawId,c=n?.eventId;return at({topic:qI,payload:{positionAssignments:i,tournamentId:e,structureId:s,eventId:c,drawId:a},key:s}),Ft({structureIds:[s],drawDefinition:t,tournamentId:e,eventId:c}),{...P}}function lb({tournamentRecord:t,drawDefinition:e,resetEntries:r,event:n}){if(!e)return{error:$};let o=e.structures?.find(s=>s.stage===Fe);if(!o)return{error:Nt};let i=o.matchUps?.map(({matchUpId:s})=>s)??[];return o.positionAssignments=[],o.seedAssignments=[],o.matchUps=[],wn({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:i,drawDefinition:e}),r&&(e.entries=e.entries.filter(s=>s.entryStage!==Fe)),Ft({tournamentId:t?.tournamentId,eventId:n?.eventId,drawDefinition:e,structureIds:[o.structureId]}),{...P}}function Ol({drawPositions:t,structure:e}){if([Z,W].includes(e.stage)&&e.stageSequence===1)return;let{positionAssignments:r}=Pt({structure:e});r?.filter(({drawPosition:o})=>t?.includes(o))?.forEach(o=>{ut({element:o,extension:{name:Pl,value:!0}})})}function Ec(t){let{appliedPolicies:e,positionAction:r,drawDefinition:n}=t;if(e?.audit?.[mu]===!1)return;let{extension:o}=ot({name:mu,element:n}),i=Array.isArray(o?.value)?o?.value??[]:[];if(!i?.length){let a=n.structures.find(c=>c.stage===W);if(a){let c=Pt({structure:a}).positionAssignments?.map(({drawPosition:u,participantId:p,bye:m,qualifier:d})=>({drawPosition:u,participantId:p,qualifier:d,bye:m}));i.push({name:"initialMainAssignments",initialAssignments:c})}}let s={value:i.concat(r),name:mu};ut({element:n,extension:s})}function ji({tournamentRecord:t,drawDefinition:e,event:r}){let o=(t?.events||r&&[r])?.map(c=>c?.drawDefinitions).flat().filter(Boolean)||e&&[e]||[],i={},s={},a=o.map(c=>c?.structures?.filter(u=>u?.structures)).flat().filter(Boolean);for(let c of a){let{structures:u,structureId:p}=c??{};u&&p&&(i[p]=u?.map(m=>m.structureId))&&u.forEach(m=>s[m.structureId]=c?.structureId)}return{containedStructures:i,containerStructures:s}}function Mp(t){let{sides:e,matchUpType:r}=t??{},n=t.potentialParticipants?.length?t.potentialParticipants.flat().map(s=>r===Rt?s?.individualParticipantIds??[]:s.participantId).flat():[],o=(e??[]).map(s=>r===Rt&&(s?.participant?.individualParticipantIds??[])||s?.participantId&&[s.participantId]||[]).flat();return{individualParticipantIds:o.concat(n).flat(),enteredIndividualParticipantIds:o,potentialIndividualParticipantIds:n}}function Dr(t){return t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{}}var fu="SIGN_IN_STATUS",fb="SIGNED_OUT",vp="SIGNED_IN",ur="TEAM",St="INDIVIDUAL",$r="GROUP",lt="PAIR",_t="TEAM",Op={TEAM_PARTICIPANT:ur,INDIVIDUAL:St,GROUP:$r,TEAM:_t,PAIR:lt},PL={INDIVIDUAL:St,GROUP:$r,PAIR:lt,TEAM:_t,SIGN_IN_STATUS:fu,SIGNED_OUT:fb,SIGNED_IN:vp};function _p({participantsProfile:t,participants:e=[],deepCopy:r}){let n=new Map,o=r!==!1?q(e,t?.convertExtensions,!0):e,i=o.filter(c=>c.participantType===_t),s=o.filter(c=>c.participantType===$r),a=o.filter(c=>c.participantType===lt);return o.forEach(c=>{if(c.participantType===St){let{participantId:u}=c;c.groupParticipantIds=[],c.teamParticipantIds=[],c.pairParticipantIds=[],c.groups=[],c.teams=[],i.forEach(p=>{(p?.individualParticipantIds??[]).forEach(m=>{m===u&&!c.teamParticipantIds?.includes(p.participantId)&&(c.teamParticipantIds.push(p.participantId),n.get(p.participantId)||n.set(p.participantId,{participantName:p.participantName,participantId:p.participantId}),c.teams.push({participantRoleResponsibilities:p.participantRoleResponsibilities,participantOtherName:p.participantOtherName,participantName:p.participantName,participantId:p.participantId,teamId:p.teamId}))})}),a.forEach(p=>{(p?.individualParticipantIds??[]).forEach(m=>{m===u&&!c.pairParticipantIds.includes(p.participantId)&&c.pairParticipantIds.push(p.participantId)})}),s.forEach(p=>{(p?.individualParticipantIds??[]).forEach(m=>{m===u&&!c.groupParticipantIds.includes(p.participantId)&&(c.groupParticipantIds.push(p.participantId),c.groups.push({participantRoleResponsibilities:p.participantRoleResponsibilities,participantOtherName:p.participantOtherName,participantName:p.participantName,participantId:p.participantId}))})})}}),{participantsWithGroupings:o,groupInfo:Object.fromEntries(n)}}function gb(t){return t&&typeof String.fromCodePoint<"u"?t.toUpperCase().replace(/./g,e=>String.fromCodePoint(e.charCodeAt(0)+127397)):t}function NL(t){let e=Object.assign({},...Ui.filter(r=>r.ioc).map(r=>({[r.ioc]:r.iso})));return gb(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 Xy({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 DL({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?hs({template:e,source:s}):s)}}}}function Do(t){let{tournamentRecord:e,participantId:r}=t,n=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};for(let o of Object.values(n)){let i=o.participants?.find(s=>s.participantId===r);if(i)return{participant:i,tournamentId:o.tournamentId}}return{error:ee}}function Jy(t){let{tournamentRecord:e,participantId:r}=t;if(r){let o=Do({tournamentRecord:e,participantId:r});return o.participant??o}let n=t.element||t.drawDefinition||t.event||t.tournamentRecord;return n||{error:nt}}function Jr(t){let{returnPreviousValues:e,itemSubTypes:r,itemType:n}=t,o=Jy(t);if(o.error)return o;if(r&&!Array.isArray(r))return{error:O,context:{itemSubTypes:r}};if(!Array.isArray(o.timeItems))return{error:rI};let i=o.timeItems.filter(a=>a?.itemType===n).filter(a=>!r?.length||r.some(c=>a?.itemSubTypes?.includes(c))).sort((a,c)=>{let u=new Date(a.createdAt||void 0).getTime(),p=new Date(c.createdAt||void 0).getTime();return u-p}),s=q(i.pop(),!1,!0);if(s){let a={timeItem:s,...P};return e&&Object.assign(a,{previousItems:i}),a}else return{info:fe}}function Zy({returnPreviousValues:t,drawDefinition:e,itemSubTypes:r,itemType:n}){if(!e)return{error:Nn};if(!e.timeItems)return{info:fe};let{timeItem:o,previousItems:i,info:s}=Jr({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function xp({returnPreviousValues:t,itemSubTypes:e,itemType:r,event:n}){if(!n)return{error:le};if(!n.timeItems)return{info:fe};let{timeItem:o,previousItems:i,info:s}=Jr({returnPreviousValues:t,element:n,itemSubTypes:e,itemType:r});return o&&{timeItem:o,previousItems:i}||{info:s}}function _l({returnPreviousValues:t,tournamentRecord:e,itemSubTypes:r,itemType:n}){if(!e)return{error:j};if(!e.timeItems)return{info:fe};let{timeItem:o,previousItems:i,info:s}=Jr({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function tE({returnPreviousValues:t,tournamentRecord:e,participantId:r,itemSubTypes:n,itemType:o}){let i=dt({tournamentRecord:e,participantId:r},[rt,sr]);if(i.error)return i;let s=Do({tournamentRecord:e,participantId:r});if(s.error)return s;let{participant:a}=s;if(!a?.timeItems)return{info:fe};let{timeItem:c,previousItems:u,info:p}=Jr({element:s.participant,returnPreviousValues:t,itemSubTypes:n,itemType:o});return c&&{timeItem:c,previousItems:u}||{info:p}}var sj={[$r]:"groupParticipantIds",[lt]:"pairParticipantIds",[_t]:"teamParticipantIds"},aj={[$r]:"groups",[_t]:"teams"};function eE({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&&pj({participantMap:p,participantId:l})}for(let d of r.participants??[]){let l=q(d,e,s),{participantId:f,individualParticipantIds:g,participantType:I}=l;if(!p[f]){u.push(f);continue}if(Object.assign(p[f].participant,l),g){let S=uj({individualParticipantIds:g,participantCopy:l,participantMap:p,participantType:I,participantId:f});S.missingParticipantIds.length&&u.push(...S.missingParticipantIds)}if(n&&(p[f].participant.signedIn=cj(l)),o){let{ratings:S,rankings:h,seedings:T}=lc({participant:l});p[f].participant.seedings=T,p[f].participant.rankings=h,p[f].participant.ratings=S}(c||a)&&Xy({participant:p[f].participant,withISO2:a,withIOC:c})}if(t){let d=Tt(t)?t:void 0;DL({participantMap:p,template:d})}let m;return i&&(m=_p({participants:Object.values(p).map(({participant:d})=>d),participantsProfile:{convertExtensions:e},deepCopy:!1}).groupInfo),{missingParticipantIds:u,participantMap:p,groupInfo:m}}function cj(t){let{timeItem:e}=Jr({itemType:fu,element:t});return e?.itemValue===vp}function uj({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[sj[n]].push(o),[_t,$r].includes(n)){let{participantRoleResponsibilities:c,participantOtherName:u,participantName:p,participantId:m,teamId:d}=e,l=aj[n];a[l].push({participantRoleResponsibilities:c,participantOtherName:u,participantName:p,participantId:m,teamId:d})}if(n===lt){let c=t.find(u=>u!==s);r[s].pairIdMap[o]=c,r[s].pairIdMap[c]=o}}return{missingParticipantIds:i}}function pj({participantMap:t,participantId:e}){if(t[e])return;let r={walkoverWins:0,defaultWins:0,walkovers:0,defaults:0,losses:0,wins:0};t[e]={structureParticipation:{},potentialMatchUps:{},scheduleConflicts:{},scheduleItems:[],participant:{groupParticipantIds:[],pairParticipantIds:[],teamParticipantIds:[],seedings:{},rankings:{},ratings:{},groups:[],teams:[]},statistics:{},opponents:{},pairIdMap:{},matchUps:{},events:{},draws:{},counters:{[Ct]:{...r},[Rt]:{...r},[_t]:{...r},...r}}}function di({participantsProfile:t,useParticipantMap:e,tournamentRecord:r,contextProfile:n,inContext:o}){if(e)return eE({...t,...n,tournamentRecord:r});let i=q(r.participants,!1,!0)??[];(t?.withIOC||t?.withISO2)&&i.forEach(a=>Xy({participant:a,...t}));let s;if((o||t?.withGroupings)&&i?.length&&({participantsWithGroupings:i,groupInfo:s}=_p({participantsProfile:t,deepCopy:!1,participants:i})),t?.withScaleValues&&i?.length)for(let a of i){let{ratings:c,rankings:u}=lc({participant:a});a.rankings=u,a.ratings=c}return{participants:i,groupInfo:s}}var rE="WALKOVER",Ib="RETIRED",xl="COMPETITIVE",gu="ROUTINE",Iu="DECISIVE",wl="winRatio";var mj={[gn]:{policyName:"Competitive Bands Default",profileBands:{[Iu]:20,[gu]:50},predictionModel:{competitiveAnchors:[{delta:0,probability:.7},{delta:1.5,probability:.25}],decisiveAnchors:[{delta:0,probability:.1},{delta:1.5,probability:.55}]}}},Hs=mj;function eo({policyDefinitions:t,tournamentRecord:e,contextProfile:r,drawDefinition:n,event:o}){let i={policies:{}};if(!r)return i;let s=fo({tournamentRecord:e,drawDefinition:n,event:o}).policyDefinitions;if(r.withCompetitiveness){let a=t?.[gn]??s?.[gn]??Hs[gn];i.policies[gn]=a}return i}function go({tournamentRecord:t,drawDefinition:e,policyType:r,structure:n,event:o}){if(!t)return{error:j};let{appliedPolicies:i}=ft({tournamentRecord:t,drawDefinition:e,structure:n,event:o});return i?.[r]?{policy:i[r]}:{info:np?.message}}function Ac({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}=go({policyType:ko,tournamentRecord:t,event:n}),s=(t?ot({element:t,name:pi}).extension:void 0)?.value,c=(n&&ot({name:pi,element:n}).extension)?.value;return{scheduleTiming:{tournamentScheduling:s,eventScheduling:c,categoryName:e,categoryType:r,policy:o}}}function XI({tournamentRecord:t,event:e}){if(!t)return{};let{extension:r}=ot({element:t,name:wR}),n=r?.value;if(!n?.events?.length)return{};let o=e?n.events.find(s=>s.eventType===e.eventType&&(!s.eventName||s.eventName===e.eventName)&&(!s.category?.categoryName||s.category?.categoryName===e.category?.categoryName)):void 0;if(!o)return{};let i={};return o.drawSize!==void 0&&(i.drawSize=o.drawSize),o.maxWildcards!==void 0&&(i.maxWildcards=o.maxWildcards),o.maxAlternates!==void 0&&(i.maxAlternates=o.maxAlternates),o.maxQualifiers!==void 0&&(i.maxQualifiers=o.maxQualifiers),Object.keys(i).length?{constraints:i}:{}}var Su="GEMscore",UL={GEM_SCORE:Su};function RL({provisionalPositioning:t,rankBy:e=Su,finishingPositions:r,groupResults:n,bestOf:o}){let i=[],s=[],a=[...r].sort(Zt),c=Math.max(...a);for(let{structureId:d,results:l}of n)for(let[f,g]of Object.entries(l)){let I=g.groupOrder||t&&g.provisionalOrder;if(!I)continue;let S={groupingValue:d,GEMscore:g.GEMscore,isBestFinisher:!1,finishingPosition:I,participantId:f};a.includes(I)?s.push(S):I>c&&i.push(S)}let u=[...s],p=o-s.length;p>0&&i.length>0&&i.toSorted((f,g)=>f.finishingPosition!==g.finishingPosition?f.finishingPosition-g.finishingPosition:e===Su?(g.GEMscore??0)-(f.GEMscore??0):0).slice(0,p).forEach(f=>{f.isBestFinisher=!0,u.push(f)});let m={};for(let d of u){let l=d.finishingPosition;m[l]=(m[l]||0)+1}return{selectedParticipants:u,consumedPositions:m}}var Zr="ALTERNATE",JI="CONFIRMED",kr="DIRECT_ACCEPTANCE",wp="FEED_IN",ZI="JUNIOR_EXEMPT",Ys="LUCKY_LOSER",tS="ORGANISER_ACCEPTANCE",Ll="QUALIFIER",dj="REGISTERED",eS="SPECIAL_EXEMPT",Gr="UNGROUPED",qi="UNPAIRED",Lp="WILDCARD",Mn="WITHDRAWN",td=[JI,kr,ZI,tS,eS],Sb=[wp,Ys,Ll],$i=[JI,kr,wp,ZI,tS,eS,Lp],yr=[JI,kr,ZI,Ys,Ll,tS,eS,Lp],hb=[Zr,JI,kr,wp,ZI,Ys,tS,Ll,dj,eS,Gr,qi,Lp,Mn],bL={ALTERNATE:Zr,CONFIRMED:JI,DIRECT_ACCEPTANCE:kr,DIRECT_ENTRY_STATUSES:$i,DRAW_SPECIFIC_STATUSES:Sb,EQUIVALENT_ACCEPTANCE_STATUSES:td,FEED_IN:wp,JUNIOR_EXEMPT:ZI,LUCKY_LOSER:Ys,ORGANISER_ACCEPTANCE:tS,QUALIFIER:Ll,SPECIAL_EXEMPT:eS,STRUCTURE_SELECTED_STATUSES:yr,UNGROUPED:Gr,UNPAIRED:qi,VALID_ENTRY_STATUSES:hb,WILDCARD:Lp,WITHDRAWN:Mn};function CL({stage:t,drawDefinition:e}){return ou.includes(t)?e?.structures?.some(n=>n.stage===t)||ou.includes(t):!1}function nE({stage:t,drawDefinition:e,entryStatus:r}){return e.entries.reduce((n,o)=>o.entryStage===t&&o.entryStatus===r?n+1:n,0)}function Ki({provisionalPositioning:t,placementGroup:e,drawDefinition:r,stageSequence:n,entryStatuses:o,structureId:i,roundTarget:s,stages:a,stage:c}){let u=r.entries?.reduce((p,m)=>{let d=ot({name:bn,element:m})?.extension?.value,l=c&&m.entryStage===c||a?.length&&m.entryStage&&a.includes(m.entryStage),f=!o||m.entryStatus&&o.includes(m.entryStatus),g=m.entryStageSequence??1;return l&&(!n||g===n)&&f&&(!s||!d||s===d)?p.concat(m):p},[])??[];if(i&&c===Vt){let{playoffEntries:p,error:m}=lj({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 lj({provisionalPositioning:t,drawDefinition:e,structureId:r}){let n=[],o=(e.links??[]).find(i=>i.linkType===fn&&i.target.structureId===r);if(o){let{finishingPositions:i,structureId:s,bestOf:a,rankBy:c}=o.source,{structure:u}=tt({drawDefinition:e,structureId:s});if(u?.structureType===de){let m=(u.structures??[]).map(d=>{let l=d.positionAssignments??[],{structureId:f}=d,g=Object.assign({},...l.map(I=>{let{participantId:S}=I,h=ot({element:I,name:Bo}).extension?.value;return h&&S?{[S]:h}:void 0}).filter(Boolean));return{structureId:f,results:g}});if(o.source.remainder)fj({provisionalPositioning:t,allGroupResults:m,drawDefinition:e,playoffEntries:n,inboundLink:o,structureId:s});else if(a!==void 0&&i){let{selectedParticipants:d}=RL({groupResults:m,provisionalPositioning:t,finishingPositions:i,bestOf:a,rankBy:c});d.forEach(l=>{let g=i.includes(l.finishingPosition)?[...i].sort(Zt).indexOf(l.finishingPosition)+1:[...i].sort(Zt).length+1;n.push({isBestFinisher:l.isBestFinisher,groupingValue:l.groupingValue,participantId:l.participantId,GEMscore:l.GEMscore,entryStatus:wp,entryStage:Vt,placementGroup:g})})}else gj({provisionalPositioning:t,finishingPositions:i,allGroupResults:m,playoffEntries:n})}}return{playoffEntries:n}}function fj({provisionalPositioning:t,allGroupResults:e,drawDefinition:r,playoffEntries:n,inboundLink:o,structureId:i}){let s=new Set,a=(r.links??[]).filter(c=>c.linkType===fn&&c.source.structureId===i&&c.target.structureId!==o.target.structureId&&c.source.bestOf!==void 0);for(let c of a){let{structure:u}=tt({structureId:c.target.structureId,drawDefinition:r});if(u)for(let p of u.positionAssignments??[])p.participantId&&s.add(p.participantId)}e.forEach(({structureId:c,results:u})=>{Object.keys(u).forEach(p=>{if(!s.has(p)){let m=u[p],{groupOrder:d,provisionalOrder:l,GEMscore:f}=m,g=d||t&&l;n.push({groupingValue:c,entryStage:Vt,entryStatus:wp,placementGroup:g||1,participantId:p,GEMscore:f})}})})}function gj({provisionalPositioning:t,finishingPositions:e,allGroupResults:r,playoffEntries:n}){r.forEach(({structureId:o,results:i})=>{let s=o,c=Object.keys(i).reduce((p,m)=>{let d=i[m],l=d.groupOrder||t&&d.provisionalOrder;return p.includes(l)||p.push(l),p},[]).length===Object.keys(i).length,u=Object.keys(i).filter(p=>{let m=i[p],d=m.groupOrder||t&&m.provisionalOrder;return e?.includes(d)});(!t||c)&&u.forEach(p=>{let m=i[p],{groupOrder:d,provisionalOrder:l,GEMscore:f}=m,g=d||t&&l,I=[...e??[]].sort(Zt).indexOf(g)+1;n.push({entryStage:Vt,entryStatus:wp,placementGroup:I,groupingValue:s,participantId:p,GEMscore:f})})})}function Ur({provisionalPositioning:t,returnAllProxies:e,drawDefinition:r,structureId:n,structure:o}){let i,s=[];o||({structure:o,error:i}=tt({drawDefinition:r,structureId:n}));let a=Pt({structure:o}).positionAssignments;if(i||!o)return{seedAssignments:[],error:Nt};n||(n=o.structureId);let{stage:c,stageSequence:u}=o,m=c===Vt&&r&&Ki({provisionalPositioning:t,drawDefinition:r,stageSequence:u,structureId:n,stage:c}),d=m?m.filter(g=>g.placementGroup===1).sort((g,I)=>g.GEMscore<I.GEMscore&&1||g.GEMscore>I.GEMscore&&-1||0).map((g,I)=>{let S=I+1;return{participantId:g.participantId,seedValue:S,seedProxy:!0,seedNumber:S}}):[],l=d?.slice(0,e?d.length:a.length/2);l.length?s=l:o.seedAssignments?s=o.seedAssignments:i=GD;let f=o.seedLimit??o?.positionAssignments?.length;return{seedAssignments:s,stageSequence:u,seedLimit:f,stage:c,error:i}}function Yo(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 ed({item:t,drawDefinition:e,structure:r,event:n}){if(t){if(t.tieFormat)return t.tieFormat;if(t.tieFormatId){if(e.tieFormat)return e.tieFormat;let o=e.tieFormats?.find(i=>t.tieFormatId===i.tieFormatId);return o||(n.tieFormat?n.tieFormat:n.tieFormats?.find(i=>t.tieFormatId===i.tieFormatId))}if(r?.tieFormat)return r.tieFormat;if(r?.tieFormatId){let o=e.tieFormats?.find(i=>r.tieFormatId===i.tieFormatId);if(o)return o}}}function ze({drawDefinition:t,structure:e,matchUp:r,event:n}){return{tieFormat:ed({item:r,drawDefinition:t,structure:e,event:n})||ed({item:e,drawDefinition:t,structure:e,event:n})||Yo(t)||Yo(n)}}function ML({matchUps:t}){let e=t.reduce((n,o)=>!o.collectionPosition||n.includes(o.collectionPosition)?n:n.concat(o.collectionPosition),[]).map(n=>({[n]:t.filter(o=>o.collectionPosition===n)}));return{collectionPositionMatchUps:Object.assign({},...e)}}function Ie({drawDefinition:t,structure:e}){let r={},n=[];return(t?.structures??[e]).filter(o=>o&&typeof o=="object").forEach(o=>{if(!o)return;let{structureId:i,matchUps:s,structures:a}=o,c=Array.isArray(a);if(c)c&&a.forEach(u=>{let{structureName:p}=u,m=u.matchUps;r[u.structureId]={matchUps:m,itemStructureIds:[],structureName:p},m&&(n.push(...m),m.forEach(d=>{d.tieMatchUps&&n.push(...d.tieMatchUps)})),r[i]||(r[i]={itemStructureIds:[],matchUps:[]}),r[i].itemStructureIds||(r[i].itemStructureIds=[]),r[i].itemStructureIds.push(u.structureId)});else{let u=s;r[i]={matchUps:u,itemStructureIds:[]},u?.forEach(p=>{n.push(p),p.tieMatchUps&&n.push(...p.tieMatchUps)})}}),{mappedMatchUps:r,drawMatchUps:n}}function jo({mappedMatchUps:t,matchUpsMap:e,structureId:r,inContext:n}){t=e?.mappedMatchUps??t;let o=t[r],i=(o?.itemStructureIds??[]).map(s=>{let{matchUps:a,structureName:c}=t[s];return n?a.map(u=>Object.assign(q(u,!0,!0),{containerStructureId:r,structureId:s,structureName:c})):a}).flat();return(o?.matchUps??[]).concat(...i)}function oE({policyDefinitions:t,tournamentRecord:e,drawDefinition:r,structure:n,event:o}){let i=t?.[gn];if(i?.profileBands)return i.profileBands;if(e){let{appliedPolicies:s}=ft({tournamentRecord:e,drawDefinition:r,structure:n,event:o}),a=s?.[gn];if(a?.profileBands)return a.profileBands}return Hs[gn].profileBands}var Ij=(t,e)=>(t||0)+(e||0);function iE(t,e){let r=Array.isArray(t)?t[0]:t;return r===void 0||Number.isNaN(r)?rE:r<=e[Iu]&&Iu||r<=e[gu]&&gu||xl}function Fl({score:t}){let e=t?.sets??[],r=e.reduce((o,i)=>(o[0]+=i.side1Score||0,o[1]+=i.side2Score||0,o),[0,0]),n=e.reduce((o,i)=>(o[0]+=i.side1TiebreakScore||0,o[1]+=i.side2TiebreakScore||0,o),[0,0]);return n.reduce(Ij)&&(r[n[0]>n[1]?0:1]+=1),{sets:e,games:r,score:t}}function Sj(t){let e=t?.games;if(!e?.length)return;let r=Math.max(...e);if(r===0)return;let n=Math.min(...e);return Math.round(n/r*100)}function sE(t){return t.map(Sj).filter(e=>e!==void 0).sort((e,r)=>e-r).map(e=>parseFloat(e.toFixed(2)))}function js({tournamentRecord:t,profileBands:e,matchUp:r}){if(!r)return{error:Xe};let{score:n,winningSide:o}=r;if(!o)return{error:O};let i=e||oE({tournamentRecord:t}),s=Fl({score:n}),a=sE([s]),c=iE(a,i),u=Array.isArray(a)?a[0]:a;return{...P,competitiveness:c,pctSpread:u}}function aE({groupedOrder:t,roundPositionsCount:e}){if(!t||t?.length<=e)return t;let n=he(t,t.length/e).map(i=>i.reduce((s,a)=>s+a)),o=n.slice().sort(Zt);return n.map(i=>o.indexOf(i)+1)}function rS(t){if(!Tt(t))return!1;let{matchUpId:e,drawPositions:r}=t,n=typeof e=="string",o=!r||Array.isArray(r)&&r.length<=2&&r.every(i=>yt(i)||i===void 0||i===null);return n&&o}function Rr(t){return Array.isArray(t)?t.every(rS):!1}function hj(t,e){return e?.find(r=>t.includes(r))}function Ue({matchUps:t=[],interpolate:e}){if(!Rr(t))return{roundMatchUps:[],error:O};let r=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?st(l.roundNumber):l.roundNumber;return!l.roundNumber||d.includes(f)?d:d.concat(f)},[]).sort(Zt).map(d=>{let l=t.filter(S=>S.roundNumber===d),g=l.find(({matchUpType:S})=>S===xt)?l.filter(({matchUpType:S})=>S===xt):l,I=S=>S.sort((h,T)=>Zt(h.roundPosition,T.roundPosition));return{[d]:I(g)}}),n=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?st(l.roundNumber):l.roundNumber;return d[f]||(d[f]=et({abbreviatedRoundName:l.abbreviatedRoundName,finishingRound:l.finishingRound,roundName:l.roundName})),d},{}),o=Object.assign({},...r);if(e){let d=Math.max(...Object.keys(o).map(f=>st(f)).filter(f=>!Number.isNaN(f))),l=o[d]?.length;if(l>1&&en(l)){let f=d+1,g=f+l/2;Q(f,g).forEach((S,h)=>{o[S]=Q(0,l/(2+h*2)).map(()=>({}))})}}let i=0,s=Object.assign({},...Object.keys(o).map(d=>{let l=o[d]?.length,f=o[d]?.filter(I=>!Ot.includes(I.matchUpStatus)&&!I.score?.scoreStringSide1)?.length,g=l&&l===f;return i=Math.max(i,l),{[d]:{matchUpsCount:l,inactiveCount:f,inactiveRound:g}}})),a=0,c=0,u=Object.keys(o).map(d=>st(d)).filter(d=>!Number.isNaN(d));u.forEach(d=>{let l=o[d].sort((g,I)=>g.roundPosition-I.roundPosition),f=l.flatMap(g=>g?.drawPositions??[]);if(s[d].roundNumber=d,s[d].roundFactor=s[d].matchUpsCount?i/s[d].matchUpsCount:1,s[d].finishingRound=n[d]?.finishingRound,s[d].roundName=n[d]?.roundName,s[d].abbreviatedRoundName=n[d]?.abbreviatedRoundName,s[d].finishingPositionRange=o[d]?.[0]?.finishingPositionRange,d===1||!s[d-1]){let g=f.sort(Zt),I=he(g,2);s[d].drawPositions=g,s[d].pairedDrawPositions=I}else{let g=s[d-1],I=g.drawPositions,S=g.matchUpsCount/s[d].matchUpsCount,h=he(I,S),T=l.map(y=>{let{roundPosition:E}=y,A=[...y.drawPositions??[],void 0,void 0].slice(0,2);if(!E)return A;let N=A?.filter(Boolean)??[];if(!N?.length)return[void 0,void 0];if(d<3&&N?.length===2)return A?.slice().sort(Zt);let D=Yt(I,N).length!==N?.length;if(N?.length&&D)return N?.length===1?[N[0],void 0]:A?.slice().sort(Zt);let R=(E-1)*2;return h.slice(R,R+2).map(b=>hj(b,N))});s[d].drawPositions=T?.flat(),s[d].pairedDrawPositions=T}s[d+1]?.matchUpsCount===s[d].matchUpsCount&&(s[d+1].feedRound=!0,s[d+1].feedRoundIndex=c,s[d].preFeedRound=!0,c+=1),s[d]&&!s[d].feedRound&&(s[d].roundIndex=a,a+=1)});let p=!!Object.values(s).some(({matchUpsCount:d})=>!en(d));return{hasNoRoundPositions:t.some(d=>!d.roundPosition),roundsNotPowerOf2:p,maxMatchUpsCount:i,roundMatchUps:o,roundNumbers:u,roundProfile:s,...P}}function kl(t){if(!Array.isArray(t))return"";let e=t.filter(Le);return e.length?pt([Math.min(...e),Math.max(...e)]).join("-"):""}function vL({drawDefinition:t,structureId:e,matchUpsMap:r}){let n=dt({drawDefinition:t,structureId:e},[Kt,mo]);if(n.error)return n;let{structure:o}=tt({drawDefinition:t,structureId:e});if(o?.stage!==me)return{error:cc,info:"Structure is not CONSOLATION stage"};let{links:i}=t,s=i?.filter(d=>d.target.structureId===e)??[],a=s?.reduce((d,l)=>{let{structureId:f}=l.source;return d.includes(f)?d:d.concat(f)},[])??[],c=Object.assign({},...a.map(d=>{let l=jo({structureId:d,matchUpsMap:r}),g=Ue({matchUps:l}).roundProfile;return{[d]:g}})),u=jo({matchUpsMap:r,structureId:e}),{roundProfile:p}=Ue({matchUps:u}),m={};return s?.forEach(d=>{let{structureId:l,roundNumber:f}=d.source,{feedProfile:g,groupedOrder:I,positionInterleave:S,roundNumber:h}=d.target,T=c[l],y=T[1]?.drawPositions,A=T[f]?.matchUpsCount;if(!A)return;let N=A?y.length/A:0,D=y.length/N,R=y.slice(),U=aE({roundPositionsCount:D,groupedOrder:I}),b=U?.length||1;if(b<=D){let w=y.length/b,L=he(R,w);g===Fi&&L.forEach(F=>F.reverse()),R=U?.length&&U?.map(F=>L[F-1]).flat()||L.flat()}let C=he(R,N);if(S){let w=Q(0,S.interleave).map(()=>{}),L=Q(0,S.offset).map(()=>{});C=C.map(x=>[x,...w]),C.unshift(L),C=C.flat(1);let F=C.length-S.offset;C=C.slice(0,F)}m[h]||(m[h]={});let v=p?.[h]?.feedRound?2:1;C.forEach((w,L)=>{let F=1+L*v;m[h][F]||(m[h][F]=kl(w))})}),{sourceDrawPositionRanges:m}}function Gl({drawDefinition:t}){if(typeof t!="object")return{error:ha};let e={},{structures:r=[],links:n=[]}=t??{},o=r.reduce((s,a)=>{let{stage:c}=a;return s[c]?s[c].push(a):s[c]=[a],s},{});for(let s of Object.keys(o)){let a=o[s].find(({stageSequence:p})=>p===1);if(!a)continue;let{structureId:c}=a;i({aggregator:{},targetRound:0,exitProfiles:e,exitProfile:"0",structureId:c,stage:s})}return{exitProfiles:e};function i({exitProfiles:s,exitProfile:a,structureId:c,targetRound:u,aggregator:p,stage:m}){s[c]||(s[c]=[]),a==="0"&&[me,Vt].includes(m)||s[c].push(a);let d=n.filter(l=>l.source.structureId===c&&l.source.roundNumber>=u);for(let l of d){let f=l.source.roundNumber,g=l.target.roundNumber,I=l.target.structureId,S=r.find(T=>T.structureId===I).stage,h=[S,I,g,f].join("|");if(p[h])return;p[h]=!0,i({exitProfile:`${a}-${f}`,structureId:I,exitProfiles:s,targetRound:g,aggregator:p,stage:S})}}}function OL({drawDefinition:t,roundProfile:e,structureId:r,matchUpsMap:n}){let o=dt({drawDefinition:t,structureId:r},[Kt,mo]);if(o.error)return o;if(!e){let u=jo({matchUpsMap:n,structureId:r});if({roundProfile:e}=Ue({matchUps:u}),!e)return{error:nt}}let s=(Math.min(...e?.[1]?.drawPositions??[])||1)-1,a=Object.keys(e);return{drawPositionsRanges:Object.assign({},...(a??[]).map(u=>{let p=e?.[u]?.matchUpsCount,m=e?.[1]?.drawPositions??[],d=he(m,m.length/p),l=d.map(kl),f=d.map(T=>T.map(y=>y-s)).map(kl),g=a.map(T=>{if(T>u)return;let y=e?.[T]?.drawPositions??[];return he(y,y.length/p)}).filter(Boolean),I=Q(0,p).map(T=>g.map(y=>y[T]).flat().filter(Boolean).sort(Zt)).map(T=>pt(T)),S=I.map(T=>dw(T).map(kl).join(", ")),h=Object.assign({},...Q(0,p).map(T=>({[T+1]:{firstRoundDrawPositionsRange:l[T],firstRoundOffsetDrawPositionsRange:f[T],possibleDrawPositions:I[T],drawPositionsRange:S[T]}})));return{[u]:h}}))}}var Tj=new Set([ai,ki]);function an(t){return!!t&&Tj.has(t)}function nS({structure:t,matchUps:e}){e=e??t?.matchUps??[];let r=Ue({matchUps:e}),n=r.roundProfile,o=r.roundNumbers;if(!n||!o?.length||o.length<2)return!1;let i=[...o].sort((s,a)=>s-a);for(let s=0;s<i.length-1;s++){let a=n[i[s]]?.matchUpsCount??0,c=n[i[s+1]]?.matchUpsCount??0;if(a%2===1&&c%2===0)return!0}return!1}function Pc({roundsNotPowerOf2:t,drawDefinition:e,structure:r,matchUps:n}){return!r||(n=n??r.matchUps??[],t=t??Ue({matchUps:n}).roundsNotPowerOf2,!(!!r.positionAssignments?.find(({drawPosition:i})=>i)||!!n?.find(({drawPositions:i})=>i?.length))||r?.structures)||e?.drawType&&an(e.drawType)||!t?!1:nS({structure:r,matchUps:n})}function Ae({structure:t}){if(!t)return!1;let e=t.matchUps||t.roundMatchUps&&Object.values(t.roundMatchUps).flat(),r=!!e?.find(o=>o?.roundPosition),n=!!e?.find(o=>o?.drawPositions?.length);return t?.stage===Fe?t?.structures||t?.structureType===su&&n?!1:t?.finishingPosition===po:!t?.structures&&(!e.length||!r&&!n)}var oS={[Fo]:{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:{[W]:"",[Vt]:"P",[Z]:"Q",[me]:"C"}}},_L=oS;function cE({roundNamingPolicy:t,drawDefinition:e,structure:r,matchUps:n}){let{roundProfile:o,roundMatchUps:i}=Ue({matchUps:n}),{structureAbbreviation:s,stage:a}=r,c=Ae({structure:r}),u=Pc({structure:r}),p=r.structures,m={},d=oS[Fo],l=r.stage===Z,f=l?Math.max(...(e?.structures??[]).filter(_=>_.stage===Z).map(({stageSequence:_})=>_??1),0):0,g=(r.stageSequence??1)<f?r.stageSequence??1:"",I=g&&(t?.affixes?.preQualifying||d.affixes.preQualifying)||"",S=t?.roundNamingMap||(d.roundNamingMap??{}),h=t?.abbreviatedRoundNamingMap||(d.abbreviatedRoundNamingMap??{}),T=t?.affixes?.preFeedRound||d.affixes.preFeedRound,y=t?.affixes?.roundNumber||d.affixes.roundNumber,A=(t?.namingConventions||d.namingConventions).round,N=a&&a!==W?a[0]:"",D=t?.stageConstants||d.stageConstants,R=a&&D?.[a]||N,U=`${I}${R}${g}`,b=o?Object.keys(o):[],C=l&&D?.[Z]?`${D?.[Z]}-`:"";if(p||c||u)Object.assign(m,...b.map(_=>{let v=`${C}${A} ${_}`,w=`${y}${_}`;return{[_]:{roundName:v,abbreviatedRoundName:w}}}));else{let _=l&&(t?.qualifyingFinishMap||(d?.qualifyingFinishMap??{}));Object.assign(m,...b.map(v=>{if(!o?.[v])return;let{matchUpsCount:w,preFeedRound:L}=o[v],F=w*2,x=_?.[o?.[v].finishingRound]||_&&`${y}${F}`||S[w]||`${y}${F}`,k=L?`-${T}`:"",G=`${x}${k}`,V=[U,s,G].filter(Boolean).join("-"),z=`${h[w]||`${y}${F}`}${k}`,H=[U,s,z].filter(Boolean).join("-");return{[v]:{abbreviatedRoundName:H,roundName:V}}}))}return{roundNamingProfile:m,roundProfile:o,roundMatchUps:i}}function uE({matchUp:t}){if(!t)return{error:Xe};if(t&&!t.sides)return{error:cr};if(t&&!t.hasContext)return{error:ap};let e=(t.sides??[])?.map(a=>a?.participantId).filter(Boolean),r=t.sides?.filter(a=>a.participant?.participantType===St).map(a=>a.participantId).filter(Boolean)??[],o=((t.sides??[])?.map(a=>a.participant?.individualParticipants).filter(Boolean)??[]).map(a=>(a??[]).map(c=>c?.participantId).filter(Boolean)),i=[...r,...o.flat()].filter(Boolean)??[],s=pt(i.concat(e)).filter(Boolean)??[];return{nestedIndividualParticipantIds:o,allRelevantParticipantIds:s,individualParticipantIds:i,sideParticipantIds:e,...P}}var Vl="CHECK_IN",Bl="CHECK_OUT",yj="SCHEDULE",Ts="SCHEDULE.ASSIGNMENT.VENUE",Io="SCHEDULE.ALLOCATION.COURTS",li="SCHEDULE.ASSIGNMENT.COURT",hu="SCHEDULE.COURT.ORDER",Tu="SCHEDULE.COURT.ANNOTATION",ys="SCHEDULE.DATE",Ej="COMPLETED.DATE",Wl="HOME_PARTICIPANT_ID",iS="SCHEDULE.ASSIGNMENT.OFFICIAL",Es="SCHEDULE.TIME.SCHEDULED",fi="SCHEDULE.TIME.START",Fa="SCHEDULE.TIME.STOP",qs="SCHEDULE.TIME.RESUME",As="SCHEDULE.TIME.END",rd="SCHEDULE.TIME.MODIFIERS",xL="TO_BE_ANNOUNCED",wL="NEXT_AVAILABLE",LL="FOLLOWED_BY",FL="AFTER_REST",kL="RAIN_DELAY",Aj="NOT_BEFORE",pE=[xL,wL,LL,FL,kL],Pj="ELIGIBILITY",Nj="REGISTRATION",Dj="SUSPENSION",Uj="MEDICAL",Rj="PENALTY",Tb="SCALE",yb="RATING",Eb="RANKING",sS="SEEDING",qo="PUBLISH",br="PUBLIC",$o="STATUS",bj="MODIFICATION",Cj="RETRIEVAL",Mj="other",GL={MUTUALLY_EXCLUSIVE_TIME_MODIFIERS:pE,AFTER_REST:FL,ALLOCATE_COURTS:Io,ASSIGN_COURT:li,ASSIGN_OFFICIAL:iS,ASSIGN_VENUE:Ts,CHECK_IN:Vl,CHECK_OUT:Bl,COMPLETED_DATE:Ej,COURT_ANNOTATION:Tu,COURT_ORDER:hu,ELIGIBILITY:Pj,END_TIME:As,FOLLOWED_BY:LL,MEDICAL:Uj,MODIFICATION:bj,NEXT_AVAILABLE:wL,NOT_BEFORE:Aj,OTHER:Mj,PENALTY:Rj,PUBLIC:br,PUBLISH:qo,RANKING:Eb,RATING:yb,RAIN_DELAY:kL,REGISTRATION:Nj,RESUME_TIME:qs,RETRIEVAL:Cj,SCALE:Tb,SCHEDULE:yj,SCHEDULED_DATE:ys,SCHEDULED_TIME:Es,SEEDING:sS,START_TIME:fi,STATUS:$o,STOP_TIME:Fa,SUSPENSION:Dj,TIME_MODIFIERS:rd,TO_BE_ANNOUNCED:xL};function $s({matchUp:t}){if(!t)return{error:Xe};if(!t.hasContext)return{error:ap};if(!t.sides||t?.sides.filter(Boolean).length!==2)return{error:cr};let{nestedIndividualParticipantIds:e,allRelevantParticipantIds:r,sideParticipantIds:n}=uE({matchUp:t}),i=(t.timeItems??[]).filter(u=>u?.itemType&&[Vl,Bl].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===Vl);e?.forEach((u,p)=>{let m=n?.[p],d=u?.length&&u.every(l=>a.includes(l));m&&d&&!a.includes(m)&&a.push(m)}),n?.forEach((u,p)=>{a.includes(u)&&(e?.[p]??[]).forEach(m=>{m&&!a.includes(m)&&a.push(m)})});let c=n?.reduce((u,p)=>a.includes(p)&&u,!0);return{allRelevantParticipantIds:r,allParticipantsCheckedIn:c,checkedInParticipantIds:a,...P}}var re=t=>e=>{let r=Tt(e)&&e?.matchUpType||wt(e)&&e;return r&&CT[t].includes(r)};function nd(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 od(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 mE({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 VL({tournamentScheduling:t,eventScheduling:e,averageMinutes:r,defaultTiming:n,matchUpFormat:o,categoryName:i,categoryType:s,policy:a}){let c=e?.matchUpRecoveryTimes&&od({...e,averageMinutes:r,matchUpFormat:o}),u=t?.matchUpRecoveryTimes&&od({...t,averageMinutes:r,matchUpFormat:o}),p=a?.matchUpRecoveryTimes&&od({...a,averageMinutes:r,matchUpFormat:o}),m=[c,u,p,a?.defaultTimes?.recoveryTimes,n?.recoveryTimes];return mE({categoryName:i,categoryType:s,timesBlockArray:m})}function BL({matchUpFormat:t,categoryName:e,categoryType:r,defaultTiming:n,tournamentScheduling:o,eventScheduling:i,policy:s}){let a=i?.matchUpAverageTimes&&nd({...i,matchUpFormat:t}),c=o?.matchUpAverageTimes&&nd({...o,matchUpFormat:t}),u=s?.matchUpAverageTimes&&nd({...s,matchUpFormat:t}),p=[a,c,u,s?.defaultTimes?.averageTimes,n?.averageTimes];return mE({categoryName:e,categoryType:r,timesBlockArray:p})}var Ab="DOUBLES_SINGLES",Pb="SINGLES_DOUBLES",So="total",dE="participantConflict",lE="potentialParticipantConflict",gi="matchUpConflict",Nb="courtDoubleBooking",Db="positionLinkConflict",Ub="ISSUE_IDS",Ks="CONFLICT",zs="WARNING",Hl="ERROR",Yl="ISSUE",aS="STATE",vj="BLOCKED",Oj="PRACTICE",_j="MAINTENANCE",WL={SINGLES_DOUBLES:Pb,DOUBLES_SINGLES:Ab,TOTAL:So,CONFLICT_MATCHUP_ORDER:gi,CONFLICT_PARTICIPANTS:dE,CONFLICT_POTENTIAL_PARTICIPANTS:lE,CONFLICT_COURT_DOUBLE_BOOKING:Nb,CONFLICT_POSITION_LINK:Db,SCHEDULE_ISSUE_IDS:Ub,SCHEDULE_CONFLICT:Ks,SCHEDULE_WARNING:zs,SCHEDULE_ERROR:Hl,SCHEDULE_ISSUE:Yl,SCHEDULE_STATE:aS,BLOCKED:vj,PRACTICE:Oj,MAINTENANCE:_j};function Fp({defaultAverageMinutes:t=90,defaultRecoveryMinutes:e=0,tournamentRecord:r,matchUpFormat:n,categoryName:o,categoryType:i,eventType:s,event:a}){if(!r)return{error:j};s=s??a?.eventType??ba;let c={averageTimes:[{minutes:{default:t}}],recoveryTimes:[{minutes:{default:e}}]},{scheduleTiming:u}=Ac({tournamentRecord:r,categoryName:o,categoryType:i,event:a}),p={...u,matchUpFormat:n,categoryType:i,defaultTiming:c};return id({eventType:s,timingDetails:p})}function id({timingDetails:t,eventType:e}){let r=BL(t),n=Object.keys(r?.minutes??{}),o=r?.minutes&&(n?.includes(e)&&r.minutes[e]||r.minutes.default),i=VL({...t,averageMinutes:o}),s=Object.keys(i?.minutes??{}),a=i?.minutes&&(s?.includes(e)&&i.minutes[e]||i.minutes.default),c=re(ba)(e)?Pb:Ab,u=i?.minutes&&(s?.includes(c)&&i.minutes[c]||a);return{averageMinutes:o,recoveryMinutes:a,typeChangeRecoveryMinutes:u}}function Rb(t){return t.createdAt?new Date(t.createdAt).getTime():0}function Ii({timeItems:t,itemType:e}){let r=t.filter(o=>o&&o.itemType===e).sort((o,i)=>Rb(o)-Rb(i)).pop(),n=r&&Rb(r);return{itemValue:r?.itemValue,timeStamp:n}}function jl({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Ii({timeItems:r?.timeItems??[],itemType:Es});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{scheduledTime:n}:e}function Qs({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Ii({timeItems:r?.timeItems??[],itemType:ys});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{scheduledDate:n}:e}function sd(t){if(ZT.test(t)){let e=SI();return new Date(`${e}T${t}`)}else return new Date(t)}function HL({matchUp:t}){if(!t)return{error:Xe};if(!t.timeItems)return{error:rI};let e=t.timeItems.filter(n=>[fi,Fa,qs,As].includes(n?.itemType)).sort((n,o)=>sd(n.itemValue).getTime()-sd(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 fi:i=0;break;case As:if(n.lastValue&&[fi,qs].includes(n.lastType)){let u=sd(o.itemValue).getTime()-sd(n.lastValue).getTime();i=n.milliseconds+u}else i=n.milliseconds;break;case Fa:if([fi,"SCHECULE.TIME.RESUME"].includes(n.lastType)){let u=sd(o.itemValue).getTime()-sd(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([fi,qs].includes(r.lastType)){let n=new Date().getTime()-sd(r.lastValue).getTime();r.milliseconds+=n}return{milliseconds:r.milliseconds,time:xj(r.milliseconds),relevantTimeItems:e}}function xj(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 YL({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===fi&&s;return a&&(!i||r(a)<r(i))?a:i},void 0)?.itemValue}}function fE(t){return parseInt(t)}function ql({startTime:t="",endTime:e=""}={}){if(!t||!e||!ru.test(t)||!ru.test(e))return!1;let[r,n]=t.split(":").map(fE),[o,i]=e.split(":").map(fE);return o<r?!1:!(r===o&&i<n)}function jL(t,e){let[r,n]=t.startTime.split(":").map(fE),[o,i]=e.startTime.split(":").map(fE);return r<o?-1:r>o?1:n<i?-1:n>i?1:0}function kp({dateAvailability:t}){if(!t)return{error:iU};if(!Array.isArray(t))return{error:$g};for(let e of t){if(typeof e!="object")return{error:$g};let{date:r,startTime:n,endTime:o,bookings:i=[]}=e;if(!n||!o)return{error:$g};let s=Lj(r);if(s)return s;let a=$L(n,o);if(a)return a;if(i){let c=Fj(i);if(c)return c}}return{valid:!0}}var wj="Dates must be formated => YYYY-MM-DD",qL="Times must be 24 hour => 00:00";function Lj(t){if(t&&!_o.test(t))return{error:ae,dateAvailability:{date:t},info:wj}}function $L(t,e){if(!ru.test(t))return{error:ws,dateAvailability:{startTime:t},info:qL};if(!ru.test(e))return{error:ws,dateAvailability:{endTime:e},info:qL};if(t===e)return{error:ws,dateAvailability:{startTime:t,endTime:e},info:"startTime and endTime are equivalent"};if(!ql({startTime:t,endTime:e}))return{error:ws,dateAvailability:{startTime:t,endTime:e},info:"endTime must be after startTime"}}function Fj(t){if(!Array.isArray(t))return{error:il};for(let e of t){if(typeof e!="object")return{error:il};let{startTime:r,endTime:n}=e,o=$L(r,n);if(o)return o}}function gE({tournamentRecord:t}){for(let e of t.venues??[])e.isPrimary&&delete e.isPrimary}function yu(t){let{disableNotice:e,venue:r,context:n}=t;if(typeof r!="object")return{error:O};let o=Dr(t);r.venueId??=it();let i;for(let s of Object.values(o)){let a=kj({disableNotice:!0,tournamentRecord:s,context:n,venue:r});if(a?.error)return a;i=a.venue}return e||at({topic:$y,payload:{venue:r}}),et({...P,venue:i})}function kj({tournamentRecord:t,disableNotice:e,context:r,venue:n}){let o=dt({tournamentRecord:t},[rt]);if(o.error)return o;if(!n)return{error:nt,info:"missing venue"};if(t.venues??=[],n.venueId??=it(),t.venues.reduce((s,a)=>s||a.venueId===n.venueId,void 0))return{error:UU};if(n.dateAvailability?.length){let s=kp({dateAvailability:n.dateAvailability});if(s.error)return s}if(n.defaultStartTime||n.defaultEndTime){if(!n.defaultStartTime||!n.defaultEndTime)return{error:O,info:"both defaultStartTime and defaultEndTime are required"};if(!ql({startTime:n.defaultStartTime,endTime:n.defaultEndTime}))return{error:O,info:"defaultEndTime must be after defaultStartTime"}}return r&&ut({element:n,extension:{value:r,name:xR}}),n.isPrimary&&gE({tournamentRecord:t}),t.venues.push(n),e||at({payload:{venue:n,tournamentId:t.tournamentId},topic:$y}),{...P,venue:q(n)}}function Ln({tournamentRecords:t,tournamentRecord:e,venueId:r}){let n=dt({tournamentRecord:e,venueId:r},[rt,Tp]);if(n.error)return n;let i=(e.venues??[]).reduce((s,a)=>a.venueId===r?a:s,void 0);if(!i&&t){let a=(bp({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let c of a){let u=t[c],p=Ln({tournamentRecord:u,venueId:r});if(p.success&&p.venue)return yu({tournamentRecord:e,venue:p.venue}),{...P,venue:i}}}return i?{...P,venue:i}:{error:wi}}function IE({convertExtensions:t,...e}){let{tournamentRecords:r,tournamentRecord:n,venueId:o}=e,i=Ln({tournamentRecords:r,tournamentRecord:n,venueId:o});return q(i,t,!0)}function Si({tournamentRecords:t,tournamentRecord:e,courtId:r}){let n=dt({tournamentRecord:e,courtId:r},[rt,Ws]);if(n.error)return n;let o="findCourt",i,s;if((e.venues??[]).forEach(a=>{(a.courts??[]).forEach(c=>{c.courtId===r&&(i=c,s=a)})}),i)return{...P,court:i,venue:s};if(t){let c=(bp({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let u of c){let p=t[u],m=Si({tournamentRecord:p,courtId:r});if(m.success)return m.venue&&yu({tournamentRecord:e,venue:m.venue}),{...P,court:i,venue:s}}}return M({result:{error:vo},stack:o})}function SE(t){return q(Si(t),!1,!0)}function $l({tournamentRecord:t,internalUse:e,courtId:r}){let n=dt({tournamentRecord:t,courtId:r},[rt,Ws]);if(n.error)return n;let o=Si({tournamentRecord:t,courtId:r});if(o.error)return o;let i=o.court&&(({altitude:s,courtId:a,courtName:c,courtDimensions:u,latitude:p,longitude:m,surfaceCategory:d,surfaceType:l,surfacedDate:f,pace:g,notes:I})=>({altitude:s,courtId:a,courtName:c,courtDimensions:u,latitude:p,longitude:m,surfaceCategory:d,surfaceType:l,surfacedDate:f,pace:g,notes:I}))(o.court);return{...P,courtInfo:q(i,!1,e)}}function Eu(t){let e=X(t,[{[rt]:!0},{venueId:!0,[jr]:Ls}]);if(e.error)return e;let{tournamentRecord:r,venueId:n}=t,o=Ln({tournamentRecord:r,venueId:n});if(o.error)return o;let s=(o.venue?.courts??[]).map(u=>(({courtInfo:p})=>({...p}))($l({courtId:u.courtId,internalUse:!0,tournamentRecord:r}))),a=o.venue&&(({venueId:u,venueName:p,venueAbbreviation:m})=>({venueAbbreviation:m,venueName:p,venueId:u}))(o.venue),c=a&&{...a,courtsInfo:s};return{...P,venueData:q(c,!1,!0)}}function KL({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===As&&s;return a&&(!i||r(a)>r(i))?a:i},void 0)?.itemValue}}function Bt({event:t,eventId:e}){if(!t)return{error:le};let n=ot({name:on,element:t})?.extension,o=e?q(n?.value,!1,!0):n?.value;return e&&t.drawDefinitions?.forEach(i=>{o?.flights?.forEach(s=>{s.drawId===i.drawId&&Object.assign(s,{drawDefinition:i})})}),{flightProfile:o}}function _e(t){let{tournamentRecord:e,eventId:r,drawId:n}=t,o="findEvent",i={},s=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},a=Object.values(s).map(({events:u,tournamentId:p})=>(u&&u.forEach(m=>{i[m.eventId]={tournamentId:p}}),u??[])).flat(),c;if(n){let u,p=a.find(m=>{let l=(m?.drawDefinitions??[]).find(f=>f.drawId===n);if(l)u=l,c=i[m.eventId].tournamentId;else{let g=(m&&Bt({event:m})?.flightProfile)?.flights?.find(I=>I.drawId===n);if(g)return c=i[m.eventId].tournamentId,{entries:g.drawEntries,drawName:g.drawName,tournamentId:c,drawId:n}}return l});if(p)return{event:p,drawDefinition:u,tournamentId:c}}if(r){let u=a.find(p=>p?.eventId===r);if(u)c=i[u.eventId].tournamentId;else return{event:void 0,drawDefinition:void 0,...M({result:{error:Wr},stack:o})};return{event:u,drawDefinition:void 0,tournamentId:c}}return{event:void 0,drawDefinition:void 0,...M({result:{error:Mr},context:{drawId:n,eventId:r},stack:o})}}function Kl(t){let e=t.event,r=t.matchUpType,{scheduleVisibilityFilters:n,afterRecoveryTimes:o,tournamentRecord:i,usePublishState:s,scheduleTiming:a,matchUpFormat:c,publishStatus:u,matchUp:p}=t;if(!p)return{error:Xe};if(o&&!p.matchUpType&&!t.matchUpType&&(e||i)&&p.drawId){let N=t.drawDefinition||e?.drawDefinitions?.find(R=>R.drawId===p.drawId);!N&&i&&({drawDefinition:N,event:e}=_e({drawId:p.drawId,tournamentRecord:i}));let D=p.structureId&&N?.structures?.find(({structureId:R})=>R===p.structureId);r=t.matchUpType||D?.matchUpType||N?.matchUpType||e?.eventType!==Oe&&e?.eventType}let{milliseconds:m,time:d}=HL({matchUp:p}),{startTime:l}=YL({matchUp:p}),{endTime:f}=KL({matchUp:p}),{eventIds:g,drawIds:I}=n??{},h=(!g||g.includes(p.eventId))&&(!I||I.includes(p.drawId))?Gj({tournamentRecord:i,scheduleTiming:a,afterRecoveryTimes:o,matchUpFormat:c,matchUpType:r,matchUp:p,endTime:f,startTime:l,milliseconds:m,time:d}):et({milliseconds:m,startTime:l,endTime:f,time:d}),{scheduledDate:T}=Qs({matchUp:p}),{scheduledTime:y}=jl({matchUp:p});if(s&&u?.displaySettings?.draws){let N=u.displaySettings.draws,D=(N?.[p.drawId]??N?.default)?.scheduleDetails;if(D){let R=(D.find(U=>T&&U.dates?.includes(T))??D.find(U=>!U.dates?.length))?.attributes;if(R){let U=Object.assign({},...Object.keys(h).map(b=>({[b]:!0})),R);h=hs({source:h,template:U})}}}let A=p.matchUpStatus&&Ot.includes(p.matchUpStatus)&&(mt(f)||mt(T)||mt(y))||void 0;return{schedule:h,endDate:A}}function Gj({tournamentRecord:t,scheduleTiming:e,afterRecoveryTimes:r,matchUpFormat:n,matchUpType:o,matchUp:i,endTime:s,startTime:a,milliseconds:c,time:u}){let p=C=>C.createdAt?new Date(C.createdAt).getTime():0,m=new Map,d=i.timeItems?.toSorted((C,_)=>p(C)-p(_))??[];for(let C of d)m.set(C.itemType,C.itemValue);let l=m.get(Wl),f=m.get(Tu),g=m.get(Io),I=m.get(Es),S=m.get(rd),h=m.get(ys),T=m.get(iS),y=m.get(hu),E=m.get(Ts),A=m.get(li),N=Vj({scheduleTiming:e,afterRecoveryTimes:r,matchUpFormat:n,matchUpType:o,matchUp:i,endTime:s,scheduledTime:I});!h&&I&&(h=mt(I));let D=ll({scheduledDate:h,scheduledTime:I}),{venueName:R,venueAbbreviation:U,courtName:b}=Bj({tournamentRecord:t,allocatedCourts:g,venueId:E,courtId:A});return et({typeChangeTimeAfterRecovery:N.typeChangeTimeAfterRecovery,typeChangeRecoveryMinutes:N.typeChangeRecoveryMinutes,timeAfterRecovery:N.timeAfterRecovery,recoveryMinutes:N.recoveryMinutes,averageMinutes:N.averageMinutes,homeParticipantId:l,courtAnnotation:f,venueAbbreviation:U,allocatedCourts:g,scheduledDate:h,scheduledTime:I,isoDateString:D,timeModifiers:S,venueName:R,venueId:E,courtOrder:y,courtName:b,courtId:A,official:T,milliseconds:c,startTime:a,endTime:s,time:u})}function Vj({scheduleTiming:t,afterRecoveryTimes:e,matchUpFormat:r,matchUpType:n,matchUp:o,endTime:i,scheduledTime:s}){let a,c,u,p,m,d=o.matchUpType??n;if(t&&s&&e&&d){let l={matchUpFormat:o.matchUpFormat??r,...t};({averageMinutes:c=0,recoveryMinutes:u=0,typeChangeRecoveryMinutes:p=0}=id({timingDetails:l,eventType:d})),(c||u)&&(a=i?Yr($t(i),u):Yr(s,c+u)),p&&(m=i?Yr($t(i),p):Yr(s,c+p))}return{timeAfterRecovery:a,averageMinutes:c,recoveryMinutes:u,typeChangeRecoveryMinutes:p,typeChangeTimeAfterRecovery:m}}function Bj({tournamentRecord:t,allocatedCourts:e,venueId:r,courtId:n}){let o={},i=(t&&r&&Eu({tournamentRecord:t,venueId:r}))?.venueData??{};r&&(o[r]=i);let{venueName:s,venueAbbreviation:a,courtsInfo:c}=i,p=(n&&c?.find(m=>m.courtId===n))?.courtName;for(let m of e??[]){if(!t)break;m.venueId&&!o[m.venueid]&&(o[m.venueId]=Eu({venueId:m.venueId,tournamentRecord:t})?.venueData);let d=o[m.venueId];m.venueName=d?.venueName;let l=d?.courtsInfo?.find(f=>f.courtId===m.courtId);m.courtName=l?.courtName}return{venueName:s,venueAbbreviation:a,courtName:p}}function zL({drawPositions:t,roundProfile:e,roundNumber:r}){let n=[void 0,void 0];if(wT(t))return{orderedDrawPositions:n,displayOrder:n};let o=e?.[r],s=o?.pairedDrawPositions?.find(c=>Re(c??[],t.filter(Boolean)))??n,a=o?.feedRound;if(xT(t)){let c=[...t].sort(Zt);return{orderedDrawPositions:c.length===2?c:s,displayOrder:a?c:s}}if(a){let u=[t.find(p=>!isNaN(st(p))),void 0];return{orderedDrawPositions:u,displayOrder:u}}return{orderedDrawPositions:s,displayOrder:s}}function ad({collectionPosition:t,collectionId:e,lineUp:r}){let n=[],o=[];if(r){let i=a=>a===void 0?-1:a,s=r.map(a=>{let{collectionAssignments:c,participantId:u}=a,p=c?.find(m=>m.collectionPosition===t&&m.collectionId===e);return p&&{participantId:u,...p}}).filter(Boolean).sort((a,c)=>i(a.substitutionOrder)-i(c.substitutionOrder));for(let a of s){let{participantId:c,previousParticipantId:u,substitutionOrder:p}=a;n.includes(c)||(u&&o.push({previousParticipantId:u,substitutionOrder:p,participantId:c}),n=n.filter(m=>m!==u),n.push(c))}}return{assignedParticipantIds:n,substitutions:o}}function Tn({tournamentParticipants:t,tournamentRecord:e,participantIds:r}){let n="getPairedParticipant";if(!t&&!e)return{error:j};if(!Array.isArray(r)||r.length>2)return{error:_r};if(!r.length)return M({result:{error:Mo},stack:n});t=t??e?.participants??[];let o=t.filter(a=>a.participantType===lt&&Yt(r,a.individualParticipantIds).length===r.length&&a.individualParticipantIds.length===r.length),i=o[0];if(!i)return M({result:{error:ee},stack:n});let s=q(o.slice(1),!1,!0);return{participant:q(i),duplicatedPairParticipants:s,...P}}function Xs({drawDefinition:t,participantId:e}){if(typeof t!="object")return{error:$};if(typeof e!="string")return{error:We};let{extension:r}=ot({element:t,name:Vo});return{lineUp:(r?.value??{})[e]}}function QL({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}=ad({collectionPosition:r,collectionId:s,lineUp:d});if(c===Rt){if(f?.length<=2){let I=o?.[f[0]]?.pairIdMap?.[f[1]],T=(I&&o[I]?.participant||Tn({participantIds:f,tournamentParticipants:t}).participant)?.participantId;return{[m]:{participantId:T,teamParticipant:l,substitutions:g}}}else if(f?.length>2)return{[m]:{teamParticipant:l,substitutions:g}}}else{let I=f?.[0];return I&&{[m]:{participantId:I,teamParticipant:l,substitutions:g}}}};if(!n?.length){let m=a?.map(d=>{let{teamParticipant:l,sideNumber:f}=d,g=d.lineUp||Xs({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||Xs({participantId:d,drawDefinition:i})?.lineUp;return u({attribute:m,lineUp:g,teamParticipant:f})}).filter(Boolean)??{};return{drawPositionCollectionAssignment:Object.assign({},...p)}}function zl(t){let e=X(t,[{[Rn]:!0}]);if(e.error)return e;let r=t?.matchUp,n=r?.matchUpType;if(!n&&r?.sides?.length){let s=r.sides.find(({participant:a})=>a)?.participant?.participantType;n=s===St&&Ct||s===lt&&Rt||s===_t&&_t||void 0}return{matchUpType:n}}function XL({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?Wj({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 Wj({displaySideNumber:t,seedAssignments:e,participantId:r,assignment:n,sideNumber:o}){let i={drawPosition:n.drawPosition,displaySideNumber:t,sideNumber:o};if(r){let s=Hj({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 Hj({seedAssignments:t,participantId:e}){return t?.find(r=>!r.seedProxy&&r.participantId===e)}function Uo(t){let e=t?.embargo;return!e||!fs(e)?!1:new Date(e).getTime()>Date.now()}function ro(t){return!!t?.published&&!Uo(t)}function Yj({publishStatus:t,drawDefinition:e,structure:r,matchUp:n,schedule:o}){if(!t||!e?.drawId||!r?.structureId)return o;let i=t?.drawDetails?.[e.drawId]?.structureDetails?.[r.structureId];if(!i)return o;let s=n.roundNumber;if(!yt(s))return o;let a=i.scheduledRounds?.[s];if(!(a&&Uo(a)))return o}function jj({matchUp:t,collectionDefinition:e,structure:r,drawDefinition:n,event:o,tournamentRecord:i}){return t.processCodes?.length&&t.processCodes||e?.processCodes?.length&&e?.processCodes||r?.processCodes?.length&&r?.processCodes||n?.processCodes?.length&&n?.processCodes||o?.processCodes?.length&&o?.processCodes||i?.processCodes}function bb({scheduleVisibilityFilters:t,sourceDrawPositionRanges:e,tournamentParticipants:r,positionAssignments:n,drawPositionsRanges:o,hydrateParticipants:i,afterRecoveryTimes:s,initialRoundOfPlay:a,additionalContext:c,roundNamingProfile:u,tournamentRecord:p,tieDrawPositions:m,appliedPolicies:d,isCollectionBye:l,seedAssignments:f,usePublishState:g,participantMap:I,contextContent:S,scheduleTiming:h,contextProfile:T,drawDefinition:y,publishStatus:E,scoringActive:A,matchUpTieId:N,isRoundRobin:D,roundProfile:R,sideLineUps:U,structure:b,context:C,matchUp:_,event:v}){c=c??{};let w=ze({drawDefinition:y,structure:b,matchUp:_,event:v})?.tieFormat,{roundOffset:L,structureId:F,structureName:x,stage:k,stageSequence:G}=b,{drawId:V,drawName:B,drawType:z}=y??{},H=w?.collectionDefinitions,K=_.collectionId&&H?.find(Vn=>Vn.collectionId===_.collectionId),Y=_.collectionId?K?.matchUpFormat:_.matchUpFormat??b?.matchUpFormat??y?.matchUpFormat??v?.matchUpFormat,J=_.matchUpType||K?.matchUpType||b?.matchUpType||y?.matchUpType||!re(Oe)(v?.eventType)&&v?.eventType,ct=l?"BYE":_.matchUpStatus,{schedule:Et,endDate:Ht}=Kl({scheduleVisibilityFilters:t,afterRecoveryTimes:s,tournamentRecord:p,usePublishState:g,scheduleTiming:h,drawDefinition:y,matchUpFormat:Y,publishStatus:E,matchUpType:J,matchUp:_,event:v});g&&Et&&(Et=Yj({publishStatus:E,drawDefinition:y,structure:b,matchUp:_,schedule:Et}));let Ut=m??_.drawPositions??[],{collectionPosition:pe,collectionId:ye,roundPosition:Jt}=_,pr=_.roundNumber??c.roundNumber,Kn=ye?QL({tournamentParticipants:r,positionAssignments:n,collectionPosition:pe,participantMap:I,drawDefinition:y,drawPositions:Ut,collectionId:ye,sideLineUps:U,matchUpType:J}):void 0,zr=u?.[pr]?.roundName||c.roundName,so=u?.[pr]?.abbreviatedRoundName||c.abbreviatedRoundName,Zo=R?.[pr]?.feedRound,ti=R?.[pr]?.preFeedRound,la=R?.[pr]?.roundFactor,fa=o?.[pr],ga=Jt?fa?.[Jt]:void 0,bm=e?.[pr],Gc=K?.category?{...C?.category,...K.category}:C?.category??v?.category,Cm=jj({matchUp:_,collectionDefinition:K,structure:b,drawDefinition:y,event:v,tournamentRecord:p}),we=T?.withCompetitiveness&&js({...S,matchUp:_}),Ai=_.finishingPositionRange??c.finishingPositionRange,as=k!==Z&&yt(a)&&a+(pr||0),ic=Vn=>et(Vn,void 0,!0),An={...ic(C),...ic({matchUpFormat:J===Oe?void 0:Y,tieFormat:J===Oe?w:void 0,gender:K?.gender??v?.gender,endDate:_.endDate??Ht,discipline:v?.discipline,category:Gc,finishingPositionRange:Ai,abbreviatedRoundName:so,drawPositionsRange:ga,competitiveProfile:we,structureName:x,stageSequence:G,drawPositions:Ut,matchUpStatus:ct,processCodes:Cm,isRoundRobin:D,matchUpTieId:N,preFeedRound:ti,matchUpType:J,roundFactor:la,roundOffset:L,structureId:F,roundNumber:pr,roundOfPlay:as,feedRound:Zo,roundName:zr,drawName:B,drawType:z,schedule:Et,drawId:V,stage:k}),...q(ic(_),!0,!0)};if(Y&&_.score?.scoreStringSide1&&qj(An,Y),Array.isArray(Ut)){let Vn=$j({sourceDrawPositionRoundRanges:bm,collectionAssignmentDetail:Kn,positionAssignments:n,seedAssignments:f,drawPositions:Ut,roundPosition:Jt,roundProfile:R,roundNumber:pr,onlyDefined:ic,matchUp:_});Object.assign(An,q({sides:Vn},!0,!0))}if(r&&An.sides){if(Kj({tournamentParticipants:r,hydrateParticipants:i,positionAssignments:n,appliedPolicies:d,drawDefinition:y,participantMap:I,contextProfile:T,matchUpWithContext:An,event:v}),!An.matchUpType){let{matchUpType:Vn}=zl({matchUp:An});Vn&&Object.assign(An,{matchUpType:Vn})}Qj({contextProfile:T,matchUpWithContext:An})}An.tieMatchUps&&Xj({matchUpWithContext:An,abbreviatedRoundName:so,roundNumber:pr,roundName:zr,drawPositions:Ut,scheduleVisibilityFilters:t,sourceDrawPositionRanges:e,drawPositionsRanges:o,initialRoundOfPlay:a,roundNamingProfile:u,appliedPolicies:d,usePublishState:g,publishStatus:E,isRoundRobin:D,roundProfile:R,event:v,tournamentParticipants:r,positionAssignments:n,tournamentRecord:p,seedAssignments:f,participantMap:I,contextContent:S,scheduleTiming:h,contextProfile:T,drawDefinition:y,scoringActive:A,structure:b,context:C});let Vc=An.sides?.filter(Vn=>Vn?.participantId).length===2,tp=!An.winningSide;if(Object.assign(An,{readyToScore:A&&Vc&&tp,hasContext:!0}),Vc){let{allParticipantsCheckedIn:Vn,checkedInParticipantIds:UT}=$s({matchUp:An});Object.assign(An,{allParticipantsCheckedIn:Vn,checkedInParticipantIds:UT})}return Array.isArray(T?.exclude)&&T?.exclude.forEach(Vn=>delete An[Vn]),An}function qj(t,e){let r=oe(e),{bestOf:n,finalSetFormat:o,setFormat:i}=r??{};!o?.tiebreakSet&&!i?.tiebreakSet&&!i?.timed||(t.score.sets=t.score.sets.sort((s,a)=>s.setNumber-a.setNumber).map((s,a)=>{let p=a+1===n&&o?o:i,m=p?.tiebreakSet&&!p?.timed,d=p?.timed;return m?(s.tiebreakSet=!0,[1,2].includes(s.winningSide)&&(s.side1Score=s.winningSide===1?1:0,s.side2Score=s.winningSide===2?1:0)):d&&(s.timed=!0),s}))}function $j({sourceDrawPositionRoundRanges:t,collectionAssignmentDetail:e,positionAssignments:r,seedAssignments:n,drawPositions:o,roundPosition:i,roundProfile:s,roundNumber:a,onlyDefined:c,matchUp:u}){let{orderedDrawPositions:p,displayOrder:m}=zL({drawPositions:o,roundProfile:s,roundNumber:a}),d=s?.[a]?.feedRound,l=m[0]!==p[0];return p.concat(void 0,void 0).slice(0,2).map((g,I)=>{let S=I+1,h=l?3-S:S,T=XL({...e,positionAssignments:r,displaySideNumber:h,seedAssignments:n,drawPosition:g,isFeedRound:d,sideNumber:S}),y=u.sides?.find(N=>N.sideNumber===S),E=i?(i-1)*2+I+1:void 0,A=E?t?.[E]:void 0;return c({sourceDrawPositionRange:A,...y,...T})})}function Kj({tournamentParticipants:t,hydrateParticipants:e,positionAssignments:r,appliedPolicies:n,drawDefinition:o,participantMap:i,contextProfile:s,matchUpWithContext:a,event:c}){let u=n?.[xa],p=m=>{let d=i?.[m]?.participant;return d&&hs({template:u?.participant,source:d})};a.sides.filter(Boolean).forEach(m=>{if(zj({side:m,getMappedParticipant:p,tournamentParticipants:t,hydrateParticipants:e,positionAssignments:r,appliedPolicies:n,drawDefinition:o,contextProfile:s,event:c}),m?.participant?.individualParticipantIds?.length&&!m.participant.individualParticipants?.length){let d=m.participant.individualParticipantIds.map(l=>p(l)||(t?ui({policyDefinitions:n,tournamentParticipants:t,internalUse:!0,contextProfile:s,participantId:l}):void 0));e!==!1&&Object.assign(m.participant,{individualParticipants:d})}})}function zj({side:t,getMappedParticipant:e,tournamentParticipants:r,hydrateParticipants:n,positionAssignments:o,appliedPolicies:i,drawDefinition:s,contextProfile:a,event:c}){if(!t.participantId)return;let u=q(e(t.participantId)||(r?ui({policyDefinitions:i,participantId:t.participantId,tournamentParticipants:r,internalUse:!0,contextProfile:a}):void 0),void 0,!0);if(!u)return;let p,m;if(s?.entries){let l=s.entries.find(g=>g.participantId===t.participantId),f=c?.entries?.find(g=>g.participantId===t.participantId);p=l?.entryStatus||f?.entryStatus,u.entryStatus=p,l?.entryStage&&(m=l.entryStage,u.entryStage=m)}let d;t.drawPosition&&o&&o.find(f=>f.drawPosition===t.drawPosition)?.extensions?.some(f=>f.name==="luckyAdvancement")&&(d=!0,u.luckyAdvancement=!0),n===!1?Object.assign(t,{participant:{entryStage:m,entryStatus:p,luckyAdvancement:d}}):Object.assign(t,{participant:u})}function Qj({contextProfile:t,matchUpWithContext:e}){if(!(t?.inferGender&&(!e.gender||e.gender===ds)&&e.sides?.length===2&&e.matchUpType!==Oe))return;let n=e.sides.map(o=>{if(re(Ct)(e.matchUpType))return o.participant?.person?.sex;if(o.participant?.individualParticipants?.length===2){let i=pt(o.participant.individualParticipants.map(s=>s.person?.sex)).filter(Boolean);if(i.length===1)return i[0]}});n.filter(Boolean).length===2&&pt(n).length===1&&(e.inferredGender=n[0])}function Xj(t){let{matchUpWithContext:e}=t,r=e.matchUpStatus==="BYE",n=e.sides?.map(({participant:o,drawPosition:i,sideNumber:s,lineUp:a})=>{let c=o?.participantType===Oe&&o;return{teamParticipant:c&&et({participantRoleResponsibilities:c.participantRoleResponsibilities,participantOtherName:c.participantOtherName,participantName:c.participantName,participantId:c.participantId,teamId:c.teamId}),drawPosition:i,sideNumber:s,lineUp:a}});e.tieMatchUps=e.tieMatchUps.map(o=>{let i=e.matchUpId,a={finishingPositionRange:e.finishingPositionRange,abbreviatedRoundName:t.abbreviatedRoundName,roundNumber:t.roundNumber,roundName:t.roundName};return bb({tieDrawPositions:t.drawPositions,scheduleVisibilityFilters:t.scheduleVisibilityFilters,sourceDrawPositionRanges:t.sourceDrawPositionRanges,sideLineUps:n,drawPositionsRanges:t.drawPositionsRanges,initialRoundOfPlay:t.initialRoundOfPlay,roundNamingProfile:t.roundNamingProfile,additionalContext:a,appliedPolicies:t.appliedPolicies,isCollectionBye:r,usePublishState:t.usePublishState,publishStatus:t.publishStatus,matchUpTieId:i,isRoundRobin:t.isRoundRobin,roundProfile:t.roundProfile,matchUp:o,event:t.event,tournamentParticipants:t.tournamentParticipants,positionAssignments:t.positionAssignments,tournamentRecord:t.tournamentRecord,seedAssignments:t.seedAssignments,participantMap:t.participantMap,contextContent:t.contextContent,scheduleTiming:t.scheduleTiming,contextProfile:t.contextProfile,drawDefinition:t.drawDefinition,scoringActive:t.scoringActive,structure:t.structure,context:t.context})})}function JL({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Ii({timeItems:r?.timeItems??[],itemType:Io});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{allocatedCourts:q(n,!1,!0)}:e}function ZL({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Ii({timeItems:r?.timeItems??[],itemType:li});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{courtId:n}:e}function t0({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Ii({timeItems:r?.timeItems??[],itemType:Ts});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{venueId:n}:e}function zi(t){if(!Array.isArray(t.matchUps))return[];let{matchUps:e,excludeMatchUpStatuses:r,hasParticipantsCount:n,isCollectionMatchUp:o,matchUpStatuses:i,hasWinningSide:s,matchUpFormats:a,roundPositions:c,matchUpFormat:u,collectionIds:p,isMatchUpTie:m,roundNumbers:d,matchUpIds:l,roundNames:f,filterMatchUpTypes:g=!0,filterMatchUpIds:I=!0,stageSequences:S,scheduledDates:h,scheduledDate:T,participantIds:y,processContext:E,tournamentIds:A,matchUpTypes:N,structureIds:D,readyToScore:R,courtIds:U,eventIds:b,venueIds:C,drawIds:_,stages:v}=t,w=Array.isArray(y)?y.filter(Boolean):[],L=Array.isArray(i)?i.filter(Boolean):[],F=Array.isArray(r)?r.filter(Boolean):[],x=Array.isArray(v)?v.filter(Boolean):[],k=Array.isArray(S)?S.filter(Boolean):[],G=Array.isArray(p)?p.filter(Boolean):[],V=Array.isArray(f)?f.filter(Boolean):[],B=Array.isArray(d)?d.filter(Boolean):[],z=Array.isArray(c)?c.filter(Boolean):[],H=Array.isArray(l)&&I?l.filter(Boolean):[],K=Array.isArray(N)&&g?N.filter(Boolean):[],Y=Array.isArray(U)?U.filter(Boolean):[],J=Array.isArray(C)?C.filter(Boolean):[],ct=Array.isArray(a)&&a.filter(Boolean)||typeof u=="string"&&[u]||[],Et=Array.isArray(h)&&h.filter(Boolean).length&&h.filter(Boolean)||typeof T=="string"&&T.length&&[T]||[],Ht=Array.isArray(A)?A.filter(Boolean):[],Ut=Array.isArray(b)?b.filter(Boolean):[],pe=Array.isArray(_)?_.filter(Boolean):[],ye=Array.isArray(D)?D.filter(Boolean):[];return e.filter(Jt=>!(!Jj({matchUp:Jt,readyToScore:R,hasWinningSide:s,isMatchUpTie:m,isCollectionMatchUp:o})||!Zj({matchUp:Jt,targetStages:x,targetStageSequences:k,targetCollectionIds:G,targetRoundNames:V,targetRoundNumbers:B,targetRoundPositions:z,targetMatchUpStatuses:L,excludeTargetMatchUpStatuses:F,targetMatchUpIds:H,targetMatchUpTypes:K,targetMatchUpFormats:ct})||!tq({matchUp:Jt,targetScheduledDates:Et,targetCourtIds:Y,targetVenueIds:J})||E&&!eq({matchUp:Jt,targetTournamentIds:Ht,targetEventIds:Ut,targetDrawIds:pe,targetStructureIds:ye,targetParticipantIds:w,hasParticipantsCount:n})))}function Jj({matchUp:t,readyToScore:e,hasWinningSide:r,isMatchUpTie:n,isCollectionMatchUp:o}){return!(e&&!re(Ir)(t)&&!t.readyToScore||t.winningSide&&r&&![1,2].includes(t.winningSide)||n!==void 0&&(n&&!t.tieMatchUps||!n&&t.tieMatchUps)||o!==void 0&&(o&&!t.collectionId||!o&&t.collectionId))}function Zj({matchUp:t,targetStages:e,targetStageSequences:r,targetCollectionIds:n,targetRoundNames:o,targetRoundNumbers:i,targetRoundPositions:s,targetMatchUpStatuses:a,excludeTargetMatchUpStatuses:c,targetMatchUpIds:u,targetMatchUpTypes:p,targetMatchUpFormats:m}){return!(e.length&&!e.includes(t.stage)||r.length&&!r.includes(t.stageSequence)||n.length&&(!t.collectionId||!n.includes(t.collectionId))||o.length&&(!t.roundName||!o.includes(t.roundName))||i.length&&(!t.roundNumber||!i.includes(t.roundNumber))||s.length&&(!t.roundPosition||!s.includes(t.roundPosition))||a.length&&(!t.matchUpStatus||!a.includes(t.matchUpStatus))||c.length&&t.matchUpStatus&&c.includes(t.matchUpStatus)||u.length&&!u.includes(t.matchUpId)||p.length&&(!t.matchUpType||!_s(p,t.matchUpType))||m.length&&(!t.matchUpFormat||!m.includes(t.matchUpFormat)))}function tq({matchUp:t,targetScheduledDates:e,targetCourtIds:r,targetVenueIds:n}){if(e?.length){let{scheduledTime:o}=jl({matchUp:t}),{scheduledDate:i}=Qs({matchUp:t}),a=mt(o)||i;if(!e.some(c=>Xn(c,a)))return!1}if(r.length){let{courtId:o}=ZL({matchUp:t}),{allocatedCourts:i}=JL({matchUp:t}),s=i?.map(({courtId:a})=>a);if(!r.filter(Boolean).includes(o)||s?.includes(o))return!1}if(n.length){let{venueId:o}=t0({matchUp:t});if(!n.filter(Boolean).includes(o))return!1}return!0}function eq({matchUp:t,targetTournamentIds:e,targetEventIds:r,targetDrawIds:n,targetStructureIds:o,targetParticipantIds:i,hasParticipantsCount:s}){if(e.length&&!e.includes(t.tournamentId)||r.length&&!r.includes(t.eventId)||n.length&&!n.includes(t.drawId)||o.length&&!o.includes(t.structureId))return!1;let a=t.sides?.map(({participantId:c})=>c).filter(Boolean)??[];return!(s&&a.length<s||i.length&&!i.some(u=>a.includes(u)))}function ht(t){let{provisionalPositioning:e,tournamentRecord:r,contextFilters:n,matchUpFilters:o,contextProfile:i,drawDefinition:s,context:a={},structure:c,inContext:u,event:p}=t,{seedAssignments:m,contextContent:d,exitProfiles:l,matchUpsMap:f}=t,g={},I={};if(!c)return{collectionPositionMatchUps:g,error:_i,roundMatchUps:I,matchUps:[]};let S=Array.isArray(o?.eventIds)?o?.eventIds.filter(Boolean):[],h=Array.isArray(o?.structureIds)?o?.structureIds.filter(Boolean):[],T=Array.isArray(o?.drawIds)?o?.drawIds.filter(Boolean):[],y=!a?.eventId||!S?.length&&!n?.eventIds?.filter(Boolean).length||S?.includes(a.eventId)||n?.eventIds?.includes(a.eventId),E=!h?.length||h.includes(c.structureId),A=!s||!T?.length||T.includes(s.drawId);if(!y||!E||!A)return{collectionPositionMatchUps:g,roundMatchUps:I,matchUps:[]};i&&!d&&(d=eo({tournamentRecord:r,contextProfile:i,drawDefinition:s}));let{appliedPolicies:N}=ft({drawDefinition:s}),D={...t.tournamentAppliedPolicies,...N,...t.policyDefinitions},R=D?.scoring?.structures,U=c.stage&&R?.stage?.[c.stage],b=c.stageSequence&&U?.stageSequence?.[c.stageSequence],C=D?.scoring?.requireAllPositionsAssigned||U?.requireAllPositionsAssigned||b?.requireAllPositionsAssigned;f??=Ie({drawDefinition:s,structure:c});let{positionAssignments:_,allPositionsAssigned:v}=se({structure:c}),w=!C||v,{seedAssignments:L}=Ur({provisionalPositioning:e,drawDefinition:s,structure:c});m=m??L;let{structureId:F}=c;l=l||s&&Gl({drawDefinition:s}).exitProfiles;let x=l?.[F],k=x?.length&&(x[0].split("-").map(Y=>Number.parseInt(Y)).reduce((Y,J)=>Y+J,0)||0),G=!!c.structures,V=jo({matchUpsMap:f,structureId:F,inContext:u}),B=D?.[Fo],z=cE({roundNamingPolicy:B,drawDefinition:s,structure:c,matchUps:V}),{roundNamingProfile:H,roundProfile:K}=z;if(I=z?.roundMatchUps??[],o){let Y=new Set(V.filter(J=>Array.isArray(J.tieMatchUps)).map(J=>J.matchUpId));V=zi({matchUps:Y.size?V.filter(J=>!Y.has(J.matchUpId)):V,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1}).concat(Y.size?V.filter(J=>Y.has(J.matchUpId)):[])}return u?V=nq({positionAssignments:_,initialRoundOfPlay:k,roundNamingProfile:H,tournamentRecord:r,appliedPolicies:D,seedAssignments:m,contextContent:d,contextProfile:i,drawDefinition:s,contextFilters:n,scoringActive:w,isRoundRobin:G,roundProfile:K,matchUpsMap:f,structureId:F,structure:c,context:a,params:t,event:p,matchUps:V}):(V=e0(V),i?.withCompetitiveness&&(V=rq({policyDefinitions:t.policyDefinitions,tournamentRecord:r,drawDefinition:s,structure:c,matchUps:V,event:p}))),o&&(V=zi({matchUps:V,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1})),(o?.matchUpTypes||o?.matchUpIds)&&(V=zi({matchUpTypes:o.matchUpTypes,matchUpIds:o.matchUpIds,matchUps:V})),(o?.matchUpTypes||o?.matchUpIds||u)&&(I=Ue({matchUps:V}).roundMatchUps??[]),ze({drawDefinition:s,structure:c,event:p})?.tieFormat&&({collectionPositionMatchUps:g}=ML({matchUps:V})),{collectionPositionMatchUps:g,roundMatchUps:I,isRoundRobin:G,roundProfile:K,matchUpsMap:f,matchUps:V}}function e0(t){let e=t?.filter(n=>Array.isArray(n.tieMatchUps)),r=t;return e.forEach(n=>{r=r.concat(...n.tieMatchUps)}),r}function rq({policyDefinitions:t,tournamentRecord:e,drawDefinition:r,structure:n,matchUps:o,event:i}){let s=oE({policyDefinitions:t,tournamentRecord:e,drawDefinition:r,structure:n,event:i});return o.map(a=>{if(a.competitiveProfile||!a.winningSide)return a;let c=js({profileBands:s,matchUp:a});return c.error?a:{...a,competitiveProfile:c}})}function nq({positionAssignments:t,initialRoundOfPlay:e,roundNamingProfile:r,tournamentRecord:n,appliedPolicies:o,seedAssignments:i,contextContent:s,contextProfile:a,drawDefinition:c,contextFilters:u,scoringActive:p,isRoundRobin:m,roundProfile:d,matchUpsMap:l,structureId:f,structure:g,context:I,params:S,event:h,matchUps:T}){let{sourceDrawPositionRanges:y}=vL({drawDefinition:c,matchUpsMap:l,structureId:f}),E=c?OL({drawDefinition:c,roundProfile:d,matchUpsMap:l,structureId:f}).drawPositionsRanges:void 0,A=S.tournamentParticipants,N=S.participantMap;!A?.length&&!N&&n&&({participants:A=[],participantMap:N}=di({participantsProfile:S.participantsProfile,useParticipantMap:S.useParticipantMap,policyDefinitions:S.policyDefinitions,tournamentRecord:n,contextProfile:a,inContext:!0}));let D=T.map(R=>bb({scheduleVisibilityFilters:S.scheduleVisibilityFilters,hydrateParticipants:S.hydrateParticipants,afterRecoveryTimes:S.afterRecoveryTimes,usePublishState:S.usePublishState,scheduleTiming:S.scheduleTiming,publishStatus:S.publishStatus,sourceDrawPositionRanges:y,tournamentParticipants:A,positionAssignments:t,drawPositionsRanges:E,initialRoundOfPlay:e,roundNamingProfile:r,tournamentRecord:n,appliedPolicies:o,seedAssignments:i,contextContent:s,participantMap:N,contextProfile:a,drawDefinition:c,scoringActive:p,isRoundRobin:m,roundProfile:d,structure:g,context:I,matchUp:R,event:h}));return D=e0(D),u&&(D=zi({processContext:!0,...u,matchUps:D})),D}function Js({matchUp:t}){return t?Ot.includes(t?.matchUpStatus)||t?.winningSide:!1}function Gp({requireParticipants:t=!0,scheduleVisibilityFilters:e,tournamentAppliedPolicies:r,tournamentParticipants:n,hydrateParticipants:o,afterRecoveryTimes:i,policyDefinitions:s,tournamentRecord:a,usePublishState:c,matchUpFilters:u,contextFilters:p,contextContent:m,participantMap:d,scheduleTiming:l,publishStatus:f,contextProfile:g,drawDefinition:I,exitProfiles:S,matchUpsMap:h,structureId:T,inContext:y,structure:E,context:A,event:N}){!E&&T&&({structure:E}=tt({drawDefinition:I,structureId:T}));let D=ht({tournamentAppliedPolicies:r,scheduleVisibilityFilters:e,tournamentParticipants:n,hydrateParticipants:o,afterRecoveryTimes:i,policyDefinitions:s,tournamentRecord:a,usePublishState:c,matchUpFilters:u,contextFilters:p,contextContent:m,participantMap:d,scheduleTiming:l,publishStatus:f,contextProfile:g,drawDefinition:I,exitProfiles:S,matchUpsMap:h,structure:E,inContext:y,context:A,event:N}),R=[],U=[],b=[],C=[],_=[];if(D.error)return D;let{matchUps:v}=D,{assignedPositions:w}=se({structure:E}),L=w?.filter(x=>x.participantId).map(x=>x.drawPosition),F;return v.filter(x=>{let k=u?.matchUpTypes?.length===1&&u.matchUpTypes[0]===xt;return!(x.matchUpType!==xt&&k)}).forEach(x=>{if(x.matchUpStatus===Fr){R.push(x);return}x.matchUpType===xt&&(F=!0);let k=!!x.collectionId,G=k&&x.sides?.every(J=>J.participantId),V=!k&&x.drawPositions?.filter(Boolean).length===2,B=!k&&x.drawPositions?.every(J=>L?.includes(J)),z=w?.filter(J=>J.bye).map(J=>J.drawPosition),H=!k&&x.drawPositions?.find(J=>z?.includes(J)),Y=By.includes(x.matchUpStatus)&&(G||V&&(!t||B));return H?_.push(x):Js({matchUp:x})?U.push(x):Y?b.push(x):C.push(x)}),{includesTeamMatchUps:F,abandonedMatchUps:R,completedMatchUps:U,upcomingMatchUps:b,pendingMatchUps:C,byeMatchUps:_,structure:E}}function r0({drawDefinition:t,roundNumber:e,structureId:r}){let n=dt({drawDefinition:t,structureId:r},[Kt,mo]);if(n.error)return n;let{links:o}=ka({drawDefinition:t,structureId:r}),i=o.source.reduce((a,c)=>!c.source.roundNumber||c.source.roundNumber===e?a.concat(c):a,[]),s=o.target.reduce((a,c)=>!c.target.roundNumber||c.target.roundNumber===e?a.concat(c):a,[]);return{links:{source:i,target:s}}}function hE({finishingPositions:t,linkCondition:e,linkType:r,source:n}){let o=n.find(i=>{let s=!i.source?.finishingPositions||!t||Re(t,i.source?.finishingPositions);return e===i.linkCondition&&s&&i.linkType===r});return[Pr,ir].includes(o?.linkType)&&!o?.source?.roundNumber?M({result:{error:O},stack:"getTargetLink",context:o}):o}function ka({drawDefinition:t,structureId:e,roundNumber:r}){let n=dt({drawDefinition:t,structureId:e},[Kt,mo]);return n.error?n:{links:(t.links??[]).filter(Boolean).reduce((s,a)=>(a.source?.structureId===e&&(!r||a.source.roundNumber===r)&&(s.source=s.source.concat(a)),a.target?.structureId===e&&(!r||a.target.roundNumber===r)&&(s.target=s.target.concat(a)),s),{source:[],target:[]})}}function n0({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 TE({sourceRoundMatchUpCount:t,inContextDrawMatchUps:e,sourceRoundPosition:r,drawDefinition:n,targetLink:o}){if(!o)return{error:kg};let{target:{structureId:i,feedProfile:s,groupedOrder:a,roundNumber:c,positionInterleave:u}}=o,{structure:p}=tt({drawDefinition:n,structureId:i}),{positionAssignments:m}=Pt({structure:p}),l=(e?.filter(U=>U.structureId===p?.structureId)).filter(U=>U.roundNumber===c&&!U.matchUpTieId),f=l.length,g=Q(1,f+1),I=f/t,S=Math.ceil(I*r),h=1-r%2;if(u?.interleave&&I!==.5){let U=u.offset+(r-1)*u.interleave,b=r+U;S=Math.ceil(b/2),h=1-b%2}let T=g,y=g[S-1],E=aE({roundPositionsCount:g.length,groupedOrder:a}),A=E?.length||1;if(A<=g.length){let U=f/A,b=he(g,U);s===Fi&&b.forEach(C=>C.reverse()),T=E?.length&&E?.map(C=>b[C-1]).flat()||T}s===qe?y=T[S-1]:s===Fi?((!E?.length||A>g.length)&&(S=l.length+1-S),y=T[S-1]):s===Ym&&je()&&console.log(iI,{feedProfile:s});let N=y&&l.reduce((U,b)=>b.roundPosition===y?b:U,void 0),D;N?.feedRound?(h=0,D=Math.min(...(N.drawPositions??[]).filter(Boolean))):D=N?.drawPositions?.length===2&&N?.drawPositions[h];let R=m?.find(({drawPosition:U})=>U===D);if(R){let{extension:U}=ot({element:R,name:Pl});if(U?.value)return{disabledDrawPosition:D}}return{matchUp:N,targetDrawPosition:D,matchUpDrawPositionIndex:h}}function er({inContextDrawMatchUps:t=[],useTargetMatchUpIds:e,inContextMatchUp:r,drawDefinition:n,matchUpId:o}){let i=r;t.length&&!i&&(i=t.find(c=>c.matchUpId===o));let{structure:s}=tt({structureId:i?.structureId,drawDefinition:n});return s?.finishingPosition===Ss?oq({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:n,structure:s,matchUp:i}):iq({matchUp:i})}function oq({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:r,structure:n,matchUp:o}){let{winnerMatchUpId:i,loserMatchUpId:s}=o,{links:a}=r0({roundNumber:o.roundNumber,structureId:n.structureId,drawDefinition:r}),c=a?.source,u=hE({source:c,linkType:Pr}),p=hE({linkCondition:Wn,linkType:ir,source:c}),m=hE({source:c,linkType:ir}),d=p&&m;m||(m=p);let l=u?.target?.feedProfile,f=m?.target?.feedProfile,g=p?.target?.feedProfile,I,S,h,T,y,E,A,N,D,R;if(e&&(i||s)&&(A=i&&l!==ln&&t.find(({matchUpId:C})=>C===i),T=s&&f!==ln&&t.find(({matchUpId:C})=>C===s),A||T))return{matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u},targetMatchUps:{loserMatchUp:T,winnerMatchUp:A}};let{roundPosition:U}=o;R=R||t.filter(C=>C.structureId===n.structureId);let b=R.reduce((C,_)=>_.roundNumber===o.roundNumber&&!_.matchUpTieId?C+1:C,0);return m&&!T&&f!==ln&&({matchUpDrawPositionIndex:E,targetDrawPosition:y,matchUp:T}=TE({targetLink:m,sourceRoundMatchUpCount:b,inContextDrawMatchUps:t,sourceRoundPosition:U,drawDefinition:r})),d&&g!==ln&&({matchUpDrawPositionIndex:h,targetDrawPosition:S,matchUp:I}=TE({targetLink:p,sourceRoundMatchUpCount:b,inContextDrawMatchUps:t,sourceRoundPosition:U,drawDefinition:r})),u&&!A&&l!==ln&&({matchUpDrawPositionIndex:D,targetDrawPosition:N,matchUp:A}=TE({targetLink:u,sourceRoundMatchUpCount:b,inContextDrawMatchUps:t,sourceRoundPosition:U,drawDefinition:r})),A||(R=R||t.filter(C=>C.structureId===n.structureId),{matchUp:A}=n0({structureMatchUps:R,matchUp:o})),et({matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u,byeTargetLink:p},targetMatchUps:{winnerMatchUpDrawPositionIndex:D,loserMatchUpDrawPositionIndex:E,byeMatchUpDrawPositionIndex:h,winnerTargetDrawPosition:N,loserTargetDrawPosition:y,byeTargetDrawPosition:S,winnerMatchUp:A,loserMatchUp:T,byeMatchUp:I},targetMatchUpIds:!!(i||s)})}function iq({matchUp:t}){return{targetLinks:{loserTargetLink:void 0,winnerTargetLink:void 0},targetMatchUps:{loserMatchUp:void 0,winnerMatchUp:void 0},matchUp:t}}function i0({drawDefinition:t,inContextDrawMatchUps:e}){let r={};return e.forEach(n=>{let{matchUpId:o,structureId:i,drawPositions:s=[]}=n,{structure:a}=tt({drawDefinition:t,structureId:i});a?.finishingPosition===po?sq({inContextMatchUp:n,structure:a,drawPositions:s}):aq({scheduleConflictMatchUpIds:r,inContextDrawMatchUps:e,inContextMatchUp:n,drawDefinition:t,matchUpId:o})}),Object.keys(r).length&&e.forEach(n=>{Object.keys(r).includes(n.matchUpId)&&(n.schedule.scheduleConflict=r[n.matchUpId])}),{scheduleConflictMatchUpIds:r}}function sq({inContextMatchUp:t,structure:e,drawPositions:r}){let{roundNumber:n}=t,o=n&&st(n)+1,i=e.matchUps??[],{roundMatchUps:s}=Ue({matchUps:i});if(o&&s?.[o]){let a=[...r].sort(Zt).map((c,u)=>{let p=s[o].find(m=>m.drawPositions?.includes(c));return{matchUpId:p?.matchUpId,roundNumber:o,schedule:p?.schedule,sideNumber:u+1,structureName:e.structureName}});Object.assign(t,{sidesTo:a})}}function aq({scheduleConflictMatchUpIds:t,inContextDrawMatchUps:e,inContextMatchUp:r,drawDefinition:n,matchUpId:o}){let i=er({useTargetMatchUpIds:!0,inContextDrawMatchUps:e,inContextMatchUp:r,drawDefinition:n,matchUpId:o}),{winnerMatchUp:s}=i.targetMatchUps,{loserMatchUp:a}=i.targetMatchUps;!r.winnerMatchUpId&&s&&(r.winnerMatchUpId=s.matchUpId),!r.loserMatchUpId&&a&&(r.loserMatchUpId=a.matchUpId);let c=Cb({upcomingMatchUp:s}),u=Cb({upcomingMatchUp:a});if(r.matchUpStatus!=="BYE"&&a?.matchUpStatus==="BYE"){let{matchUp:m}=s0({matchUp:a,drawDefinition:n,inContextDrawMatchUps:e})??{};u=m&&Cb({upcomingMatchUp:m})||u}let p=r.schedule?.timeAfterRecovery;p&&(o0({scheduleConflictMatchUpIds:t,inContextMatchUp:r,timeAfterRecovery:p,upcomingTo:c}),o0({scheduleConflictMatchUpIds:t,inContextMatchUp:r,timeAfterRecovery:p,upcomingTo:u})),Object.assign(r,{winnerTo:c,loserTo:u}),r.drawPositions?.filter(Boolean).length&&cq({inContextDrawMatchUps:e,inContextMatchUp:r,winnerMatchUp:s,loserMatchUp:a,targetData:i})}function o0({scheduleConflictMatchUpIds:t,inContextMatchUp:e,timeAfterRecovery:r,upcomingTo:n}){n?.schedule?.scheduledTime&&jt(n.schedule.scheduledTime)<jt(r)&&(t[n.matchUpId]=e.matchUpId,n.schedule.scheduleConflict=e.matchUpId)}function cq({inContextDrawMatchUps:t,inContextMatchUp:e,winnerMatchUp:r,loserMatchUp:n,targetData:o}){let s=o.targetLinks?.loserTargetLink?.linkCondition===Wn,a=uq(e);if(!a.length)return;let c=LI(r?.sides),u=LI(n?.sides),m=a.find(({participantId:f})=>c.includes(f))?[]:a,l=a.find(({participantId:f})=>u.includes(f))?[]:a;n&&s&&l.length<2&&l.push({bye:!0,tbd:!0}),m?.length&&r&&(!o.targetMatchUpIds&&r&&(r=t.find(({matchUpId:f})=>f===r.matchUpId)),r.potentialParticipants??=[],r.potentialParticipants.push(m)),l?.length&&n&&(o.targetMatchUpIds||(r=t.find(({matchUpId:f})=>f===n.matchUpId)),n.potentialParticipants||(n.potentialParticipants=[]),n.potentialParticipants.push(l))}function uq(t){return t?.sides?.map(({participant:e,participantId:r,qualifier:n})=>e||r&&{participantId:r}||n&&{qualifier:n}).filter(Boolean)??[]}function s0({matchUp:t,drawDefinition:e,inContextDrawMatchUps:r}){let{matchUpId:n,matchUpStatus:o,structureId:i}=t??{};if(!t||!i||t?.matchUpStatus===zt)return{matchUp:t};if(o==="BYE"){let s;return t.winnerMatchUpId?s=r.find(({matchUpId:a})=>a===t.winnerMatchUpId):{winnerMatchUp:s}=er({inContextDrawMatchUps:r,drawDefinition:e,matchUpId:n})?.targetMatchUps??{},s0({matchUp:s,drawDefinition:e,inContextDrawMatchUps:r})}return{matchUp:void 0}}function Cb(t){if(t?.upcomingMatchUp)return(({matchUpId:e,structureId:r,schedule:n,roundNumber:o,roundPosition:i,structureName:s})=>({matchUpId:e,structureId:r,schedule:n,roundNumber:o,roundPosition:i,structureName:s}))(t.upcomingMatchUp)}function te(t){let e="getAllDrawMatchUps";Object.assign(t,{requireParticipants:!1});let r=Ga(t);if(r.error)return M({result:r,stack:e});let{abandonedMatchUps:n,completedMatchUps:o,upcomingMatchUps:i,pendingMatchUps:s,byeMatchUps:a,matchUpsMap:c}=r;return{matchUps:(n??[]).concat(...o??[],...i??[],...s??[],...a??[]),matchUpsMap:c}}function Ga(t){if(!t?.drawDefinition)return{error:$};let{tournamentParticipants:e,contextContent:r,matchUpsMap:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,requireParticipants:s,participantsProfile:a,afterRecoveryTimes:c,policyDefinitions:u,tournamentRecord:p,usePublishState:m,contextFilters:d,matchUpFilters:l,scheduleTiming:f,participantMap:g,publishStatus:I,contextProfile:S,drawDefinition:h,nextMatchUps:T,inContext:y,context:E,event:A}=t,N=[],D=[],R=[],U=[],b=[];S&&!r&&(r=eo({policyDefinitions:u,tournamentRecord:p,contextProfile:S,event:A}));let C;!e?.length&&p&&(e=p?.participants,(y||a?.withGroupings)&&e?.length&&({participantsWithGroupings:e,groupInfo:C}=_p({participants:e,participantsProfile:a})));let{structures:_}=Sn({drawDefinition:h});if(!_)return{error:Nt};n||(n=Ie({drawDefinition:h}));let v=h&&Gl({drawDefinition:h}).exitProfiles;_.forEach(F=>{let{byeMatchUps:x=[],pendingMatchUps:k=[],upcomingMatchUps:G=[],completedMatchUps:V=[],abandonedMatchUps:B=[]}=Gp({matchUpFilters:T?void 0:l,contextFilters:T?void 0:d,inContext:y||T||d,hydrateParticipants:t.hydrateParticipants,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,tournamentParticipants:e,requireParticipants:s,afterRecoveryTimes:c,policyDefinitions:u,tournamentRecord:p,usePublishState:m,contextContent:r,participantMap:g,scheduleTiming:f,publishStatus:I,contextProfile:S,drawDefinition:h,exitProfiles:v,matchUpsMap:n,structure:F,context:E,event:A});N=N.concat(...B),D=D.concat(...V),R=R.concat(...G),U=U.concat(...k),b=b.concat(...x)});let w=F=>(!l&&!T&&!d||(l&&(F=zi({matchUps:F,...l})),d&&(F=zi({matchUps:F,...d,processContext:!0}))),F),L={abandonedMatchUps:w(N),completedMatchUps:w(D),upcomingMatchUps:w(R),pendingMatchUps:w(U),byeMatchUps:w(b),matchUpsMap:n,...P,groupInfo:C};if(T){let F=typeof T=="object"||{abandoned:!0,completed:!0,upcoming:!0,pending:!0,bye:!0},{abandoned:x,completed:k,upcoming:G,pending:V,bye:B}=F,z=[].concat(...(x&&N)??[],...(k&&D)??[],...(G&&R)??[],...(V&&U)??[],...(B&&b)??[]);i0({inContextDrawMatchUps:z,drawDefinition:h})}return L}function vn(t){let{participants:e=[],contextContent:r,participantMap:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,usePublishState:m,contextFilters:d,matchUpFilters:l,contextProfile:f,nextMatchUps:g,inContext:I,context:S,event:h}=t;if(!h)return{error:le};let{eventId:T,eventName:y,endDate:E,eventType:A,category:N,gender:D,matchUpFormat:R}=h??{},U={...S,...et({indoorOutDoor:h.indoorOutdoor??p?.indoorOutdoor,surfaceCategory:h.surfaceCategory??p?.surfaceCategory,endDate:h.endDate??p?.endDate,tournamentId:p?.tournamentId,matchUpFormat:R,eventName:y,eventType:A,category:N,eventId:T,gender:D})};E&&(U.endDate=E),f&&!r&&(r=eo({policyDefinitions:c,tournamentRecord:p,contextProfile:f,event:h}));let b;if(!e?.length&&!n&&p){let w=di({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:f,inContext:I});n=w.participantMap,e=w.participants??[],b=w.groupInfo}let C=h.drawDefinitions??[],_=Ac({tournamentRecord:p,event:h}).scheduleTiming;return{matchUps:C.flatMap(w=>{let{matchUps:L}=te({tournamentParticipants:e,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,context:U,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,usePublishState:m,contextFilters:d,contextProfile:f,drawDefinition:w,contextContent:r,matchUpFilters:l,participantMap:n,scheduleTiming:_,nextMatchUps:g,inContext:I,event:h});return L??[]}),groupInfo:b}}function qt(t){let e=X(t,[{tournamentRecord:!0}]);if(e.error)return e;if(!t?.tournamentRecord)return{error:j};let{participantMap:r,participants:n}=t,{scheduleVisibilityFilters:o,participantsProfile:i,afterRecoveryTimes:s,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,inContext:p=!0,usePublishState:m,contextProfile:d,matchUpFilters:l,contextFilters:f,nextMatchUps:g,context:I}=t,S=t.tournamentId??u.tournamentId,h=u?.events??[];n||({participants:n,participantMap:r}=di({participantsProfile:i,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,contextProfile:d,inContext:p}));let{appliedPolicies:T}=ft({tournamentRecord:u}),y={...I,tournamentId:S,indoorOutDoor:u.indoorOutdoor,surfaceCategory:u.surfaceCategory,endDate:u.endDate},E=eo({policyDefinitions:c,tournamentRecord:u,contextProfile:d});return{matchUps:h.flatMap(N=>(y.eventDrawsCount=N.drawDefinitions?.length??0,vn({context:y,scheduleVisibilityFilters:o,tournamentAppliedPolicies:T,participantsProfile:i,afterRecoveryTimes:s,policyDefinitions:c,tournamentRecord:u,usePublishState:m,contextContent:E,contextFilters:f,contextProfile:d,matchUpFilters:l,participantMap:r,nextMatchUps:g,participants:n,inContext:p,event:N}).matchUps??[])).concat(...u.matchUps??[])}}function cn({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,tournamentRecords:n,policyDefinitions:o,usePublishState:i,matchUpFilters:s,contextFilters:a,nextMatchUps:c,inContext:u}){if(typeof n!="object"||!Object.keys(n).length)return{error:kt};let m=Object.keys(n).map(d=>{let l=n[d];return qt({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,policyDefinitions:o,tournamentRecord:l,usePublishState:i,matchUpFilters:s,contextFilters:a,nextMatchUps:c,inContext:u}).matchUps??[]}).flat();return{...P,matchUps:m}}function Qi(t,e){return pq(t,e)||(t?.stageSequence||0)-(e?.stageSequence||0)||t?.roundNumber&&e.roundNumber&&t?.roundNumber-e?.roundNumber||(t?.roundPosition??0)-(e?.roundPosition??0)}function pq(t,e){return(Ca[t?.stage]||0)-(Ca[e?.stage]||0)}function rr(t){let{participants:e,participantMap:r,contextContent:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,matchUpFilters:m,contextFilters:d,contextProfile:l,drawDefinition:f,nextMatchUps:g,inContext:I,context:S,event:h}=t,{eventId:T,eventName:y,endDate:E,eventType:A,category:N,gender:D,matchUpFormat:R}=h??{},U={...S,surfaceCategory:h?.surfaceCategory??p?.surfaceCategory,indoorOutDoor:h?.indoorOutdoor??p?.indoorOutdoor,matchUpFormat:R,eventType:A,eventName:y,category:N,eventId:T,endDate:E,gender:D},b;return!e?.length&&!r&&p&&({participants:e=[],participantMap:r,groupInfo:b}=di({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:l,inContext:I})),l&&!n&&(n=eo({policyDefinitions:c,tournamentRecord:p,contextProfile:l,drawDefinition:f,event:h})),{...te({context:U,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,tournamentParticipants:e,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,drawDefinition:f,contextContent:n,contextFilters:d,contextProfile:l,matchUpFilters:m,participantMap:r,nextMatchUps:g,inContext:I,event:h}),groupInfo:b}}var Mb=t=>e=>!t||typeof e!="object"?void 0:Array.isArray(t)&&t.map(r=>({[r]:Bi({element:e,accessor:r})?.value}))||typeof t=="object"&&Object.keys(t).map(r=>({[r]:Bi({element:e,accessor:r})?.value}))||(typeof t=="string"&&Bi({element:e,accessor:t}))?.value,Vr=Mb;function Nc({finishingPositionOffset:t=0,finishingPositionLimit:e,positionsFed:r,roundsCount:n,roundLimit:o,matchUps:i,lucky:s,fmlc:a}){if(!Rr(i))return[];let{roundProfile:c,roundNumbers:u=[]}=Ue({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(Vr("matchUpsCount")),l=(I,S)=>{let h=Math.min(...I);m&&S&&h===1&&(h=m);let T=Math.max(...I);return e&&T>e&&(T=e),[h,T]},f=c&&Object.assign({},...u.map(I=>{let S=(n??0)+1-I-p,h=c[I].matchUpsCount,T={finishingPositionRange:{},finishingRound:S},y=d?.slice(I-1).reduce((C,_)=>C+(_||0),0),E=a&&I!==1,A=1+t+(E?r??0:0),N=1,D=Q(A,s?A+h*2:y+A+N),R=y+N-h,U=l(D.slice(R)),b=l(D.slice(0,R),!0);return T.finishingPositionRange={loser:U,winner:b},{[I]:T}})),g=je({finishingRound:!0});return i.filter(Boolean).forEach(I=>{let S=I.roundNumber&&f[I.roundNumber];g&&!S&&console.log({roundFinishingData:f,matchUp:I}),I.finishingRound=S?.finishingRound,I.finishingPositionRange=S?.finishingPositionRange}),i}function Ps({inContextDrawMatchUps:t,drawDefinition:e,matchUpsMap:r}){if(!e)return{error:$};let n={loserMatchUpIds:{},winnerMatchUpIds:{}};if(t||({matchUps:t,matchUpsMap:r}=te({inContext:!0,drawDefinition:e,matchUpsMap:r})),!r?.drawMatchUps.some(i=>i.finishingPositionRange)&&e?.structures?.length===1&&!e?.structures[0].structures){let i=r?.drawMatchUps??[];Nc({matchUps:i})}return(t??[]).filter(({collectionId:i})=>!i).forEach(i=>{let{matchUpId:s,structureId:a}=i,c=er({inContextDrawMatchUps:t,drawDefinition:e,matchUpId:s}),{winnerMatchUp:u,loserMatchUp:p}=c.targetMatchUps,m=u?.matchUpId,d=p?.matchUpId,f=jo({matchUpsMap:r,structureId:a}).find(g=>g.matchUpId===s);if(f&&(m&&(n.winnerMatchUpIds[f.matchUpId]=m,Object.assign(f,{winnerMatchUpId:m}),Object.assign(i,{winnerMatchUpId:m})),d&&(n.loserMatchUpIds[f.matchUpId]=d,i.loserMatchUpId=d,f.loserMatchUpId=d,i.finishingPositionRange))){let g=p.finishingPositionRange&&[...i.finishingPositionRange.loser,...p.finishingPositionRange.loser],I=g&&[Math.min(...g),Math.max(...g)];i.finishingPositionRange.loser=I,f.finishingPositionRange.loser=I}}),{inContextDrawMatchUps:t,goesToMap:n}}function tn(t){let e=Dr(t),r=t.matchUps??[],n=t.drawIds??[],{includeParticipantDependencies:o,tournamentRecord:i,drawDefinition:s}=t;if(!Array.isArray(r))return{error:Bn};if(!Array.isArray(n))return{error:Nn};let a=t.matchUpIds?.length?t.matchUpIds:r.map(T=>T.matchUpId);if(!Array.isArray(a))return{error:xs};let c={},u={},p={},m={};i&&!Object.keys(e).length&&(e={[i.tournamentId]:i});let d=Object.values(e),f=d.reduce((T,y)=>T.concat(y.events??[]).map(E=>(E.drawDefinitions??[]).map(A=>A.links??[])).flat(1/0),[]).filter(({linkType:T})=>T===fn),g=r;f.length&&(g=cn({nextMatchUps:!0,tournamentRecords:e}).matchUps,mq({positionLinks:f,sourceStructureIdMap:p,positionDependencies:c,matchUps:g}));let I=T=>{u[T]||(u[T]={dependentMatchUpIds:[],participantIds:[],matchUpIds:[],sources:[]},m[T]=[])},S=(T,y)=>{u[T].matchUpIds.forEach(A=>{u[y].matchUpIds.push(A)}),u[y].matchUpIds.push(T),u[T].dependentMatchUpIds.push(y),o&&u[T].participantIds.forEach(A=>u[y].participantIds.push(A))},h=T=>{let y=Object.keys(c).length;for(let E of T??[]){let{matchUpId:A,winnerMatchUpId:N,loserMatchUpId:D}=E;if(!a.length||a.includes(A)){if(I(A),o){let{individualParticipantIds:b}=Mp(E);u[A].participantIds=b}N&&(I(N),S(A,N),m[N].push(A)),D&&(I(D),S(A,D),m[D].push(A)),u[A].sources.push(m[A]);let R=m[A].map(b=>u[b].sources[0]).flat(),U=m[A].map(b=>u[b].sources[1]).flat();if(u[A].sources.push(R,U),y){let b=E.containerStructureId||E.structureId,C=p[b];if(c[C])for(let _ of c[C])I(_),S(_,A),m[_].push(A)}}}};if(s)Ps({drawDefinition:s}),g?.length||(g=rr({drawDefinition:s}).matchUps),h(g);else{g?.length||(g=cn({nextMatchUps:!0,tournamentRecords:e}).matchUps),n.length||(n=dq(d));for(let T of n)lq({matchUps:g,drawId:T,tournamentRecords:e,processMatchUps:h})}return{positionDependencies:c,matchUpDependencies:u,sourceMatchUpIds:m,matchUps:g,...P}}function mq({positionLinks:t,sourceStructureIdMap:e,positionDependencies:r,matchUps:n}){let o=t.reduce((i,s)=>{let a=s.source?.structureId,c=s.target?.structureId;return a&&c&&(e[c]=a),a&&!i.includes(a)&&i.push(a),i},[]);for(let i of o)r[i]=[];for(let i of n??[]){let s=i.containerStructureId||i.structureId;o.includes(s)&&r[s].push(i.matchUpId)}}function dq(t){return t?.length?t.map(({events:e=[]})=>e.map(({drawDefinitions:r=[]})=>r.map(({drawId:n})=>n))).flat(1/0):[]}function lq({matchUps:t,drawId:e,tournamentRecords:r,processMatchUps:n}){let o=t?.filter(s=>s.drawId===e).sort(Qi);if(!o?.find(({roundPosition:s})=>!s)){let s=o?.find(({tournamentId:c})=>c),{drawDefinition:a}=_e({tournamentRecord:r[s?.tournamentId],drawId:e});a&&Ps({drawDefinition:a})}n(o)}function ue(t){let e=t?.matchUp,r=t?.score||e?.score,n=r?.sets?.[0],{side1Score:o,side2Score:i,side1TiebreakScore:s,side2TiebreakScore:a,side1PointScore:c,side2PointScore:u}=n??{},p=o||i||s||a||c||u;return!!(r?.sets?.length>1||p)}function Va({matchUpStatus:t}){return Gy.includes(t)}function a0({matchUpStatus:t}){return Rl.includes(t)}function cS({matchUpStatus:t}){return Vy.includes(t)}function uS({matchUpStatus:t,winningSide:e,tieMatchUps:r,sides:n,score:o}){let i=n?.find(({participantId:c})=>c),s=r?.filter(uS)?.length;return ue({score:o})||s||e&&i||t&&a0({matchUpStatus:t})&&![Mt,vt,Cn].includes(t)}function Xi(t){let{drawDefinition:e,findContainer:r,structureId:n,event:o}=t,i=t.structure,{containedStructures:s}=ji({drawDefinition:e}),a=n?s[n]??[]:[],c={isCollectionMatchUp:!1};if(!i){let N=tt({drawDefinition:e,structureId:n});if(N.error)return N;i=r?N.containingStructure??N.structure:N.structure}if(Ae({structure:i}))return{structure:i,isAdHoc:!0,error:ps};let{matchUps:u}=te({inContext:!0,matchUpFilters:c,drawDefinition:e,event:o}),p=u?.filter(N=>N.structureId===n||a.includes(N.structureId)),{matchUpDependencies:m}=tn({drawIds:[e.drawId],matchUps:u,drawDefinition:e}),d=[],l=[],f={},g=[];for(let N of u??[]){if(N.structureId===n||a.includes(N.structureId)){l.push(...N.drawPositions??[]);let D=N.roundNumber;for(let R of(N.drawPositions??[]).filter(Boolean))(!f[R]||D&&f[R]>D)&&(f[R]=D)}uS(N)&&(g.push(N),d.push(N.matchUpId,...m?.[N?.matchUpId]?.matchUpIds??[]))}let I=pt(l.filter(Boolean)).sort(Zt),S=pt(d),h=pt(p?.map(({matchUpId:N,drawPositions:D})=>S.includes(N)?D:[]).flat().filter(Boolean)).sort(Zt),{positionAssignments:T}=Pt({drawDefinition:e,structure:i}),y=T?.filter(N=>N.bye).map(N=>N.drawPosition),E=T?.filter(N=>N.qualifier).map(N=>N.drawPosition),A=I?.filter(N=>!h.includes(N))??[];return{allDrawPositions:I,inContextStructureMatchUps:p,drawPositionInitialRounds:f,activeDependentMatchUpIds:S,qualifyingDrawPositions:E,inactiveDrawPositions:A,positionAssignments:T,activeDrawPositions:h,byeDrawPositions:y,activeMatchUps:g,structure:i}}function Zs({drawPosition:t,matchUps:e=[]}){return{initialRoundNumber:e.filter(({drawPositions:n})=>t&&n?.includes(t)).map(({roundNumber:n})=>n).sort(Zt)[0]}}var Dc={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 yE=[];function Pe(t,e){wt(t)&&(t={method:t}),(e||je())&&yE.push(t)}function fq(t){let e=yE.slice();return t&&(yE.length=0),e}function c0(t){let r=fq(t).map(n=>{let{color:o,keyColors:i,method:s,newline:a}=n,c=Object.keys(Dc).includes(o)?Dc[o]:Dc.cyan,p=Object.keys(n).filter(d=>!["color","keyColors","method","newline"].includes(d)).map(d=>{let l=i&&Object.keys(i).includes(d)&&Dc[i[d]]?Dc[i[d]]:Dc.brightwhite;return`${Dc.white}${d}: ${l}${n[d]}`}).join(", "),m=s?.length<15?" ":" ";return[a?`
|
|
1
|
+
var _W=Object.defineProperty;var Gt=(t,e)=>{for(var r in e)_W(t,r,{get:e[r],enumerable:!0})};var tw="3.4.2";function cs(){return tw}var oD={};Gt(oD,{competitionGovernor:()=>ob,drawsGovernor:()=>hv,entriesGovernor:()=>Uv,eventGovernor:()=>Vv,generationGovernor:()=>jv,matchUpFormatGovernor:()=>eN,matchUpGovernor:()=>mO,mocksGovernor:()=>xh,officiatingGovernor:()=>hx,participantGovernor:()=>WO,policyGovernor:()=>qM,publishingGovernor:()=>XO,queryGovernor:()=>Iv,rankingGovernor:()=>wh,reportGovernor:()=>o_,scheduleGovernor:()=>h_,scoreGovernor:()=>nh,temporalGovernor:()=>ax,tieFormatGovernor:()=>b_,tournamentGovernor:()=>q_,venueGovernor:()=>Cx});var ob={};Gt(ob,{getCompetitionLeaderboard:()=>Yy,getCompetitionParticipantState:()=>Hy,getCompetitionPolicy:()=>Ao,getCompetitionState:()=>Wo,getLinkedTournamentIds:()=>bp,getTournamentIds:()=>Xm,initializeCompetitionState:()=>XR,linkTournaments:()=>FR,mutate:()=>rb,processCompetitionMatchUp:()=>Jm,processCompetitionRound:()=>tb,query:()=>nb,resetCompetitionState:()=>eb,unlinkTournament:()=>GR,unlinkTournaments:()=>kR});var rb={};Gt(rb,{initializeCompetitionState:()=>XR,linkTournaments:()=>FR,processCompetitionMatchUp:()=>Jm,processCompetitionRound:()=>tb,resetCompetitionState:()=>eb,unlinkTournament:()=>GR,unlinkTournaments:()=>kR});var Os="SINGLES",Ct="SINGLES",ei="DOUBLES",Rt="DOUBLES",Ir="TEAM",xt="TEAM",wW="HYBRID",Mm="HYBRID",ew={SINGLES_MATCHUP:Os,SINGLES:Ct,DOUBLES_MATCHUP:ei,DOUBLES:Rt,TEAM_MATCHUP:Ir,TEAM:xt,HYBRID_MATCHUP:wW,HYBRID:Mm};var CT={[Ct]:[Ct,"S"],[Rt]:[Rt,"D"],[xt]:[xt,"T"],[Mm]:[Mm,"H"],S:[Ct,"S"],D:[Rt,"D"],T:[xt,"T"],H:[Mm,"H"]};function Zt(t,e){return(t??0)-(e??0)}function st(t){return typeof t=="number"?parseInt(t.toString()):typeof t=="string"?parseInt(t):0}function Br(t){return typeof t=="function"}function wt(t){return typeof t=="string"}function Tt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function rw(t,e){if(!Tt(t)||!Tt(e))return!1;let r=Object.keys(t),n=Object.keys(e);if(r.length!==n.length)return!1;for(let o of r)if(t[o]!==e[o])return!1;return!0}function vT(t,e){return Array.isArray(t)?Object.assign({},...(t??[]).filter(Tt).map(r=>r[e]&&{[r[e]]:r}).filter(Boolean)):{}}var nw=t=>e=>Object.keys(t).every(r=>e[r]===t[r]);function MT(t,e){if(t===void 0)return null;if(!Tt(t)||t===null)return t;let r=Object.keys(t),n=o=>o===void 0?null:o;return Object.assign({},...r.map(o=>Array.isArray(t[o])?{[o]:e?t[o]:t[o].map(i=>MT(i))}:{[o]:e?n(t[o]):MT(t[o])}))}function AD(t){return Array.isArray(t)?t.length+t.map(AD).reduce((e,r)=>e+r,0):Tt(t)&&t!==null?Object.keys(t).length+Object.keys(t).map(e=>AD(t[e])).reduce((e,r)=>e+r,0):0}function ow(t){if(t===null||typeof t!="object")return;let e=JSON.stringify(t),r=AD(t),n=e.split("").reduce((o,i)=>o+i.charCodeAt(0),0);return[e.length,r,n].map(o=>o.toString(36)).join("")}function en(t){return Number.isNaN(Number(t))?!1:t>0&&(t&t-1)===0}function iw(t){if(!t.length)return;let e=[...t].sort(Zt),r=Math.floor(e.length/2);return e.length%2?e[r]:(e[r-1]+e[r])/2}function sw(t){if(t===1||Number.isNaN(Number(t))||!en(t))return!1;let e=t,r=1;for(;e!==2;)r+=1,e=e/2;return r}function el(t){return Number.isNaN(Number(t))?0:t%2&&t+1||t}function rl(t){return Math.pow(2,Math.round(Math.log(t)/Math.log(2)))}function Le(t){return!Number.isNaN(Number.parseFloat(t))}function OT(t){let e=st(t);if(!Number.isNaN(e))return e===0?!1:(e&-e)===1}function Pi(t){if(Number.isNaN(Number(t)))return!1;for(;!en(t);)t++;return t}function pn(t,e,r){return t=Math.ceil(t),e=Math.floor(e),Math.floor((r??Math.random)()*(e-t+1))+t}function yt(t){return wt(t)&&!t.trim().length?!1:Number.isSafeInteger(typeof t=="string"?+t:t)}function aw(t=1,e=3,r=!0,n){let o=n??Math.random,i=0;for(let s=0;s<e;s++)i+=o()*(t/e);return r&&t>1?Math.round(i):i}function LW(t,e){e||(e=1);let r=1/e;return Math.round(t*r)/r}function PD(t,e,r,n,o=2,i){let s=i??Math.random,a=1-s(),c=1-s(),u=Math.sqrt(-2*Math.log(a))*Math.cos(2*Math.PI*c);return u=u/10+.5,u>1||u<0?u=PD(t,e,r,void 0,2,i):(u=Math.pow(u,r),u*=e-t,u+=t),n&&(u=LW(u,n)),Number.parseFloat(u.toFixed(o))}function xg(t,e=2){return Number.parseFloat(Number(Math.round(t*1e3)/1e3).toFixed(e))}function pt(t){return Array.isArray(t)?t?.filter((e,r,n)=>n.lastIndexOf(e)===r):[]}function cw(t){return Array.isArray(t)?t?.map(e=>e===null?void 0:e):t}function ar(t,e){if(!Array.isArray(t))return[];let r=e??Math.random;return t.map(n=>[r(),n]).sort((n,o)=>n[0]-o[0]).map(n=>n[1])}function Wc(t){return yt(t)?t:1/0}function mn(t){return Array.isArray(t)?t.reduce((e,r)=>(e[r]||(e[r]=0),e[r]++,e),{}):{}}function uw(t){return ND(mn(t))}function ND(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return e[n]?e[n].push(r):e[n]=[r],e},{})}function FW(t,e,r){return r.indexOf(t)===e}function _T(t){return t.filter(FW)}function Sr(t,e){return Array.isArray(t)&&t.length?t.splice(Math.floor((e??Math.random)()*t.length),1)[0]:void 0}function Pn(t,e){let r=Math.floor((e??Math.random)()*t.length);return t[r]}function Q(t,e){return Array.from({length:e-t},(r,n)=>n+t)}function us(t,e){return e.reduce((r,n,o)=>(n===t&&r.push(o),r),[])}function Yt(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(r=>e.indexOf(r)!==-1).filter((r,n,o)=>o.indexOf(r)===n)}function DD(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(r=>!e.includes(r))}function Re(t,e){return!Array.isArray(t)||!Array.isArray(e)?!1:t.some(r=>e.includes(r))}function pw(t,e){return Array.isArray(e)&&e.reduce((r,n)=>(r[n]=1+r[n]||1,r),{})[t]||0}function mw(t,e,r,n){return Array.isArray(t)?[].concat(...t.slice(0,e),...t.slice(e,e+r).sort(n),...t.slice(e+r,t.length)):[]}function he(t,e){return Array.isArray(t)?t.reduce((r,n,o)=>{let i=Math.floor(o/e);return r[i]=[].concat(r[i]??[],n),r},[]):[]}function UD(t,[e,...r]){return t.length?[t.slice(0,e),...UD(t.slice(e),[...r,e])]:[]}function dw(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 xT(t){return Array.isArray(t)?t.reduce((e,r)=>!isNaN(parseInt(r))&&e,!0):!1}function wT(t){return Array.isArray(t)?t.reduce((e,r)=>isNaN(parseInt(r))&&e,!0):!1}function wg(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 lw(t,e=1){if(!Array.isArray(t)||!t.every(yt))return[];let r=Math.min(...t,e),n=Math.max(...t);return Q(r,n+1).filter(o=>!t.includes(o))}function _s(t,e){return!Array.isArray(t)||!wt(e)?!1:Yt(t,CT[e]).length}var P={success:!0},RD="error",fw={SUCCESS:P,ERROR:RD};function LT({collectionValueProfiles:t,matchUpCount:e}){let r=[];if(!Array.isArray(t))return r.push(`collectionValueProfiles is not an array: ${t}`),{errors:r};if(t.length&&t.length!==e)return r.push("collectionValueProfiles do not align with matchUpsCount"),{errors:r};for(let o of t){if(typeof o!="object")return r.push(`valueProfile is not type object: ${o}`),{errors:r};let{matchUpValue:i,collectionPosition:s}=o;if(typeof i!="number"||typeof s!="number"||s>e||s<1)return r.push("Invalid value profile: value and collectionPosition must be numeric. collectionPosition cannot be greater than matchUpCount"),{errors:r}}let n=t.map(o=>o.collectionPosition);return n.length!==pt(n).length?(r.push("collectionPositions are not unique"),{errors:r}):{...P}}var bw={};Gt(bw,{addNotice:()=>at,callListener:()=>cl,createInstanceState:()=>$U,cycleMutationStatus:()=>pI,deepCopyEnabled:()=>uI,deleteNotice:()=>zT,deleteNotices:()=>ms,disableNotifications:()=>KU,enableNotifications:()=>cI,getDevContext:()=>je,getMethods:()=>mI,getNotices:()=>KT,getProvider:()=>QT,getTopics:()=>vr,getTournamentId:()=>Fs,getTournamentRecord:()=>dI,getTournamentRecords:()=>oi,globalLog:()=>XU,handleCaughtError:()=>km,hasTopic:()=>tu,removeTournamentRecord:()=>QU,setDeepCopy:()=>pp,setDevContext:()=>up,setGlobalLog:()=>Dw,setGlobalMethods:()=>Uw,setGlobalSubscriptions:()=>fH,setMethods:()=>Rw,setStateMethods:()=>JU,setStateProvider:()=>dH,setSubscriptions:()=>gH,setTournamentId:()=>Fm,setTournamentRecord:()=>zU,setTournamentRecords:()=>ul,timeKeeper:()=>lH});var FT={message:"Chronological error; time violation.",code:"ANACHRONISM"},nl={message:"Duplicate entry",code:"DUPLICATE_ENTRY"},bD={message:"Cannot remove main structure",code:"ERR_CANNOT_REMOVE_MAIN_STRUCTURE"},kT={message:"records must be an object with tournamentId keys",code:"ERR_INVALID_TOURNAMENTS"},kt={message:"Missing tournamentRecords",code:"ERR_MISSING_TOURNAMENTS"},j={message:"Missing tournamentRecord",code:"ERR_MISSING_TOURNAMENT"},Hc={message:"Invalid tournamentRecord",code:"ERR_INVALID_TOURNAMENT"},ac={message:"Missing tournamentId",code:"ERR_MISSING_TOURNAMENT_ID"},ha={message:"Invalid drawDefinition",code:"ERR_INVALID_DRAWDEF"},$={message:"Missing drawDefinition",code:"ERR_MISSING_DRAWDEF"},CD={message:"Existing drawDefinition(s)",code:"ERR_EXISTING_DRAWDEFS"},Mr={message:"drawDefinition not found",code:"ERR_NOT_FOUND_DRAWDEF"},Co={message:"Invalid structure",code:"ERR_INVALID_STRUCTURE"},Lg={message:"Incomplete source structure",code:"ERR_INCOMPLETE_STRUCTURE"},Fg={message:"Invalid drawPosition for seedAssignment",code:"ERR_INVALID_SEEDING_POSITION"},Yc={message:"drawPosition already assigned",code:"ERR_EXISTING_POSITION_ASSIGNMENT"},MD={message:"Schedule not cleared",code:"ERR_UNCHANGED_SCHEDULE_NOT_CLEARED"},vD={message:"Schedule conflict: court slot already occupied",code:"ERR_SCHEDULE_CONFLICT_DOUBLE_BOOKING"},OD={message:"Schedule conflict: matchUps scheduled outside court availability",code:"ERR_SCHEDULE_CONFLICT_COURT_UNAVAILABLE"},_D={message:"drawPosition not cleared",code:"ERR_FAILURE_POSITION_NOT_CLEARED"},kW={message:"drawPosition not found",code:"ERR_NOT_FOUND_DRAW_POSITION"},rp={message:"Unrecognized drawType",code:"ERR_UNRECOGNIZED_DRAW_TYPE"},jc={message:"Missing drawPositions",code:"ERR_MISSING_DRAW_POSITIONS"},qc={message:"drawPosition is active",code:"ERR_ACTIVE_DRAW_POSITION"},gw={message:"drawPosition is occupied",code:"ERR_OCCUPIED_DRAW_POSITION"},ps={message:"Invlid drawPosition",code:"ERR_INVALID_DRAW_POSITION"},Ta={message:"Missing drawPosition",code:"ERR_MISSING_DRAW_POSITION"},ol={message:"Invalid drawType",code:"ERR_INVALID_DRAW_TYPE"},vm={message:"Invalid drawSize",code:"ERR_INVALID_DRAW_SIZE"},GW={message:"Cannot set drawSize to be less than existing entries",code:"ERR_INVALID_DRAW_SIZE_MISMATCH"},$c={message:"Missing drawSize",code:"ERR_MISSING_DRAW_SIZE"},Nn={message:"Missing drawId",code:"ERR_MISSING_DRAW_ID"},xD={message:"drawId exists",code:"ERR_EXISTING_DRAW_ID"},wD={message:"participantId cannot be assigned to multiple seedNumbers",code:"INVALID_PARTICIPANT_SEEDING"},LD={message:"seedsCount greater than drawSize",code:"ERR_INVALID_SEED_COUNT"},FD={message:"Missing seedCountThresholds",code:"ERR_MISSING_SEED_COUNT_THRESHOLD"},kD={message:"Invalid action",code:"ERR_INVALID_ACTION"},GT={message:"Invalid assignment",code:"ERR_INVALID_ASSIGNMENT"},GD={message:"Missing seedAssignments",code:"ERR_MISSING_SEED_ASSIGNMENTS"},VD={message:"Invalid seedNumber",code:"ERR_INVALID_SEED_NUMBER"},BD={message:"Invalid seedPosition",code:"ERR_INVALID_SEED_POSITION"},kg={message:"Missing targetLink",code:"ERR_MISSING_LINK_TARGET"},WD={message:"Existing round",code:"ERR_EXISTING_ROUND"},VW={message:"Missing roundNumber",code:"ERR_MISSING_ROUND_NUMBER"},dn={message:"Missing structureId",code:"ERR_MISSING_STRUCTURE_ID"},Nt={message:"structure not found",code:"ERR_NOT_FOUND_STRUCTURE"},Gg={message:"Missing structures",code:"ERR_MISSING_STRUCTURES"},_i={message:"Missing structure",code:"ERR_MISSING_STRUCTURE"},Vg={message:"Missing MAIN structure",code:"ERR_MISSING_MAIN_STRUCTURE"},HD={message:"drawDefinition contains unlinked structures",code:"ERR_MISSING_STRUCTURE_LINKS"},zn={message:"Invalid eventType",code:"ERR_INVALID_EVENT_TYPE"};var le={message:"Missing event / eventId",code:"ERR_MISSING_EVENT_ID"},Wr={message:"Event not found",code:"ERR_NOT_FOUND_EVENT"},YD={message:"Event exists",code:"ERR_EXISTING_EVENT"},jD={message:"Missing entries",code:"ERR_MISSING_ENTRIES"},qD={message:"Invalid entries",code:"ERR_INVALID_ENTRIES"},Bg={message:"Missing assignments",code:"ERR_MISSING_ASSIGNMENTS"},Wg={message:"Missing stage",code:"ERR_MISSING_STAGE"},cc={message:"Invalid stage",code:"ERR_INVALID_STAGE"},$D={message:"stageSequence limit",code:"ERR_LIMIT_STAGE_SEQUENCE"},KD={message:"Missing positionAssignments",code:"ERR_MISSING_POSITION_ASSIGNMENTS"},zD={message:"Cannot Assign BYE status if no assignment: { bye: true }",code:"ERR_UNCHANGED_CANNOT_ASSIGN_BYE"},QD={message:"Lucky draw first round allows at most one BYE",code:"ERR_LUCKY_DRAW_BYE_LIMIT"},VT={message:"Unrecognized matchUpStatus",code:"ERR_UNRECOGNIZED_MATCHUP_STATUS"},Kc={message:"Unrecognized matchUpFormat",code:"ERR_UNRECOGNIZED_MATCHUP_FORMAT"},Hg={message:"Incompatible matchUpStatus",code:"ERR_INCOMPATIBLE_MATCHUP_STATUS"},Iw={message:"Propagated exits downstream",code:"ERR_PROPAGATED_EXITS_DOWNSTREAM"},uc={message:"Invalid matchUpStatus",code:"ERR_INVALID_MATCHUP_STATUS"},ri={message:"Invalid tieFormat",code:"ERR_INVALID_TIE_FORMAT"},XD={message:"Invalid matchUpFormat",code:"ERR_INVALID_MATCHUP_FORMAT"},JD={message:"Missing matchUpFormat",code:"ERR_MISSING_MATCHUP_FORMAT"},ZD={message:"Missing collectionDefinition",code:"ERR_MISSING_COLLECTION_DEFINITION"},ya={message:"Missing tieFormat",code:"ERR_MISSING_TIE_FORMAT"},mr={message:"Missing matchUpId",code:"ERR_MISSING_MATCHUP_ID"},xs={message:"Missing matchUpIds",code:"ERR_MISSING_MATCHUP_IDS"},Be={message:"matchUp not found",code:"ERR_NOT_FOUND_MATCHUP"},Bn={message:"Missing matchUps",code:"ERR_MISSING_MATCHUPS"},Xe={message:"Missing matchUp",code:"ERR_MISSING_MATCHUP"},cr={message:"Invalid matchUp",code:"ERR_INVALID_MATCHUP"},BT={message:"Missing policyType",code:"ERR_MISSING_POLICY_TYPE"},Ea={message:"Missing policyDefinitions",code:"ERR_MISSING_POLICY_DEFINITIONS"},BW={message:"Missing seeding policy",code:"ERR_MISSING_POLICY_SEEDING"},tU={message:"Missing avoidance policy",code:"ERR_MISSING_POLICY_AVOIDANCE"},WT={message:"Missing policy attributes",code:"ERR_MISSING_POLICY_ATTRIBUTES"},eU={message:"Invalid policyDefinitions",code:"ERR_INVALID_POLICY_DEFINITIONS"},HT={message:"existing policyType",code:"ERR_EXISTING_POLICY_TYPE"},WW={message:"Policy not attached",code:"ERR_FAILURE_POLICY_NOT_ATTACHED"},np={message:"Policy not found",code:"ERR_NOT_FOUND_POLICY"},HW={message:"Missing scoring policy / matchUpFormats",code:"ERR_MISSING_POLICY_SCORING_MATCHUP_FORMATS"},rU={message:"Invalid sideNumber",code:"ERR_INVALID_SIDE_NUMBER"},YW={message:"Invalid setNumber",code:"ERR_INVALID_SET_NUMBER"},Yg={message:"Missing setObject",code:"ERR_MISSING_SET_ATTRIBUTE"},jW={message:"Missing setNumber",code:"ERR_MISSING_SET_NUMBER"},qW={message:"Missing sideNumber",code:"ERR_MISSING_SIDE_NUMBER"},jg={message:"Missing courtId",code:"ERR_MISSING_COURT_ID"},nt={message:"Missing value",code:"ERR_MISSING_VALUE"},nU={message:"Missing birthdate",code:"ERR_MISSING_BIRTH_DATE"},oU={message:"Missing date",code:"ERR_MISSING_DATE"},qg={message:"No valid dates",code:"ERR_NO_VALID_DATES"},il={message:"Invalid bookings",code:"ERR_INVALID_BOOKINGS"},$g={message:"Invalid dateAvailability",code:"ERR_INVALID_DATE_AVAILABILITY"},iU={message:"Missing dateAvailability",code:"ERR_MISSING_DATE_AVAILABILITY"},ae={message:"Invalid Date",code:"ERR_INVALID_DATE"},ws={message:"Invalid time",code:"ERR_INVALID_TIME"},sU={message:"Invalid tournament dates",code:"ERR_INVALID_DATES_TOURNAMENT"},Sw={message:"Missing date range",info:"Event or tournament must have start and end dates",code:"ERR_MISSING_DATE_RANGE"},op={message:"Invalid Time Zone",code:"ERR_INVALID_TIME_ZONE"},ip={message:"Invalid embargo: must be an ISO 8601 datetime with timezone (Z or \xB1HH:MM offset)",code:"ERR_INVALID_EMBARGO"},YT={message:"Invalid game scores",code:"ERR_INVALID_SCORES_GAME"},aU={message:"Invalid score",code:"ERR_INVALID_SCORE"},sl={message:"Invalid winningSide",code:"ERR_INVALID_WINNING_SIDE"};var hw={message:"No participants generated",code:"ERR_NO_PARTICIPANTS_GENERATED"},Kg={message:"Cannot modify tieFormat",code:"ERR_UNCHANGED_CANNOT_MODIFY_TIEFORMAT"},cU={message:"Cannot modify participantType",code:"ERR_UNCHANGED_CANNOT_MODIFY_PARTICIPANT_TYPE"},Om={message:"Cannot remove participants",code:"ERR_UNCHANGED_CANNOT_REMOVE_PARTICIPANTS"},uU={message:"Participant category mismatch",code:"ERR_CATEGORY_MISMATCH"},al={message:"Cannot change winningSide",code:"ERR_UNCHANGED_CANNOT_CHANGE_WINNING_SIDE"},xi={message:"Invalid participant",code:"ERR_INVALID_PARTICIPANT"},Hr={message:"Invalid participantId",code:"ERR_INVALID_PARTICIPANT_ID"},_r={message:"Invalid participantIds",code:"ERR_INVALID_PARTICIPANT_IDS"},pU={message:"Invalid participantRole",code:"ERR_INVALID_PARTICIPANT_ROLE"},Dn={message:"Invalid participantType",code:"ERR_INVALID_PARTICIPANT_TYPE"},mU={message:"Missing participantRole",code:"ERR_MISSING_PARTICIPANT_ROLE"},Aa={message:"Missing participant",code:"ERR_MISSING_PARTICIPANT"},zc={message:"Missing participants",code:"ERR_MISSING_PARTICIPANTS"},We={message:"Missing participantId",code:"ERR_MISSING_PARTICIPANT_ID"},dU={message:"Missing qualified participants",code:"ERR_MISSING_QUALIFIED_PARTICIPANTS"},ee={message:"Participant Not Found",code:"ERR_NOT_FOUND_PARTICIPANT"},lU={message:"participantId exists",code:"ERR_EXISTING_PARTICIPANT_ID"},$W={message:"participant pair exists",code:"ERR_EXISTING_PARTICIPANT_PAIR"},fU={message:"No participant removed",code:"ERR_UNCHANGED_NO_PARTICIPANT_REMOVED"},Mo={message:"Missing participantIds",code:"ERR_MISSING_PARTICIPANT_IDS"},gU={message:"Missing participantsCount",code:"ERR_MISSING_PARTICIPANT_COUNT"},IU={message:"Participant not checked in",code:"ERR_UNCHANGED_PARTICIPANT_NOT_CHECKED_IN"},SU={message:"Missing person details",code:"ERR_MISSING_PERSON_DETAILS"},Pa={message:"Existing participant drawPosition assignment",code:"ERR_EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT"},_m={message:"Existing participant",code:"ERR_EXISTING_PARTICIPANT"},zg={message:"participantsCount exceeds drawSize",code:"ERR_INVALID_PARTICIPANT_COUNT"},Qg={message:"Invalid entry status",code:"ERR_INVALID_ENTRY_STATUS"},jT={message:"Participant Entry Not Found",code:"ERR_NOT_FOUND_PARTICIPANT_ENTRY"},Tw={message:"Participant not entered in stage",code:"ERR_UNCHANGED_PARTICIPANT_NOT_ENTERED"},yw={message:"Participant not found in stageSequence",code:"ERR_NOT_FOUND_PARTICIPANT_IN_STAGE"},hU={message:"entryStatus not allowed in stage",code:"ERR_INVALID_ENTRY_STATUS_IN_STAGE"},TU={message:"entryStatus not allowed for event",code:"ERR_INVALID_ENTRY_STATUS_IN_EVENT"},Xg={message:"No stage space available for entryStatus",code:"ERR_UNCHANGED_NO_AVAILABLE_STAGE_SPACE"},Jg={message:"Insufficient drawPositions to accommodate qualifiers",code:"ERR_UNCHANGED_NO_DRAW_POSITIONS_FOR_QUALIFIERS"},Zg={message:"Insufficient drawPositions to accommodate entries",code:"ERR_INSUFFICIENT_DRAW_POSITIONS"},yU={message:"Missing penaltyType",code:"ERR_MISSING_PENALTY_TYPE"},EU={message:"Missing penaltyId",code:"ERR_MISSING_PENALTY_ID"},sp={message:"Penalty not found",code:"ERR_NOT_FOUND_PENALTY"},AU={message:"Missing courtsCount/courtNames",code:"ERR_MISSING_COURTS_INFO"},vo={message:"Court not found",code:"ERR_NOT_FOUND_COURT"},PU={message:"Court exists",code:"ERR_EXISTING_COURT"},qT={message:"Booking not found",code:"ERR_NOT_FOUND_BOOKING"},NU={message:"An active draft already exists for this draw",code:"ERR_EXISTING_DRAFT"},DU={message:"Existing matchUps conflict with booking",code:"ERR_EXISTING_MATCHUPS"},UU={message:"Venue exists",code:"ERR_EXISTING_VENUE"},wi={message:"Venue not found",code:"ERR_NOT_FOUND_VENUE"},Ls={message:"Missing venueId",code:"ERR_MISSING_VENUE_ID"},RU={message:"Invalid endTime",code:"ERR_INVALID_END_TIME"},bU={message:"Existing endTime",code:"ERR_EXISTING_END_TIME"},CU={message:"Invalid stopTime",code:"ERR_INVALID_STOP_TIME"},MU={message:"Invalid startTime",code:"ERR_INVALID_START_TIME"},Ew={message:"Invalid resumeTime",code:"ERR_INVALID_RESUME_TIME"},tI={message:"Invalid timeItem",code:"ERR_INVALID_TIME_ITEMS"},vU={message:"Missing async state provider",code:"ERR_MISSING_ASYNC_STATE_PROVIDER"},eI={message:"Missing timeItem",code:"ERR_MISSING_TIME_ITEM"},rI={message:"Missing timeItems",code:"ERR_MISSING_TIME_ITEMS"},ap={message:"Missing context",code:"ERR_MISSING_CONTEXT"},OU={message:"Missing schedule",code:"ERR_MISSING_SCHEDULE"},Qc={message:"Invalid scaleItem",code:"ERR_INVALID_SCALE_ITEM"},_U={message:"Modifications failed",code:"ERR_FAILURE_MODIFICATIONS"},Na={message:"No modifications applied",code:"ERR_UNCHANGED_NO_MODIFICATIONS_APPLIED"},xU={message:"Unable to assign court",code:"ERR_UNCHANGED_COURT_NOT_ASSIGNED"},xm={message:"No Candidates",code:"ERR_UNCHANGED_NO_CANDIDATES"},ni={message:"Invalid configuration",code:"ERR_INVALID_CONFIG"},wU={message:"Invalid collectionDefinition",code:"ERR_INVALID_COLLECTION_DEFINITION"},yo={message:"Invalid object",code:"ERR_INVALID_OBJECT"},wm={message:"Invalid gender",code:"ERR_INVALID_GENDER"},cp={message:"Invalid category",code:"ERR_INVALID_CATEGORY"},O={message:"Invalid values",code:"ERR_INVALID_VALUES"},LU={message:"Duplicate value",code:"ERR_DUPLICATE_VALUE"},nI={message:"Team not found",code:"ERR_NOT_FOUND_TEAM"},FU={message:"No valid actions",code:"ERR_NO_VALID_ACTIONS"},Xc={message:"No valid attributes",code:"ERR_NO_VALID_ATTRIBUTES"},oI={message:"Value unchanged",code:"ABORT_UNCHANGED"},fe={message:"Not found",code:"ERR_NOT_FOUND"},iI={message:"Not implemented",code:"ERR_NOT_IMPLEMENTED"},kU={message:"Existing flight",code:"ERR_EXISTING_FLIGHT"},sI={message:"Existing flight profile",code:"ERR_EXISTING_FLIGHT_PROFILE"},GU={message:"Existing outcome",code:"ERR_EXISTING_OUTCOME"},VU={message:"Existing matchUpId",code:"ERR_EXISTING_MATCHUP_ID"},$T={message:"Existing stage",code:"ERR_EXISTING_STAGE"},aI={message:"Existing structure",code:"ERR_EXISTING_STRUCTURE"},Jc={message:"Method not found",code:"ERR_NOT_FOUND_METHOD"},BU={message:"Mutation blocked by active lock",code:"ERR_MUTATION_LOCKED"},WU={message:"Active mutation lock already exists for scope",code:"ERR_EXISTING_MUTATION_LOCK"},HU={message:"Mutation lock not found",code:"ERR_NOT_FOUND_MUTATION_LOCK"},YU={message:"Lock token does not match",code:"ERR_UNAUTHORIZED_LOCK_OPERATION"},jU={message:"Scheduled matchUps",code:"ERR_SCHEDULED_MATCHUPS"},Zc={message:"Scores present",code:"ERR_SCORES_PRESENT"},Aw={ANACHRONISM:FT,BOOKING_NOT_FOUND:qT,CANNOT_CHANGE_WINNING_SIDE:al,CANNOT_MODIFY_TIEFORMAT:Kg,CANNOT_MODIFY_PARTICIPANT_TYPE:cU,CANNOT_REMOVE_MAIN_STRUCTURE:bD,CANNOT_REMOVE_PARTICIPANTS:Om,CATEGORY_MISMATCH:uU,COURT_EXISTS:PU,COURT_NOT_FOUND:vo,EXISTING_DRAFT:NU,EXISTING_MATCHUPS:DU,DRAW_DEFINITION_NOT_FOUND:Mr,DRAW_ID_EXISTS:xD,DRAW_POSITION_ACTIVE:qc,DRAW_POSITION_ASSIGNED:Yc,DRAW_POSITION_NOT_CLEARED:_D,DRAW_POSITION_NOT_FOUND:kW,DRAW_SIZE_MISMATCH:GW,DUPLICATE_ENTRY:nl,DUPLICATE_VALUE:LU,ENTRY_STATUS_NOT_ALLOWED_FOR_EVENT:TU,ENTRY_STATUS_NOT_ALLOWED_IN_STAGE:hU,EVENT_EXISTS:YD,EVENT_NOT_FOUND:Wr,EXISTING_DRAW_DEFINITIONS:CD,EXISTING_END_TIME:bU,EXISTING_FLIGHT:kU,EXISTING_MATCHUP_ID:VU,EXISTING_OUTCOME:GU,EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT:Pa,EXISTING_PARTICIPANT:_m,EXISTING_POLICY_TYPE:HT,EXISTING_PROFILE:sI,EXISTING_ROUND:WD,EXISTING_STAGE:$T,EXISTING_STRUCTURE:aI,INCOMPATIBLE_MATCHUP_STATUS:Hg,INCOMPLETE_SOURCE_STRUCTURE:Lg,INSUFFICIENT_DRAW_POSITIONS:Zg,INVALID_ACTION:kD,INVALID_ASSIGNMENT:GT,INVALID_BOOKINGS:il,INVALID_CATEGORY:cp,INVALID_COLLECTION_DEFINITION:wU,INVALID_CONFIGURATION:ni,INVALID_DATE_AVAILABILITY:$g,INVALID_DATE:ae,INVALID_DRAW_DEFINITION:ha,INVALID_DRAW_POSITION_FOR_SEEDING:Fg,INVALID_DRAW_POSITION:ps,INVALID_DRAW_SIZE:vm,INVALID_END_TIME:RU,INVALID_ENTRIES:qD,INVALID_EVENT_TYPE:zn,INVALID_GAME_SCORES:YT,INVALID_GENDER:wm,INVALID_MATCHUP_FORMAT:XD,INVALID_MATCHUP_STATUS:uc,INVALID_MATCHUP_STATUS_BYE:zD,INVALID_MATCHUP:cr,INVALID_OBJECT:yo,INVALID_PARTICIPANT_ID:Hr,INVALID_PARTICIPANT_IDS:_r,INVALID_PARTICIPANT_ROLE:pU,INVALID_PARTICIPANT_SEEDING:wD,INVALID_PARTICIPANT_TYPE:Dn,INVALID_PARTICIPANT:xi,INVALID_POLICY_DEFINITION:eU,INVALID_RECORDS:kT,INVALID_SCALE_ITEM:Qc,INVALID_SEED_NUMBER:VD,INVALID_SEED_POSITION:BD,INVALID_SET_NUMBER:YW,INVALID_SIDE_NUMBER:rU,INVALID_SCORE:aU,INVALID_STAGE:cc,INVALID_START_TIME:MU,INVALID_STRUCTURE:Co,INVALID_STOP_TIME:CU,INVALID_TIE_FORMAT:ri,INVALID_TIME:ws,INVALID_TIME_ITEM:tI,INVALID_TOURNAMENT_DATES:sU,INVALID_TOURNAMENT_RECORD:Hc,INVALID_VALUES:O,INVALID_WINNING_SIDE:sl,LUCKY_DRAW_BYE_LIMIT:QD,MATCHUP_NOT_FOUND:Be,METHOD_NOT_FOUND:Jc,MUTATION_LOCKED:BU,MUTATION_LOCK_EXISTS:WU,MUTATION_LOCK_NOT_FOUND:HU,MISSING_ASSIGNMENTS:Bg,MISSING_ASYNC_STATE_PROVIDER:vU,MISSING_AVOIDANCE_POLICY:tU,MISSING_BIRTH_DATE:nU,MISSING_COLLECTION_DEFINITION:ZD,MISSING_COURT_ID:jg,MISSING_COURTS_INFO:AU,MISSING_DATE_AVAILABILITY:iU,MISSING_DATE:oU,MISSING_DRAW_DEFINITION:$,MISSING_DRAW_ID:Nn,MISSING_DRAW_POSITION:Ta,MISSING_DRAW_POSITIONS:jc,MISSING_DRAW_SIZE:$c,MISSING_ENTRIES:jD,MISSING_EVENT:le,MISSING_QUALIFIED_PARTICIPANTS:dU,MISSING_MATCHUP_FORMAT:JD,MISSING_MATCHUP_ID:mr,MISSING_MATCHUP_IDS:xs,MISSING_MATCHUP:Xe,MISSING_MATCHUPS:Bn,MISSING_PARTICIPANT_COUNT:gU,MISSING_PARTICIPANT_ID:We,MISSING_PARTICIPANT_IDS:Mo,MISSING_PARTICIPANT_ROLE:mU,MISSING_PARTICIPANT:Aa,MISSING_PARTICIPANTS:zc,MISSING_PENALTY_ID:EU,MISSING_PENALTY_TYPE:yU,MISSING_PERSON_DETAILS:SU,MISSING_POLICY_ATTRIBUTES:WT,MISSING_POLICY_DEFINITION:Ea,MISSING_POLICY_TYPE:BT,MISSING_POSITION_ASSIGNMENTS:KD,MISSING_ROUND_NUMBER:VW,MISSING_SCHEDULE:OU,MISSING_SCORING_POLICY:HW,MISSING_SEED_ASSIGNMENTS:GD,MISSING_SEEDCOUNT_THRESHOLDS:FD,MISSING_SEEDING_POLICY:BW,MISSING_SET_NUMBER:jW,MISSING_SET_OBJECT:Yg,MISSING_SIDE_NUMBER:qW,MISSING_STAGE:Wg,MISSING_STRUCTURE_ID:dn,MISSING_STRUCTURE:_i,MISSING_MAIN_STRUCTURE:Vg,MISSING_STRUCTURES:Gg,MISSING_TARGET_LINK:kg,MISSING_TIE_FORMAT:ya,MISSING_TIME_ITEM:eI,MISSING_TIME_ITEMS:rI,MISSING_TOURNAMENT_ID:ac,MISSING_TOURNAMENT_RECORD:j,MISSING_TOURNAMENT_RECORDS:kt,MISSING_VALUE:nt,MISSING_VENUE_ID:Ls,MODIFICATIONS_FAILED:_U,NO_CANDIDATES:xm,NO_DRAW_POSITIONS_AVAILABLE_FOR_QUALIFIERS:Jg,NO_MODIFICATIONS_APPLIED:Na,NO_STAGE_SPACE_AVAILABLE_FOR_ENTRY_STATUS:Xg,NO_PARTICIPANT_REMOVED:fU,NO_VALID_ACTIONS:FU,NO_VALID_ATTRIBUTES:Xc,NO_VALID_DATES:qg,NOT_FOUND:fe,NOT_IMPLEMENTED:iI,PARTICIPANT_COUNT_EXCEEDS_DRAW_SIZE:zg,PARTICIPANT_ID_EXISTS:lU,PARTICIPANT_NOT_CHECKED_IN:IU,PARTICIPANT_NOT_FOUND:ee,PARTICIPANT_PAIR_EXISTS:$W,PENALTY_NOT_FOUND:sp,POLICY_NOT_ATTACHED:WW,POLICY_NOT_FOUND:np,SCHEDULE_NOT_CLEARED:MD,SCHEDULE_CONFLICT_DOUBLE_BOOKING:vD,SCHEDULE_CONFLICT_COURT_UNAVAILABLE:OD,SCHEDULED_MATCHUPS:jU,SCORES_PRESENT:Zc,SEEDSCOUNT_GREATER_THAN_DRAW_SIZE:LD,STAGE_SEQUENCE_LIMIT:$D,STRUCTURE_NOT_FOUND:Nt,TEAM_NOT_FOUND:nI,UNABLE_TO_ASSIGN_COURT:xU,UNAUTHORIZED_LOCK_OPERATION:YU,UNLINKED_STRUCTURES:HD,UNRECOGNIZED_DRAW_TYPE:rp,UNRECOGNIZED_MATCHUP_FORMAT:Kc,UNRECOGNIZED_MATCHUP_STATUS:VT,VALUE_UNCHANGED:oI,VENUE_EXISTS:UU};var Qe={disableNotifications:!1,tournamentId:void 0,tournamentRecords:{},subscriptions:{},modified:!1,methods:{},notices:[]},qU={addNotice:iH,callListener:pH,cycleMutationStatus:oH,deleteNotice:cH,deleteNotices:aH,disableNotifications:KW,enableNotifications:zW,getMethods:Lm,getNotices:sH,getTopics:uH,getTournamentId:Pw,getTournamentRecord:QW,getTournamentRecords:XW,removeTournamentRecord:eH,setMethods:nH,setSubscriptions:rH,setTournamentId:ZW,setTournamentRecord:JW,setTournamentRecords:tH,handleCaughtError:mH};function KW(){Qe.disableNotifications=!0}function zW(){Qe.disableNotifications=!1}function Pw(){return Qe.tournamentId}function QW(t){return Qe.tournamentRecords[t]}function XW(){return Qe.tournamentRecords}function JW(t){let e=t?.tournamentId;return e?(Qe.tournamentRecords[e]=t,{success:!0}):{error:Hc}}function ZW(t){return t?Qe.tournamentRecords[t]?(Qe.tournamentId=t,{success:!0}):{error:j}:(Qe.tournamentId=void 0,{success:!0})}function tH(t){Qe.tournamentRecords=t;let e=Object.keys(t);e.length===1?Qe.tournamentId=e[0]:e.length||(Qe.tournamentId=void 0)}function eH(t){if(typeof t!="string")return{error:O};if(!Qe.tournamentRecords[t])return{error:fe};delete Qe.tournamentRecords[t];let e=Object.keys(Qe.tournamentRecords);return e.length===1?Qe.tournamentId=e[0]:e.length||(Qe.tournamentId=void 0),{success:!0}}function rH(t){return t.subscriptions===null||Object.keys(t.subscriptions).length===0?(Qe.subscriptions={},{...P}):typeof t.subscriptions!="object"?{error:O}:(Object.keys(t.subscriptions).forEach(e=>{typeof t.subscriptions[e]=="function"?Qe.subscriptions[e]=t.subscriptions[e]:delete Qe.subscriptions[e]}),{...P})}function nH(t){return typeof t!="object"?{error:O}:(Object.keys(t).forEach(e=>{typeof t[e]=="function"&&(Qe.methods[e]=t[e])}),{...P})}function oH(){let t=Qe.modified;return Qe.modified=!1,t}function iH({topic:t,payload:e,key:r},n){if(!(typeof t!="string"||typeof e!="object")&&(Qe.disableNotifications||(Qe.modified=!0),!(Qe.disableNotifications||!Qe.subscriptions[t]&&!n)))return r&&(Qe.notices=Qe.notices.filter(o=>!(o.topic===t&&o.key===r))),Qe.notices.push({topic:t,payload:e,key:r}),{...P}}function Lm(){return Qe.methods??{}}function sH({topic:t}){return Qe.notices.filter(e=>e.topic===t).map(e=>e.payload)}function aH(){Qe.notices=[]}function cH({topic:t,key:e}){Qe.notices=Qe.notices.filter(r=>(!t||r.topic===t)&&r.key!==e)}function uH(){return{topics:Object.keys(Qe.subscriptions)}}function pH({topic:t,notices:e},r){let n=Qe.subscriptions[t];n&&typeof n=="function"&&n(e);let o=r?.[t];o&&typeof o=="function"&&o(e)}function mH({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:Pw(),params:JSON.stringify(r),engine:t,methodName:e,error:o}),{error:o}}var be={timers:{default:{elapsedTime:0}},globalSubscriptions:{},deepCopyAttributes:{stringify:[],ignore:[],toJSON:[]},globalMethods:[],deepCopy:!0},rn=qU,Nw=["addNotice","callListener","cycleMutationStatus","deleteNotice","deleteNotices","disableNotifications","enableNotifications","getMethods","getNotices","getTopics","getTournamentId","getTournamentRecord","getTournamentRecords","removeTournamentRecord","setSubscriptions","setTournamentId","setTournamentRecord","setTournamentRecords"];function dH(t){if(typeof t!="object")throw new Error("Global state provider can not be undefined or null");if(Yt(Object.keys(t),Nw).length!==Nw.length)throw new Error("Global state provider is missing required methods");return rn=t,{success:!0}}function $U(){if(rn.createInstanceState){try{rn.createInstanceState()}catch(t){return{error:t}}return{success:!0}}else return{error:vU}}function je(t){return!t||typeof t!="object"?be.devContext??!1:typeof be.devContext!="object"?!1:Object.keys(t).every(e=>be.devContext?.[e]===t[e])&&be.devContext}function lH(t="reset",e="default"){let r=Date.now();if(t==="report"){if(e==="allTimers")return Object.keys(be.timers).filter(o=>o!=="default"||be.timers[o].startTime).map(o=>{let i=be.timers[o],s=i.state==="stopped"?0:(r-(i?.startTime??0))/1e3,a=i.elapsedTime+s;return{state:be.timers[o].state,elapsedTime:a.toFixed(2),timer:o}});{let n=be.timers[e].state==="stopped"?0:(r-(be.timers[e]?.startTime??0))/1e3,o=be.timers[e].elapsedTime+n;return{state:be.timers[e].state,elapsedTime:o.toFixed(2),timer:e}}}if(!be.timers[e]||t==="reset"){if(e==="allTimers")return be.timers={default:{elapsedTime:0}},!0;be.timers[e]={startTime:r,state:"active",elapsedTime:0}}return be.timers[e].elapsedTime||(be.timers[e].elapsedTime=0),t==="stop"&&be.timers[e].state!=="stopped"&&(be.timers[e].state="stopped")&&(be.timers[e].elapsedTime+=(r-(be.timers[e]?.startTime??0))/1e3),t==="start"&&(be.timers[e].startTime=r)&&(be.timers[e].state="active"),be.timers[e]}function Dw(t){Br(t)?be.globalLog=t:delete be.globalLog}function up(t){be.devContext=t}function KU(){rn.disableNotifications()}function cI(){rn.enableNotifications()}function pp(t,e){typeof t=="boolean"&&(be.deepCopy=t),typeof e=="object"&&(Array.isArray(e.ignore)&&(be.deepCopyAttributes.ignore=e.ignore),Array.isArray(e.toJSON)&&(be.deepCopyAttributes.toJSON=e.toJSON),Array.isArray(e.stringify)&&(be.deepCopyAttributes.stringify=e.stringify),e.threshold&&(be.deepCopyAttributes.threshold=e.threshold))}function uI(){return{enabled:be.deepCopy,...be.deepCopyAttributes}}function fH(t){return t?.subscriptions?(Object.keys(t.subscriptions).forEach(e=>{be.globalSubscriptions[e]=t.subscriptions[e]}),{...P}):{error:nt,info:"missing subscriptions"}}function gH(t){return t?.subscriptions?rn.setSubscriptions({subscriptions:t.subscriptions}):{error:nt,info:"missing subscriptions"}}function Uw(t){return t?typeof t!="object"?{error:O}:(Object.keys(t).forEach(e=>{Br(t[e])&&(be.globalMethods[e]=t[e])}),{...P}):{error:nt,info:"missing method declarations"}}function Rw(t){return t?typeof t!="object"?{error:O}:rn.setMethods(t):{error:nt,info:"missing method declarations"}}function pI(){return rn.cycleMutationStatus()}function at(t){if(typeof t?.topic!="string")return;let e=be.globalSubscriptions[t.topic];return rn.addNotice(t,e)}function mI(){return{...be.globalMethods,...rn.getMethods()}}function KT(t){return rn.getNotices(t)}function zT({key:t,topic:e}){return rn.deleteNotice({key:t,topic:e})}function ms(){return rn.deleteNotices()}function vr(){return rn.getTopics()}function tu(t){return vr()?.topics?.includes(t)}async function cl(t){return rn.callListener(t,be.globalSubscriptions)}function Fs(){return rn.getTournamentId()}function dI(t){return rn.getTournamentRecord(t)}function oi(){return rn.getTournamentRecords()}function zU(t){return rn.setTournamentRecord(t)}function ul(t){return rn.setTournamentRecords(t)}function Fm(t){return rn.setTournamentId(t)}function QU(t){return rn.removeTournamentRecord(t)}function QT(){return rn}function km({engineName:t,methodName:e,params:r,err:n}){let o=Br(rn.handleCaughtError)&&rn.handleCaughtError||qU.handleCaughtError,{tournamentRecord:i,...s}=r;return o({params:s,engineName:t,methodName:e,err:n})}function XU(t,e){if(be.globalLog)try{be.globalLog({log:t,engine:e})}catch(r){console.log("globalLog error",r),console.log(e,t),Dw()}else console.log(e,t)}function JU(t,e,r,n){if(!Tt(t))return{error:O};Le||(r=1);let o=Array.isArray(e)?e:[],i={},s=(a,c=0)=>{Object.keys(a).forEach(u=>{Br(a[u])?i[u]=a[u]:Tt(a[u])&&(e===!0||o?.includes(u))&&(r===void 0||c<r)&&s(a[u],c+1)})};return s(t),n?Uw(i):Rw(i),{methods:i}}function IH(t,e,r){return Object.keys(t).filter(n=>!e.includes(t[n])&&(!r||(Array.isArray(t[n])?t[n].length:!0)))}function et(t,e,r,n){if(typeof t!="object"||t===null)return t;uI()?.enabled||(n=!0);let i=["",void 0,null];e&&i.push(!1);let s=IH(t,i,r);return Object.assign({},...s.map(a=>Array.isArray(t[a])?{[a]:n?t[a]:t[a].map(c=>et(c))}:{[a]:n?t[a]:et(t[a])}))}function M({context:t,result:e,stack:r,info:n}){return e&&!Array.isArray(e?.stack)&&(e.stack=[]),e&&Array.isArray(e?.stack)&&typeof r=="string"&&e.stack.push(r),e&&n&&(e.info=n),e&&typeof t=="object"&&Object.keys(t).length&&(e.context??={},Object.assign(e.context,et(t))),e&&!e?.error&&!e?.success&&Object.assign(e,{...P}),e??{success:!0}}var Je="FEMALE",ii="OTHER",ds="MIXED",Ce="MALE";var pl={FEMALE_ABBR:"F",OTHER_ABBR:"O",MIXED_ABBR:"X",MALE_ABBR:"M",ANY_ABBR:"A",FEMALE:Je,MIXED:ds,OTHER:ii,MALE:Ce,ANY:"ANY"};function ls(t){return[Je,"F"].includes(t)}function Da(t){return[Ce,"M"].includes(t)}function nn(t){return[ds,"X"].includes(t)}function Oo(t){return["ANY","A"].includes(t)}function Ar(t){if(t){if(ls(t))return Je;if(nn(t))return ds;if(Da(t))return Ce;if(Oo(t))return"ANY"}return ii}function Un(t){return ls(t)||Da(t)}var EH="MIXED events can not contain mixed singles or { gender: ANY } collections",AH="events with { gender: ANY } can not contain MIXED singles collections";function ml(t){let e="tieFormatGenderValidityCheck",{referenceGender:r,matchUpType:n,gender:o}=t;return r&&o&&Un(r)&&Ar(r)!==Ar(o)?M({result:{valid:!1,error:wm},context:{gender:o},stack:e}):nn(r)&&(Oo(o)||nn(o)&&n!==Rt)?M({result:{error:wm,valid:!1},info:EH,stack:e}):Oo(r)&&nn(o)&&n!==Rt?M({result:{error:wm,valid:!1},info:AH,stack:e}):{valid:!0}}var PH="normal",ZU="timed",NH="final",lI="NOAD";var tR=["SET","HAL","QTR","PER","INN","RND","FRM","MAP","MAT"],XT="CONSECUTIVE",JT="TRADITIONAL",DH="game",UH="matchUp",Cw={S:PH,F:NH,G:DH,M:UH};function mp(t,e){if(Tt(t)&&(t?.bestOf||t?.exactly)&&t?.setFormat)return bH(t,e)}function fI(t){return!Number.isNaN(Number(t))&&Number(t)}function Ow(t){let e=`T${t.minutes}`;return t.based==="P"&&(e+="P"),t.tiebreakFormat?.tiebreakTo&&(e+=`/TB${t.tiebreakFormat.tiebreakTo}`),t.modifier&&(e+=`@${t.modifier}`),e}function RH(t){let e=t?.deuceAfter?`${t.deuceAfter}D`:"";if(t?.type===JT)return`TN${e}`;if(t?.type===XT&&Number.isInteger(t.count))return`${t.count}C${e}`}function bH(t,e){let r=fI(t.bestOf)||void 0,n=fI(t.exactly)||void 0,o=r||n;if(t.setFormat?.timed&&t.simplified&&o===1)return Ow(t.setFormat);let i=t.matchRoot||"SET",s=n&&n!==1?"X":"",a=t.aggregate?"A":"",c=o&&`${i}${o}${s}${a}`||"",u=Mw(t.setFormat,e),p=u&&`S:${u}`||"",m=Mw(t.finalSetFormat,e),d=o&&o>1&&m&&u!==m&&`F:${m}`||"",l=t.gameFormat?`G:${RH(t.gameFormat)}`:"",f=t.matchUpConstraint?.timed?`M:T${t.matchUpConstraint.minutes}`:"";if(c&&u)return[c,p,l,d,f].filter(Boolean).join("-")}function Mw(t,e){if(typeof t=="object"&&Object.keys(t).length){if(t.timed)return Ow(t);if(t.outs)return`O${t.outs}`;if(t.tiebreakSet)return vw(t.tiebreakSet);let r=fI(t.setTo);if(r){let n=t.NoAD&&lI||"",o=vw(t.tiebreakFormat),i=o&&`/${o}`||"",s=fI(t.tiebreakAt),a=s&&(s!==r||e)&&`@${s}`||"";if(o!==!1)return`${r}${n}${i}${a}`}}}function vw(t){if(t){if(typeof t=="object"&&!t.tiebreakTo)return"";if(typeof t=="object"&&fI(t.tiebreakTo)){let e=`TB${t.tiebreakTo}${t.NoAD?lI:""}`;return t.modifier&&(e+=`@${t.modifier}`),e}else return!1}}function oe(t){if(wt(t)){let e=t.startsWith("T")&&ZU||tR.some(r=>t.startsWith(r))&&"SET"||"";if(e===ZU){let r=Lw(t),n={simplified:!0,setFormat:r,bestOf:1};if(r)return n}if(e==="SET")return vH(t)}}function CH(t){let e=tR.find(u=>t.startsWith(u));if(!e)return;let r=t.slice(e.length),n=/^(\d+)([A-Z]*)$/.exec(r);if(!n)return;let o=Gm(n[1]);if(!o)return;let i=n[2],s=!1,a=!1,c=[];for(let u of i)u==="X"?s=!0:u==="A"?a=!0:c.push(u);return{matchRoot:e,count:o,exactly:s,aggregate:a,matchMods:c}}function MH(t){let e=/^(.+?)(\d+D)$/.exec(t),r=e?e[1]:t,n=e?Number(e[2].slice(0,-1)):void 0;if(n!==void 0&&(n<1||!Number.isInteger(n)))return;if(r==="TN"){let i={type:JT};return n&&(i.deuceAfter=n),i}let o=/^([1-9]\d*)C$/.exec(r);if(o){let i={type:XT,count:Number(o[1])};return n&&(i.deuceAfter=n),i}}function vH(t){let e=t.split("-"),r=CH(e[0]);if(!r)return;let{matchRoot:n,count:o,exactly:i,aggregate:s,matchMods:a}=r,c=i&&o!==1?void 0:o,u=i&&o!==1?o:void 0,p,m,d,l,h={setFormat:p,finalSetFormat:m,gameFormat:d,matchUpConstraint:l,sCount:0,fCount:0,gCount:0,mCount:0};for(let T=1;T<e.length;T++)if(!OH(e[T],h))return;return{setFormat:p,finalSetFormat:m,gameFormat:d,matchUpConstraint:l}=h,_H({setFormat:p,finalSetFormat:m,gameFormat:d,matchUpConstraint:l,matchRoot:n,aggregate:s,matchMods:a,bestOf:c,exactly:u})}function OH(t,e){let r=t.indexOf(":");if(r<0)return!1;let n=t.slice(0,r),o=t.slice(r+1);if(!(n in Cw))return!1;if(n==="S"){if(e.sCount++,e.sCount>1)return!1;e.setFormat=_w(t,o)}else if(n==="F"){if(e.fCount++,e.fCount>1)return!1;e.finalSetFormat=_w(t,o)}else if(n==="G"){if(e.gCount++,e.gCount>1||(e.gameFormat=MH(o),!e.gameFormat))return!1}else if(n==="M"&&(e.mCount++,e.mCount>1||(e.matchUpConstraint=GH(o),!e.matchUpConstraint)))return!1;return!0}function _H({setFormat:t,finalSetFormat:e,gameFormat:r,matchUpConstraint:n,matchRoot:o,aggregate:i,matchMods:s,bestOf:a,exactly:c}){let u=t&&t.timed||e&&e.timed;if(o==="SET"&&!(a&&a<6||u&&c)||!t||!(!e||e))return;let d=et({setFormat:t,exactly:c,bestOf:a});return o!=="SET"&&(d.matchRoot=o),i&&(d.aggregate=!0),s.length>0&&(d.matchMods=s),e&&(d.finalSetFormat=e),r&&(d.gameFormat=r),n&&(d.matchUpConstraint=n),d}function _w(t,e){return e.startsWith("TB")?xH(e):e.startsWith("O")?wH(e):e.startsWith("T")?Lw(e):LH(t,e)}function xH(t){let e=ww(t);return e===!1?!1:typeof e=="object"?{tiebreakSet:e}:void 0}function wH(t){let e=/^O([1-9]\d*)$/.exec(t);if(e)return{outs:Number(e[1])}}function LH(t,e){let r=/^[FS]:(\d+)([A-Za-z]*)/.exec(t),n=r&&Fw(r[2])||!1,o=!r?.[2]||n,i=r?Gm(r[1]):void 0,s=xw(e),a=s!==!1,c=a&&s||i,u=ww(e.split("/")[1]);return!i||!o||!(u!==!1)||!a?!1:FH(i,n,u,c)}function FH(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 xw(t,e=!0){let r=t?.indexOf("@")>0&&t.split("@");if(r)return(e?Gm(r[1]):r[1])||!1}function ww(t){if(t)return t.startsWith("TB")?kH(t):!1}function kH(t){let e=xw(t,!1),r=/^TB(\d+)([A-Za-z]*)/.exec(t),n=r?.[1],o=r&&Fw(r[2]),i=!r?.[2]||o,s=Gm(n);if(!s||!i)return!1;let a={tiebreakTo:s};return e&&typeof e=="string"&&!yt(e)&&(a.modifier=e),o&&(a.NoAD=!0),a}function Lw(t){let e=t.slice(1),r=/^(\d+)([PG])?(?:\/TB(\d+))?(@[A-Za-z]+)?$/.exec(e),n=Gm(r?.[1]);if(!n)return;let o={timed:!0,minutes:n},i=r?.[2];i==="P"?o.based="P":i==="G"&&(o.based="G");let s=r?.[3];if(s){let u=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 GH(t){let e=/^T(\d+)$/.exec(t);if(!e)return;let r=Gm(e[1]);if(r)return{timed:!0,minutes:r}}function Fw(t){return t?.includes(lI)}function Gm(t){let e=Number(t);return Number.isNaN(e)?0:e}function VH(t){return t.replaceAll(/T(\d+)G(?=\/TB|@|-|$)/g,"T$1")}function xr({matchUpFormat:t}){if(!wt(t)||t==="")return!1;let e=oe(t),r=/-S:(\d+)\/TB(\d{1,2})@?(\d?)/.exec(t),n=r?.[1],o=r?.[2],i=r?.[3],s=/-F:(\d+)\/TB(\d{1,2})@?(\d?)/.exec(t),a=s?.[1],c=s?.[2],u=s?.[3];return mp(e,!!(r&&o&&n===i||s&&c&&a===u))===VH(t)}var Vm=/^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2]\d|3[0-1])$/,ZT=/^((0\d|1\d|2[0-3]):[0-5]\d(:[0-5]\d)?)([.,]\d{3})?$/,_o=/^(\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?$/,ru=/^(\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 ll(t){let{scheduledDate:e}=t;if(!e&&t.scheduledTime&&(e=mt(t.scheduledTime)),!e)return;let r=$t(t.scheduledTime),n=mt(e);return n&&r&&(n+=`T${r}`),n}function kw(t){return typeof t!="object"||Array.isArray(t)?!1:Object.prototype.toString.call(t)==="[object Date]"}function Bm(t){let e=typeof t=="string"?t?.split(" "):[];if(t&&e?.length>1&&!["AM","PM"].includes(e[1].toUpperCase()))return!1;let r=dp(t,!0,!0);return!!(!t||r&&ru.test(r))}function Me(t){return fs(t)||Vm.test(t)}function BH(t){let e=new Date(t),r=e.getSeconds()+60*e.getMinutes()+3600*e.getHours();return WH(r,{displaySeconds:!1})}function WH(t,e){let r=Number.parseInt(t,10),n=Math.floor(r/3600),o=Math.floor((r-n*3600)/60),i=r-n*3600-o*60;return(!e||e?.displaySeconds?n+":"+o+":"+i:n+":"+o).split(":").map(co).join(":")}var SI=t=>{let e=gI(t)||fs(t)?new Date(t):new Date,r=e.getUTCMonth()+1,n=r<10?`0${r}`:`${r}`;return`${e.getUTCFullYear()}-${co(n)}-${co(e.getUTCDate())}`};function HH(t){let e=gI(t)||fs(t)?new Date(t):new Date;return Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())}function Qn(t,e="-",r="YMD"){if(!t)return"";typeof t=="string"&&!t.includes("T")&&(t=t+"T00:00");let n=new Date(t),o=""+(n.getMonth()+1),i=""+n.getDate(),s=n.getFullYear();return o.length<2&&(o="0"+o),i.length<2&&(i="0"+i),r==="DMY"?[i,o,s].join(e):r==="MDY"?[o,i,s].join(e):r==="YDM"?[s,i,o].join(e):r==="DYM"?[i,s,o].join(e):r==="MYD"?[o,s,i].join(e):[s,o,i].join(e)}function ty(t){let e=t?new Date(t):new Date,r=e.getTimezoneOffset();return new Date(e.getTime()-r*60*1e3)}function YH(t){return ty(t).getTime()}function gI(t){if(typeof t=="boolean")return!1;let e=t instanceof Date&&t||!Number.isNaN(Number(t))&&new Date(t)||!1;return e&&!Number.isNaN(Number(e.valueOf()))}function jH(t,e){return t<=e}function Ua(t,e){if(!Me(t)||!Me(e))return[];let r=mt(t)+"T00:00",n=mt(e)+"T00:00",o=new Date(r),i=new Date(n),s=gI(i)&&gI(o)&&jH(o,i),a=[],c=0;if(s){let u=o,p=u.getTime();for(;p<=i.getTime()&&c<300;)c+=1,a.push(new Date(u)),p=u.setDate(u.getDate()+1)}return a.map(u=>Qn(u))}var qH=/^([+-]?\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 fs(t){return typeof t!="string"?!1:qH.test(t)}function Ra(t){return typeof t!="string"||!fs(t)?!1:/([zZ]|[+-]\d{2}:?\d{2})$/.test(t)}function ry(t){if(typeof t!="string")return!1;let r=t.split("Z")[0].split(":"),n=r.every(i=>!Number.isNaN(Number.parseInt(i)));return!(r.length<2||!n||Number.parseInt(r[0])>23||Number.parseInt(r[1])>60)}function jt(t){let e=$t(t);if(!e)return 0;let[r,n]=e.split(":").map(o=>Number.parseInt(o));return r*60+n}function Gw(t){let e=Math.floor(t/60),r=t-e*60;return e>23&&(e=e%24),[co(e),co(r)].join(":")}function II(t){return ry(t)?t.split(":").slice(0,2).map(co).join(":"):void 0}function $t(t){return fs(t)&&t.indexOf("T")>0?II(t.split("T").reverse()[0]):II(t)}function mt(t){return fs(t)||_o.test(t)?t.split("T")[0]:""}function Wm(t,e){let r=new Date(t);return r.setUTCDate(r.getUTCDate()+e),mt(r.toISOString())}function ey(t){t=typeof t=="string"?t:"00:00";let e={},r={};return{0:e.time,1:e.ampm}=t.split(" ")??[],{0:r.hours,1:r.minutes}=e.time.split(":")??[],r.ampm=e.ampm,Number.isNaN(Number.parseInt(r.hours))||Number.isNaN(Number.parseInt(r.minutes))||r.ampm&&!["AM","PM"].includes(r.ampm.toUpperCase())?{}:r}function $H(t){let e=ey(t);return e.ampm&&e.hours&&(e.ampm.toLowerCase()==="pm"&&Number.parseInt(e.hours)<12&&(e.hours=(e.hours&&Number.parseInt(e.hours)||0)+12),e.ampm.toLowerCase()==="am"&&e.hours==="12"&&(e.hours="00")),`${e.hours||"12"}:${e.minutes||"00"}`.split(":").map(co).join(":")}function KH(t){let e=ey(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 dp(t,e,r){let n=mt(t),o=$t(t),i=n?o:t;return t?e&&(n&&r&&t||$H(i))||KH(i):void 0}function ny(t,e){let r=ey(t),n=ey(e);if(Number.parseInt(r.hours)<Number.parseInt(n.hours))return-1;if(Number.parseInt(r.hours)>Number.parseInt(n.hours))return 1;if(r.hours===n.hours){if(Number.parseInt(r.minutes)<Number.parseInt(n.minutes))return-1;if(Number.parseInt(r.minutes)>Number.parseInt(n.minutes))return 1}return 0}function oy(t,e=7){let r=mt(t)+"T00:00",n=new Date(r),o=new Date(n.setDate(n.getDate()+e));return Qn(o)}function zH(t){return oy(t)}function QH(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())),Qn(o,r)}function Vw(t,e,r){let n=new Date(t,0);return Qn(new Date(n.setDate(e)),r)}function ve(t,e=void 0){let[r,n]=(t||"00:00").split(":").map(co),o=ty(e).setHours(r,n,0,0);return ty(o)}function ks(t,e,r=!0){let n=new Date(t),i=(new Date(e).getTime()-n.getTime())/1e3/60;return r?Math.abs(Math.round(i)):Math.round(i)}function Yr(t,e){let r=$t(t);if(!r)return"00:00";let n=Number.isNaN(e)?0:e;return $t(hI(ve(r),n).toISOString())||"00:00"}function hI(t,e){let r=new Date(t);return new Date(r.getTime()+e*6e4)}function co(t){return t.toString()[1]?t:"0"+t}function Xn(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 iy={addDays:oy,addWeek:zH,addMinutesToTimeString:Yr,convertTime:dp,getIsoDateString:ll,getUTCdateString:SI,DateHHMM:BH,extractDate:mt,extractTime:$t,formatDate:Qn,getDateByWeek:QH,isISODateString:fs,isValidEmbargoDate:Ra,isDate:gI,isTimeString:ry,offsetDate:ty,offsetTime:YH,sameDay:Xn,timeStringMinutes:jt,timeToDate:ve,timeUTC:HH,validTimeValue:Bm,validDateString:Vm,timeValidation:ru,dateValidation:_o};var XH=(t,e)=>t.filter(Boolean).every(r=>typeof r===e),JH=t=>t.filter(Boolean).every(Le);function fl(t,e){return`${t}-${e}`}function gs(t){let e=t.category;if(typeof e!="object"||!e)return{error:cp};let{ageCategoryCode:r,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s}=e,a=e.categoryName,c;if(!(XH([r,n,o,a],"string")&&JH([i,s])&&[n,o].filter(Boolean).every(Me)))return{error:cp};let p=t.consideredDate??mt(new Date().toLocaleDateString("sv"));if(!p||!Me(p))return{error:ae};let[m]=p.split("-").slice(0,3).map(B=>Number.parseInt(B)),d=Wm(p,-1);if(!d)return{error:ae};let[l,f]=d.split("-").slice(1,3).map(B=>Number.parseInt(B)),g=`${co(l)}-${co(f)}`,I=Wm(p,1);if(!I)return{error:ae};let[S,h]=I.split("-").slice(1,3).map(B=>Number.parseInt(B)),T=`${co(S)}-${co(h)}`,y=s&&Wm(p,-1*365*s),E=i&&Wm(p,-1*365*i),A=[],N=B=>!A.includes(B)&&A.push(B);r=r??a;let D=/^([UO]?)(\d{1,2})([UO]?)$/,R=/^C(\d{1,2})-(\d{1,2})$/,U=r?.includes("-"),b=U&&r?.match(R),C=r?.match(D);function _(B){let z=m-B,H=fl(z,T);e.ageMinDate&&e.ageMinDate!==H&&N(`Invalid submitted ageMinDate: ${o}`),o=H,r&&(e.ageMax&&e.ageMax!==B-1&&(N(`Invalid submitted ageMax: ${i}`),E=void 0),i=B-1)}function v(B){let z=m-B-1,H=fl(z,T);e.ageMin&&e.ageMin>B&&N(`Invalid submitted ageMin: ${s}`),e.ageMax&&e.ageMax>B&&N(`Invalid submitted ageMax: ${i}`),e.ageMinDate&&e.ageMinDate!==H&&N(`Invalid submitted ageMinDate: ${o}`),o=H,r&&(e.ageMax&&e.ageMax!==B&&(N(`Invalid submitted ageMax: ${i}`),y=void 0),i=B)}function w(B){let z=m-B,H=fl(z,g);e.ageMaxDate&&e.ageMaxDate!==H&&N(`Invalid submitted ageMaxDate: ${n}`),n=H,r&&(e.ageMin&&e.ageMin!==B+1&&(N(`Invalid submitted ageMin: ${s}`),y=void 0),s=B+1)}function L(B){let z=m-B-1,H=fl(z,g);e.ageMaxDate&&e.ageMaxDate!==H&&N(`Invalid submitted ageMaxDate: ${n}`),n=H,r&&(e.ageMin&&e.ageMin!==B&&(N(`Invalid submitted ageMin: ${s}`),y=void 0),s=B)}function F(B){let z=D.exec(B)??[],[H,K,Y]=z.slice(1),J=Number.parseInt(K);H==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&N(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),_(J)):H==="O"&&w(J),Y==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&N(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),v(J)):Y==="O"&&L(J),n=(n??y)||void 0,o=(o??E)||void 0}function x(){if(n=void 0,o=void 0,i=void 0,s=void 0,e.ageMin){let H=m-e.ageMin;n=fl(H,g)}if(e.ageMax){let H=m-e.ageMax-1;o=fl(H,T)}let[B,z]=(r?.match(R)??[]).slice(1).map(H=>Number.parseInt(H));B<=z?(s=B,i=z,c=!0):N(`Invalid combined age range ${r}`)}function k(){s&&w(s),i&&v(i)}function G(){b?x():U?r?.split("-").forEach(F):C&&r?F(r):k()}G(),i&&e?.ageMin&&e?.ageMin>i&&(N(`Invalid submitted ageMin: ${e?.ageMin}`),s=void 0);let V=et({consideredDate:p,combinedAge:c,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s});return A.length&&(V.errors=A),V}function lp({category:t}){if(!Tt(t))return{error:O};let e=gs({category:t});if(e.error)return{error:e};let{ratingMax:r,ratingMin:n}=t;return r&&!Le(r)?M({result:{error:O},context:{ratingMax:r}}):n&&!Le(n)?M({result:{error:O},context:{ratingMin:n}}):{...e}}function fp({childCategory:t,withDetails:e,category:r}){let n=lp({category:r}),o=lp({category:t}),i=o.ageMin&&(n.ageMin&&o.ageMin<n.ageMin||n.ageMax&&o.ageMin>n.ageMax),s=o.ageMax&&(n.ageMax&&o.ageMax>n.ageMax||n.ageMin&&o.ageMax<n.ageMin),a=o.ageMinDate&&n.ageMaxDate&&new Date(o.ageMinDate)>new Date(n.ageMaxDate),c=o.ageMaxDate&&n.ageMinDate&&new Date(o.ageMaxDate)<new Date(n.ageMinDate),p=r?.ratingType&&t?.ratingType&&r.ratingType===t.ratingType&&(r.ratingMin&&t.ratingMin&&t.ratingMin<r.ratingMin||r.ratingMax&&t.ratingMax&&t.ratingMax>r.ratingMax||r.ratingMin&&t.ratingMax&&t.ratingMax<r.ratingMin||r.ratingMax&&t.ratingMin&&t.ratingMin>r.ratingMax),m=r?.ballType&&t?.ballType&&r.ballType!==t.ballType,f=et({invalidRatingRange:p,invalidAgeMinDate:a,invalidAgeMaxDate:c,invalidBallType:m,invalidAgeMax:s,invalidAgeMin:i,valid:!p&&!a&&!c&&!m&&!s&&!i},!0);return e&&Object.assign(f,{categoryDetails:n,childCategoryDetails:o}),f}function gp({checkCategory:t=!0,collectionDefinition:e,checkCollectionIds:r,checkGender:n=!0,referenceCategory:o,referenceGender:i,event:s}){i=i??s?.gender;let a="validateCollectionDefinition",c=[];if(typeof e!="object")return c.push(`collectionDefinition must be an object: ${e}`),M({result:{errors:c,error:yo},stack:a});let{collectionValueProfiles:u,collectionGroupNumber:p,collectionValue:m,collectionId:d,matchUpCount:l,matchUpFormat:f,matchUpValue:g,matchUpType:I,scoreValue:S,setValue:h,category:T,gender:y}=e;if(r&&typeof d!="string"&&c.push(`collectionId is not type string: ${d}`),typeof l!="number"&&c.push(`matchUpCount is not type number: ${l}`),I&&!_s([Ct,Rt,Mm],I)&&c.push(`matchUpType must be SINGLES, DOUBLES, or HYBRID: ${I}`),[!!u?.length].concat([g,m,S,h].map(yt)).filter(Boolean).length!==1&&c.push("Missing value definition for matchUps: matchUpValue, collectionValue, or collectionValueProfiles"),g&&typeof g!="number"&&c.push(`matchUpValue is not type number: ${g}`),m&&typeof m!="number"&&c.push(`collectionValue is not type number: ${m}`),u&&l){let A=LT({collectionValueProfiles:u,matchUpCount:l});A.errors&&c.push(...A.errors)}if(p&&typeof p!="number"&&c.push(`collectionGroupNumber is not type number: ${m}`),f&&!xr({matchUpFormat:f})&&c.push(`Invalid matchUpFormat: ${f}`),n){let A=ml({referenceGender:i,matchUpType:I,gender:y});if(A.error)return M({context:{referenceGender:i,gender:y},result:A,stack:a})}if(t&&o&&T){let A=fp({category:o,childCategory:T});if(!A.valid)return M({result:{error:cp},context:A,stack:a})}return c.length?M({result:{errors:c,error:wU},stack:a}):{valid:!0}}function or(t){let e=!!(t?.enforceCategory!==!1&&t?.category),r=!!(t?.enforceGender!==!1&&t?.gender),n=t?.checkCollectionIds,o=t?.tieFormat,i=t?.event,s="validateTieFormat",a=[],c=ZH({...t,stack:s});if(c?.error)return c;let u,p=o.collectionDefinitions.every(I=>{let{setValue:S,scoreValue:h,collectionValue:T}=I;(S||h)&&!T&&(u=!0);let{valid:y,errors:E}=gp({referenceCategory:t.category,referenceGender:t.gender,collectionDefinition:I,checkCollectionIds:n,checkCategory:e,checkGender:r,event:i});return y?!0:(Array.isArray(E)&&a.push(...E),!1)}),m=typeof o.winCriteria?.valueGoal=="number"&&o.winCriteria?.valueGoal>0&&!u||o.winCriteria?.aggregateValue;if(!(m||o.winCriteria?.aggregateValue))return u?a.push("aggregateValue is required"):a.push("Either non-zero valueGoal, or { aggregateValue: true } must be specified in winCriteria"),M({context:{tieFormat:o,errors:a,aggregateValueImperative:u},result:{error:ri},stack:s});let d=o.collectionDefinitions.map(({collectionId:I})=>I),l=!n||d.length===pt(d).length,f=p&&m&&l,g={valid:f,errors:a};return f?g:M({result:{error:ri},context:{tieFormat:o,errors:a},stack:s})}function ZH(t){let{tieFormat:e,stack:r}=t;return!t||!e||!Tt(e)?M({result:{error:ri},context:{tieFormat:e,message:"tieformat must be an object"},stack:r}):Tt(e.winCriteria)?Array.isArray(e.collectionDefinitions)?{...P}:M({result:{error:ri},context:{tieFormat:e,message:"collectionDefinitions must be an array"},stack:r}):M({result:{error:ri},context:{tieFormat:e,message:"tieformat.winCritiera must be an object"},stack:r})}var gl="resourceSubType",Il="resourceType",nu="identifier",sy="name",Bw={RESOURCE_SUB_TYPE:gl,RESOURCE_TYPE:Il,IDENTIFIER:nu,NAME:sy};function q(t,e,r,n,o=0){if(QT().makeDeepCopy)return QT().makeDeepCopy(t,e,r,n);let i=uI(),{stringify:s,toJSON:a,ignore:c,modulate:u}=i??{};if(!i?.enabled&&!r||typeof t!="object"||Br(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)||Br(c)&&!c(l)),d=(l,f)=>{p[l]=Br(f?.toString)?f.toString():JSON.stringify(f)};for(let l of m){let f=t[l],g=Br(u)?u(f):void 0;if(g!==void 0)p[l]=g;else if(e&&l==="extensions"&&Array.isArray(f)){let I=TI(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)&&Br(f?.toJSON)?p[l]=f.toJSON():f===null?p[l]=void 0:kw(f)?p[l]=new Date(f).toISOString():p[l]=q(f,e,r,n,o+1)}return p}function TI(t){return t?.map(e=>{let{name:r,value:n}=e;return r&&n&&{[`_${r}`]:n}}).filter(Boolean)}function ay(t=1,e,r){return Q(0,t).map(()=>it(e,r))}function it(t,e){let r=e??Math.random,n=[];for(let u=0;u<256;u++)n[u]=(u<16?"0":"")+u.toString(16);let o=Math.trunc(r()*4294967295),i=Math.trunc(r()*4294967295),s=Math.trunc(r()*4294967295),a=Math.trunc(r()*4294967295),c=n[o&255]+n[o>>8&255]+n[o>>16&255]+n[o>>24&255]+"-"+n[i&255]+n[i>>8&255]+"-"+n[i>>16&15|64]+n[i>>24&255]+"-"+n[s&63|128]+n[s>>8&255]+"-"+n[s>>16&255]+n[s>>24&255]+n[a&255]+n[a>>8&255]+n[a>>16&255]+n[a>>24&255];return typeof t=="string"?`${t}_${c.replaceAll("-","")}`:c}var cy={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 uy={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 py={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 my={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 dy={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 ly={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 fy={collectionDefinitions:[{category:{ageCategoryCode:"14U"},collectionName:"14U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"14U"},collectionName:"14U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],collectionGroups:[{groupNumber:1,groupName:"Doubles",groupValue:1,winCriteria:{valueGoal:2}}],tieFormatName:"Brewer Cup",winCriteria:{valueGoal:4}};var gy={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 xn="SET3-S:6/TB7",cY="SET3-S:6NOAD",eR="SET3-S:6NOAD/TB7-F:TB10",uY="SET3-S:4/TB7",pY="SET3-S:4/TB5@3",mY="SET5-S:6/TB7",dY="SET1-S:6/TB7",lY="SET1-S:TB10",fY="SET3-S:6/TB7-F:TB7",gY="SET1-S:T20",IY="SET1-S:8/TB7",SY="SET1-S:8/TB7@7",Ww={FORMAT_STANDARD:xn,FORMAT_STANDARD_NOAD:cY,FORMAT_ATP_DOUBLES:eR,FORMAT_SHORT_SETS:uY,FORMAT_FAST4:pY,FORMAT_GRAND_SLAM:mY,FORMAT_ONE_SET:dY,FORMAT_MATCH_TIEBREAK:lY,FORMAT_SET3_TB7:fY,FORMAT_PRO_SET:IY,FORMAT_COLLEGE_PRO_SET:SY,TIMED20:gY};var Iy={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 Sy={collectionDefinitions:[{collectionName:"Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",collectionValue:1},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"USTA Collegiate",winCriteria:{valueGoal:4}};var hy={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 Ty={collectionDefinitions:[{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Male Singles",matchUpCount:1,gender:"MALE",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Overtime",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"World Team Tennis ITT",winCriteria:{aggregateValue:!0}};var Hw={tieFormatName:"INTENNSE 2026",winCriteria:{aggregateValue:!0},collectionDefinitions:[{collectionId:"intennse-ms",collectionName:"Men's Singles",matchUpType:"SINGLES",matchUpCount:2,matchUpFormat:"SET2XA-S:T10",scoreValue:1,gender:"MALE",category:{categoryName:"MS"}},{collectionId:"intennse-ws",collectionName:"Women's Singles",matchUpType:"SINGLES",matchUpCount:2,matchUpFormat:"SET2XA-S:T10",scoreValue:1,gender:"FEMALE",category:{categoryName:"WS"}},{collectionId:"intennse-md",collectionName:"Men's Doubles",matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET1A-S:T10",scoreValue:1,gender:"MALE",category:{categoryName:"MD"}},{collectionId:"intennse-wd",collectionName:"Women's Doubles",matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET1A-S:T10",scoreValue:1,gender:"FEMALE",category:{categoryName:"WD"}},{collectionId:"intennse-xd",collectionName:"Mixed Doubles",matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET1A-S:T10",scoreValue:1,gender:"MIXED",category:{categoryName:"XD"}}]};var yy={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 Ey={collectionDefinitions:[{collectionGroupNumber:1,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6NOAD/TB7-F:TB10",matchUpValue:1},{collectionGroupNumber:1,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:1},{collectionGroupNumber:2,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6NOAD/TB7-F:TB10",matchUpValue:2},{collectionGroupNumber:2,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:2},{collectionGroupNumber:3,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6NOAD/TB7-F:TB10",matchUpValue:3},{collectionGroupNumber:3,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:3}],collectionGroups:[{groupNumber:1,groupName:"Day 1"},{groupNumber:2,groupName:"Day 2"},{groupNumber:3,groupName:"Day 3"}],tieFormatName:"Laver Cup",winCriteria:{valueGoal:13}};var Ay={collectionDefinitions:[{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Male Singles",matchUpCount:1,gender:"MALE",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Overtime",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"USTA Tennis on Campus",winCriteria:{aggregateValue:!0}};var yI="COLLEGE_DEFAULT",rR="COLLEGE_JUCO",nR="COLLEGE_D3",oR="DOMINANT_DUO",iR="DOMINANT_DUO_MIXED",sR="INTENNSE_2026",aR="LAVER_CUP",cR="TEAM_DOUBLES_3_AGGREGATION",uR="USTA_BREWER_CUP",pR="USTA_OZAKI_CUP",mR="USTA_COLLEGE",dR="USTA_GOLD_TEAM_CHALLENGE",lR="USTA_LEVEL_1",fR="USTA_INTERSECTIONAL",gR="USTA_SECTION_BATTLE",IR="USTA_SOUTHERN_LEVEL_5",SR="USTA_TOC",hR="USTA_WTT_ITT",TR="USTA_ZONAL",Yw={COLLEGE_D3:nR,COLLEGE_DEFAULT:yI,COLLEGE_JUCO:rR,DOMINANT_DUO:oR,DOMINANT_DUO_MIXED:iR,INTENNSE_2026:sR,LAVER_CUP:aR,TEAM_DOUBLES_3_AGGREGATION:cR,USTA_BREWER_CUP:uR,USTA_OZAKI_CUP:pR,USTA_COLLEGE:mR,USTA_GOLD_TEAM_CHALLENGE:dR,USTA_INTERSECTIONAL:fR,USTA_LEVEL_1:lR,USTA_SECTION_BATTLE:gR,USTA_SOUTHERN_LEVEL_5:IR,USTA_TOC:SR,USTA_WTT_ITT:hR,USTA_ZONAL:TR};var qw="STANDARD",jw={[qw]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1},singles:{matchUpCount:6,matchUpValue:1},valueGoal:5},[nR]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7@7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:xn,matchUpCount:6,matchUpValue:1},tieFormatName:"College D3",valueGoal:5},[yI]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:6/TB7",collectionValue:1,matchUpCount:3},singles:{matchUpFormat:xn,matchUpCount:6,matchUpValue:1},tieFormatName:"College Default",valueGoal:4},[rR]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:xn,matchUpCount:6,matchUpValue:1},tieFormatName:"College JUCO",valueGoal:5},[aR]:Ey,[oR]:Iy,[iR]:ly,[sR]:Hw,[cR]:uy,[uR]:fy,[pR]:gy,[mR]:Sy,[dR]:cy,[fR]:dy,[lR]:hy,[gR]:my,[IR]:py,[hR]:Ty,[SR]:Ay,[TR]:yy},UY=t=>{let e=t?.namedFormat&&Object.keys(jw).includes(t.namedFormat)?t.namedFormat:qw,r=Array.isArray(t?.uuids)?t?.uuids:[],n,{category:o,gender:i}=t?.event??{},s=q(jw[e],!1,!0),a=c=>{if(!t?.isMock&&!t?.event?.isMock||!t.event)return r?.pop()??it();let u=t?.event?.eventId;return r.pop()??`${u}-COL-${c+1}`};return s.hydrate?(n={winCriteria:{valueGoal:s.valueGoal},collectionDefinitions:[{collectionId:a(0),matchUpFormat:eR,collectionName:"Doubles",matchUpType:Rt,...s.doubles},{collectionId:a(1),matchUpFormat:xn,collectionName:"Singles",matchUpType:Ct,...s.singles}]},s.tieFormatName&&(n.tieFormatName=s.tieFormatName)):(s.collectionDefinitions.forEach((c,u)=>c.collectionId=a(u)),n=s),t?.hydrateCollections&&n.collectionDefinitions.forEach(c=>{o&&!c.category&&(c.category=o),i&&!c.gender&&(c.gender=i)}),n},uo=UY;var Dt="SINGLES",ba="SINGLES",Lt="DOUBLES",si="DOUBLES",Oe="TEAM",Ze="TEAM",Ip="HYBRID",EI="HYBRID";var RY="RATING",bY="BOTH",$w={AGE:"AGE",BOTH:bY,DOUBLES:Lt,DOUBLES_EVENT:si,HYBRID:Ip,HYBRID_EVENT:EI,RATING:RY,SINGLES:Dt,SINGLES_EVENT:ba,TEAM_EVENT:Ze,TEAM:Oe};var W="MAIN",Z="QUALIFYING",me="CONSOLATION",Fe="VOLUNTARY_CONSOLATION",Vt="PLAY_OFF",ou=[W,Z,me,Vt,Fe],Ca={[Z]:1,[W]:2,[Vt]:3,[me]:3,[Fe]:4},yR="finishingPositions",ER="aggregateEventStructures",AR={[W]:1,[Vt]:2,[me]:3,[Z]:4,[Fe]:5},Kw={[Vt]:1,[W]:2,[me]:3,[Z]:4,[Fe]:5},iu="CLUSTER",Hm="ADJACENT",PR="SEPARATE",Li="WATERFALL",su="ITEM",de="CONTAINER",ln="DRAW",Ym="RANDOM",qe="TOP_DOWN",Fi="BOTTOM_UP",fn="POSITION",Pr="WINNER",ir="LOSER",Wn="FIRST_MATCHUP",Ni="AD_HOC",CY="AD_HOC",pc="FEED_IN",xo="COMPASS",Sp="OLYMPIC",MY="SINGLE_ELIMINATION";var Nr="SINGLE_ELIMINATION",Gs="DOUBLE_ELIMINATION",wo="FIRST_MATCH_LOSER_CONSOLATION",Ma="FIRST_ROUND_LOSER_CONSOLATION",ai="LUCKY_DRAW",ki="ADAPTIVE",AI="CURTIS_CONSOLATION",PI="CURTIS_CONSOLATION",Py="FEED_IN_CHAMPIONSHIP_TO_SF",Is="FEED_IN_CHAMPIONSHIP_TO_SF",Ny="FEED_IN_CHAMPIONSHIP_TO_QF",va="FEED_IN_CHAMPIONSHIP_TO_QF",Dy="FEED_IN_CHAMPIONSHIP_TO_R16",au="FEED_IN_CHAMPIONSHIP_TO_R16",NR="MODIFIED_FEED_IN_CHAMPIONSHIP",Oa="MODIFIED_FEED_IN_CHAMPIONSHIP",Vs="FEED_IN_CHAMPIONSHIP",jm="PAGE_PLAYOFF",qm="PLAYOFF",Bs="SWISS",vY={0:{name:"Qualifier 1",abbreviation:"Q1"},"0-1":{name:"Eliminator",abbreviation:"EL"},"0-2":{name:"Final",abbreviation:"F"}},Uy="DOUBLE_ROUND_ROBIN",hr="ROUND_ROBIN",Tr="ROUND_ROBIN_WITH_PLAYOFF",DR="DECIDER",UR="BACKDRAW",NI={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"}},DI={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-1-1":{name:"South",abbreviation:"S"}},UI={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"}},po="WIN_RATIO",Ss="ROUND_OUTCOME",RR=[ki,xo,AI,va,au,Is,Vs,Ny,Dy,Py,wo,Ma,ai,Oa,Sp,jm,qm,Tr],OY=[Ni,ki,xo,AI,Gs,va,au,Is,Vs,pc,wo,Ma,ai,Oa,Sp,jm,qm,hr,Tr,Nr,Bs],bR={MAIN:W,QUALIFYING:Z,CONSOLATION:me,ITEM:su,CONTAINER:de,FIRST_MATCHUP:Wn,WINNER:Pr,LOSER:ir,AD_HOC:Ni,FEED_IN:pc,FLEX_ROUNDS:CY,COMPASS:xo,PLAY_OFF:Vt,PAGE_PLAYOFF:jm,PAGE_PLAYOFF_ATTRIBUTES:vY,PLAYOFF:qm,SWISS:Bs,OLYMPIC:Sp,KNOCKOUT:MY,SINGLE_ELIMINATION:Nr,DOUBLE_ELIMINATION:Gs,CURTIS:AI,FICSF:Py,FICQF:Ny,FICR16:Dy,MFIC:NR,VOLUNTARY_CONSOLATION:Fe,FIRST_MATCH_LOSER_CONSOLATION:wo,FIRST_ROUND_LOSER_CONSOLATION:Ma,MODIFIED_FEED_IN_CHAMPIONSHIP:Oa,FEED_IN_CHAMPIONSHIP_TO_R16:au,FEED_IN_CHAMPIONSHIP_TO_QF:va,FEED_IN_CHAMPIONSHIP_TO_SF:Is,FEED_IN_CHAMPIONSHIP:Vs,LUCKY_DRAW:ai,ADAPTIVE:ki,ROUND_ROBIN_WITH_PLAYOFF:Tr,ROUND_ROBIN:hr,DECIDER:DR,BACKDRAW:UR,COMPASS_ATTRIBUTES:NI,OLYMPIC_ATTRIBUTES:DI,ADAPTIVE_ATTRIBUTES:UI,DRAW:ln,RANDOM:Ym,TOP_DOWN:qe,BOTTOM_UP:Fi,CLUSTER:iu,ADJACENT:Hm,SEPARATE:PR,WATERFALL:Li,WIN_RATIO:po,ROUND_OUTCOME:Ss,MULTI_STRUCTURE_DRAWS:RR,generatedDrawTypes:OY,stageOrder:Ca,finishOrder:AR,AGGREGATE_EVENT_STRUCTURES:ER,FINISHING_POSITIONS:yR},zw=bR;var Ee="tournamentRecords",RI="policyDefinitions",rt="tournamentRecord",Ry="onlineResource",Kt="drawDefinition",by="tieFormatName",Sl="matchUpFormat",sr="participantId",hl="scheduleDates",Qw="tournamentId",Xw="scheduleDate",Jw="roundNumber",mo="structureId",$m="participant",cu="matchUpIds",Cy="entryStage",Zw="policyType",CR="structures",bI="eventType",wr="matchUpId",Tl="tieFormat",hp="inContext",mc="structure",Km="courtIds",tL="personId",zm="venueIds",CI="matchUps",Ws="courtId",My="eventId",Rn="matchUp",dc="drawId",jr="error",ce="event",Gi="param",MI="uuids",vy="penaltyType",yl="penaltyId",Tp="venueId",eL="stage",rL="averageMatchUpMinutes",nL="recoveryMinutes",oL="periodLength",iL="number";var qr="object",ke="array";var $e="_validate",Oy="_message",Lr="_invalid",Ge="_ofType",yp="_anyOf",_a="_oneOf";var sL={[Ry]:t=>Yt(Object.keys(t),[gl,Il,nu]).length===3,[by]:t=>t&&uo({namedFormat:t}),[MI]:t=>!t||Array.isArray(t)&&t.every(wt),[Tl]:t=>!or({tieFormat:t}).error,[bI]:t=>[Dt,Lt,Oe].includes(t),[Cy]:t=>ou.includes(t)},_Y={[Ee]:kt,[rt]:j,[RI]:Ea,[Kt]:$,[sr]:We,[Sl]:JD,[Qw]:ac,[mo]:dn,[cu]:xs,[$m]:Aa,[Ry]:yo,[bI]:zn,[CR]:Gg,[wr]:mr,[Tl]:ri,[mc]:_i,[Ws]:jg,[CI]:Bn,[My]:Wr,[Rn]:Xe,[Km]:nt,[zm]:nt,[vy]:yU,[yl]:EU,[Tp]:Ls,[dc]:Nn,[ce]:le,[eL]:Wg},xY={[Ee]:qr,[RI]:qr,[rt]:qr,[Kt]:qr,[Ry]:qr,[hl]:ke,[$m]:qr,[cu]:ke,[CR]:ke,[Tl]:qr,[mc]:qr,[Km]:ke,[zm]:ke,[CI]:ke,[Rn]:qr,[ce]:qr,[MI]:ke};function X(t,e,r){if(!t&&!Tt(t))return{error:O};if(!e?.length||t?._bypassParamCheck)return{valid:!0};if(!Array.isArray(e))return{error:O};let{paramError:n,errorParam:o}=FY(t,e);if(!n)return{valid:!0};let i=n[$e]&&(n[jr]||n[Lr])||t?.[o]==null&&(n[jr]||n[Lr]||_Y[o]||O)||O,s=o??(n[_a]&&Object.keys(n[_a]).join(", "));return M({info:{param:s,message:n[Oy]},result:{error:i},stack:r})}function aL(t,e){let r=Object.keys(t),n=Object.keys(e);return Yt(r,n)}function wY(t,e){if(!e)return;let r=aL(t,e);return r.length!==1?{error:O}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function LY(t,e){if(!e)return;let r=aL(t,e).filter(n=>t[n]);return r.length<1?{error:O}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function FY(t,e){let r,n;return{paramError:e.find(({_ofType:i,_oneOf:s,_anyOf:a,_validate:c,_info:u,...p})=>{let m=s&&wY(t,s);if(m?.error)return m.error;m&&Object.assign(p,m);let d=a&&LY(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&&!Br(c),S=t[g]!==void 0&&!c&&kY(t,g,i),h=p[g]&&t[g]==null,y=I||S||h||c&&t[g]!==void 0&&!GY(t[g],c)||sL[g]&&!sL[g](t[g]);return y&&(r=g,n=u),y});return!l.length||f}),errorParam:r,paramInfo:n}}function kY(t,e,r){return r=r||xY[e]||"string",r==="array"?!Array.isArray(t[e]):typeof t[e]!==r}function GY(t,e){return Br(e)?e(t):!0}var Ep="DYNAMIC",Jn="RANKING",Lo="RATING",ci="SCALE",Eo="SEEDING",cL={RANKING:Jn,RATING:Lo,SCALE:ci,SEEDING:Eo};function lc(t){let e=X(t,[{[$m]:!0}]);if(e.error)return e;let r=t.participant.timeItems?.filter(({itemType:o})=>o?.startsWith(ci)&&[Jn,Lo,Eo].includes(o.split(".")[1])),n={ratings:{},rankings:{},seedings:{}};if(r?.length){let o=s=>r.filter(a=>a?.itemType===s).sort((a,c)=>new Date(a.createdAt||void 0).getTime()-new Date(c.createdAt||void 0).getTime()).pop(),i=pt(r.map(({itemType:s})=>s));for(let s of i){let a=o(s);if(a){let[,c,u,p,m]=a.itemType.split("."),d=m?`${p}.${m}`:p,l=c===Eo&&"seedings"||c===Jn&&"rankings"||"ratings";n[l][u]||(n[l][u]=[]),n[l][u].push({scaleValue:a.itemValue,scaleDate:a.itemDate,scaleName:d})}}}return{...P,...n}}function hs(t){if(t===null)return{};let{source:e,template:r}=t??{};if(!r)return e;let n={};return o(e,r,n),n;function o(i,s,a){if(!i||!s)return;let c=Object.keys(i),u=Object.keys(s),p=Object.assign({},...u.filter(l=>l.indexOf("||")).map(l=>l.split("||").map(f=>({[f]:l}))).flat()),m=u.concat(...Object.keys(p)),d=m.includes("*");for(let l of c)if(m.indexOf(l)>=0||d){let f=p[l]||l,g=s[f]||d,I=i[l];if(typeof g=="object"&&typeof I!="function"&&!Array.isArray(g))if(Array.isArray(I)){let S=I.map(h=>{let T={};return o(h,g,T)!==!1?T:void 0}).filter(Boolean);a[l]=S}else I&&(a[l]={},o(I,g,a[l]));else{let S=i[l];if(Array.isArray(g)&&!g.includes(S))return!1;(s[l]||d&&s[l]!==!1)&&(a[l]=S)}}}}var _y="voluntaryConsolation",gn="competitiveBands",vI="roundRobinTally",Zn="positionActions",He="matchUpActions",gr="rankingPoints",Fo="roundNaming",xa="participant",Ap="progression",ko="scheduling",fc="avoidance",VY="participant",BY="display",Qr="scoring",Hn="seeding",uu="feedIn",WY="sanctioning",HY="audit",pu="competition",El="draws",MR="print",uL={POLICY_TYPE_VOLUNTARY_CONSOLATION:_y,POLICY_TYPE_COMPETITIVE_BANDS:gn,POLICY_TYPE_ROUND_ROBIN_TALLY:vI,POLICY_TYPE_POSITION_ACTIONS:Zn,POLICY_TYPE_MATCHUP_ACTIONS:He,POLICY_TYPE_RANKING_POINTS:gr,POLICY_TYPE_ROUND_NAMING:Fo,POLICY_TYPE_PARTICIPANT:xa,POLICY_TYPE_PROGRESSION:Ap,POLICY_TYPE_SCHEDULING:ko,POLICY_TYPE_AVOIDANCE:fc,POLICY_TYPE_COMPETITION:pu,POLICY_TYPE_DISPLAY:BY,POLICY_TYPE_PRIVACY:VY,POLICY_TYPE_FEED_IN:uu,POLICY_TYPE_SCORING:Qr,POLICY_TYPE_SEEDING:Hn,POLICY_TYPE_SANCTIONING:WY,POLICY_TYPE_AUDIT:HY,POLICY_TYPE_DRAWS:El,POLICY_TYPE_PRINT:MR};function ui({tournamentParticipants:t=[],policyDefinitions:e={},contextProfile:r,participantId:n,internalUse:o,personId:i}){let s=t.find(c=>n&&c.participantId===n||i&&c.person&&c.person.personId===i),a=q(s,!1,o);if(a){let c=e?.[xa];if(r?.withScaleValues){let{ratings:u,rankings:p}=lc({participant:a});a.rankings=p,a.ratings=u}if(c?.participant)return hs({template:c.participant,source:a})}return a}var pL="element required",mL="missing name";function dr(t){if(!t||typeof t!="object")return{error:nt};if(t.element&&typeof t?.element!="object")return{error:O};if(!t?.name)return{error:nt,info:mL};if(!t?.element){if(t.discover&&t.tournamentRecords){for(let e of Object.keys(t.tournamentRecords)){let r=t.tournamentRecords[e],n=dr({element:r,name:t.name});if(n.error)return M({result:n,stack:"removeExtension"})}return{...P}}return{error:nt,info:pL}}return t?.element.extensions?(t.element.extensions=t.element.extensions.filter(e=>e?.name!==t.name),{...P}):{...P,info:fe}}function Yn({requiredAttributes:t=["name","value"],extension:e}){if(!e||typeof e!="object"||typeof e.name!="string")return!1;let r=Object.keys(e);return t.filter(n=>r.includes(n)).length===t.length}function ut(t){if(typeof t!="object")return{error:nt};let e="addExtension";if(t?.element&&typeof t.element!="object")return M({result:{error:O},stack:e});if(!Yn({extension:t.extension}))return M({result:{error:O,info:"invalid extension"},stack:e});if(!t.element)if(t.discover&&!t.tournamentId&&t.tournamentRecords){for(let o of Object.values(t.tournamentRecords)){let i=ut({extension:t.extension,element:o});if(i.error)return M({result:i,stack:e})}return{...P}}else return M({result:{error:nt},stack:e});if(t.element.extensions||(t.element.extensions=[]),t?.creationTime??!0){let o=new Date().toISOString();Object.assign(t.extension,{createdAt:o})}let n=t.element.extensions.find(({name:o})=>o===t.extension.name);return n?n.value=t.extension.value:t.extension.value&&t.element.extensions.push(t.extension),{...P}}function OI(t){return!t||typeof t!="object"?{error:nt}:t.tournamentRecord?ut({creationTime:t.creationTime,element:t.tournamentRecord,extension:t.extension}):{error:j}}function _I(t){return!t||typeof t!="object"?{error:nt}:t.drawDefinition?ut({creationTime:t.creationTime,element:t.drawDefinition,extension:t.extension}):{error:Mr}}function Go(t){return!t||typeof t!="object"?{error:nt}:t.event?ut({creationTime:t.creationTime,extension:t.extension,element:t.event}):{error:Wr}}function vR(t){if(!t||typeof t!="object")return{error:nt};if(!t.participantId)return{error:We};let e=t.tournamentRecord?.participants??[],r=ui({participantId:t.participantId,tournamentParticipants:e});return r?ut({creationTime:t.creationTime,extension:t.extension,element:r}):{error:ee}}function xI(t){return!t||typeof t!="object"?{error:nt}:t.tournamentRecord?dr({element:t.tournamentRecord,name:t.name}):{error:j}}function OR(t){return!t||typeof t!="object"?{error:nt}:t.drawDefinition?dr({element:t.drawDefinition,name:t.name}):{error:Mr}}function Qm(t){return!t||typeof t!="object"?{error:nt}:t?.event?dr({element:t.event,name:t.name}):{error:Wr}}function _R(t){if(!t||typeof t!="object")return{error:nt};if(!t.participantId)return{error:We};let e=t.tournamentRecord?.participants??[],r=ui({participantId:t.participantId,tournamentParticipants:e});return r?dr({element:r,name:t.name}):{error:ee}}function Xm({tournamentRecords:t}){return{tournamentIds:Tt(t)?Object.keys(t):[],...P}}var YY="extensionQueries";function ot({discover:t,element:e,name:r,...n}){if(!e||!r){if(t&&n){let s=Object.keys(n).filter(p=>typeof t=="boolean"||Array.isArray(t)&&t.includes(p)).find(p=>Array.isArray(n[p]?.extensions)?n[p].extensions.find(m=>m?.name===r):!1),a=s&&n[s];!a&&n.tournamentRecords&&(a=Object.values(n.tournamentRecords).find(p=>p.extensions?.length));let c=a?.extensions?.find(p=>p?.name===r);return{extension:c,info:c?void 0:fe}}return M({result:{error:nt},stack:YY})}if(!Array.isArray(e.extensions))return{info:"no extensions"};let o=e.extensions.find(s=>s?.name===r);return{extension:o,info:o?void 0:fe}}var jY="activeSuspension",Pp="appliedPolicies",wa="competitionState",xR="context",Al="delegatedOutcome",lo="disabled",gc="disableAutoCalc",Pl="disableLinks",Nl="display",Vi="draftState",Ic="drawDeletions",qY="drawProfile",$Y="eventProfile",KY="eventWithdrawalRequests",zY="factory",on="flightProfile",xy="groupingAttribute",Vo="lineUps",La="linkedTournamentsIds",sn="mutationLocks",wy="participantRepresentatives",Sc="personRequests",mu="positionActions",QY="rankingPoints",XY="registration",bn="roundTarget",wR="sanctioningConstraints",Np="scheduleLimits",pi="scheduleTiming",hc="schedulingProfile",JY="statusDetail",du="subOrder",Bo="tally",Dl="tieFormatModification",Ly={ACTIVE_SUSPENSION:jY,APPLIED_POLICIES:Pp,COMPETITION_STATE:wa,CONTEXT:xR,DELEGATED_OUTCOME:Al,DISABLED:lo,DISABLE_LINKS:Pl,DISABLE_AUTO_CALC:gc,DISPLAY:Nl,DRAFT_STATE:Vi,DRAW_DELETIONS:Ic,DRAW_PROFILE:qY,EVENT_PROFILE:$Y,EVENT_WITHDRAWAL_REQUESTS:KY,FLIGHT_PROFILE:on,GROUPING_ATTRIBUTE:xy,LINEUPS:Vo,LINKED_TOURNAMENTS:La,MUTATION_LOCKS:sn,PARTICIPANT_REPRESENTATIVES:wy,PERSON_REQUESTS:Sc,POSITION_ACTIONS:mu,RANKING_POINTS:QY,REGISTRATION:XY,ROUND_TARGET:bn,SANCTIONING_CONSTRAINTS:wR,SCHEDULE_LIMITS:Np,SCHEDULE_TIMING:pi,SCHEDULING_PROFILE:hc,STATUS_DETAIL:JY,SUB_ORDER:du,TALLY:Bo,TIE_FORMAT_MODIFICATIONS:Dl,FACTORY:zY},LR=[Al,lo,gc,Pl,on,Vo,La,sn,wy,Sc,bn,Np,pi,hc,du,Bo,Dl];function FR({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:kt};let e=Xm({tournamentRecords:t}),{tournamentIds:r}=e;return r?.length>1?ut({tournamentRecords:t,discover:!0,extension:{name:La,value:{tournamentIds:r}}}):{...P}}function kR({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:kt};let e=dr({name:La,tournamentRecords:t,discover:!0});return M({result:e,stack:"unlinkTournaments"})}function GR({tournamentRecords:t,tournamentId:e}){if(typeof t!="object")return{error:O};if(!e)return{error:ac};let r=Xm({tournamentRecords:t}),{tournamentIds:n}=r;if(!n.includes(e))return{error:ac};let o;return n.every(i=>{let s=t[i],{extension:a}=ot({element:s,name:La});if(!a)return!0;let c=a?.value?.tournamentIds??[];if(!c?.length||c.length===1&&c.includes(e)||i===e){let m=xI({name:La,tournamentRecord:s});return m.error&&(o=m.error),m.success}let u=c.filter(m=>m!==e);a.value={tournamentIds:u};let p=OI({tournamentRecord:s,extension:a});return p.error&&(o=p.error),p.success}),o?{error:o}:{...P}}function ft({onlySpecifiedPolicyTypes:t=!1,policyTypes:e=[],tournamentRecord:r,drawDefinition:n,structure:o,event:i}){if(!Array.isArray(e))return{error:BT};let s={};return r&&a(r),i&&a(i),n&&a(n),o&&a(o),{appliedPolicies:s,...P};function a(c){let p=c?.extensions?.find(m=>m.name===Pp)?.value;if(p)for(let m of Object.keys(p))(t?e.includes(m):!e.length||e.includes(m))&&(s[m]=q(p[m],!1,!0))}}function fo({policyTypes:t=[],tournamentRecord:e,drawDefinition:r,structure:n,event:o}){if(!Array.isArray(t))return{error:BT};let{appliedPolicies:i}=ft({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:np.message}}function Ao(t){let{appliedPolicies:e}=ft({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,event:t.event});return{competitionPolicy:e?.[pu]}}function Bi({element:t,accessor:e}){if(typeof e!="string")return{values:[]};let r=q(t),n=e.split("."),o=[],i;a({targetElement:r,attributes:n});let s={value:i};return o.length&&(s.values=o),s;function a({targetElement:c,attributes:u=[],significantCharacters:p}){for(let[d,l]of u.entries())if(c?.[l]){let f=u.slice(d+1);f.length?Array.isArray(c[l])?c[l].forEach(I=>a({targetElement:I,attributes:f})):(c=c[l],m({targetElement:c,index:d})):(i||(i=c[l]),o.includes(c[l])||o.push(c[l]))}function m({targetElement:d,index:l}){if(d&&l===u.length-1&&["string","number"].includes(typeof d)){let f=p?d.slice(0,p):d;i?o.includes(f)||o.push(f):(i=f,o.push(f))}}}}function Po({requireTimeStamp:t,scaleAttributes:e,participant:r}){if(!r)return{error:Aa};if(!Tt(e))return{error:O};if(r.timeItems??=[],Array.isArray(r.timeItems)){let{accessor:n,scaleType:o,eventType:i,scaleName:s}=e,a=[ci,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!==ci)return{error:Qc};let f=n&&Bi({element:u.itemValue,accessor:n}),g=f?.value||u.itemValue,I={rawValue:f&&u.itemValue,eventType:d,scaleDate:u.itemDate,scaleValue:g,scaleName:l,scaleType:m};return{...P,scaleItem:I}}}return{...P,scaleItem:void 0}}function Dp({value:t,sourceRange:e,targetRange:r}){if(!Array.isArray(e)||e.length!==2)return 0;let n=Math.min(...e),o=Math.max(...e),i=Math.min(...r),s=Math.max(...r);return(t-n)*(s-i)/(o-n)+i}var VR="NTRP";var BR="DUPR",WR="UTR_P",HR="UTPR";var YR="SQUASH_LEVELS",jR="US_SQUASH",qR="USATT",$R="ITTF",KR="USAR";var dL={ELO:"ELO",NTRP:VR,TRN:"TRN",UTR:"UTR",WTN:"WTN",DUPR:BR,UTR_P:WR,UTPR:HR,PSA:"PSA",SQUASH_LEVELS:YR,US_SQUASH:jR,USATT:qR,ITTF:$R,USAR:KR,BWF:"BWF"};var rj={ELO:{defaultInitialization:1500,decimalsCount:0,range:[0,3e3],ascending:!1},[VR]:{accessors:["ntrpRating","dntrpRatingHundredths"],attributes:{ustaRatingType:""},accessor:"dntrpRatingHundredths",defaultInitialization:3,decimalsCount:1,ascending:!1,range:[1,7]},UTR:{defaultInitialization:6,accessors:["utrRating"],accessor:"utrRating",decimalsCount:2,ascending:!1,range:[1,16]},WTN:{attributes:{confidence:{generator:!0,range:[60,100]}},accessors:["wtnRating","confidence"],defaultInitialization:23,accessor:"wtnRating",ascending:!0,decimalsCount:2,range:[40,1]},[BR]:{defaultInitialization:3.5,accessors:["duprRating","reliabilityScore"],accessor:"duprRating",attributes:{reliabilityScore:{generator:!0,range:[0,100]}},decimalsCount:3,ascending:!1,range:[2,8]},[WR]:{defaultInitialization:5,accessors:["utrpRating","verified"],accessor:"utrpRating",attributes:{verified:{type:"boolean"},provisional:{type:"string"}},decimalsCount:1,ascending:!1,range:[1,10]},[HR]:{defaultInitialization:3.5,accessor:"utprRating",decimalsCount:1,ascending:!1,range:[2,5],deprecated:!0},PSA:{defaultInitialization:500,accessor:"psaPoints",decimalsCount:0,ascending:!1,range:[0,3e3],attributes:{tournaments:{generator:!0,range:[1,20]},divisor:{generator:!0,range:[10,20]}}},[YR]:{defaultInitialization:2e3,accessor:"squashLevel",decimalsCount:0,ascending:!1,range:[0,7e3]},[jR]:{defaultInitialization:3.5,accessor:"usSquashRating",decimalsCount:1,ascending:!1,range:[2,6]},[qR]:{defaultInitialization:1e3,accessor:"usattRating",decimalsCount:0,ascending:!1,range:[200,3e3]},[$R]:{defaultInitialization:500,accessor:"ittfPoints",decimalsCount:0,ascending:!1,range:[0,2e4]},[KR]:{defaultInitialization:1e4,accessor:"usarRanking",decimalsCount:0,ascending:!0,range:[1,25e3]},BWF:{defaultInitialization:5e3,accessor:"bwfPoints",decimalsCount:0,ascending:!0,range:[0,15e4],attributes:{tournaments:{generator:!0,range:[1,10]}}}},Ke=rj;function Up({sourceRatingType:t,sourceRating:e}){let r=Ke[t]?.range,n=r?.[0]>r?.[1],o=Ke["ELO"].range;return Dp({value:n?r[0]-e:e,sourceRange:r,targetRange:o})}function lL({targetRatingType:t,sourceRating:e}){let r=Ke[t]?.decimalsCount||0,n=Ke[t]?.range,o=n?.[0]>n?.[1],i=Math.max(...n),s=Ke["ELO"]?.range,a=Dp({targetRange:n,sourceRange:s,value:e}),c=Number.parseFloat(a?.toFixed(r))||0;return o?i-c:c}function Ul(t){let{tournamentRecord:e,participantIds:r,scaleName:n,eventType:o,convertToELO:i,adHocRatings:s={}}=t,a=t.scaleAccessor??Ke[n]?.accessor,c=e.participants??[];for(let u of r??[]){let p=c?.find(d=>d.participantId===u),m;i&&(m=QR({scaleName:`${"ELO"}.${Ep}`,participant:p,eventType:o})),m||(m=QR({scaleName:`${n}.${Ep}`,participant:p,eventType:o}),m&&i&&n!=="ELO"&&(m=Up({sourceRatingType:n,sourceRating:m}))),!m&&n&&(m=QR({scaleAccessor:a,participant:p,scaleName:n,eventType:o}),m&&i&&n!=="ELO"&&(m=Up({sourceRatingType:n,sourceRating:m}))),m&&!s[u]&&(s[u]=m)}return s}function QR({scaleType:t=Lo,scaleAccessor:e,participant:r,scaleName:n,eventType:o}){let a=(r&&Po({scaleAttributes:{eventType:o??ba,scaleType:t,scaleName:n},participant:r}))?.scaleItem?.scaleValue;return e&&Tt(a)?a[e]:a}function XR(t){let{tournamentRecord:e,drawDefinition:r,participantIds:n,event:o}=t;if(!r)return{error:$};if(!n?.length)return{error:nt};let{competitionPolicy:i}=Ao({tournamentRecord:e,drawDefinition:r,event:o});if(!i)return{...P};let s=i.ratingPolicy,a=s.baselineRating.scaleName,c=s.ratingAggregation??"AVERAGE",u=o?.eventType,p=a?Ul({tournamentRecord:e,participantIds:n,scaleName:a,eventType:u}):{},m={};for(let l of n){let f=nj({tournamentRecord:e,participantId:l,adHocRatings:p,aggregation:c,eventType:u});m[l]={participantId:l,baselineRating:f,dynamicFormRating:f,pressureRating:0,roundsPlayed:0,wins:0,losses:0,draws:0,totalPointsWon:0,totalPointsLost:0,ratingHistory:[]}}let d={participantStates:m,roundStates:{}};return ut({element:r,extension:{name:wa,value:d}}),{competitionState:d,...P}}function nj({tournamentRecord:t,participantId:e,adHocRatings:r,aggregation:n,eventType:o}){if(r[e]!==void 0)return r[e];if(o===Lt){let s=t.participants?.find(a=>a.participantId===e)?.individualParticipantIds;if(s?.length){let a=s.map(c=>r[c]??0);return oj(a,n)}}return 0}function oj(t,e){if(!t.length)return 0;switch(e){case"MIN":return Math.min(...t);case"MAX":return Math.max(...t);case"SUM":return t.reduce((r,n)=>r+n,0);default:return t.reduce((r,n)=>r+n,0)/t.length}}function Wo({drawDefinition:t}){let{extension:e}=ot({element:t,name:wa});return{competitionState:e?.value}}function gL(t){let e=t.score?.sets??[];if(!e.length)return fL(t);let r=0,n=0;for(let o of e){let i=o.side1Score??0,s=o.side2Score??0;if(o.side1TiebreakScore!==void 0||o.side2TiebreakScore!==void 0){let a=o.side1TiebreakScore??0,c=o.side2TiebreakScore??0,u=a+c;if(u>0){r+=i-(o.winningSide===1?1:0)+a/u,n+=s-(o.winningSide===2?1:0)+c/u;continue}}r+=i,n+=s}return r>0||n>0?{side1Count:r,side2Count:n}:fL(t)}function fL(t){let{winningSide:e}=t;return e===1?{side1Count:1,side2Count:0}:e===2?{side1Count:0,side2Count:1}:{side1Count:0,side2Count:0}}function JR({pointsWon:t,pointsLost:e,competitionPolicy:r}){let n=t+e;if(n===0)return .5;let o=t/n,i=r.ratingPolicy.pressureRating;if(!i||i.actualOutputMethod==="POINT_SHARE")return o;let s=i.weights??{pointShare:1},a=(t-e)/n,c=0,u=s.pointShare??1,p=s.pointDifferential??0,m=s.contextFactor??0,d=u+p+m;return d===0?o:(u*o+p*a+m*c)/d}function wI(t,e,r){return 1/(1+Math.pow(10,(e-t)/r))}function Jm(t){let{tournamentRecord:e,drawDefinition:r,matchUp:n,event:o}=t;if(!r)return{error:$};if(!n)return{error:Xe};let{competitionPolicy:i}=Ao({tournamentRecord:e,drawDefinition:r,event:o});if(!i)return{...P};let{competitionState:s}=Wo({drawDefinition:r});if(!s)return{...P};let a=n.sides??[],c=a[0]?.participantId,u=a[1]?.participantId;if(!c||!u)return{...P};let p=s.participantStates[c],m=s.participantStates[u];if(!p||!m)return{...P};let{winningSide:d}=n,{side1Count:l,side2Count:f}=gL(n),g=JR({pointsWon:l,pointsLost:f,competitionPolicy:i}),I=JR({pointsWon:f,pointsLost:l,competitionPolicy:i}),S=i.ratingPolicy.dynamicFormRating.logisticScale,h=i.ratingPolicy.dynamicFormRating.kFactor,T=wI(p.baselineRating,m.baselineRating,S),y=wI(m.baselineRating,p.baselineRating,S),E=wI(p.dynamicFormRating,m.dynamicFormRating,S),A=wI(m.dynamicFormRating,p.dynamicFormRating,S),N=i.ratingPolicy.pressureRating?.enabled,D=N?g-T:0,R=N?I-y:0,U=i.ratingPolicy.dynamicFormRating.enabled,b=U?p.dynamicFormRating+h*(g-E):p.dynamicFormRating,C=U?m.dynamicFormRating+h*(I-A):m.dynamicFormRating,_=n.roundNumber??0;return p.dynamicFormRating=b,p.pressureRating+=D,p.roundsPlayed+=1,p.wins+=d===1?1:0,p.losses+=d===2?1:0,p.draws+=d?0:1,p.totalPointsWon+=l,p.totalPointsLost+=f,p.ratingHistory.push({roundNumber:_,opponentParticipantId:u,dynamicFormRatingBefore:p.dynamicFormRating-h*(g-E),dynamicFormRatingAfter:b,pressureDelta:D,actualOutput:g,expectedOutput:T}),m.dynamicFormRating=C,m.pressureRating+=R,m.roundsPlayed+=1,m.wins+=d===2?1:0,m.losses+=d===1?1:0,m.draws+=d?0:1,m.totalPointsWon+=f,m.totalPointsLost+=l,m.ratingHistory.push({roundNumber:_,opponentParticipantId:c,dynamicFormRatingBefore:m.dynamicFormRating-h*(I-A),dynamicFormRatingAfter:C,pressureDelta:R,actualOutput:I,expectedOutput:y}),ut({element:r,extension:{name:wa,value:s}}),{...P}}var Fr="ABANDONED",lu="AWAITING_RESULT";var to="CANCELLED",ie="COMPLETED",Rp="DEAD_RUBBER",Mt="DEFAULTED",ge="DOUBLE_DEFAULT",Qt="DOUBLE_WALKOVER",Cn="IN_PROGRESS",Xr="INCOMPLETE",ZR="NOT_PLAYED",De="RETIRED",Wi="SUSPENDED",zt="TO_BE_PLAYED",vt="WALKOVER",IL=[lu,ie,Mt,Cn,Xr,De,Wi],Fy=[lu,ie,Mt,Qt,ge,Cn,Xr,De,Wi,vt],ky=[Fr,lu,"BYE",to,ie,Rp,Mt,Qt,ge,Cn,Xr,ZR,De,Wi,zt,vt],Gy=["BYE",Qt,ge,ie,Mt,De,vt],Vy=[Fr,lu,to,Rp,Cn,Xr,ZR,Wi,zt,void 0],Ot=[to,Fr,ie,Rp,Mt,Qt,ge,De,vt],Rl=[Fr,ie,Mt,Qt,ge,Cn,De,vt],By=[Cn,Xr,Wi,zt],Wy={ABANDONED:Fr,AWAITING_RESULT:lu,BYE:"BYE",CANCELLED:to,COMPLETED:ie,DEAD_RUBBER:Rp,DEFAULTED:Mt,DOUBLE_WALKOVER:Qt,DOUBLE_DEFAULT:ge,IN_PROGRESS:Cn,INCOMPLETE:Xr,NOT_PLAYED:ZR,RETIRED:De,SUSPENDED:Wi,TO_BE_PLAYED:zt,WALKOVER:vt};function tb(t){let{tournamentRecord:e,drawDefinition:r,roundNumber:n,matchUps:o,event:i}=t;if(!r)return{error:$};let{competitionPolicy:s}=Ao({tournamentRecord:e,drawDefinition:r,event:i});if(!s)return{...P};let{competitionState:a}=Wo({drawDefinition:r});if(!a)return{...P};if(a.roundStates[n]?.processed)return{...P};let c=o.filter(p=>p.roundNumber===n&&(p.winningSide||Ot.includes(p.matchUpStatus)));for(let p of c)Jm({tournamentRecord:e,drawDefinition:r,matchUp:p,event:i});let{competitionState:u}=Wo({drawDefinition:r});return u&&(u.roundStates[n]={roundNumber:n,processed:!0},ut({element:r,extension:{name:wa,value:u}})),{...P}}function eb({drawDefinition:t}){return t?(ut({element:t,extension:{name:wa,value:void 0}}),{...P}):{error:$}}var nb={};Gt(nb,{getCompetitionLeaderboard:()=>Yy,getCompetitionParticipantState:()=>Hy,getCompetitionPolicy:()=>Ao,getCompetitionState:()=>Wo,getLinkedTournamentIds:()=>bp,getTournamentIds:()=>Xm});function Hy({drawDefinition:t,participantId:e}){let{competitionState:r}=Wo({drawDefinition:t});return{participantState:r?.participantStates?.[e]}}function Yy(t){let{tournamentRecord:e,drawDefinition:r,event:n}=t,{competitionPolicy:o}=Ao({tournamentRecord:e,drawDefinition:r,event:n}),{competitionState:i}=Wo({drawDefinition:r});if(!i||!o)return{leaderboard:[]};let s=o.victoryPolicy.primaryRanking;return{leaderboard:[...Object.values(i.participantStates)].sort((p,m)=>{let d=SL(m,s)-SL(p,s);if(d!==0)return d;for(let l of o.victoryPolicy.tiebreakOrder??[]){let f=ij(p,m,l,i.participantStates);if(f!==0)return f}return 0}).map((p,m)=>({participantId:p.participantId,rank:m+1,baselineRating:p.baselineRating,dynamicFormRating:p.dynamicFormRating,pressureRating:p.pressureRating,wins:p.wins,losses:p.losses,draws:p.draws,pointsWon:p.totalPointsWon,pointsLost:p.totalPointsLost}))}}function SL(t,e){switch(e){case"PRESSURE_RATING":return t.pressureRating;case"DYNAMIC_FORM_RATING":return t.dynamicFormRating;case"WINS":return t.wins;case"POINTS":return t.totalPointsWon;default:return t.wins}}function ij(t,e,r,n){switch(r){case"POINT_DIFFERENTIAL":return e.totalPointsWon-e.totalPointsLost-(t.totalPointsWon-t.totalPointsLost);case"DYNAMIC_FORM_RATING":return e.dynamicFormRating-t.dynamicFormRating;case"PRESSURE_RATING":return e.pressureRating-t.pressureRating;case"HEAD_TO_HEAD":{let o=t.ratingHistory.filter(c=>c.opponentParticipantId===e.participantId),i=e.ratingHistory.filter(c=>c.opponentParticipantId===t.participantId),s=o.filter(c=>c.actualOutput>.5).length;return i.filter(c=>c.actualOutput>.5).length-s}case"HEAD_TO_HEAD_PRESSURE":{let o=t.ratingHistory.filter(c=>c.opponentParticipantId===e.participantId),i=e.ratingHistory.filter(c=>c.opponentParticipantId===t.participantId),s=o.reduce((c,u)=>c+u.pressureDelta,0);return i.reduce((c,u)=>c+u.pressureDelta,0)-s}case"STRENGTH_OF_OPPOSITION":{let o=t.ratingHistory.map(c=>n[c.opponentParticipantId]?.baselineRating??0),i=e.ratingHistory.map(c=>n[c.opponentParticipantId]?.baselineRating??0),s=o.length?o.reduce((c,u)=>c+u,0)/o.length:0;return(i.length?i.reduce((c,u)=>c+u,0)/i.length:0)-s}default:return 0}}function bp({tournamentRecords:t}){return typeof t!="object"||!Object.keys(t).length?{error:kt}:{linkedTournamentIds:Object.assign({},...Object.keys(t).map(r=>{let n=t[r],o=n?.tournamentId,{extension:i}=ot({element:n,name:La}),s=(i?.value?.tournamentIds??[]).filter(a=>a!==o);return{[r]:s}}))}}var hv={};Gt(hv,{adHocPositionSwap:()=>OC,addAdHocMatchUps:()=>Jp,addDrawDefinitionTimeItem:()=>OS,addFinishingRounds:()=>Nc,addGoesTo:()=>Ps,addLinkedConsolationStructure:()=>uC,addPlayoffStructures:()=>GS,addQualifyingStructure:()=>MC,addVoluntaryConsolationStructure:()=>gS,allPlayoffPositionsFilled:()=>qE,alternateDrawPositionAssignment:()=>mC,assignDrawPosition:()=>FC,assignDrawPositionBye:()=>Or,attachConsolationStructures:()=>AS,attachPlayoffStructures:()=>PS,attachQualifyingStructure:()=>vS,attachStructures:()=>NS,autoSeeding:()=>$k,automatedPlayoffPositioning:()=>Ha,automatedPositioning:()=>Ou,buildDrawHierarchy:()=>qk,checkValidEntries:()=>Nf,deleteAdHocMatchUps:()=>GC,drawMatic:()=>im,findDrawDefinition:()=>pA,generateAdHocMatchUps:()=>Mc,generateAdHocRounds:()=>Lf,generateAndPopulatePlayoffStructures:()=>Sf,generateConsolationStructure:()=>cC,generateDrawDefinition:()=>xc,generateDrawMaticRound:()=>bf,generateDrawStructuresAndLinks:()=>Df,generateDrawTypeAndModifyDrawDefinition:()=>Uf,generateQualifyingStructure:()=>lf,generateSwissRound:()=>Yk,generateVoluntaryConsolation:()=>xA,getAssignedParticipantIds:()=>Ji,getAvailableMatchUpsCount:()=>hf,getAvailablePlayoffProfiles:()=>qp,getDraftState:()=>RA,getDrawDefinitionTimeItem:()=>Zy,getDrawParticipantRepresentativeIds:()=>sA,getDrawStructures:()=>Sn,getDrawTypeCoercion:()=>em,getEligibleVoluntaryConsolationParticipants:()=>iA,getLuckyDrawRoundStatus:()=>ff,getMatchUpsMap:()=>Ie,getParticipantIdFinishingPositions:()=>Ef,getPositionAssignments:()=>xu,getPositionsPlayedOff:()=>bu,getRandomQualifierList:()=>PA,getSeedingThresholds:()=>bE,getSeedsCount:()=>rm,getStructureSeedAssignments:()=>Ur,getSwissChart:()=>UA,getSwissStandings:()=>NA,getTeamLineUp:()=>Xs,getValidGroupSizes:()=>ud,hasLuckyRounds:()=>nS,initializeDraft:()=>kC,isAdHoc:()=>Ae,isCompletedStructure:()=>Ro,isValidForQualifying:()=>DA,luckyDrawAdvancement:()=>_C,luckyLoserDrawPositionAssignment:()=>rC,modifyDrawDefinition:()=>xC,modifyDrawName:()=>VS,modifySeedAssignment:()=>TC,mutate:()=>WC,positionActions:()=>AA,predictDrawCompetitiveBands:()=>Zp,pruneDrawDefinition:()=>LC,qualifierDrawPositionAssignment:()=>US,qualifierProgression:()=>dC,query:()=>nM,remapDrawDefinitionMatchUpIds:()=>DS,removeDrawPositionAssignment:()=>jp,removeRoundMatchUps:()=>VC,removeSeededParticipant:()=>CC,removeStructure:()=>NC,renameStructures:()=>EC,resetDrawDefinition:()=>wC,resetQualifyingStructure:()=>PC,resetVoluntaryConsolationStructure:()=>lb,resolveDraftPositions:()=>AC,seedWithdrawalCascade:()=>vC,setDrawParticipantRepresentativeIds:()=>ib,setDrawPositionPreferences:()=>pC,setPositionAssignments:()=>oC,setStructureOrder:()=>yC,setSubOrder:()=>BC,shiftAdHocRounds:()=>nC,swapAdHocRounds:()=>iC,swapDrawPositionAssignments:()=>bC,updateTeamLineUp:()=>Us,validatePlayoffGroups:()=>pf,withdrawParticipantAtDrawPosition:()=>tC});var WC={};Gt(WC,{adHocPositionSwap:()=>OC,addAdHocMatchUps:()=>Jp,addDrawDefinitionTimeItem:()=>OS,addLinkedConsolationStructure:()=>uC,addPlayoffStructures:()=>GS,addQualifyingStructure:()=>MC,addVoluntaryConsolationStructure:()=>gS,alternateDrawPositionAssignment:()=>mC,assignDrawPosition:()=>FC,assignDrawPositionBye:()=>Or,attachConsolationStructures:()=>AS,attachPlayoffStructures:()=>PS,attachQualifyingStructure:()=>vS,attachStructures:()=>NS,automatedPlayoffPositioning:()=>Ha,automatedPositioning:()=>Ou,deleteAdHocMatchUps:()=>GC,initializeDraft:()=>kC,luckyDrawAdvancement:()=>_C,luckyLoserDrawPositionAssignment:()=>rC,modifyDrawDefinition:()=>xC,modifyDrawName:()=>VS,modifySeedAssignment:()=>TC,pruneDrawDefinition:()=>LC,qualifierDrawPositionAssignment:()=>US,qualifierProgression:()=>dC,remapDrawDefinitionMatchUpIds:()=>DS,removeDrawPositionAssignment:()=>jp,removeRoundMatchUps:()=>VC,removeSeededParticipant:()=>CC,removeStructure:()=>NC,renameStructures:()=>EC,resetDrawDefinition:()=>wC,resetQualifyingStructure:()=>PC,resetVoluntaryConsolationStructure:()=>lb,resolveDraftPositions:()=>AC,seedWithdrawalCascade:()=>vC,setDrawParticipantRepresentativeIds:()=>ib,setDrawPositionPreferences:()=>pC,setPositionAssignments:()=>oC,setStructureOrder:()=>yC,setSubOrder:()=>BC,shiftAdHocRounds:()=>nC,swapAdHocRounds:()=>iC,swapDrawPositionAssignments:()=>bC,updateTeamLineUp:()=>Us,withdrawParticipantAtDrawPosition:()=>tC});var jy=t=>e=>t[e],bl=(t=[])=>t.map(Te).filter(Boolean),LI=(t=[])=>t.map(gt).filter(Boolean),gt=(t={})=>jy(t)("participantId"),hL=(t={})=>jy(t)("drawPosition");var Te=(t={})=>jy(t)("matchUpId"),Tc=(t={})=>jy(t)("drawId");function ib({representativeParticipantIds:t,drawDefinition:e}){if(!e)return{error:Mr};if(!Array.isArray(t))return{error:O};let r=LI(e?.entries??[]);return t.length&&Yt(t,r).length<t.length?{error:O}:_I({drawDefinition:e,extension:{name:wy,value:t}})}function Hi(t,e,r){let n=m=>ot({element:m,name:bn})?.extension?.value,o=r?.deprioritizeCompleted,i=r?.mode===ER&&Kw,s=r?.mode===yR&&AR,a=s||i||Ca,c=m=>m?.stage===W&&m?.stageSequence===1,u=m=>c(m)?-1:a[m?.stage],p=m=>m?.matchUps.every(({matchUpStatus:d})=>Ot.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)||(FI(t)||0)-(FI(e)||0)}function FI(t){return(t?.matchUps??[]).reduce((e,r)=>{let n=(r.finishingPositionRange?.winner??[]).reduce((o,i)=>o+i,0);return!e||n<e?n:e},void 0)}function tt(t){let e=X(t,[{[Kt]:!0,[mo]:!0}]);if(e.error)return e;let{drawDefinition:r,structureId:n}=t,{structures:o}=Sn({drawDefinition:r}),i=o?.flatMap(c=>c.structures?[...c.structures].concat(c):c),s=i?.find(c=>c.structureId===n);if(!s)return{error:Nt};let a=s.structureType===su?i?.find(c=>c.structures?.some(u=>u.structureId===n)):void 0;return{structure:s,containingStructure:a}}function Sn({withStageGrouping:t,drawDefinition:e,stageSequences:r,stageSequence:n,roundTarget:o,sortConfig:i,stages:s,stage:a}){let c=!e&&$||!e?.structures&&Gg||void 0;if(c)return{error:c,structures:[],stageStructures:{}};let u=f=>{let g=ot({element:f,name:bn})?.extension?.value;return!o||o===g},p=e?.structures?.filter(d).filter(l).filter(u).sort((f,g)=>Hi(f,g,i))??[],m=t?Object.assign({},...ou.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 qy({drawDefinition:t}){if(!t)return{error:$};let e={};return{allPositionedParticipantIds:(t.structures??[]).map(n=>{let o=n.stage;e[o]||(e[o]=[]);let{positionAssignments:i}=Pt({structure:n}),s=i?.map(gt).filter(Boolean)??[];return e[o].push(...s),s}).flat(),stagePositionedParticipantIds:e}}function Pt({drawDefinition:t,structureId:e,structure:r}){let n,o=[];if(!r){if(!t)return{positionAssignments:o,error:$};if({structure:r,error:n}=tt({drawDefinition:t,structureId:e}),n)return{positionAssignments:o,error:n}}return r.structures?o=[].concat(...r.structures.map(i=>Pt({structure:i}).positionAssignments)):r.positionAssignments?o=r.positionAssignments:n=KD,{positionAssignments:o,error:n}}function se({drawDefinition:t,structureId:e,structure:r}){let n=Pt({drawDefinition:t,structureId:e,structure:r})?.positionAssignments??[],o=n?.filter(u=>u.participantId??u.bye??u.qualifier),i=n&&n?.length===o?.length,s=n?.filter(u=>!u.participantId&&!u.bye&&!u.qualifier),a=n?.filter(u=>!u.participantId&&u.bye),c=n?.filter(u=>!u.participantId&&u.qualifier);return{allPositionsAssigned:i,positionAssignments:n,unassignedPositions:s,assignedPositions:o,qualifierPositions:c,byePositions:a}}function dt(t,e,r){let n=e.reduce((o,i)=>(o[i]=!0,o),{});return X(t,[n],r)}var kI="addDrawDefinition",Zm="addMatchUps",Di="addParticipants",GI="addScaleItems",sb="addEvent",$y="addVenue",Yi="audit",Ky="dataIssue",VI="deleteParticipants",BI="deleteVenue",WI="deletedDrawIds",HI="deletedMatchUpIds",YI="modifyDrawDefinition",ab="modifyDrawEntries",cb="modifyEventEntries",jI="modifyMatchUp",tr="modifyParticipants",qI="modifyPositionAssignments",$I="modifySeedAssignments",mi="modifyTournamentDetail",No="modifyVenue",Cl="mutations",zy="publishEvent",ub="publishEventSeeding",pb="publishOrderOfPlay",mb="publishParticipants",KI="unPublishEvent",zI="unPublishEventSeeding",QI="unPublishOrderOfPlay",db="unPublishParticipants",Ml="unPublishTournament",Cp="updateInContextMatchUp",TL={ADD_DRAW_DEFINITION:kI,ADD_MATCHUPS:Zm,ADD_PARTICIPANTS:Di,ADD_SCALE_ITEMS:GI,ADD_EVENT:sb,ADD_VENUE:$y,AUDIT:Yi,DATA_ISSUE:Ky,DELETE_PARTICIPANTS:VI,DELETE_VENUE:BI,DELETED_DRAW_IDS:WI,DELETED_MATCHUP_IDS:HI,MODIFY_DRAW_DEFINITION:YI,MODIFY_DRAW_ENTRIES:ab,MODIFY_EVENT_ENTRIES:cb,MODIFY_MATCHUP:jI,MODIFY_PARTICIPANTS:tr,MODIFY_POSITION_ASSIGNMENTS:qI,MODIFY_SEED_ASSIGNMENTS:$I,MODIFY_TOURNAMENT_DETAIL:mi,MODIFY_VENUE:No,MUTATIONS:Cl,PUBLISH_EVENT_SEEDING:ub,PUBLISH_EVENT:zy,PUBLISH_ORDER_OF_PLAY:pb,PUBLISH_PARTICIPANTS:mb,UNPUBLISH_EVENT_SEEDING:zI,UNPUBLISH_EVENT:KI,UNPUBLISH_ORDER_OF_PLAY:QI,UNPUBLISH_PARTICIPANTS:db,UNPUBLISH_TOURNAMENT:Ml,UPDATE_INCONTEXT_MATCHUP:Cp};function Qy(t,e){if(!t)return{error:$};let r=Date.now();t.updatedAt&&r===new Date(t.updatedAt).getTime()&&(r+=1);let n=new Date(r).toISOString(),o=e?.filter(Boolean);return t.updatedAt=n,t.structures?.filter(Boolean).forEach(i=>{(!o?.length||o?.includes(i.structureId))&&(i.updatedAt=n)}),{...P}}function yL(t){if(!t)return;let e=Date.now(),r=t.updatedAt;if(r){let n=typeof r=="string"?new Date(r).getTime():r.getTime();!Number.isNaN(n)&&e<=n&&(e=n+1)}t.updatedAt=new Date(e).toISOString()}function Ho({drawDefinition:t,tournamentId:e,matchUps:r,eventId:n}){if(t&&Qy(t),Array.isArray(r))for(let o of r)yL(o);return at({payload:{matchUps:r,tournamentId:e,eventId:n},topic:Zm}),{...P}}function wn({drawDefinition:t,tournamentId:e,matchUpIds:r,eventId:n,action:o}){t&&Qy(t),at({topic:HI,payload:{tournamentId:e,matchUpIds:r,eventId:n,action:o}});for(let i of r)zT({key:i});return{...P}}function It({drawDefinition:t,tournamentId:e,structureId:r,context:n,eventId:o,matchUp:i}){return i?(t&&Ft({drawDefinition:t,structureIds:r?[r]:void 0,tournamentId:e,eventId:o}),yL(i),at({topic:jI,payload:{matchUp:i,tournamentId:e,context:n},key:i.matchUpId}),{...P}):(console.log(Xe),{error:Xe})}function EL({tournamentId:t,inContextMatchUp:e}){return e?(at({payload:{inContextMatchUp:e,tournamentId:t},topic:Cp,key:e.matchUpId}),{...P}):{error:Xe}}function yc({tournamentId:t,eventId:e,drawDefinition:r}){return r?(Qy(r),at({payload:{drawDefinition:r,tournamentId:t,eventId:e},topic:kI,key:r.drawId}),{...P}):(console.log($),{error:$})}function AL({tournamentId:t,eventId:e,drawId:r}){return at({payload:{drawId:r,tournamentId:t,eventId:e},topic:WI,key:r}),zT({key:r}),{...P}}function Ft({drawDefinition:t,tournamentId:e,structureIds:r,eventId:n}){return t?(Qy(t,r),at({payload:{tournamentId:e,eventId:n,drawDefinition:t},topic:YI,key:t.drawId}),{...P}):{error:$}}function vl({drawDefinition:t,tournamentId:e,structure:r,eventId:n}){let o=dt({drawDefinition:t,structure:r},[Kt,mc]);if(o.error)return o;let i=r.seedAssignments,s=r.structureId,a=t.drawId;return at({payload:{tournamentId:e,eventId:n,drawId:a,structureId:s,seedAssignments:i},topic:$I,key:t.drawId}),Ft({structureIds:[s],drawDefinition:t,tournamentId:e,eventId:n}),{...P}}function hn({drawDefinition:t,tournamentId:e,structure:r,event:n}){let o=dt({drawDefinition:t,structure:r},[Kt,mc]);if(o.error)return o;let i=Pt({structure:r}),s=r.structureId,a=t.drawId,c=n?.eventId;return at({topic:qI,payload:{positionAssignments:i,tournamentId:e,structureId:s,eventId:c,drawId:a},key:s}),Ft({structureIds:[s],drawDefinition:t,tournamentId:e,eventId:c}),{...P}}function lb({tournamentRecord:t,drawDefinition:e,resetEntries:r,event:n}){if(!e)return{error:$};let o=e.structures?.find(s=>s.stage===Fe);if(!o)return{error:Nt};let i=o.matchUps?.map(({matchUpId:s})=>s)??[];return o.positionAssignments=[],o.seedAssignments=[],o.matchUps=[],wn({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:i,drawDefinition:e}),r&&(e.entries=e.entries.filter(s=>s.entryStage!==Fe)),Ft({tournamentId:t?.tournamentId,eventId:n?.eventId,drawDefinition:e,structureIds:[o.structureId]}),{...P}}function Ol({drawPositions:t,structure:e}){if([Z,W].includes(e.stage)&&e.stageSequence===1)return;let{positionAssignments:r}=Pt({structure:e});r?.filter(({drawPosition:o})=>t?.includes(o))?.forEach(o=>{ut({element:o,extension:{name:Pl,value:!0}})})}function Ec(t){let{appliedPolicies:e,positionAction:r,drawDefinition:n}=t;if(e?.audit?.[mu]===!1)return;let{extension:o}=ot({name:mu,element:n}),i=Array.isArray(o?.value)?o?.value??[]:[];if(!i?.length){let a=n.structures.find(c=>c.stage===W);if(a){let c=Pt({structure:a}).positionAssignments?.map(({drawPosition:u,participantId:p,bye:m,qualifier:d})=>({drawPosition:u,participantId:p,qualifier:d,bye:m}));i.push({name:"initialMainAssignments",initialAssignments:c})}}let s={value:i.concat(r),name:mu};ut({element:n,extension:s})}function ji({tournamentRecord:t,drawDefinition:e,event:r}){let o=(t?.events||r&&[r])?.map(c=>c?.drawDefinitions).flat().filter(Boolean)||e&&[e]||[],i={},s={},a=o.map(c=>c?.structures?.filter(u=>u?.structures)).flat().filter(Boolean);for(let c of a){let{structures:u,structureId:p}=c??{};u&&p&&(i[p]=u?.map(m=>m.structureId))&&u.forEach(m=>s[m.structureId]=c?.structureId)}return{containedStructures:i,containerStructures:s}}function Mp(t){let{sides:e,matchUpType:r}=t??{},n=t.potentialParticipants?.length?t.potentialParticipants.flat().map(s=>r===Rt?s?.individualParticipantIds??[]:s.participantId).flat():[],o=(e??[]).map(s=>r===Rt&&(s?.participant?.individualParticipantIds??[])||s?.participantId&&[s.participantId]||[]).flat();return{individualParticipantIds:o.concat(n).flat(),enteredIndividualParticipantIds:o,potentialIndividualParticipantIds:n}}function Dr(t){return t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{}}var fu="SIGN_IN_STATUS",fb="SIGNED_OUT",vp="SIGNED_IN",ur="TEAM",St="INDIVIDUAL",$r="GROUP",lt="PAIR",_t="TEAM",Op={TEAM_PARTICIPANT:ur,INDIVIDUAL:St,GROUP:$r,TEAM:_t,PAIR:lt},PL={INDIVIDUAL:St,GROUP:$r,PAIR:lt,TEAM:_t,SIGN_IN_STATUS:fu,SIGNED_OUT:fb,SIGNED_IN:vp};function _p({participantsProfile:t,participants:e=[],deepCopy:r}){let n=new Map,o=r!==!1?q(e,t?.convertExtensions,!0):e,i=o.filter(c=>c.participantType===_t),s=o.filter(c=>c.participantType===$r),a=o.filter(c=>c.participantType===lt);return o.forEach(c=>{if(c.participantType===St){let{participantId:u}=c;c.groupParticipantIds=[],c.teamParticipantIds=[],c.pairParticipantIds=[],c.groups=[],c.teams=[],i.forEach(p=>{(p?.individualParticipantIds??[]).forEach(m=>{m===u&&!c.teamParticipantIds?.includes(p.participantId)&&(c.teamParticipantIds.push(p.participantId),n.get(p.participantId)||n.set(p.participantId,{participantName:p.participantName,participantId:p.participantId}),c.teams.push({participantRoleResponsibilities:p.participantRoleResponsibilities,participantOtherName:p.participantOtherName,participantName:p.participantName,participantId:p.participantId,teamId:p.teamId}))})}),a.forEach(p=>{(p?.individualParticipantIds??[]).forEach(m=>{m===u&&!c.pairParticipantIds.includes(p.participantId)&&c.pairParticipantIds.push(p.participantId)})}),s.forEach(p=>{(p?.individualParticipantIds??[]).forEach(m=>{m===u&&!c.groupParticipantIds.includes(p.participantId)&&(c.groupParticipantIds.push(p.participantId),c.groups.push({participantRoleResponsibilities:p.participantRoleResponsibilities,participantOtherName:p.participantOtherName,participantName:p.participantName,participantId:p.participantId}))})})}}),{participantsWithGroupings:o,groupInfo:Object.fromEntries(n)}}function gb(t){return t&&typeof String.fromCodePoint<"u"?t.toUpperCase().replace(/./g,e=>String.fromCodePoint(e.charCodeAt(0)+127397)):t}function NL(t){let e=Object.assign({},...Ui.filter(r=>r.ioc).map(r=>({[r.ioc]:r.iso})));return gb(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 Xy({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 DL({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?hs({template:e,source:s}):s)}}}}function Do(t){let{tournamentRecord:e,participantId:r}=t,n=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};for(let o of Object.values(n)){let i=o.participants?.find(s=>s.participantId===r);if(i)return{participant:i,tournamentId:o.tournamentId}}return{error:ee}}function Jy(t){let{tournamentRecord:e,participantId:r}=t;if(r){let o=Do({tournamentRecord:e,participantId:r});return o.participant??o}let n=t.element||t.drawDefinition||t.event||t.tournamentRecord;return n||{error:nt}}function Jr(t){let{returnPreviousValues:e,itemSubTypes:r,itemType:n}=t,o=Jy(t);if(o.error)return o;if(r&&!Array.isArray(r))return{error:O,context:{itemSubTypes:r}};if(!Array.isArray(o.timeItems))return{error:rI};let i=o.timeItems.filter(a=>a?.itemType===n).filter(a=>!r?.length||r.some(c=>a?.itemSubTypes?.includes(c))).sort((a,c)=>{let u=new Date(a.createdAt||void 0).getTime(),p=new Date(c.createdAt||void 0).getTime();return u-p}),s=q(i.pop(),!1,!0);if(s){let a={timeItem:s,...P};return e&&Object.assign(a,{previousItems:i}),a}else return{info:fe}}function Zy({returnPreviousValues:t,drawDefinition:e,itemSubTypes:r,itemType:n}){if(!e)return{error:Nn};if(!e.timeItems)return{info:fe};let{timeItem:o,previousItems:i,info:s}=Jr({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function xp({returnPreviousValues:t,itemSubTypes:e,itemType:r,event:n}){if(!n)return{error:le};if(!n.timeItems)return{info:fe};let{timeItem:o,previousItems:i,info:s}=Jr({returnPreviousValues:t,element:n,itemSubTypes:e,itemType:r});return o&&{timeItem:o,previousItems:i}||{info:s}}function _l({returnPreviousValues:t,tournamentRecord:e,itemSubTypes:r,itemType:n}){if(!e)return{error:j};if(!e.timeItems)return{info:fe};let{timeItem:o,previousItems:i,info:s}=Jr({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function tE({returnPreviousValues:t,tournamentRecord:e,participantId:r,itemSubTypes:n,itemType:o}){let i=dt({tournamentRecord:e,participantId:r},[rt,sr]);if(i.error)return i;let s=Do({tournamentRecord:e,participantId:r});if(s.error)return s;let{participant:a}=s;if(!a?.timeItems)return{info:fe};let{timeItem:c,previousItems:u,info:p}=Jr({element:s.participant,returnPreviousValues:t,itemSubTypes:n,itemType:o});return c&&{timeItem:c,previousItems:u}||{info:p}}var sj={[$r]:"groupParticipantIds",[lt]:"pairParticipantIds",[_t]:"teamParticipantIds"},aj={[$r]:"groups",[_t]:"teams"};function eE({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&&pj({participantMap:p,participantId:l})}for(let d of r.participants??[]){let l=q(d,e,s),{participantId:f,individualParticipantIds:g,participantType:I}=l;if(!p[f]){u.push(f);continue}if(Object.assign(p[f].participant,l),g){let S=uj({individualParticipantIds:g,participantCopy:l,participantMap:p,participantType:I,participantId:f});S.missingParticipantIds.length&&u.push(...S.missingParticipantIds)}if(n&&(p[f].participant.signedIn=cj(l)),o){let{ratings:S,rankings:h,seedings:T}=lc({participant:l});p[f].participant.seedings=T,p[f].participant.rankings=h,p[f].participant.ratings=S}(c||a)&&Xy({participant:p[f].participant,withISO2:a,withIOC:c})}if(t){let d=Tt(t)?t:void 0;DL({participantMap:p,template:d})}let m;return i&&(m=_p({participants:Object.values(p).map(({participant:d})=>d),participantsProfile:{convertExtensions:e},deepCopy:!1}).groupInfo),{missingParticipantIds:u,participantMap:p,groupInfo:m}}function cj(t){let{timeItem:e}=Jr({itemType:fu,element:t});return e?.itemValue===vp}function uj({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[sj[n]].push(o),[_t,$r].includes(n)){let{participantRoleResponsibilities:c,participantOtherName:u,participantName:p,participantId:m,teamId:d}=e,l=aj[n];a[l].push({participantRoleResponsibilities:c,participantOtherName:u,participantName:p,participantId:m,teamId:d})}if(n===lt){let c=t.find(u=>u!==s);r[s].pairIdMap[o]=c,r[s].pairIdMap[c]=o}}return{missingParticipantIds:i}}function pj({participantMap:t,participantId:e}){if(t[e])return;let r={walkoverWins:0,defaultWins:0,walkovers:0,defaults:0,losses:0,wins:0};t[e]={structureParticipation:{},potentialMatchUps:{},scheduleConflicts:{},scheduleItems:[],participant:{groupParticipantIds:[],pairParticipantIds:[],teamParticipantIds:[],seedings:{},rankings:{},ratings:{},groups:[],teams:[]},statistics:{},opponents:{},pairIdMap:{},matchUps:{},events:{},draws:{},counters:{[Ct]:{...r},[Rt]:{...r},[_t]:{...r},...r}}}function di({participantsProfile:t,useParticipantMap:e,tournamentRecord:r,contextProfile:n,inContext:o}){if(e)return eE({...t,...n,tournamentRecord:r});let i=q(r.participants,!1,!0)??[];(t?.withIOC||t?.withISO2)&&i.forEach(a=>Xy({participant:a,...t}));let s;if((o||t?.withGroupings)&&i?.length&&({participantsWithGroupings:i,groupInfo:s}=_p({participantsProfile:t,deepCopy:!1,participants:i})),t?.withScaleValues&&i?.length)for(let a of i){let{ratings:c,rankings:u}=lc({participant:a});a.rankings=u,a.ratings=c}return{participants:i,groupInfo:s}}var rE="WALKOVER",Ib="RETIRED",xl="COMPETITIVE",gu="ROUTINE",Iu="DECISIVE",wl="winRatio";var mj={[gn]:{policyName:"Competitive Bands Default",profileBands:{[Iu]:20,[gu]:50},predictionModel:{competitiveAnchors:[{delta:0,probability:.7},{delta:1.5,probability:.25}],decisiveAnchors:[{delta:0,probability:.1},{delta:1.5,probability:.55}]}}},Hs=mj;function eo({policyDefinitions:t,tournamentRecord:e,contextProfile:r,drawDefinition:n,event:o}){let i={policies:{}};if(!r)return i;let s=fo({tournamentRecord:e,drawDefinition:n,event:o}).policyDefinitions;if(r.withCompetitiveness){let a=t?.[gn]??s?.[gn]??Hs[gn];i.policies[gn]=a}return i}function go({tournamentRecord:t,drawDefinition:e,policyType:r,structure:n,event:o}){if(!t)return{error:j};let{appliedPolicies:i}=ft({tournamentRecord:t,drawDefinition:e,structure:n,event:o});return i?.[r]?{policy:i[r]}:{info:np?.message}}function Ac({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}=go({policyType:ko,tournamentRecord:t,event:n}),s=(t?ot({element:t,name:pi}).extension:void 0)?.value,c=(n&&ot({name:pi,element:n}).extension)?.value;return{scheduleTiming:{tournamentScheduling:s,eventScheduling:c,categoryName:e,categoryType:r,policy:o}}}function XI({tournamentRecord:t,event:e}){if(!t)return{};let{extension:r}=ot({element:t,name:wR}),n=r?.value;if(!n?.events?.length)return{};let o=e?n.events.find(s=>s.eventType===e.eventType&&(!s.eventName||s.eventName===e.eventName)&&(!s.category?.categoryName||s.category?.categoryName===e.category?.categoryName)):void 0;if(!o)return{};let i={};return o.drawSize!==void 0&&(i.drawSize=o.drawSize),o.maxWildcards!==void 0&&(i.maxWildcards=o.maxWildcards),o.maxAlternates!==void 0&&(i.maxAlternates=o.maxAlternates),o.maxQualifiers!==void 0&&(i.maxQualifiers=o.maxQualifiers),Object.keys(i).length?{constraints:i}:{}}var Su="GEMscore",UL={GEM_SCORE:Su};function RL({provisionalPositioning:t,rankBy:e=Su,finishingPositions:r,groupResults:n,bestOf:o}){let i=[],s=[],a=[...r].sort(Zt),c=Math.max(...a);for(let{structureId:d,results:l}of n)for(let[f,g]of Object.entries(l)){let I=g.groupOrder||t&&g.provisionalOrder;if(!I)continue;let S={groupingValue:d,GEMscore:g.GEMscore,isBestFinisher:!1,finishingPosition:I,participantId:f};a.includes(I)?s.push(S):I>c&&i.push(S)}let u=[...s],p=o-s.length;p>0&&i.length>0&&i.toSorted((f,g)=>f.finishingPosition!==g.finishingPosition?f.finishingPosition-g.finishingPosition:e===Su?(g.GEMscore??0)-(f.GEMscore??0):0).slice(0,p).forEach(f=>{f.isBestFinisher=!0,u.push(f)});let m={};for(let d of u){let l=d.finishingPosition;m[l]=(m[l]||0)+1}return{selectedParticipants:u,consumedPositions:m}}var Zr="ALTERNATE",JI="CONFIRMED",kr="DIRECT_ACCEPTANCE",wp="FEED_IN",ZI="JUNIOR_EXEMPT",Ys="LUCKY_LOSER",tS="ORGANISER_ACCEPTANCE",Ll="QUALIFIER",dj="REGISTERED",eS="SPECIAL_EXEMPT",Gr="UNGROUPED",qi="UNPAIRED",Lp="WILDCARD",Mn="WITHDRAWN",td=[JI,kr,ZI,tS,eS],Sb=[wp,Ys,Ll],$i=[JI,kr,wp,ZI,tS,eS,Lp],yr=[JI,kr,ZI,Ys,Ll,tS,eS,Lp],hb=[Zr,JI,kr,wp,ZI,Ys,tS,Ll,dj,eS,Gr,qi,Lp,Mn],bL={ALTERNATE:Zr,CONFIRMED:JI,DIRECT_ACCEPTANCE:kr,DIRECT_ENTRY_STATUSES:$i,DRAW_SPECIFIC_STATUSES:Sb,EQUIVALENT_ACCEPTANCE_STATUSES:td,FEED_IN:wp,JUNIOR_EXEMPT:ZI,LUCKY_LOSER:Ys,ORGANISER_ACCEPTANCE:tS,QUALIFIER:Ll,SPECIAL_EXEMPT:eS,STRUCTURE_SELECTED_STATUSES:yr,UNGROUPED:Gr,UNPAIRED:qi,VALID_ENTRY_STATUSES:hb,WILDCARD:Lp,WITHDRAWN:Mn};function CL({stage:t,drawDefinition:e}){return ou.includes(t)?e?.structures?.some(n=>n.stage===t)||ou.includes(t):!1}function nE({stage:t,drawDefinition:e,entryStatus:r}){return e.entries.reduce((n,o)=>o.entryStage===t&&o.entryStatus===r?n+1:n,0)}function Ki({provisionalPositioning:t,placementGroup:e,drawDefinition:r,stageSequence:n,entryStatuses:o,structureId:i,roundTarget:s,stages:a,stage:c}){let u=r.entries?.reduce((p,m)=>{let d=ot({name:bn,element:m})?.extension?.value,l=c&&m.entryStage===c||a?.length&&m.entryStage&&a.includes(m.entryStage),f=!o||m.entryStatus&&o.includes(m.entryStatus),g=m.entryStageSequence??1;return l&&(!n||g===n)&&f&&(!s||!d||s===d)?p.concat(m):p},[])??[];if(i&&c===Vt){let{playoffEntries:p,error:m}=lj({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 lj({provisionalPositioning:t,drawDefinition:e,structureId:r}){let n=[],o=(e.links??[]).find(i=>i.linkType===fn&&i.target.structureId===r);if(o){let{finishingPositions:i,structureId:s,bestOf:a,rankBy:c}=o.source,{structure:u}=tt({drawDefinition:e,structureId:s});if(u?.structureType===de){let m=(u.structures??[]).map(d=>{let l=d.positionAssignments??[],{structureId:f}=d,g=Object.assign({},...l.map(I=>{let{participantId:S}=I,h=ot({element:I,name:Bo}).extension?.value;return h&&S?{[S]:h}:void 0}).filter(Boolean));return{structureId:f,results:g}});if(o.source.remainder)fj({provisionalPositioning:t,allGroupResults:m,drawDefinition:e,playoffEntries:n,inboundLink:o,structureId:s});else if(a!==void 0&&i){let{selectedParticipants:d}=RL({groupResults:m,provisionalPositioning:t,finishingPositions:i,bestOf:a,rankBy:c});d.forEach(l=>{let g=i.includes(l.finishingPosition)?[...i].sort(Zt).indexOf(l.finishingPosition)+1:[...i].sort(Zt).length+1;n.push({isBestFinisher:l.isBestFinisher,groupingValue:l.groupingValue,participantId:l.participantId,GEMscore:l.GEMscore,entryStatus:wp,entryStage:Vt,placementGroup:g})})}else gj({provisionalPositioning:t,finishingPositions:i,allGroupResults:m,playoffEntries:n})}}return{playoffEntries:n}}function fj({provisionalPositioning:t,allGroupResults:e,drawDefinition:r,playoffEntries:n,inboundLink:o,structureId:i}){let s=new Set,a=(r.links??[]).filter(c=>c.linkType===fn&&c.source.structureId===i&&c.target.structureId!==o.target.structureId&&c.source.bestOf!==void 0);for(let c of a){let{structure:u}=tt({structureId:c.target.structureId,drawDefinition:r});if(u)for(let p of u.positionAssignments??[])p.participantId&&s.add(p.participantId)}e.forEach(({structureId:c,results:u})=>{Object.keys(u).forEach(p=>{if(!s.has(p)){let m=u[p],{groupOrder:d,provisionalOrder:l,GEMscore:f}=m,g=d||t&&l;n.push({groupingValue:c,entryStage:Vt,entryStatus:wp,placementGroup:g||1,participantId:p,GEMscore:f})}})})}function gj({provisionalPositioning:t,finishingPositions:e,allGroupResults:r,playoffEntries:n}){r.forEach(({structureId:o,results:i})=>{let s=o,c=Object.keys(i).reduce((p,m)=>{let d=i[m],l=d.groupOrder||t&&d.provisionalOrder;return p.includes(l)||p.push(l),p},[]).length===Object.keys(i).length,u=Object.keys(i).filter(p=>{let m=i[p],d=m.groupOrder||t&&m.provisionalOrder;return e?.includes(d)});(!t||c)&&u.forEach(p=>{let m=i[p],{groupOrder:d,provisionalOrder:l,GEMscore:f}=m,g=d||t&&l,I=[...e??[]].sort(Zt).indexOf(g)+1;n.push({entryStage:Vt,entryStatus:wp,placementGroup:I,groupingValue:s,participantId:p,GEMscore:f})})})}function Ur({provisionalPositioning:t,returnAllProxies:e,drawDefinition:r,structureId:n,structure:o}){let i,s=[];o||({structure:o,error:i}=tt({drawDefinition:r,structureId:n}));let a=Pt({structure:o}).positionAssignments;if(i||!o)return{seedAssignments:[],error:Nt};n||(n=o.structureId);let{stage:c,stageSequence:u}=o,m=c===Vt&&r&&Ki({provisionalPositioning:t,drawDefinition:r,stageSequence:u,structureId:n,stage:c}),d=m?m.filter(g=>g.placementGroup===1).sort((g,I)=>g.GEMscore<I.GEMscore&&1||g.GEMscore>I.GEMscore&&-1||0).map((g,I)=>{let S=I+1;return{participantId:g.participantId,seedValue:S,seedProxy:!0,seedNumber:S}}):[],l=d?.slice(0,e?d.length:a.length/2);l.length?s=l:o.seedAssignments?s=o.seedAssignments:i=GD;let f=o.seedLimit??o?.positionAssignments?.length;return{seedAssignments:s,stageSequence:u,seedLimit:f,stage:c,error:i}}function Yo(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 ed({item:t,drawDefinition:e,structure:r,event:n}){if(t){if(t.tieFormat)return t.tieFormat;if(t.tieFormatId){if(e.tieFormat)return e.tieFormat;let o=e.tieFormats?.find(i=>t.tieFormatId===i.tieFormatId);return o||(n.tieFormat?n.tieFormat:n.tieFormats?.find(i=>t.tieFormatId===i.tieFormatId))}if(r?.tieFormat)return r.tieFormat;if(r?.tieFormatId){let o=e.tieFormats?.find(i=>r.tieFormatId===i.tieFormatId);if(o)return o}}}function ze({drawDefinition:t,structure:e,matchUp:r,event:n}){return{tieFormat:ed({item:r,drawDefinition:t,structure:e,event:n})||ed({item:e,drawDefinition:t,structure:e,event:n})||Yo(t)||Yo(n)}}function ML({matchUps:t}){let e=t.reduce((n,o)=>!o.collectionPosition||n.includes(o.collectionPosition)?n:n.concat(o.collectionPosition),[]).map(n=>({[n]:t.filter(o=>o.collectionPosition===n)}));return{collectionPositionMatchUps:Object.assign({},...e)}}function Ie({drawDefinition:t,structure:e}){let r={},n=[];return(t?.structures??[e]).filter(o=>o&&typeof o=="object").forEach(o=>{if(!o)return;let{structureId:i,matchUps:s,structures:a}=o,c=Array.isArray(a);if(c)c&&a.forEach(u=>{let{structureName:p}=u,m=u.matchUps;r[u.structureId]={matchUps:m,itemStructureIds:[],structureName:p},m&&(n.push(...m),m.forEach(d=>{d.tieMatchUps&&n.push(...d.tieMatchUps)})),r[i]||(r[i]={itemStructureIds:[],matchUps:[]}),r[i].itemStructureIds||(r[i].itemStructureIds=[]),r[i].itemStructureIds.push(u.structureId)});else{let u=s;r[i]={matchUps:u,itemStructureIds:[]},u?.forEach(p=>{n.push(p),p.tieMatchUps&&n.push(...p.tieMatchUps)})}}),{mappedMatchUps:r,drawMatchUps:n}}function jo({mappedMatchUps:t,matchUpsMap:e,structureId:r,inContext:n}){t=e?.mappedMatchUps??t;let o=t[r],i=(o?.itemStructureIds??[]).map(s=>{let{matchUps:a,structureName:c}=t[s];return n?a.map(u=>Object.assign(q(u,!0,!0),{containerStructureId:r,structureId:s,structureName:c})):a}).flat();return(o?.matchUps??[]).concat(...i)}function oE({policyDefinitions:t,tournamentRecord:e,drawDefinition:r,structure:n,event:o}){let i=t?.[gn];if(i?.profileBands)return i.profileBands;if(e){let{appliedPolicies:s}=ft({tournamentRecord:e,drawDefinition:r,structure:n,event:o}),a=s?.[gn];if(a?.profileBands)return a.profileBands}return Hs[gn].profileBands}var Ij=(t,e)=>(t||0)+(e||0);function iE(t,e){let r=Array.isArray(t)?t[0]:t;return r===void 0||Number.isNaN(r)?rE:r<=e[Iu]&&Iu||r<=e[gu]&&gu||xl}function Fl({score:t}){let e=t?.sets??[],r=e.reduce((o,i)=>(o[0]+=i.side1Score||0,o[1]+=i.side2Score||0,o),[0,0]),n=e.reduce((o,i)=>(o[0]+=i.side1TiebreakScore||0,o[1]+=i.side2TiebreakScore||0,o),[0,0]);return n.reduce(Ij)&&(r[n[0]>n[1]?0:1]+=1),{sets:e,games:r,score:t}}function Sj(t){let e=t?.games;if(!e?.length)return;let r=Math.max(...e);if(r===0)return;let n=Math.min(...e);return Math.round(n/r*100)}function sE(t){return t.map(Sj).filter(e=>e!==void 0).sort((e,r)=>e-r).map(e=>parseFloat(e.toFixed(2)))}function js({tournamentRecord:t,profileBands:e,matchUp:r}){if(!r)return{error:Xe};let{score:n,winningSide:o}=r;if(!o)return{error:O};let i=e||oE({tournamentRecord:t}),s=Fl({score:n}),a=sE([s]),c=iE(a,i),u=Array.isArray(a)?a[0]:a;return{...P,competitiveness:c,pctSpread:u}}function aE({groupedOrder:t,roundPositionsCount:e}){if(!t||t?.length<=e)return t;let n=he(t,t.length/e).map(i=>i.reduce((s,a)=>s+a)),o=n.slice().sort(Zt);return n.map(i=>o.indexOf(i)+1)}function rS(t){if(!Tt(t))return!1;let{matchUpId:e,drawPositions:r}=t,n=typeof e=="string",o=!r||Array.isArray(r)&&r.length<=2&&r.every(i=>yt(i)||i===void 0||i===null);return n&&o}function Rr(t){return Array.isArray(t)?t.every(rS):!1}function hj(t,e){return e?.find(r=>t.includes(r))}function Ue({matchUps:t=[],interpolate:e}){if(!Rr(t))return{roundMatchUps:[],error:O};let r=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?st(l.roundNumber):l.roundNumber;return!l.roundNumber||d.includes(f)?d:d.concat(f)},[]).sort(Zt).map(d=>{let l=t.filter(S=>S.roundNumber===d),g=l.find(({matchUpType:S})=>S===xt)?l.filter(({matchUpType:S})=>S===xt):l,I=S=>S.sort((h,T)=>Zt(h.roundPosition,T.roundPosition));return{[d]:I(g)}}),n=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?st(l.roundNumber):l.roundNumber;return d[f]||(d[f]=et({abbreviatedRoundName:l.abbreviatedRoundName,finishingRound:l.finishingRound,roundName:l.roundName})),d},{}),o=Object.assign({},...r);if(e){let d=Math.max(...Object.keys(o).map(f=>st(f)).filter(f=>!Number.isNaN(f))),l=o[d]?.length;if(l>1&&en(l)){let f=d+1,g=f+l/2;Q(f,g).forEach((S,h)=>{o[S]=Q(0,l/(2+h*2)).map(()=>({}))})}}let i=0,s=Object.assign({},...Object.keys(o).map(d=>{let l=o[d]?.length,f=o[d]?.filter(I=>!Ot.includes(I.matchUpStatus)&&!I.score?.scoreStringSide1)?.length,g=l&&l===f;return i=Math.max(i,l),{[d]:{matchUpsCount:l,inactiveCount:f,inactiveRound:g}}})),a=0,c=0,u=Object.keys(o).map(d=>st(d)).filter(d=>!Number.isNaN(d));u.forEach(d=>{let l=o[d].sort((g,I)=>g.roundPosition-I.roundPosition),f=l.flatMap(g=>g?.drawPositions??[]);if(s[d].roundNumber=d,s[d].roundFactor=s[d].matchUpsCount?i/s[d].matchUpsCount:1,s[d].finishingRound=n[d]?.finishingRound,s[d].roundName=n[d]?.roundName,s[d].abbreviatedRoundName=n[d]?.abbreviatedRoundName,s[d].finishingPositionRange=o[d]?.[0]?.finishingPositionRange,d===1||!s[d-1]){let g=f.sort(Zt),I=he(g,2);s[d].drawPositions=g,s[d].pairedDrawPositions=I}else{let g=s[d-1],I=g.drawPositions,S=g.matchUpsCount/s[d].matchUpsCount,h=he(I,S),T=l.map(y=>{let{roundPosition:E}=y,A=[...y.drawPositions??[],void 0,void 0].slice(0,2);if(!E)return A;let N=A?.filter(Boolean)??[];if(!N?.length)return[void 0,void 0];if(d<3&&N?.length===2)return A?.slice().sort(Zt);let D=Yt(I,N).length!==N?.length;if(N?.length&&D)return N?.length===1?[N[0],void 0]:A?.slice().sort(Zt);let R=(E-1)*2;return h.slice(R,R+2).map(b=>hj(b,N))});s[d].drawPositions=T?.flat(),s[d].pairedDrawPositions=T}s[d+1]?.matchUpsCount===s[d].matchUpsCount&&(s[d+1].feedRound=!0,s[d+1].feedRoundIndex=c,s[d].preFeedRound=!0,c+=1),s[d]&&!s[d].feedRound&&(s[d].roundIndex=a,a+=1)});let p=!!Object.values(s).some(({matchUpsCount:d})=>!en(d));return{hasNoRoundPositions:t.some(d=>!d.roundPosition),roundsNotPowerOf2:p,maxMatchUpsCount:i,roundMatchUps:o,roundNumbers:u,roundProfile:s,...P}}function kl(t){if(!Array.isArray(t))return"";let e=t.filter(Le);return e.length?pt([Math.min(...e),Math.max(...e)]).join("-"):""}function vL({drawDefinition:t,structureId:e,matchUpsMap:r}){let n=dt({drawDefinition:t,structureId:e},[Kt,mo]);if(n.error)return n;let{structure:o}=tt({drawDefinition:t,structureId:e});if(o?.stage!==me)return{error:cc,info:"Structure is not CONSOLATION stage"};let{links:i}=t,s=i?.filter(d=>d.target.structureId===e)??[],a=s?.reduce((d,l)=>{let{structureId:f}=l.source;return d.includes(f)?d:d.concat(f)},[])??[],c=Object.assign({},...a.map(d=>{let l=jo({structureId:d,matchUpsMap:r}),g=Ue({matchUps:l}).roundProfile;return{[d]:g}})),u=jo({matchUpsMap:r,structureId:e}),{roundProfile:p}=Ue({matchUps:u}),m={};return s?.forEach(d=>{let{structureId:l,roundNumber:f}=d.source,{feedProfile:g,groupedOrder:I,positionInterleave:S,roundNumber:h}=d.target,T=c[l],y=T[1]?.drawPositions,A=T[f]?.matchUpsCount;if(!A)return;let N=A?y.length/A:0,D=y.length/N,R=y.slice(),U=aE({roundPositionsCount:D,groupedOrder:I}),b=U?.length||1;if(b<=D){let w=y.length/b,L=he(R,w);g===Fi&&L.forEach(F=>F.reverse()),R=U?.length&&U?.map(F=>L[F-1]).flat()||L.flat()}let C=he(R,N);if(S){let w=Q(0,S.interleave).map(()=>{}),L=Q(0,S.offset).map(()=>{});C=C.map(x=>[x,...w]),C.unshift(L),C=C.flat(1);let F=C.length-S.offset;C=C.slice(0,F)}m[h]||(m[h]={});let v=p?.[h]?.feedRound?2:1;C.forEach((w,L)=>{let F=1+L*v;m[h][F]||(m[h][F]=kl(w))})}),{sourceDrawPositionRanges:m}}function Gl({drawDefinition:t}){if(typeof t!="object")return{error:ha};let e={},{structures:r=[],links:n=[]}=t??{},o=r.reduce((s,a)=>{let{stage:c}=a;return s[c]?s[c].push(a):s[c]=[a],s},{});for(let s of Object.keys(o)){let a=o[s].find(({stageSequence:p})=>p===1);if(!a)continue;let{structureId:c}=a;i({aggregator:{},targetRound:0,exitProfiles:e,exitProfile:"0",structureId:c,stage:s})}return{exitProfiles:e};function i({exitProfiles:s,exitProfile:a,structureId:c,targetRound:u,aggregator:p,stage:m}){s[c]||(s[c]=[]),a==="0"&&[me,Vt].includes(m)||s[c].push(a);let d=n.filter(l=>l.source.structureId===c&&l.source.roundNumber>=u);for(let l of d){let f=l.source.roundNumber,g=l.target.roundNumber,I=l.target.structureId,S=r.find(T=>T.structureId===I).stage,h=[S,I,g,f].join("|");if(p[h])return;p[h]=!0,i({exitProfile:`${a}-${f}`,structureId:I,exitProfiles:s,targetRound:g,aggregator:p,stage:S})}}}function OL({drawDefinition:t,roundProfile:e,structureId:r,matchUpsMap:n}){let o=dt({drawDefinition:t,structureId:r},[Kt,mo]);if(o.error)return o;if(!e){let u=jo({matchUpsMap:n,structureId:r});if({roundProfile:e}=Ue({matchUps:u}),!e)return{error:nt}}let s=(Math.min(...e?.[1]?.drawPositions??[])||1)-1,a=Object.keys(e);return{drawPositionsRanges:Object.assign({},...(a??[]).map(u=>{let p=e?.[u]?.matchUpsCount,m=e?.[1]?.drawPositions??[],d=he(m,m.length/p),l=d.map(kl),f=d.map(T=>T.map(y=>y-s)).map(kl),g=a.map(T=>{if(T>u)return;let y=e?.[T]?.drawPositions??[];return he(y,y.length/p)}).filter(Boolean),I=Q(0,p).map(T=>g.map(y=>y[T]).flat().filter(Boolean).sort(Zt)).map(T=>pt(T)),S=I.map(T=>dw(T).map(kl).join(", ")),h=Object.assign({},...Q(0,p).map(T=>({[T+1]:{firstRoundDrawPositionsRange:l[T],firstRoundOffsetDrawPositionsRange:f[T],possibleDrawPositions:I[T],drawPositionsRange:S[T]}})));return{[u]:h}}))}}var Tj=new Set([ai,ki]);function an(t){return!!t&&Tj.has(t)}function nS({structure:t,matchUps:e}){e=e??t?.matchUps??[];let r=Ue({matchUps:e}),n=r.roundProfile,o=r.roundNumbers;if(!n||!o?.length||o.length<2)return!1;let i=[...o].sort((s,a)=>s-a);for(let s=0;s<i.length-1;s++){let a=n[i[s]]?.matchUpsCount??0,c=n[i[s+1]]?.matchUpsCount??0;if(a%2===1&&c%2===0)return!0}return!1}function Pc({roundsNotPowerOf2:t,drawDefinition:e,structure:r,matchUps:n}){return!r||(n=n??r.matchUps??[],t=t??Ue({matchUps:n}).roundsNotPowerOf2,!(!!r.positionAssignments?.find(({drawPosition:i})=>i)||!!n?.find(({drawPositions:i})=>i?.length))||r?.structures)||e?.drawType&&an(e.drawType)||!t?!1:nS({structure:r,matchUps:n})}function Ae({structure:t}){if(!t)return!1;let e=t.matchUps||t.roundMatchUps&&Object.values(t.roundMatchUps).flat(),r=!!e?.find(o=>o?.roundPosition),n=!!e?.find(o=>o?.drawPositions?.length);return t?.stage===Fe?t?.structures||t?.structureType===su&&n?!1:t?.finishingPosition===po:!t?.structures&&(!e.length||!r&&!n)}var oS={[Fo]:{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:{[W]:"",[Vt]:"P",[Z]:"Q",[me]:"C"}}},_L=oS;function cE({roundNamingPolicy:t,drawDefinition:e,structure:r,matchUps:n}){let{roundProfile:o,roundMatchUps:i}=Ue({matchUps:n}),{structureAbbreviation:s,stage:a}=r,c=Ae({structure:r}),u=Pc({structure:r}),p=r.structures,m={},d=oS[Fo],l=r.stage===Z,f=l?Math.max(...(e?.structures??[]).filter(_=>_.stage===Z).map(({stageSequence:_})=>_??1),0):0,g=(r.stageSequence??1)<f?r.stageSequence??1:"",I=g&&(t?.affixes?.preQualifying||d.affixes.preQualifying)||"",S=t?.roundNamingMap||(d.roundNamingMap??{}),h=t?.abbreviatedRoundNamingMap||(d.abbreviatedRoundNamingMap??{}),T=t?.affixes?.preFeedRound||d.affixes.preFeedRound,y=t?.affixes?.roundNumber||d.affixes.roundNumber,A=(t?.namingConventions||d.namingConventions).round,N=a&&a!==W?a[0]:"",D=t?.stageConstants||d.stageConstants,R=a&&D?.[a]||N,U=`${I}${R}${g}`,b=o?Object.keys(o):[],C=l&&D?.[Z]?`${D?.[Z]}-`:"";if(p||c||u)Object.assign(m,...b.map(_=>{let v=`${C}${A} ${_}`,w=`${y}${_}`;return{[_]:{roundName:v,abbreviatedRoundName:w}}}));else{let _=l&&(t?.qualifyingFinishMap||(d?.qualifyingFinishMap??{}));Object.assign(m,...b.map(v=>{if(!o?.[v])return;let{matchUpsCount:w,preFeedRound:L}=o[v],F=w*2,x=_?.[o?.[v].finishingRound]||_&&`${y}${F}`||S[w]||`${y}${F}`,k=L?`-${T}`:"",G=`${x}${k}`,V=[U,s,G].filter(Boolean).join("-"),z=`${h[w]||`${y}${F}`}${k}`,H=[U,s,z].filter(Boolean).join("-");return{[v]:{abbreviatedRoundName:H,roundName:V}}}))}return{roundNamingProfile:m,roundProfile:o,roundMatchUps:i}}function uE({matchUp:t}){if(!t)return{error:Xe};if(t&&!t.sides)return{error:cr};if(t&&!t.hasContext)return{error:ap};let e=(t.sides??[])?.map(a=>a?.participantId).filter(Boolean),r=t.sides?.filter(a=>a.participant?.participantType===St).map(a=>a.participantId).filter(Boolean)??[],o=((t.sides??[])?.map(a=>a.participant?.individualParticipants).filter(Boolean)??[]).map(a=>(a??[]).map(c=>c?.participantId).filter(Boolean)),i=[...r,...o.flat()].filter(Boolean)??[],s=pt(i.concat(e)).filter(Boolean)??[];return{nestedIndividualParticipantIds:o,allRelevantParticipantIds:s,individualParticipantIds:i,sideParticipantIds:e,...P}}var Vl="CHECK_IN",Bl="CHECK_OUT",yj="SCHEDULE",Ts="SCHEDULE.ASSIGNMENT.VENUE",Io="SCHEDULE.ALLOCATION.COURTS",li="SCHEDULE.ASSIGNMENT.COURT",hu="SCHEDULE.COURT.ORDER",Tu="SCHEDULE.COURT.ANNOTATION",ys="SCHEDULE.DATE",Ej="COMPLETED.DATE",Wl="HOME_PARTICIPANT_ID",iS="SCHEDULE.ASSIGNMENT.OFFICIAL",Es="SCHEDULE.TIME.SCHEDULED",fi="SCHEDULE.TIME.START",Fa="SCHEDULE.TIME.STOP",qs="SCHEDULE.TIME.RESUME",As="SCHEDULE.TIME.END",rd="SCHEDULE.TIME.MODIFIERS",xL="TO_BE_ANNOUNCED",wL="NEXT_AVAILABLE",LL="FOLLOWED_BY",FL="AFTER_REST",kL="RAIN_DELAY",Aj="NOT_BEFORE",pE=[xL,wL,LL,FL,kL],Pj="ELIGIBILITY",Nj="REGISTRATION",Dj="SUSPENSION",Uj="MEDICAL",Rj="PENALTY",Tb="SCALE",yb="RATING",Eb="RANKING",sS="SEEDING",qo="PUBLISH",br="PUBLIC",$o="STATUS",bj="MODIFICATION",Cj="RETRIEVAL",Mj="other",GL={MUTUALLY_EXCLUSIVE_TIME_MODIFIERS:pE,AFTER_REST:FL,ALLOCATE_COURTS:Io,ASSIGN_COURT:li,ASSIGN_OFFICIAL:iS,ASSIGN_VENUE:Ts,CHECK_IN:Vl,CHECK_OUT:Bl,COMPLETED_DATE:Ej,COURT_ANNOTATION:Tu,COURT_ORDER:hu,ELIGIBILITY:Pj,END_TIME:As,FOLLOWED_BY:LL,MEDICAL:Uj,MODIFICATION:bj,NEXT_AVAILABLE:wL,NOT_BEFORE:Aj,OTHER:Mj,PENALTY:Rj,PUBLIC:br,PUBLISH:qo,RANKING:Eb,RATING:yb,RAIN_DELAY:kL,REGISTRATION:Nj,RESUME_TIME:qs,RETRIEVAL:Cj,SCALE:Tb,SCHEDULE:yj,SCHEDULED_DATE:ys,SCHEDULED_TIME:Es,SEEDING:sS,START_TIME:fi,STATUS:$o,STOP_TIME:Fa,SUSPENSION:Dj,TIME_MODIFIERS:rd,TO_BE_ANNOUNCED:xL};function $s({matchUp:t}){if(!t)return{error:Xe};if(!t.hasContext)return{error:ap};if(!t.sides||t?.sides.filter(Boolean).length!==2)return{error:cr};let{nestedIndividualParticipantIds:e,allRelevantParticipantIds:r,sideParticipantIds:n}=uE({matchUp:t}),i=(t.timeItems??[]).filter(u=>u?.itemType&&[Vl,Bl].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===Vl);e?.forEach((u,p)=>{let m=n?.[p],d=u?.length&&u.every(l=>a.includes(l));m&&d&&!a.includes(m)&&a.push(m)}),n?.forEach((u,p)=>{a.includes(u)&&(e?.[p]??[]).forEach(m=>{m&&!a.includes(m)&&a.push(m)})});let c=n?.reduce((u,p)=>a.includes(p)&&u,!0);return{allRelevantParticipantIds:r,allParticipantsCheckedIn:c,checkedInParticipantIds:a,...P}}var re=t=>e=>{let r=Tt(e)&&e?.matchUpType||wt(e)&&e;return r&&CT[t].includes(r)};function nd(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 od(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 mE({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 VL({tournamentScheduling:t,eventScheduling:e,averageMinutes:r,defaultTiming:n,matchUpFormat:o,categoryName:i,categoryType:s,policy:a}){let c=e?.matchUpRecoveryTimes&&od({...e,averageMinutes:r,matchUpFormat:o}),u=t?.matchUpRecoveryTimes&&od({...t,averageMinutes:r,matchUpFormat:o}),p=a?.matchUpRecoveryTimes&&od({...a,averageMinutes:r,matchUpFormat:o}),m=[c,u,p,a?.defaultTimes?.recoveryTimes,n?.recoveryTimes];return mE({categoryName:i,categoryType:s,timesBlockArray:m})}function BL({matchUpFormat:t,categoryName:e,categoryType:r,defaultTiming:n,tournamentScheduling:o,eventScheduling:i,policy:s}){let a=i?.matchUpAverageTimes&&nd({...i,matchUpFormat:t}),c=o?.matchUpAverageTimes&&nd({...o,matchUpFormat:t}),u=s?.matchUpAverageTimes&&nd({...s,matchUpFormat:t}),p=[a,c,u,s?.defaultTimes?.averageTimes,n?.averageTimes];return mE({categoryName:e,categoryType:r,timesBlockArray:p})}var Ab="DOUBLES_SINGLES",Pb="SINGLES_DOUBLES",So="total",dE="participantConflict",lE="potentialParticipantConflict",gi="matchUpConflict",Nb="courtDoubleBooking",Db="positionLinkConflict",Ub="ISSUE_IDS",Ks="CONFLICT",zs="WARNING",Hl="ERROR",Yl="ISSUE",aS="STATE",vj="BLOCKED",Oj="PRACTICE",_j="MAINTENANCE",WL={SINGLES_DOUBLES:Pb,DOUBLES_SINGLES:Ab,TOTAL:So,CONFLICT_MATCHUP_ORDER:gi,CONFLICT_PARTICIPANTS:dE,CONFLICT_POTENTIAL_PARTICIPANTS:lE,CONFLICT_COURT_DOUBLE_BOOKING:Nb,CONFLICT_POSITION_LINK:Db,SCHEDULE_ISSUE_IDS:Ub,SCHEDULE_CONFLICT:Ks,SCHEDULE_WARNING:zs,SCHEDULE_ERROR:Hl,SCHEDULE_ISSUE:Yl,SCHEDULE_STATE:aS,BLOCKED:vj,PRACTICE:Oj,MAINTENANCE:_j};function Fp({defaultAverageMinutes:t=90,defaultRecoveryMinutes:e=0,tournamentRecord:r,matchUpFormat:n,categoryName:o,categoryType:i,eventType:s,event:a}){if(!r)return{error:j};s=s??a?.eventType??ba;let c={averageTimes:[{minutes:{default:t}}],recoveryTimes:[{minutes:{default:e}}]},{scheduleTiming:u}=Ac({tournamentRecord:r,categoryName:o,categoryType:i,event:a}),p={...u,matchUpFormat:n,categoryType:i,defaultTiming:c};return id({eventType:s,timingDetails:p})}function id({timingDetails:t,eventType:e}){let r=BL(t),n=Object.keys(r?.minutes??{}),o=r?.minutes&&(n?.includes(e)&&r.minutes[e]||r.minutes.default),i=VL({...t,averageMinutes:o}),s=Object.keys(i?.minutes??{}),a=i?.minutes&&(s?.includes(e)&&i.minutes[e]||i.minutes.default),c=re(ba)(e)?Pb:Ab,u=i?.minutes&&(s?.includes(c)&&i.minutes[c]||a);return{averageMinutes:o,recoveryMinutes:a,typeChangeRecoveryMinutes:u}}function Rb(t){return t.createdAt?new Date(t.createdAt).getTime():0}function Ii({timeItems:t,itemType:e}){let r=t.filter(o=>o&&o.itemType===e).sort((o,i)=>Rb(o)-Rb(i)).pop(),n=r&&Rb(r);return{itemValue:r?.itemValue,timeStamp:n}}function jl({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Ii({timeItems:r?.timeItems??[],itemType:Es});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{scheduledTime:n}:e}function Qs({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Ii({timeItems:r?.timeItems??[],itemType:ys});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{scheduledDate:n}:e}function sd(t){if(ZT.test(t)){let e=SI();return new Date(`${e}T${t}`)}else return new Date(t)}function HL({matchUp:t}){if(!t)return{error:Xe};if(!t.timeItems)return{error:rI};let e=t.timeItems.filter(n=>[fi,Fa,qs,As].includes(n?.itemType)).sort((n,o)=>sd(n.itemValue).getTime()-sd(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 fi:i=0;break;case As:if(n.lastValue&&[fi,qs].includes(n.lastType)){let u=sd(o.itemValue).getTime()-sd(n.lastValue).getTime();i=n.milliseconds+u}else i=n.milliseconds;break;case Fa:if([fi,"SCHECULE.TIME.RESUME"].includes(n.lastType)){let u=sd(o.itemValue).getTime()-sd(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([fi,qs].includes(r.lastType)){let n=new Date().getTime()-sd(r.lastValue).getTime();r.milliseconds+=n}return{milliseconds:r.milliseconds,time:xj(r.milliseconds),relevantTimeItems:e}}function xj(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 YL({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===fi&&s;return a&&(!i||r(a)<r(i))?a:i},void 0)?.itemValue}}function fE(t){return parseInt(t)}function ql({startTime:t="",endTime:e=""}={}){if(!t||!e||!ru.test(t)||!ru.test(e))return!1;let[r,n]=t.split(":").map(fE),[o,i]=e.split(":").map(fE);return o<r?!1:!(r===o&&i<n)}function jL(t,e){let[r,n]=t.startTime.split(":").map(fE),[o,i]=e.startTime.split(":").map(fE);return r<o?-1:r>o?1:n<i?-1:n>i?1:0}function kp({dateAvailability:t}){if(!t)return{error:iU};if(!Array.isArray(t))return{error:$g};for(let e of t){if(typeof e!="object")return{error:$g};let{date:r,startTime:n,endTime:o,bookings:i=[]}=e;if(!n||!o)return{error:$g};let s=Lj(r);if(s)return s;let a=$L(n,o);if(a)return a;if(i){let c=Fj(i);if(c)return c}}return{valid:!0}}var wj="Dates must be formated => YYYY-MM-DD",qL="Times must be 24 hour => 00:00";function Lj(t){if(t&&!_o.test(t))return{error:ae,dateAvailability:{date:t},info:wj}}function $L(t,e){if(!ru.test(t))return{error:ws,dateAvailability:{startTime:t},info:qL};if(!ru.test(e))return{error:ws,dateAvailability:{endTime:e},info:qL};if(t===e)return{error:ws,dateAvailability:{startTime:t,endTime:e},info:"startTime and endTime are equivalent"};if(!ql({startTime:t,endTime:e}))return{error:ws,dateAvailability:{startTime:t,endTime:e},info:"endTime must be after startTime"}}function Fj(t){if(!Array.isArray(t))return{error:il};for(let e of t){if(typeof e!="object")return{error:il};let{startTime:r,endTime:n}=e,o=$L(r,n);if(o)return o}}function gE({tournamentRecord:t}){for(let e of t.venues??[])e.isPrimary&&delete e.isPrimary}function yu(t){let{disableNotice:e,venue:r,context:n}=t;if(typeof r!="object")return{error:O};let o=Dr(t);r.venueId??=it();let i;for(let s of Object.values(o)){let a=kj({disableNotice:!0,tournamentRecord:s,context:n,venue:r});if(a?.error)return a;i=a.venue}return e||at({topic:$y,payload:{venue:r}}),et({...P,venue:i})}function kj({tournamentRecord:t,disableNotice:e,context:r,venue:n}){let o=dt({tournamentRecord:t},[rt]);if(o.error)return o;if(!n)return{error:nt,info:"missing venue"};if(t.venues??=[],n.venueId??=it(),t.venues.reduce((s,a)=>s||a.venueId===n.venueId,void 0))return{error:UU};if(n.dateAvailability?.length){let s=kp({dateAvailability:n.dateAvailability});if(s.error)return s}if(n.defaultStartTime||n.defaultEndTime){if(!n.defaultStartTime||!n.defaultEndTime)return{error:O,info:"both defaultStartTime and defaultEndTime are required"};if(!ql({startTime:n.defaultStartTime,endTime:n.defaultEndTime}))return{error:O,info:"defaultEndTime must be after defaultStartTime"}}return r&&ut({element:n,extension:{value:r,name:xR}}),n.isPrimary&&gE({tournamentRecord:t}),t.venues.push(n),e||at({payload:{venue:n,tournamentId:t.tournamentId},topic:$y}),{...P,venue:q(n)}}function Ln({tournamentRecords:t,tournamentRecord:e,venueId:r}){let n=dt({tournamentRecord:e,venueId:r},[rt,Tp]);if(n.error)return n;let i=(e.venues??[]).reduce((s,a)=>a.venueId===r?a:s,void 0);if(!i&&t){let a=(bp({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let c of a){let u=t[c],p=Ln({tournamentRecord:u,venueId:r});if(p.success&&p.venue)return yu({tournamentRecord:e,venue:p.venue}),{...P,venue:i}}}return i?{...P,venue:i}:{error:wi}}function IE({convertExtensions:t,...e}){let{tournamentRecords:r,tournamentRecord:n,venueId:o}=e,i=Ln({tournamentRecords:r,tournamentRecord:n,venueId:o});return q(i,t,!0)}function Si({tournamentRecords:t,tournamentRecord:e,courtId:r}){let n=dt({tournamentRecord:e,courtId:r},[rt,Ws]);if(n.error)return n;let o="findCourt",i,s;if((e.venues??[]).forEach(a=>{(a.courts??[]).forEach(c=>{c.courtId===r&&(i=c,s=a)})}),i)return{...P,court:i,venue:s};if(t){let c=(bp({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let u of c){let p=t[u],m=Si({tournamentRecord:p,courtId:r});if(m.success)return m.venue&&yu({tournamentRecord:e,venue:m.venue}),{...P,court:i,venue:s}}}return M({result:{error:vo},stack:o})}function SE(t){return q(Si(t),!1,!0)}function $l({tournamentRecord:t,internalUse:e,courtId:r}){let n=dt({tournamentRecord:t,courtId:r},[rt,Ws]);if(n.error)return n;let o=Si({tournamentRecord:t,courtId:r});if(o.error)return o;let i=o.court&&(({altitude:s,courtId:a,courtName:c,courtDimensions:u,latitude:p,longitude:m,surfaceCategory:d,surfaceType:l,surfacedDate:f,pace:g,notes:I})=>({altitude:s,courtId:a,courtName:c,courtDimensions:u,latitude:p,longitude:m,surfaceCategory:d,surfaceType:l,surfacedDate:f,pace:g,notes:I}))(o.court);return{...P,courtInfo:q(i,!1,e)}}function Eu(t){let e=X(t,[{[rt]:!0},{venueId:!0,[jr]:Ls}]);if(e.error)return e;let{tournamentRecord:r,venueId:n}=t,o=Ln({tournamentRecord:r,venueId:n});if(o.error)return o;let s=(o.venue?.courts??[]).map(u=>(({courtInfo:p})=>({...p}))($l({courtId:u.courtId,internalUse:!0,tournamentRecord:r}))),a=o.venue&&(({venueId:u,venueName:p,venueAbbreviation:m})=>({venueAbbreviation:m,venueName:p,venueId:u}))(o.venue),c=a&&{...a,courtsInfo:s};return{...P,venueData:q(c,!1,!0)}}function KL({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===As&&s;return a&&(!i||r(a)>r(i))?a:i},void 0)?.itemValue}}function Bt({event:t,eventId:e}){if(!t)return{error:le};let n=ot({name:on,element:t})?.extension,o=e?q(n?.value,!1,!0):n?.value;return e&&t.drawDefinitions?.forEach(i=>{o?.flights?.forEach(s=>{s.drawId===i.drawId&&Object.assign(s,{drawDefinition:i})})}),{flightProfile:o}}function _e(t){let{tournamentRecord:e,eventId:r,drawId:n}=t,o="findEvent",i={},s=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},a=Object.values(s).map(({events:u,tournamentId:p})=>(u&&u.forEach(m=>{i[m.eventId]={tournamentId:p}}),u??[])).flat(),c;if(n){let u,p=a.find(m=>{let l=(m?.drawDefinitions??[]).find(f=>f.drawId===n);if(l)u=l,c=i[m.eventId].tournamentId;else{let g=(m&&Bt({event:m})?.flightProfile)?.flights?.find(I=>I.drawId===n);if(g)return c=i[m.eventId].tournamentId,{entries:g.drawEntries,drawName:g.drawName,tournamentId:c,drawId:n}}return l});if(p)return{event:p,drawDefinition:u,tournamentId:c}}if(r){let u=a.find(p=>p?.eventId===r);if(u)c=i[u.eventId].tournamentId;else return{event:void 0,drawDefinition:void 0,...M({result:{error:Wr},stack:o})};return{event:u,drawDefinition:void 0,tournamentId:c}}return{event:void 0,drawDefinition:void 0,...M({result:{error:Mr},context:{drawId:n,eventId:r},stack:o})}}function Kl(t){let e=t.event,r=t.matchUpType,{scheduleVisibilityFilters:n,afterRecoveryTimes:o,tournamentRecord:i,usePublishState:s,scheduleTiming:a,matchUpFormat:c,publishStatus:u,matchUp:p}=t;if(!p)return{error:Xe};if(o&&!p.matchUpType&&!t.matchUpType&&(e||i)&&p.drawId){let N=t.drawDefinition||e?.drawDefinitions?.find(R=>R.drawId===p.drawId);!N&&i&&({drawDefinition:N,event:e}=_e({drawId:p.drawId,tournamentRecord:i}));let D=p.structureId&&N?.structures?.find(({structureId:R})=>R===p.structureId);r=t.matchUpType||D?.matchUpType||N?.matchUpType||e?.eventType!==Oe&&e?.eventType}let{milliseconds:m,time:d}=HL({matchUp:p}),{startTime:l}=YL({matchUp:p}),{endTime:f}=KL({matchUp:p}),{eventIds:g,drawIds:I}=n??{},h=(!g||g.includes(p.eventId))&&(!I||I.includes(p.drawId))?Gj({tournamentRecord:i,scheduleTiming:a,afterRecoveryTimes:o,matchUpFormat:c,matchUpType:r,matchUp:p,endTime:f,startTime:l,milliseconds:m,time:d}):et({milliseconds:m,startTime:l,endTime:f,time:d}),{scheduledDate:T}=Qs({matchUp:p}),{scheduledTime:y}=jl({matchUp:p});if(s&&u?.displaySettings?.draws){let N=u.displaySettings.draws,D=(N?.[p.drawId]??N?.default)?.scheduleDetails;if(D){let R=(D.find(U=>T&&U.dates?.includes(T))??D.find(U=>!U.dates?.length))?.attributes;if(R){let U=Object.assign({},...Object.keys(h).map(b=>({[b]:!0})),R);h=hs({source:h,template:U})}}}let A=p.matchUpStatus&&Ot.includes(p.matchUpStatus)&&(mt(f)||mt(T)||mt(y))||void 0;return{schedule:h,endDate:A}}function Gj({tournamentRecord:t,scheduleTiming:e,afterRecoveryTimes:r,matchUpFormat:n,matchUpType:o,matchUp:i,endTime:s,startTime:a,milliseconds:c,time:u}){let p=C=>C.createdAt?new Date(C.createdAt).getTime():0,m=new Map,d=i.timeItems?.toSorted((C,_)=>p(C)-p(_))??[];for(let C of d)m.set(C.itemType,C.itemValue);let l=m.get(Wl),f=m.get(Tu),g=m.get(Io),I=m.get(Es),S=m.get(rd),h=m.get(ys),T=m.get(iS),y=m.get(hu),E=m.get(Ts),A=m.get(li),N=Vj({scheduleTiming:e,afterRecoveryTimes:r,matchUpFormat:n,matchUpType:o,matchUp:i,endTime:s,scheduledTime:I});!h&&I&&(h=mt(I));let D=ll({scheduledDate:h,scheduledTime:I}),{venueName:R,venueAbbreviation:U,courtName:b}=Bj({tournamentRecord:t,allocatedCourts:g,venueId:E,courtId:A});return et({typeChangeTimeAfterRecovery:N.typeChangeTimeAfterRecovery,typeChangeRecoveryMinutes:N.typeChangeRecoveryMinutes,timeAfterRecovery:N.timeAfterRecovery,recoveryMinutes:N.recoveryMinutes,averageMinutes:N.averageMinutes,homeParticipantId:l,courtAnnotation:f,venueAbbreviation:U,allocatedCourts:g,scheduledDate:h,scheduledTime:I,isoDateString:D,timeModifiers:S,venueName:R,venueId:E,courtOrder:y,courtName:b,courtId:A,official:T,milliseconds:c,startTime:a,endTime:s,time:u})}function Vj({scheduleTiming:t,afterRecoveryTimes:e,matchUpFormat:r,matchUpType:n,matchUp:o,endTime:i,scheduledTime:s}){let a,c,u,p,m,d=o.matchUpType??n;if(t&&s&&e&&d){let l={matchUpFormat:o.matchUpFormat??r,...t};({averageMinutes:c=0,recoveryMinutes:u=0,typeChangeRecoveryMinutes:p=0}=id({timingDetails:l,eventType:d})),(c||u)&&(a=i?Yr($t(i),u):Yr(s,c+u)),p&&(m=i?Yr($t(i),p):Yr(s,c+p))}return{timeAfterRecovery:a,averageMinutes:c,recoveryMinutes:u,typeChangeRecoveryMinutes:p,typeChangeTimeAfterRecovery:m}}function Bj({tournamentRecord:t,allocatedCourts:e,venueId:r,courtId:n}){let o={},i=(t&&r&&Eu({tournamentRecord:t,venueId:r}))?.venueData??{};r&&(o[r]=i);let{venueName:s,venueAbbreviation:a,courtsInfo:c}=i,p=(n&&c?.find(m=>m.courtId===n))?.courtName;for(let m of e??[]){if(!t)break;m.venueId&&!o[m.venueid]&&(o[m.venueId]=Eu({venueId:m.venueId,tournamentRecord:t})?.venueData);let d=o[m.venueId];m.venueName=d?.venueName;let l=d?.courtsInfo?.find(f=>f.courtId===m.courtId);m.courtName=l?.courtName}return{venueName:s,venueAbbreviation:a,courtName:p}}function zL({drawPositions:t,roundProfile:e,roundNumber:r}){let n=[void 0,void 0];if(wT(t))return{orderedDrawPositions:n,displayOrder:n};let o=e?.[r],s=o?.pairedDrawPositions?.find(c=>Re(c??[],t.filter(Boolean)))??n,a=o?.feedRound;if(xT(t)){let c=[...t].sort(Zt);return{orderedDrawPositions:c.length===2?c:s,displayOrder:a?c:s}}if(a){let u=[t.find(p=>!isNaN(st(p))),void 0];return{orderedDrawPositions:u,displayOrder:u}}return{orderedDrawPositions:s,displayOrder:s}}function ad({collectionPosition:t,collectionId:e,lineUp:r}){let n=[],o=[];if(r){let i=a=>a===void 0?-1:a,s=r.map(a=>{let{collectionAssignments:c,participantId:u}=a,p=c?.find(m=>m.collectionPosition===t&&m.collectionId===e);return p&&{participantId:u,...p}}).filter(Boolean).sort((a,c)=>i(a.substitutionOrder)-i(c.substitutionOrder));for(let a of s){let{participantId:c,previousParticipantId:u,substitutionOrder:p}=a;n.includes(c)||(u&&o.push({previousParticipantId:u,substitutionOrder:p,participantId:c}),n=n.filter(m=>m!==u),n.push(c))}}return{assignedParticipantIds:n,substitutions:o}}function Tn({tournamentParticipants:t,tournamentRecord:e,participantIds:r}){let n="getPairedParticipant";if(!t&&!e)return{error:j};if(!Array.isArray(r)||r.length>2)return{error:_r};if(!r.length)return M({result:{error:Mo},stack:n});t=t??e?.participants??[];let o=t.filter(a=>a.participantType===lt&&Yt(r,a.individualParticipantIds).length===r.length&&a.individualParticipantIds.length===r.length),i=o[0];if(!i)return M({result:{error:ee},stack:n});let s=q(o.slice(1),!1,!0);return{participant:q(i),duplicatedPairParticipants:s,...P}}function Xs({drawDefinition:t,participantId:e}){if(typeof t!="object")return{error:$};if(typeof e!="string")return{error:We};let{extension:r}=ot({element:t,name:Vo});return{lineUp:(r?.value??{})[e]}}function QL({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}=ad({collectionPosition:r,collectionId:s,lineUp:d});if(c===Rt){if(f?.length<=2){let I=o?.[f[0]]?.pairIdMap?.[f[1]],T=(I&&o[I]?.participant||Tn({participantIds:f,tournamentParticipants:t}).participant)?.participantId;return{[m]:{participantId:T,teamParticipant:l,substitutions:g}}}else if(f?.length>2)return{[m]:{teamParticipant:l,substitutions:g}}}else{let I=f?.[0];return I&&{[m]:{participantId:I,teamParticipant:l,substitutions:g}}}};if(!n?.length){let m=a?.map(d=>{let{teamParticipant:l,sideNumber:f}=d,g=d.lineUp||Xs({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||Xs({participantId:d,drawDefinition:i})?.lineUp;return u({attribute:m,lineUp:g,teamParticipant:f})}).filter(Boolean)??{};return{drawPositionCollectionAssignment:Object.assign({},...p)}}function zl(t){let e=X(t,[{[Rn]:!0}]);if(e.error)return e;let r=t?.matchUp,n=r?.matchUpType;if(!n&&r?.sides?.length){let s=r.sides.find(({participant:a})=>a)?.participant?.participantType;n=s===St&&Ct||s===lt&&Rt||s===_t&&_t||void 0}return{matchUpType:n}}function XL({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?Wj({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 Wj({displaySideNumber:t,seedAssignments:e,participantId:r,assignment:n,sideNumber:o}){let i={drawPosition:n.drawPosition,displaySideNumber:t,sideNumber:o};if(r){let s=Hj({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 Hj({seedAssignments:t,participantId:e}){return t?.find(r=>!r.seedProxy&&r.participantId===e)}function Uo(t){let e=t?.embargo;return!e||!fs(e)?!1:new Date(e).getTime()>Date.now()}function ro(t){return!!t?.published&&!Uo(t)}function Yj({publishStatus:t,drawDefinition:e,structure:r,matchUp:n,schedule:o}){if(!t||!e?.drawId||!r?.structureId)return o;let i=t?.drawDetails?.[e.drawId]?.structureDetails?.[r.structureId];if(!i)return o;let s=n.roundNumber;if(!yt(s))return o;let a=i.scheduledRounds?.[s];if(!(a&&Uo(a)))return o}function jj({matchUp:t,collectionDefinition:e,structure:r,drawDefinition:n,event:o,tournamentRecord:i}){return t.processCodes?.length&&t.processCodes||e?.processCodes?.length&&e?.processCodes||r?.processCodes?.length&&r?.processCodes||n?.processCodes?.length&&n?.processCodes||o?.processCodes?.length&&o?.processCodes||i?.processCodes}function bb({scheduleVisibilityFilters:t,sourceDrawPositionRanges:e,tournamentParticipants:r,positionAssignments:n,drawPositionsRanges:o,hydrateParticipants:i,afterRecoveryTimes:s,initialRoundOfPlay:a,additionalContext:c,roundNamingProfile:u,tournamentRecord:p,tieDrawPositions:m,appliedPolicies:d,isCollectionBye:l,seedAssignments:f,usePublishState:g,participantMap:I,contextContent:S,scheduleTiming:h,contextProfile:T,drawDefinition:y,publishStatus:E,scoringActive:A,matchUpTieId:N,isRoundRobin:D,roundProfile:R,sideLineUps:U,structure:b,context:C,matchUp:_,event:v}){c=c??{};let w=ze({drawDefinition:y,structure:b,matchUp:_,event:v})?.tieFormat,{roundOffset:L,structureId:F,structureName:x,stage:k,stageSequence:G}=b,{drawId:V,drawName:B,drawType:z}=y??{},H=w?.collectionDefinitions,K=_.collectionId&&H?.find(Vn=>Vn.collectionId===_.collectionId),Y=_.collectionId?K?.matchUpFormat:_.matchUpFormat??b?.matchUpFormat??y?.matchUpFormat??v?.matchUpFormat,J=_.matchUpType||K?.matchUpType||b?.matchUpType||y?.matchUpType||!re(Oe)(v?.eventType)&&v?.eventType,ct=l?"BYE":_.matchUpStatus,{schedule:Et,endDate:Ht}=Kl({scheduleVisibilityFilters:t,afterRecoveryTimes:s,tournamentRecord:p,usePublishState:g,scheduleTiming:h,drawDefinition:y,matchUpFormat:Y,publishStatus:E,matchUpType:J,matchUp:_,event:v});g&&Et&&(Et=Yj({publishStatus:E,drawDefinition:y,structure:b,matchUp:_,schedule:Et}));let Ut=m??_.drawPositions??[],{collectionPosition:pe,collectionId:ye,roundPosition:Jt}=_,pr=_.roundNumber??c.roundNumber,Kn=ye?QL({tournamentParticipants:r,positionAssignments:n,collectionPosition:pe,participantMap:I,drawDefinition:y,drawPositions:Ut,collectionId:ye,sideLineUps:U,matchUpType:J}):void 0,zr=u?.[pr]?.roundName||c.roundName,so=u?.[pr]?.abbreviatedRoundName||c.abbreviatedRoundName,Zo=R?.[pr]?.feedRound,ti=R?.[pr]?.preFeedRound,la=R?.[pr]?.roundFactor,fa=o?.[pr],ga=Jt?fa?.[Jt]:void 0,bm=e?.[pr],Gc=K?.category?{...C?.category,...K.category}:C?.category??v?.category,Cm=jj({matchUp:_,collectionDefinition:K,structure:b,drawDefinition:y,event:v,tournamentRecord:p}),we=T?.withCompetitiveness&&js({...S,matchUp:_}),Ai=_.finishingPositionRange??c.finishingPositionRange,as=k!==Z&&yt(a)&&a+(pr||0),ic=Vn=>et(Vn,void 0,!0),An={...ic(C),...ic({matchUpFormat:J===Oe?void 0:Y,tieFormat:J===Oe?w:void 0,gender:K?.gender??v?.gender,endDate:_.endDate??Ht,discipline:v?.discipline,category:Gc,finishingPositionRange:Ai,abbreviatedRoundName:so,drawPositionsRange:ga,competitiveProfile:we,structureName:x,stageSequence:G,drawPositions:Ut,matchUpStatus:ct,processCodes:Cm,isRoundRobin:D,matchUpTieId:N,preFeedRound:ti,matchUpType:J,roundFactor:la,roundOffset:L,structureId:F,roundNumber:pr,roundOfPlay:as,feedRound:Zo,roundName:zr,drawName:B,drawType:z,schedule:Et,drawId:V,stage:k}),...q(ic(_),!0,!0)};if(Y&&_.score?.scoreStringSide1&&qj(An,Y),Array.isArray(Ut)){let Vn=$j({sourceDrawPositionRoundRanges:bm,collectionAssignmentDetail:Kn,positionAssignments:n,seedAssignments:f,drawPositions:Ut,roundPosition:Jt,roundProfile:R,roundNumber:pr,onlyDefined:ic,matchUp:_});Object.assign(An,q({sides:Vn},!0,!0))}if(r&&An.sides){if(Kj({tournamentParticipants:r,hydrateParticipants:i,positionAssignments:n,appliedPolicies:d,drawDefinition:y,participantMap:I,contextProfile:T,matchUpWithContext:An,event:v}),!An.matchUpType){let{matchUpType:Vn}=zl({matchUp:An});Vn&&Object.assign(An,{matchUpType:Vn})}Qj({contextProfile:T,matchUpWithContext:An})}An.tieMatchUps&&Xj({matchUpWithContext:An,abbreviatedRoundName:so,roundNumber:pr,roundName:zr,drawPositions:Ut,scheduleVisibilityFilters:t,sourceDrawPositionRanges:e,drawPositionsRanges:o,initialRoundOfPlay:a,roundNamingProfile:u,appliedPolicies:d,usePublishState:g,publishStatus:E,isRoundRobin:D,roundProfile:R,event:v,tournamentParticipants:r,positionAssignments:n,tournamentRecord:p,seedAssignments:f,participantMap:I,contextContent:S,scheduleTiming:h,contextProfile:T,drawDefinition:y,scoringActive:A,structure:b,context:C});let Vc=An.sides?.filter(Vn=>Vn?.participantId).length===2,tp=!An.winningSide;if(Object.assign(An,{readyToScore:A&&Vc&&tp,hasContext:!0}),Vc){let{allParticipantsCheckedIn:Vn,checkedInParticipantIds:UT}=$s({matchUp:An});Object.assign(An,{allParticipantsCheckedIn:Vn,checkedInParticipantIds:UT})}return Array.isArray(T?.exclude)&&T?.exclude.forEach(Vn=>delete An[Vn]),An}function qj(t,e){let r=oe(e),{bestOf:n,finalSetFormat:o,setFormat:i}=r??{};!o?.tiebreakSet&&!i?.tiebreakSet&&!i?.timed||(t.score.sets=t.score.sets.sort((s,a)=>s.setNumber-a.setNumber).map((s,a)=>{let p=a+1===n&&o?o:i,m=p?.tiebreakSet&&!p?.timed,d=p?.timed;return m?(s.tiebreakSet=!0,[1,2].includes(s.winningSide)&&(s.side1Score=s.winningSide===1?1:0,s.side2Score=s.winningSide===2?1:0)):d&&(s.timed=!0),s}))}function $j({sourceDrawPositionRoundRanges:t,collectionAssignmentDetail:e,positionAssignments:r,seedAssignments:n,drawPositions:o,roundPosition:i,roundProfile:s,roundNumber:a,onlyDefined:c,matchUp:u}){let{orderedDrawPositions:p,displayOrder:m}=zL({drawPositions:o,roundProfile:s,roundNumber:a}),d=s?.[a]?.feedRound,l=m[0]!==p[0];return p.concat(void 0,void 0).slice(0,2).map((g,I)=>{let S=I+1,h=l?3-S:S,T=XL({...e,positionAssignments:r,displaySideNumber:h,seedAssignments:n,drawPosition:g,isFeedRound:d,sideNumber:S}),y=u.sides?.find(N=>N.sideNumber===S),E=i?(i-1)*2+I+1:void 0,A=E?t?.[E]:void 0;return c({sourceDrawPositionRange:A,...y,...T})})}function Kj({tournamentParticipants:t,hydrateParticipants:e,positionAssignments:r,appliedPolicies:n,drawDefinition:o,participantMap:i,contextProfile:s,matchUpWithContext:a,event:c}){let u=n?.[xa],p=m=>{let d=i?.[m]?.participant;return d&&hs({template:u?.participant,source:d})};a.sides.filter(Boolean).forEach(m=>{if(zj({side:m,getMappedParticipant:p,tournamentParticipants:t,hydrateParticipants:e,positionAssignments:r,appliedPolicies:n,drawDefinition:o,contextProfile:s,event:c}),m?.participant?.individualParticipantIds?.length&&!m.participant.individualParticipants?.length){let d=m.participant.individualParticipantIds.map(l=>p(l)||(t?ui({policyDefinitions:n,tournamentParticipants:t,internalUse:!0,contextProfile:s,participantId:l}):void 0));e!==!1&&Object.assign(m.participant,{individualParticipants:d})}})}function zj({side:t,getMappedParticipant:e,tournamentParticipants:r,hydrateParticipants:n,positionAssignments:o,appliedPolicies:i,drawDefinition:s,contextProfile:a,event:c}){if(!t.participantId)return;let u=q(e(t.participantId)||(r?ui({policyDefinitions:i,participantId:t.participantId,tournamentParticipants:r,internalUse:!0,contextProfile:a}):void 0),void 0,!0);if(!u)return;let p,m;if(s?.entries){let l=s.entries.find(g=>g.participantId===t.participantId),f=c?.entries?.find(g=>g.participantId===t.participantId);p=l?.entryStatus||f?.entryStatus,u.entryStatus=p,l?.entryStage&&(m=l.entryStage,u.entryStage=m)}let d;t.drawPosition&&o&&o.find(f=>f.drawPosition===t.drawPosition)?.extensions?.some(f=>f.name==="luckyAdvancement")&&(d=!0,u.luckyAdvancement=!0),n===!1?Object.assign(t,{participant:{entryStage:m,entryStatus:p,luckyAdvancement:d}}):Object.assign(t,{participant:u})}function Qj({contextProfile:t,matchUpWithContext:e}){if(!(t?.inferGender&&(!e.gender||e.gender===ds)&&e.sides?.length===2&&e.matchUpType!==Oe))return;let n=e.sides.map(o=>{if(re(Ct)(e.matchUpType))return o.participant?.person?.sex;if(o.participant?.individualParticipants?.length===2){let i=pt(o.participant.individualParticipants.map(s=>s.person?.sex)).filter(Boolean);if(i.length===1)return i[0]}});n.filter(Boolean).length===2&&pt(n).length===1&&(e.inferredGender=n[0])}function Xj(t){let{matchUpWithContext:e}=t,r=e.matchUpStatus==="BYE",n=e.sides?.map(({participant:o,drawPosition:i,sideNumber:s,lineUp:a})=>{let c=o?.participantType===Oe&&o;return{teamParticipant:c&&et({participantRoleResponsibilities:c.participantRoleResponsibilities,participantOtherName:c.participantOtherName,participantName:c.participantName,participantId:c.participantId,teamId:c.teamId}),drawPosition:i,sideNumber:s,lineUp:a}});e.tieMatchUps=e.tieMatchUps.map(o=>{let i=e.matchUpId,a={finishingPositionRange:e.finishingPositionRange,abbreviatedRoundName:t.abbreviatedRoundName,roundNumber:t.roundNumber,roundName:t.roundName};return bb({tieDrawPositions:t.drawPositions,scheduleVisibilityFilters:t.scheduleVisibilityFilters,sourceDrawPositionRanges:t.sourceDrawPositionRanges,sideLineUps:n,drawPositionsRanges:t.drawPositionsRanges,initialRoundOfPlay:t.initialRoundOfPlay,roundNamingProfile:t.roundNamingProfile,additionalContext:a,appliedPolicies:t.appliedPolicies,isCollectionBye:r,usePublishState:t.usePublishState,publishStatus:t.publishStatus,matchUpTieId:i,isRoundRobin:t.isRoundRobin,roundProfile:t.roundProfile,matchUp:o,event:t.event,tournamentParticipants:t.tournamentParticipants,positionAssignments:t.positionAssignments,tournamentRecord:t.tournamentRecord,seedAssignments:t.seedAssignments,participantMap:t.participantMap,contextContent:t.contextContent,scheduleTiming:t.scheduleTiming,contextProfile:t.contextProfile,drawDefinition:t.drawDefinition,scoringActive:t.scoringActive,structure:t.structure,context:t.context})})}function JL({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Ii({timeItems:r?.timeItems??[],itemType:Io});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{allocatedCourts:q(n,!1,!0)}:e}function ZL({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Ii({timeItems:r?.timeItems??[],itemType:li});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{courtId:n}:e}function t0({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Ii({timeItems:r?.timeItems??[],itemType:Ts});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{venueId:n}:e}function zi(t){if(!Array.isArray(t.matchUps))return[];let{matchUps:e,excludeMatchUpStatuses:r,hasParticipantsCount:n,isCollectionMatchUp:o,matchUpStatuses:i,hasWinningSide:s,matchUpFormats:a,roundPositions:c,matchUpFormat:u,collectionIds:p,isMatchUpTie:m,roundNumbers:d,matchUpIds:l,roundNames:f,filterMatchUpTypes:g=!0,filterMatchUpIds:I=!0,stageSequences:S,scheduledDates:h,scheduledDate:T,participantIds:y,processContext:E,tournamentIds:A,matchUpTypes:N,structureIds:D,readyToScore:R,courtIds:U,eventIds:b,venueIds:C,drawIds:_,stages:v}=t,w=Array.isArray(y)?y.filter(Boolean):[],L=Array.isArray(i)?i.filter(Boolean):[],F=Array.isArray(r)?r.filter(Boolean):[],x=Array.isArray(v)?v.filter(Boolean):[],k=Array.isArray(S)?S.filter(Boolean):[],G=Array.isArray(p)?p.filter(Boolean):[],V=Array.isArray(f)?f.filter(Boolean):[],B=Array.isArray(d)?d.filter(Boolean):[],z=Array.isArray(c)?c.filter(Boolean):[],H=Array.isArray(l)&&I?l.filter(Boolean):[],K=Array.isArray(N)&&g?N.filter(Boolean):[],Y=Array.isArray(U)?U.filter(Boolean):[],J=Array.isArray(C)?C.filter(Boolean):[],ct=Array.isArray(a)&&a.filter(Boolean)||typeof u=="string"&&[u]||[],Et=Array.isArray(h)&&h.filter(Boolean).length&&h.filter(Boolean)||typeof T=="string"&&T.length&&[T]||[],Ht=Array.isArray(A)?A.filter(Boolean):[],Ut=Array.isArray(b)?b.filter(Boolean):[],pe=Array.isArray(_)?_.filter(Boolean):[],ye=Array.isArray(D)?D.filter(Boolean):[];return e.filter(Jt=>!(!Jj({matchUp:Jt,readyToScore:R,hasWinningSide:s,isMatchUpTie:m,isCollectionMatchUp:o})||!Zj({matchUp:Jt,targetStages:x,targetStageSequences:k,targetCollectionIds:G,targetRoundNames:V,targetRoundNumbers:B,targetRoundPositions:z,targetMatchUpStatuses:L,excludeTargetMatchUpStatuses:F,targetMatchUpIds:H,targetMatchUpTypes:K,targetMatchUpFormats:ct})||!tq({matchUp:Jt,targetScheduledDates:Et,targetCourtIds:Y,targetVenueIds:J})||E&&!eq({matchUp:Jt,targetTournamentIds:Ht,targetEventIds:Ut,targetDrawIds:pe,targetStructureIds:ye,targetParticipantIds:w,hasParticipantsCount:n})))}function Jj({matchUp:t,readyToScore:e,hasWinningSide:r,isMatchUpTie:n,isCollectionMatchUp:o}){return!(e&&!re(Ir)(t)&&!t.readyToScore||t.winningSide&&r&&![1,2].includes(t.winningSide)||n!==void 0&&(n&&!t.tieMatchUps||!n&&t.tieMatchUps)||o!==void 0&&(o&&!t.collectionId||!o&&t.collectionId))}function Zj({matchUp:t,targetStages:e,targetStageSequences:r,targetCollectionIds:n,targetRoundNames:o,targetRoundNumbers:i,targetRoundPositions:s,targetMatchUpStatuses:a,excludeTargetMatchUpStatuses:c,targetMatchUpIds:u,targetMatchUpTypes:p,targetMatchUpFormats:m}){return!(e.length&&!e.includes(t.stage)||r.length&&!r.includes(t.stageSequence)||n.length&&(!t.collectionId||!n.includes(t.collectionId))||o.length&&(!t.roundName||!o.includes(t.roundName))||i.length&&(!t.roundNumber||!i.includes(t.roundNumber))||s.length&&(!t.roundPosition||!s.includes(t.roundPosition))||a.length&&(!t.matchUpStatus||!a.includes(t.matchUpStatus))||c.length&&t.matchUpStatus&&c.includes(t.matchUpStatus)||u.length&&!u.includes(t.matchUpId)||p.length&&(!t.matchUpType||!_s(p,t.matchUpType))||m.length&&(!t.matchUpFormat||!m.includes(t.matchUpFormat)))}function tq({matchUp:t,targetScheduledDates:e,targetCourtIds:r,targetVenueIds:n}){if(e?.length){let{scheduledTime:o}=jl({matchUp:t}),{scheduledDate:i}=Qs({matchUp:t}),a=mt(o)||i;if(!e.some(c=>Xn(c,a)))return!1}if(r.length){let{courtId:o}=ZL({matchUp:t}),{allocatedCourts:i}=JL({matchUp:t}),s=i?.map(({courtId:a})=>a);if(!r.filter(Boolean).includes(o)||s?.includes(o))return!1}if(n.length){let{venueId:o}=t0({matchUp:t});if(!n.filter(Boolean).includes(o))return!1}return!0}function eq({matchUp:t,targetTournamentIds:e,targetEventIds:r,targetDrawIds:n,targetStructureIds:o,targetParticipantIds:i,hasParticipantsCount:s}){if(e.length&&!e.includes(t.tournamentId)||r.length&&!r.includes(t.eventId)||n.length&&!n.includes(t.drawId)||o.length&&!o.includes(t.structureId))return!1;let a=t.sides?.map(({participantId:c})=>c).filter(Boolean)??[];return!(s&&a.length<s||i.length&&!i.some(u=>a.includes(u)))}function ht(t){let{provisionalPositioning:e,tournamentRecord:r,contextFilters:n,matchUpFilters:o,contextProfile:i,drawDefinition:s,context:a={},structure:c,inContext:u,event:p}=t,{seedAssignments:m,contextContent:d,exitProfiles:l,matchUpsMap:f}=t,g={},I={};if(!c)return{collectionPositionMatchUps:g,error:_i,roundMatchUps:I,matchUps:[]};let S=Array.isArray(o?.eventIds)?o?.eventIds.filter(Boolean):[],h=Array.isArray(o?.structureIds)?o?.structureIds.filter(Boolean):[],T=Array.isArray(o?.drawIds)?o?.drawIds.filter(Boolean):[],y=!a?.eventId||!S?.length&&!n?.eventIds?.filter(Boolean).length||S?.includes(a.eventId)||n?.eventIds?.includes(a.eventId),E=!h?.length||h.includes(c.structureId),A=!s||!T?.length||T.includes(s.drawId);if(!y||!E||!A)return{collectionPositionMatchUps:g,roundMatchUps:I,matchUps:[]};i&&!d&&(d=eo({tournamentRecord:r,contextProfile:i,drawDefinition:s}));let{appliedPolicies:N}=ft({drawDefinition:s}),D={...t.tournamentAppliedPolicies,...N,...t.policyDefinitions},R=D?.scoring?.structures,U=c.stage&&R?.stage?.[c.stage],b=c.stageSequence&&U?.stageSequence?.[c.stageSequence],C=D?.scoring?.requireAllPositionsAssigned||U?.requireAllPositionsAssigned||b?.requireAllPositionsAssigned;f??=Ie({drawDefinition:s,structure:c});let{positionAssignments:_,allPositionsAssigned:v}=se({structure:c}),w=!C||v,{seedAssignments:L}=Ur({provisionalPositioning:e,drawDefinition:s,structure:c});m=m??L;let{structureId:F}=c;l=l||s&&Gl({drawDefinition:s}).exitProfiles;let x=l?.[F],k=x?.length&&(x[0].split("-").map(Y=>Number.parseInt(Y)).reduce((Y,J)=>Y+J,0)||0),G=!!c.structures,V=jo({matchUpsMap:f,structureId:F,inContext:u}),B=D?.[Fo],z=cE({roundNamingPolicy:B,drawDefinition:s,structure:c,matchUps:V}),{roundNamingProfile:H,roundProfile:K}=z;if(I=z?.roundMatchUps??[],o){let Y=new Set(V.filter(J=>Array.isArray(J.tieMatchUps)).map(J=>J.matchUpId));V=zi({matchUps:Y.size?V.filter(J=>!Y.has(J.matchUpId)):V,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1}).concat(Y.size?V.filter(J=>Y.has(J.matchUpId)):[])}return u?V=nq({positionAssignments:_,initialRoundOfPlay:k,roundNamingProfile:H,tournamentRecord:r,appliedPolicies:D,seedAssignments:m,contextContent:d,contextProfile:i,drawDefinition:s,contextFilters:n,scoringActive:w,isRoundRobin:G,roundProfile:K,matchUpsMap:f,structureId:F,structure:c,context:a,params:t,event:p,matchUps:V}):(V=e0(V),i?.withCompetitiveness&&(V=rq({policyDefinitions:t.policyDefinitions,tournamentRecord:r,drawDefinition:s,structure:c,matchUps:V,event:p}))),o&&(V=zi({matchUps:V,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1})),(o?.matchUpTypes||o?.matchUpIds)&&(V=zi({matchUpTypes:o.matchUpTypes,matchUpIds:o.matchUpIds,matchUps:V})),(o?.matchUpTypes||o?.matchUpIds||u)&&(I=Ue({matchUps:V}).roundMatchUps??[]),ze({drawDefinition:s,structure:c,event:p})?.tieFormat&&({collectionPositionMatchUps:g}=ML({matchUps:V})),{collectionPositionMatchUps:g,roundMatchUps:I,isRoundRobin:G,roundProfile:K,matchUpsMap:f,matchUps:V}}function e0(t){let e=t?.filter(n=>Array.isArray(n.tieMatchUps)),r=t;return e.forEach(n=>{r=r.concat(...n.tieMatchUps)}),r}function rq({policyDefinitions:t,tournamentRecord:e,drawDefinition:r,structure:n,matchUps:o,event:i}){let s=oE({policyDefinitions:t,tournamentRecord:e,drawDefinition:r,structure:n,event:i});return o.map(a=>{if(a.competitiveProfile||!a.winningSide)return a;let c=js({profileBands:s,matchUp:a});return c.error?a:{...a,competitiveProfile:c}})}function nq({positionAssignments:t,initialRoundOfPlay:e,roundNamingProfile:r,tournamentRecord:n,appliedPolicies:o,seedAssignments:i,contextContent:s,contextProfile:a,drawDefinition:c,contextFilters:u,scoringActive:p,isRoundRobin:m,roundProfile:d,matchUpsMap:l,structureId:f,structure:g,context:I,params:S,event:h,matchUps:T}){let{sourceDrawPositionRanges:y}=vL({drawDefinition:c,matchUpsMap:l,structureId:f}),E=c?OL({drawDefinition:c,roundProfile:d,matchUpsMap:l,structureId:f}).drawPositionsRanges:void 0,A=S.tournamentParticipants,N=S.participantMap;!A?.length&&!N&&n&&({participants:A=[],participantMap:N}=di({participantsProfile:S.participantsProfile,useParticipantMap:S.useParticipantMap,policyDefinitions:S.policyDefinitions,tournamentRecord:n,contextProfile:a,inContext:!0}));let D=T.map(R=>bb({scheduleVisibilityFilters:S.scheduleVisibilityFilters,hydrateParticipants:S.hydrateParticipants,afterRecoveryTimes:S.afterRecoveryTimes,usePublishState:S.usePublishState,scheduleTiming:S.scheduleTiming,publishStatus:S.publishStatus,sourceDrawPositionRanges:y,tournamentParticipants:A,positionAssignments:t,drawPositionsRanges:E,initialRoundOfPlay:e,roundNamingProfile:r,tournamentRecord:n,appliedPolicies:o,seedAssignments:i,contextContent:s,participantMap:N,contextProfile:a,drawDefinition:c,scoringActive:p,isRoundRobin:m,roundProfile:d,structure:g,context:I,matchUp:R,event:h}));return D=e0(D),u&&(D=zi({processContext:!0,...u,matchUps:D})),D}function Js({matchUp:t}){return t?Ot.includes(t?.matchUpStatus)||t?.winningSide:!1}function Gp({requireParticipants:t=!0,scheduleVisibilityFilters:e,tournamentAppliedPolicies:r,tournamentParticipants:n,hydrateParticipants:o,afterRecoveryTimes:i,policyDefinitions:s,tournamentRecord:a,usePublishState:c,matchUpFilters:u,contextFilters:p,contextContent:m,participantMap:d,scheduleTiming:l,publishStatus:f,contextProfile:g,drawDefinition:I,exitProfiles:S,matchUpsMap:h,structureId:T,inContext:y,structure:E,context:A,event:N}){!E&&T&&({structure:E}=tt({drawDefinition:I,structureId:T}));let D=ht({tournamentAppliedPolicies:r,scheduleVisibilityFilters:e,tournamentParticipants:n,hydrateParticipants:o,afterRecoveryTimes:i,policyDefinitions:s,tournamentRecord:a,usePublishState:c,matchUpFilters:u,contextFilters:p,contextContent:m,participantMap:d,scheduleTiming:l,publishStatus:f,contextProfile:g,drawDefinition:I,exitProfiles:S,matchUpsMap:h,structure:E,inContext:y,context:A,event:N}),R=[],U=[],b=[],C=[],_=[];if(D.error)return D;let{matchUps:v}=D,{assignedPositions:w}=se({structure:E}),L=w?.filter(x=>x.participantId).map(x=>x.drawPosition),F;return v.filter(x=>{let k=u?.matchUpTypes?.length===1&&u.matchUpTypes[0]===xt;return!(x.matchUpType!==xt&&k)}).forEach(x=>{if(x.matchUpStatus===Fr){R.push(x);return}x.matchUpType===xt&&(F=!0);let k=!!x.collectionId,G=k&&x.sides?.every(J=>J.participantId),V=!k&&x.drawPositions?.filter(Boolean).length===2,B=!k&&x.drawPositions?.every(J=>L?.includes(J)),z=w?.filter(J=>J.bye).map(J=>J.drawPosition),H=!k&&x.drawPositions?.find(J=>z?.includes(J)),Y=By.includes(x.matchUpStatus)&&(G||V&&(!t||B));return H?_.push(x):Js({matchUp:x})?U.push(x):Y?b.push(x):C.push(x)}),{includesTeamMatchUps:F,abandonedMatchUps:R,completedMatchUps:U,upcomingMatchUps:b,pendingMatchUps:C,byeMatchUps:_,structure:E}}function r0({drawDefinition:t,roundNumber:e,structureId:r}){let n=dt({drawDefinition:t,structureId:r},[Kt,mo]);if(n.error)return n;let{links:o}=ka({drawDefinition:t,structureId:r}),i=o.source.reduce((a,c)=>!c.source.roundNumber||c.source.roundNumber===e?a.concat(c):a,[]),s=o.target.reduce((a,c)=>!c.target.roundNumber||c.target.roundNumber===e?a.concat(c):a,[]);return{links:{source:i,target:s}}}function hE({finishingPositions:t,linkCondition:e,linkType:r,source:n}){let o=n.find(i=>{let s=!i.source?.finishingPositions||!t||Re(t,i.source?.finishingPositions);return e===i.linkCondition&&s&&i.linkType===r});return[Pr,ir].includes(o?.linkType)&&!o?.source?.roundNumber?M({result:{error:O},stack:"getTargetLink",context:o}):o}function ka({drawDefinition:t,structureId:e,roundNumber:r}){let n=dt({drawDefinition:t,structureId:e},[Kt,mo]);return n.error?n:{links:(t.links??[]).filter(Boolean).reduce((s,a)=>(a.source?.structureId===e&&(!r||a.source.roundNumber===r)&&(s.source=s.source.concat(a)),a.target?.structureId===e&&(!r||a.target.roundNumber===r)&&(s.target=s.target.concat(a)),s),{source:[],target:[]})}}function n0({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 TE({sourceRoundMatchUpCount:t,inContextDrawMatchUps:e,sourceRoundPosition:r,drawDefinition:n,targetLink:o}){if(!o)return{error:kg};let{target:{structureId:i,feedProfile:s,groupedOrder:a,roundNumber:c,positionInterleave:u}}=o,{structure:p}=tt({drawDefinition:n,structureId:i}),{positionAssignments:m}=Pt({structure:p}),l=(e?.filter(U=>U.structureId===p?.structureId)).filter(U=>U.roundNumber===c&&!U.matchUpTieId),f=l.length,g=Q(1,f+1),I=f/t,S=Math.ceil(I*r),h=1-r%2;if(u?.interleave&&I!==.5){let U=u.offset+(r-1)*u.interleave,b=r+U;S=Math.ceil(b/2),h=1-b%2}let T=g,y=g[S-1],E=aE({roundPositionsCount:g.length,groupedOrder:a}),A=E?.length||1;if(A<=g.length){let U=f/A,b=he(g,U);s===Fi&&b.forEach(C=>C.reverse()),T=E?.length&&E?.map(C=>b[C-1]).flat()||T}s===qe?y=T[S-1]:s===Fi?((!E?.length||A>g.length)&&(S=l.length+1-S),y=T[S-1]):s===Ym&&je()&&console.log(iI,{feedProfile:s});let N=y&&l.reduce((U,b)=>b.roundPosition===y?b:U,void 0),D;N?.feedRound?(h=0,D=Math.min(...(N.drawPositions??[]).filter(Boolean))):D=N?.drawPositions?.length===2&&N?.drawPositions[h];let R=m?.find(({drawPosition:U})=>U===D);if(R){let{extension:U}=ot({element:R,name:Pl});if(U?.value)return{disabledDrawPosition:D}}return{matchUp:N,targetDrawPosition:D,matchUpDrawPositionIndex:h}}function er({inContextDrawMatchUps:t=[],useTargetMatchUpIds:e,inContextMatchUp:r,drawDefinition:n,matchUpId:o}){let i=r;t.length&&!i&&(i=t.find(c=>c.matchUpId===o));let{structure:s}=tt({structureId:i?.structureId,drawDefinition:n});return s?.finishingPosition===Ss?oq({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:n,structure:s,matchUp:i}):iq({matchUp:i})}function oq({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:r,structure:n,matchUp:o}){let{winnerMatchUpId:i,loserMatchUpId:s}=o,{links:a}=r0({roundNumber:o.roundNumber,structureId:n.structureId,drawDefinition:r}),c=a?.source,u=hE({source:c,linkType:Pr}),p=hE({linkCondition:Wn,linkType:ir,source:c}),m=hE({source:c,linkType:ir}),d=p&&m;m||(m=p);let l=u?.target?.feedProfile,f=m?.target?.feedProfile,g=p?.target?.feedProfile,I,S,h,T,y,E,A,N,D,R;if(e&&(i||s)&&(A=i&&l!==ln&&t.find(({matchUpId:C})=>C===i),T=s&&f!==ln&&t.find(({matchUpId:C})=>C===s),A||T))return{matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u},targetMatchUps:{loserMatchUp:T,winnerMatchUp:A}};let{roundPosition:U}=o;R=R||t.filter(C=>C.structureId===n.structureId);let b=R.reduce((C,_)=>_.roundNumber===o.roundNumber&&!_.matchUpTieId?C+1:C,0);return m&&!T&&f!==ln&&({matchUpDrawPositionIndex:E,targetDrawPosition:y,matchUp:T}=TE({targetLink:m,sourceRoundMatchUpCount:b,inContextDrawMatchUps:t,sourceRoundPosition:U,drawDefinition:r})),d&&g!==ln&&({matchUpDrawPositionIndex:h,targetDrawPosition:S,matchUp:I}=TE({targetLink:p,sourceRoundMatchUpCount:b,inContextDrawMatchUps:t,sourceRoundPosition:U,drawDefinition:r})),u&&!A&&l!==ln&&({matchUpDrawPositionIndex:D,targetDrawPosition:N,matchUp:A}=TE({targetLink:u,sourceRoundMatchUpCount:b,inContextDrawMatchUps:t,sourceRoundPosition:U,drawDefinition:r})),A||(R=R||t.filter(C=>C.structureId===n.structureId),{matchUp:A}=n0({structureMatchUps:R,matchUp:o})),et({matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u,byeTargetLink:p},targetMatchUps:{winnerMatchUpDrawPositionIndex:D,loserMatchUpDrawPositionIndex:E,byeMatchUpDrawPositionIndex:h,winnerTargetDrawPosition:N,loserTargetDrawPosition:y,byeTargetDrawPosition:S,winnerMatchUp:A,loserMatchUp:T,byeMatchUp:I},targetMatchUpIds:!!(i||s)})}function iq({matchUp:t}){return{targetLinks:{loserTargetLink:void 0,winnerTargetLink:void 0},targetMatchUps:{loserMatchUp:void 0,winnerMatchUp:void 0},matchUp:t}}function i0({drawDefinition:t,inContextDrawMatchUps:e}){let r={};return e.forEach(n=>{let{matchUpId:o,structureId:i,drawPositions:s=[]}=n,{structure:a}=tt({drawDefinition:t,structureId:i});a?.finishingPosition===po?sq({inContextMatchUp:n,structure:a,drawPositions:s}):aq({scheduleConflictMatchUpIds:r,inContextDrawMatchUps:e,inContextMatchUp:n,drawDefinition:t,matchUpId:o})}),Object.keys(r).length&&e.forEach(n=>{Object.keys(r).includes(n.matchUpId)&&(n.schedule.scheduleConflict=r[n.matchUpId])}),{scheduleConflictMatchUpIds:r}}function sq({inContextMatchUp:t,structure:e,drawPositions:r}){let{roundNumber:n}=t,o=n&&st(n)+1,i=e.matchUps??[],{roundMatchUps:s}=Ue({matchUps:i});if(o&&s?.[o]){let a=[...r].sort(Zt).map((c,u)=>{let p=s[o].find(m=>m.drawPositions?.includes(c));return{matchUpId:p?.matchUpId,roundNumber:o,schedule:p?.schedule,sideNumber:u+1,structureName:e.structureName}});Object.assign(t,{sidesTo:a})}}function aq({scheduleConflictMatchUpIds:t,inContextDrawMatchUps:e,inContextMatchUp:r,drawDefinition:n,matchUpId:o}){let i=er({useTargetMatchUpIds:!0,inContextDrawMatchUps:e,inContextMatchUp:r,drawDefinition:n,matchUpId:o}),{winnerMatchUp:s}=i.targetMatchUps,{loserMatchUp:a}=i.targetMatchUps;!r.winnerMatchUpId&&s&&(r.winnerMatchUpId=s.matchUpId),!r.loserMatchUpId&&a&&(r.loserMatchUpId=a.matchUpId);let c=Cb({upcomingMatchUp:s}),u=Cb({upcomingMatchUp:a});if(r.matchUpStatus!=="BYE"&&a?.matchUpStatus==="BYE"){let{matchUp:m}=s0({matchUp:a,drawDefinition:n,inContextDrawMatchUps:e})??{};u=m&&Cb({upcomingMatchUp:m})||u}let p=r.schedule?.timeAfterRecovery;p&&(o0({scheduleConflictMatchUpIds:t,inContextMatchUp:r,timeAfterRecovery:p,upcomingTo:c}),o0({scheduleConflictMatchUpIds:t,inContextMatchUp:r,timeAfterRecovery:p,upcomingTo:u})),Object.assign(r,{winnerTo:c,loserTo:u}),r.drawPositions?.filter(Boolean).length&&cq({inContextDrawMatchUps:e,inContextMatchUp:r,winnerMatchUp:s,loserMatchUp:a,targetData:i})}function o0({scheduleConflictMatchUpIds:t,inContextMatchUp:e,timeAfterRecovery:r,upcomingTo:n}){n?.schedule?.scheduledTime&&jt(n.schedule.scheduledTime)<jt(r)&&(t[n.matchUpId]=e.matchUpId,n.schedule.scheduleConflict=e.matchUpId)}function cq({inContextDrawMatchUps:t,inContextMatchUp:e,winnerMatchUp:r,loserMatchUp:n,targetData:o}){let s=o.targetLinks?.loserTargetLink?.linkCondition===Wn,a=uq(e);if(!a.length)return;let c=LI(r?.sides),u=LI(n?.sides),m=a.find(({participantId:f})=>c.includes(f))?[]:a,l=a.find(({participantId:f})=>u.includes(f))?[]:a;n&&s&&l.length<2&&l.push({bye:!0,tbd:!0}),m?.length&&r&&(!o.targetMatchUpIds&&r&&(r=t.find(({matchUpId:f})=>f===r.matchUpId)),r.potentialParticipants??=[],r.potentialParticipants.push(m)),l?.length&&n&&(o.targetMatchUpIds||(r=t.find(({matchUpId:f})=>f===n.matchUpId)),n.potentialParticipants||(n.potentialParticipants=[]),n.potentialParticipants.push(l))}function uq(t){return t?.sides?.map(({participant:e,participantId:r,qualifier:n})=>e||r&&{participantId:r}||n&&{qualifier:n}).filter(Boolean)??[]}function s0({matchUp:t,drawDefinition:e,inContextDrawMatchUps:r}){let{matchUpId:n,matchUpStatus:o,structureId:i}=t??{};if(!t||!i||t?.matchUpStatus===zt)return{matchUp:t};if(o==="BYE"){let s;return t.winnerMatchUpId?s=r.find(({matchUpId:a})=>a===t.winnerMatchUpId):{winnerMatchUp:s}=er({inContextDrawMatchUps:r,drawDefinition:e,matchUpId:n})?.targetMatchUps??{},s0({matchUp:s,drawDefinition:e,inContextDrawMatchUps:r})}return{matchUp:void 0}}function Cb(t){if(t?.upcomingMatchUp)return(({matchUpId:e,structureId:r,schedule:n,roundNumber:o,roundPosition:i,structureName:s})=>({matchUpId:e,structureId:r,schedule:n,roundNumber:o,roundPosition:i,structureName:s}))(t.upcomingMatchUp)}function te(t){let e="getAllDrawMatchUps";Object.assign(t,{requireParticipants:!1});let r=Ga(t);if(r.error)return M({result:r,stack:e});let{abandonedMatchUps:n,completedMatchUps:o,upcomingMatchUps:i,pendingMatchUps:s,byeMatchUps:a,matchUpsMap:c}=r;return{matchUps:(n??[]).concat(...o??[],...i??[],...s??[],...a??[]),matchUpsMap:c}}function Ga(t){if(!t?.drawDefinition)return{error:$};let{tournamentParticipants:e,contextContent:r,matchUpsMap:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,requireParticipants:s,participantsProfile:a,afterRecoveryTimes:c,policyDefinitions:u,tournamentRecord:p,usePublishState:m,contextFilters:d,matchUpFilters:l,scheduleTiming:f,participantMap:g,publishStatus:I,contextProfile:S,drawDefinition:h,nextMatchUps:T,inContext:y,context:E,event:A}=t,N=[],D=[],R=[],U=[],b=[];S&&!r&&(r=eo({policyDefinitions:u,tournamentRecord:p,contextProfile:S,event:A}));let C;!e?.length&&p&&(e=p?.participants,(y||a?.withGroupings)&&e?.length&&({participantsWithGroupings:e,groupInfo:C}=_p({participants:e,participantsProfile:a})));let{structures:_}=Sn({drawDefinition:h});if(!_)return{error:Nt};n||(n=Ie({drawDefinition:h}));let v=h&&Gl({drawDefinition:h}).exitProfiles;_.forEach(F=>{let{byeMatchUps:x=[],pendingMatchUps:k=[],upcomingMatchUps:G=[],completedMatchUps:V=[],abandonedMatchUps:B=[]}=Gp({matchUpFilters:T?void 0:l,contextFilters:T?void 0:d,inContext:y||T||d,hydrateParticipants:t.hydrateParticipants,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,tournamentParticipants:e,requireParticipants:s,afterRecoveryTimes:c,policyDefinitions:u,tournamentRecord:p,usePublishState:m,contextContent:r,participantMap:g,scheduleTiming:f,publishStatus:I,contextProfile:S,drawDefinition:h,exitProfiles:v,matchUpsMap:n,structure:F,context:E,event:A});N=N.concat(...B),D=D.concat(...V),R=R.concat(...G),U=U.concat(...k),b=b.concat(...x)});let w=F=>(!l&&!T&&!d||(l&&(F=zi({matchUps:F,...l})),d&&(F=zi({matchUps:F,...d,processContext:!0}))),F),L={abandonedMatchUps:w(N),completedMatchUps:w(D),upcomingMatchUps:w(R),pendingMatchUps:w(U),byeMatchUps:w(b),matchUpsMap:n,...P,groupInfo:C};if(T){let F=typeof T=="object"||{abandoned:!0,completed:!0,upcoming:!0,pending:!0,bye:!0},{abandoned:x,completed:k,upcoming:G,pending:V,bye:B}=F,z=[].concat(...(x&&N)??[],...(k&&D)??[],...(G&&R)??[],...(V&&U)??[],...(B&&b)??[]);i0({inContextDrawMatchUps:z,drawDefinition:h})}return L}function vn(t){let{participants:e=[],contextContent:r,participantMap:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,usePublishState:m,contextFilters:d,matchUpFilters:l,contextProfile:f,nextMatchUps:g,inContext:I,context:S,event:h}=t;if(!h)return{error:le};let{eventId:T,eventName:y,endDate:E,eventType:A,category:N,gender:D,matchUpFormat:R}=h??{},U={...S,...et({indoorOutDoor:h.indoorOutdoor??p?.indoorOutdoor,surfaceCategory:h.surfaceCategory??p?.surfaceCategory,endDate:h.endDate??p?.endDate,tournamentId:p?.tournamentId,matchUpFormat:R,eventName:y,eventType:A,category:N,eventId:T,gender:D})};E&&(U.endDate=E),f&&!r&&(r=eo({policyDefinitions:c,tournamentRecord:p,contextProfile:f,event:h}));let b;if(!e?.length&&!n&&p){let w=di({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:f,inContext:I});n=w.participantMap,e=w.participants??[],b=w.groupInfo}let C=h.drawDefinitions??[],_=Ac({tournamentRecord:p,event:h}).scheduleTiming;return{matchUps:C.flatMap(w=>{let{matchUps:L}=te({tournamentParticipants:e,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,context:U,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,usePublishState:m,contextFilters:d,contextProfile:f,drawDefinition:w,contextContent:r,matchUpFilters:l,participantMap:n,scheduleTiming:_,nextMatchUps:g,inContext:I,event:h});return L??[]}),groupInfo:b}}function qt(t){let e=X(t,[{tournamentRecord:!0}]);if(e.error)return e;if(!t?.tournamentRecord)return{error:j};let{participantMap:r,participants:n}=t,{scheduleVisibilityFilters:o,participantsProfile:i,afterRecoveryTimes:s,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,inContext:p=!0,usePublishState:m,contextProfile:d,matchUpFilters:l,contextFilters:f,nextMatchUps:g,context:I}=t,S=t.tournamentId??u.tournamentId,h=u?.events??[];n||({participants:n,participantMap:r}=di({participantsProfile:i,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,contextProfile:d,inContext:p}));let{appliedPolicies:T}=ft({tournamentRecord:u}),y={...I,tournamentId:S,indoorOutDoor:u.indoorOutdoor,surfaceCategory:u.surfaceCategory,endDate:u.endDate},E=eo({policyDefinitions:c,tournamentRecord:u,contextProfile:d});return{matchUps:h.flatMap(N=>(y.eventDrawsCount=N.drawDefinitions?.length??0,vn({context:y,scheduleVisibilityFilters:o,tournamentAppliedPolicies:T,participantsProfile:i,afterRecoveryTimes:s,policyDefinitions:c,tournamentRecord:u,usePublishState:m,contextContent:E,contextFilters:f,contextProfile:d,matchUpFilters:l,participantMap:r,nextMatchUps:g,participants:n,inContext:p,event:N}).matchUps??[])).concat(...u.matchUps??[])}}function cn({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,tournamentRecords:n,policyDefinitions:o,usePublishState:i,matchUpFilters:s,contextFilters:a,nextMatchUps:c,inContext:u}){if(typeof n!="object"||!Object.keys(n).length)return{error:kt};let m=Object.keys(n).map(d=>{let l=n[d];return qt({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,policyDefinitions:o,tournamentRecord:l,usePublishState:i,matchUpFilters:s,contextFilters:a,nextMatchUps:c,inContext:u}).matchUps??[]}).flat();return{...P,matchUps:m}}function Qi(t,e){return pq(t,e)||(t?.stageSequence||0)-(e?.stageSequence||0)||t?.roundNumber&&e.roundNumber&&t?.roundNumber-e?.roundNumber||(t?.roundPosition??0)-(e?.roundPosition??0)}function pq(t,e){return(Ca[t?.stage]||0)-(Ca[e?.stage]||0)}function rr(t){let{participants:e,participantMap:r,contextContent:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,matchUpFilters:m,contextFilters:d,contextProfile:l,drawDefinition:f,nextMatchUps:g,inContext:I,context:S,event:h}=t,{eventId:T,eventName:y,endDate:E,eventType:A,category:N,gender:D,matchUpFormat:R}=h??{},U={...S,surfaceCategory:h?.surfaceCategory??p?.surfaceCategory,indoorOutDoor:h?.indoorOutdoor??p?.indoorOutdoor,matchUpFormat:R,eventType:A,eventName:y,category:N,eventId:T,endDate:E,gender:D},b;return!e?.length&&!r&&p&&({participants:e=[],participantMap:r,groupInfo:b}=di({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:l,inContext:I})),l&&!n&&(n=eo({policyDefinitions:c,tournamentRecord:p,contextProfile:l,drawDefinition:f,event:h})),{...te({context:U,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,tournamentParticipants:e,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,drawDefinition:f,contextContent:n,contextFilters:d,contextProfile:l,matchUpFilters:m,participantMap:r,nextMatchUps:g,inContext:I,event:h}),groupInfo:b}}var Mb=t=>e=>!t||typeof e!="object"?void 0:Array.isArray(t)&&t.map(r=>({[r]:Bi({element:e,accessor:r})?.value}))||typeof t=="object"&&Object.keys(t).map(r=>({[r]:Bi({element:e,accessor:r})?.value}))||(typeof t=="string"&&Bi({element:e,accessor:t}))?.value,Vr=Mb;function Nc({finishingPositionOffset:t=0,finishingPositionLimit:e,positionsFed:r,roundsCount:n,roundLimit:o,matchUps:i,lucky:s,fmlc:a}){if(!Rr(i))return[];let{roundProfile:c,roundNumbers:u=[]}=Ue({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(Vr("matchUpsCount")),l=(I,S)=>{let h=Math.min(...I);m&&S&&h===1&&(h=m);let T=Math.max(...I);return e&&T>e&&(T=e),[h,T]},f=c&&Object.assign({},...u.map(I=>{let S=(n??0)+1-I-p,h=c[I].matchUpsCount,T={finishingPositionRange:{},finishingRound:S},y=d?.slice(I-1).reduce((C,_)=>C+(_||0),0),E=a&&I!==1,A=1+t+(E?r??0:0),N=1,D=Q(A,s?A+h*2:y+A+N),R=y+N-h,U=l(D.slice(R)),b=l(D.slice(0,R),!0);return T.finishingPositionRange={loser:U,winner:b},{[I]:T}})),g=je({finishingRound:!0});return i.filter(Boolean).forEach(I=>{let S=I.roundNumber&&f[I.roundNumber];g&&!S&&console.log({roundFinishingData:f,matchUp:I}),I.finishingRound=S?.finishingRound,I.finishingPositionRange=S?.finishingPositionRange}),i}function Ps({inContextDrawMatchUps:t,drawDefinition:e,matchUpsMap:r}){if(!e)return{error:$};let n={loserMatchUpIds:{},winnerMatchUpIds:{}};if(t||({matchUps:t,matchUpsMap:r}=te({inContext:!0,drawDefinition:e,matchUpsMap:r})),!r?.drawMatchUps.some(i=>i.finishingPositionRange)&&e?.structures?.length===1&&!e?.structures[0].structures){let i=r?.drawMatchUps??[];Nc({matchUps:i})}return(t??[]).filter(({collectionId:i})=>!i).forEach(i=>{let{matchUpId:s,structureId:a}=i,c=er({inContextDrawMatchUps:t,drawDefinition:e,matchUpId:s}),{winnerMatchUp:u,loserMatchUp:p}=c.targetMatchUps,m=u?.matchUpId,d=p?.matchUpId,f=jo({matchUpsMap:r,structureId:a}).find(g=>g.matchUpId===s);if(f&&(m&&(n.winnerMatchUpIds[f.matchUpId]=m,Object.assign(f,{winnerMatchUpId:m}),Object.assign(i,{winnerMatchUpId:m})),d&&(n.loserMatchUpIds[f.matchUpId]=d,i.loserMatchUpId=d,f.loserMatchUpId=d,i.finishingPositionRange))){let g=p.finishingPositionRange&&[...i.finishingPositionRange.loser,...p.finishingPositionRange.loser],I=g&&[Math.min(...g),Math.max(...g)];i.finishingPositionRange.loser=I,f.finishingPositionRange.loser=I}}),{inContextDrawMatchUps:t,goesToMap:n}}function tn(t){let e=Dr(t),r=t.matchUps??[],n=t.drawIds??[],{includeParticipantDependencies:o,tournamentRecord:i,drawDefinition:s}=t;if(!Array.isArray(r))return{error:Bn};if(!Array.isArray(n))return{error:Nn};let a=t.matchUpIds?.length?t.matchUpIds:r.map(T=>T.matchUpId);if(!Array.isArray(a))return{error:xs};let c={},u={},p={},m={};i&&!Object.keys(e).length&&(e={[i.tournamentId]:i});let d=Object.values(e),f=d.reduce((T,y)=>T.concat(y.events??[]).map(E=>(E.drawDefinitions??[]).map(A=>A.links??[])).flat(1/0),[]).filter(({linkType:T})=>T===fn),g=r;f.length&&(g=cn({nextMatchUps:!0,tournamentRecords:e}).matchUps,mq({positionLinks:f,sourceStructureIdMap:p,positionDependencies:c,matchUps:g}));let I=T=>{u[T]||(u[T]={dependentMatchUpIds:[],participantIds:[],matchUpIds:[],sources:[]},m[T]=[])},S=(T,y)=>{u[T].matchUpIds.forEach(A=>{u[y].matchUpIds.push(A)}),u[y].matchUpIds.push(T),u[T].dependentMatchUpIds.push(y),o&&u[T].participantIds.forEach(A=>u[y].participantIds.push(A))},h=T=>{let y=Object.keys(c).length;for(let E of T??[]){let{matchUpId:A,winnerMatchUpId:N,loserMatchUpId:D}=E;if(!a.length||a.includes(A)){if(I(A),o){let{individualParticipantIds:b}=Mp(E);u[A].participantIds=b}N&&(I(N),S(A,N),m[N].push(A)),D&&(I(D),S(A,D),m[D].push(A)),u[A].sources.push(m[A]);let R=m[A].map(b=>u[b].sources[0]).flat(),U=m[A].map(b=>u[b].sources[1]).flat();if(u[A].sources.push(R,U),y){let b=E.containerStructureId||E.structureId,C=p[b];if(c[C])for(let _ of c[C])I(_),S(_,A),m[_].push(A)}}}};if(s)Ps({drawDefinition:s}),g?.length||(g=rr({drawDefinition:s}).matchUps),h(g);else{g?.length||(g=cn({nextMatchUps:!0,tournamentRecords:e}).matchUps),n.length||(n=dq(d));for(let T of n)lq({matchUps:g,drawId:T,tournamentRecords:e,processMatchUps:h})}return{positionDependencies:c,matchUpDependencies:u,sourceMatchUpIds:m,matchUps:g,...P}}function mq({positionLinks:t,sourceStructureIdMap:e,positionDependencies:r,matchUps:n}){let o=t.reduce((i,s)=>{let a=s.source?.structureId,c=s.target?.structureId;return a&&c&&(e[c]=a),a&&!i.includes(a)&&i.push(a),i},[]);for(let i of o)r[i]=[];for(let i of n??[]){let s=i.containerStructureId||i.structureId;o.includes(s)&&r[s].push(i.matchUpId)}}function dq(t){return t?.length?t.map(({events:e=[]})=>e.map(({drawDefinitions:r=[]})=>r.map(({drawId:n})=>n))).flat(1/0):[]}function lq({matchUps:t,drawId:e,tournamentRecords:r,processMatchUps:n}){let o=t?.filter(s=>s.drawId===e).sort(Qi);if(!o?.find(({roundPosition:s})=>!s)){let s=o?.find(({tournamentId:c})=>c),{drawDefinition:a}=_e({tournamentRecord:r[s?.tournamentId],drawId:e});a&&Ps({drawDefinition:a})}n(o)}function ue(t){let e=t?.matchUp,r=t?.score||e?.score,n=r?.sets?.[0],{side1Score:o,side2Score:i,side1TiebreakScore:s,side2TiebreakScore:a,side1PointScore:c,side2PointScore:u}=n??{},p=o||i||s||a||c||u;return!!(r?.sets?.length>1||p)}function Va({matchUpStatus:t}){return Gy.includes(t)}function a0({matchUpStatus:t}){return Rl.includes(t)}function cS({matchUpStatus:t}){return Vy.includes(t)}function uS({matchUpStatus:t,winningSide:e,tieMatchUps:r,sides:n,score:o}){let i=n?.find(({participantId:c})=>c),s=r?.filter(uS)?.length;return ue({score:o})||s||e&&i||t&&a0({matchUpStatus:t})&&![Mt,vt,Cn].includes(t)}function Xi(t){let{drawDefinition:e,findContainer:r,structureId:n,event:o}=t,i=t.structure,{containedStructures:s}=ji({drawDefinition:e}),a=n?s[n]??[]:[],c={isCollectionMatchUp:!1};if(!i){let N=tt({drawDefinition:e,structureId:n});if(N.error)return N;i=r?N.containingStructure??N.structure:N.structure}if(Ae({structure:i}))return{structure:i,isAdHoc:!0,error:ps};let{matchUps:u}=te({inContext:!0,matchUpFilters:c,drawDefinition:e,event:o}),p=u?.filter(N=>N.structureId===n||a.includes(N.structureId)),{matchUpDependencies:m}=tn({drawIds:[e.drawId],matchUps:u,drawDefinition:e}),d=[],l=[],f={},g=[];for(let N of u??[]){if(N.structureId===n||a.includes(N.structureId)){l.push(...N.drawPositions??[]);let D=N.roundNumber;for(let R of(N.drawPositions??[]).filter(Boolean))(!f[R]||D&&f[R]>D)&&(f[R]=D)}uS(N)&&(g.push(N),d.push(N.matchUpId,...m?.[N?.matchUpId]?.matchUpIds??[]))}let I=pt(l.filter(Boolean)).sort(Zt),S=pt(d),h=pt(p?.map(({matchUpId:N,drawPositions:D})=>S.includes(N)?D:[]).flat().filter(Boolean)).sort(Zt),{positionAssignments:T}=Pt({drawDefinition:e,structure:i}),y=T?.filter(N=>N.bye).map(N=>N.drawPosition),E=T?.filter(N=>N.qualifier).map(N=>N.drawPosition),A=I?.filter(N=>!h.includes(N))??[];return{allDrawPositions:I,inContextStructureMatchUps:p,drawPositionInitialRounds:f,activeDependentMatchUpIds:S,qualifyingDrawPositions:E,inactiveDrawPositions:A,positionAssignments:T,activeDrawPositions:h,byeDrawPositions:y,activeMatchUps:g,structure:i}}function Zs({drawPosition:t,matchUps:e=[]}){return{initialRoundNumber:e.filter(({drawPositions:n})=>t&&n?.includes(t)).map(({roundNumber:n})=>n).sort(Zt)[0]}}var Dc={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 yE=[];function Pe(t,e){wt(t)&&(t={method:t}),(e||je())&&yE.push(t)}function fq(t){let e=yE.slice();return t&&(yE.length=0),e}function c0(t){let r=fq(t).map(n=>{let{color:o,keyColors:i,method:s,newline:a}=n,c=Object.keys(Dc).includes(o)?Dc[o]:Dc.cyan,p=Object.keys(n).filter(d=>!["color","keyColors","method","newline"].includes(d)).map(d=>{let l=i&&Object.keys(i).includes(d)&&Dc[i[d]]?Dc[i[d]]:Dc.brightwhite;return`${Dc.white}${d}: ${l}${n[d]}`}).join(", "),m=s?.length<15?" ":" ";return[a?`
|
|
2
2
|
`:"",c,s,m,Dc.white,p,Dc.reset,`
|
|
3
3
|
`].join("")});r?.length&&console.log(...r)}function u0(){yE.length=0}function Ql(t){let e=t.bye,r=t.qualifier,n=t.participantId;return{containsBye:e,containsQualifier:r,containsParticipant:n,filled:e||r||n}}function Ye(t){return[Mt,vt,De].includes(t)}function Or({provisionalPositioning:t,isPositionAction:e,tournamentRecord:r,drawDefinition:n,drawPosition:o,loserMatchUp:i,matchUpsMap:s,structureId:a,structure:c,event:u}){if(!n)return{error:$};if(c||({structure:c}=tt({drawDefinition:n,structureId:a})),!c)return{error:Nt};a||({structureId:a}=c);let p="assignDrawPositionBye";Pe({method:p,color:"cyan",drawPosition:o}),s??=Ie({drawDefinition:n});let{positionAssignments:m}=Pt({structure:c}),{activeDrawPositions:d}=Xi({drawDefinition:n,structureId:a});if(m?.find(v=>v.drawPosition===o)?.bye)return{...P};if(an(n.drawType)&&m?.filter(w=>w.bye&&w.drawPosition!==o)?.length)return M({result:{error:QD},stack:p});let f=!!(i&&s.drawMatchUps.some(v=>v.loserMatchUpId===i?.matchUpId&&Ye(v.matchUpStatus)));if(d?.includes(o)&&!f)return{error:qc};let I=m?.find(v=>v.drawPosition===o);I||(I={drawPosition:o},m?.push(I));let{filled:S,containsBye:h,containsParticipant:T}=Ql(I);if(h)return{...P};if(S&&!h&&!f)return M({result:{error:Yc},stack:p});let y=ft({tournamentRecord:r,drawDefinition:n,event:u}).appliedPolicies??{},E=te({inContext:!0,drawDefinition:n,matchUpsMap:s}).matchUps??[],A={isCollectionMatchUp:!1},{matchUps:N}=ht({provisionalPositioning:t,drawDefinition:n,matchUpFilters:A,matchUpsMap:s,structure:c});if(m?.forEach(v=>{v.drawPosition===o&&(v.bye=!0,f&&(v.participantId=void 0))}),c.structureType===de)return gq({tournamentRecord:r,drawDefinition:n,drawPosition:o,matchUps:N}),hn({tournamentId:r?.tournamentId,drawDefinition:n,structure:c,event:u}),p0({assignedParticipantId:T,isPositionAction:e,appliedPolicies:y,drawDefinition:n,drawPosition:o,structureId:a,stack:p});let{roundProfile:D,roundMatchUps:R}=Ue({matchUps:N}),b=(D&&Object.keys(D).map(v=>Number.parseInt(v)).reverse())?.find(v=>D?.[v].drawPositions?.includes(o)),C=b?R?.[b].find(({drawPositions:v})=>v?.includes(o)):void 0;C&&m0({tournamentRecord:r,drawDefinition:n,matchUp:C,event:u});let _=C?.drawPositions?.find(v=>v!==o);if(C&&_){let v=EE({sourceDrawPositions:C.drawPositions,matchUpId:C.matchUpId,inContextDrawMatchUps:E,drawPositionToAdvance:_,tournamentRecord:r,drawDefinition:n,matchUpsMap:s});if(v.error)return v}return hn({tournamentId:r?.tournamentId,drawDefinition:n,structure:c,event:u}),p0({assignedParticipantId:T,isPositionAction:e,appliedPolicies:y,drawDefinition:n,drawPosition:o,structureId:a,stack:p})}function p0({assignedParticipantId:t,isPositionAction:e,appliedPolicies:r,drawDefinition:n,drawPosition:o,structureId:i,stack:s}){return e&&Ec({appliedPolicies:r,drawDefinition:n,positionAction:{removedParticipantId:t,drawPosition:o,structureId:i,name:s}}),M({result:{...P},stack:s})}function m0({tournamentRecord:t,drawDefinition:e,eventId:r,matchUp:n,event:o}){Object.assign(n,{matchUpStatus:"BYE",score:void 0,winningSide:void 0}),It({tournamentId:t?.tournamentId,eventId:r??o?.eventId,context:"setMatchUpStatusBye",drawDefinition:e,matchUp:n})}function gq({tournamentRecord:t,drawDefinition:e,drawPosition:r,matchUps:n,event:o}){n.forEach(i=>{i.drawPositions?.includes(r)&&m0({eventId:o?.eventId,tournamentRecord:t,drawDefinition:e,matchUp:i})})}function EE({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,matchUpsMap:i,matchUpId:s,event:a}){Pe({method:"advanceDrawPosition",color:"cyan",drawPositionToAdvance:t});let u=i.drawMatchUps.find(N=>N.matchUpId===s),m=e.find(N=>N.matchUpId===s)?.structureId,{structure:d}=tt({drawDefinition:o,structureId:m}),{positionAssignments:l}=Pt({structure:d}),f=l?.filter(N=>N.bye).map(N=>N.drawPosition),g=u?.drawPositions?.find(N=>N!==t),I=g&&f?.includes(g),{targetLinks:{loserTargetLink:S},targetMatchUps:{loserMatchUp:h,winnerMatchUp:T,loserTargetDrawPosition:y}}=er({inContextDrawMatchUps:e,drawDefinition:o,matchUpId:s}),E=an(o?.drawType),A=!E||!u?.roundNumber||!d?.matchUps?!1:d.matchUps.filter(D=>D.roundNumber===u.roundNumber).length%2!==0;if(T&&T.structureId===d?.structureId&&(!E||!A)&&Iq({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,winnerMatchUp:T,matchUpsMap:i,event:a}),h&&I&&h.structureId!==d?.structureId){let{roundNumber:N}=h;if(N===1){let D=Or({structureId:S.target.structureId,drawPosition:y,tournamentRecord:n,drawDefinition:o,event:a});if(D.error)return D}else d0({loserTargetDrawPosition:y,tournamentRecord:n,loserTargetLink:S,drawDefinition:o,loserMatchUp:h,matchUpsMap:i,event:a})}return{...P}}function Iq({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,winnerMatchUp:i,matchUpsMap:s,event:a}){let c="advanceWinner",u=s.drawMatchUps.find(x=>x.matchUpId===i.matchUpId),m=e.find(x=>x.matchUpId===i.matchUpId)?.structureId,{structure:d}=tt({drawDefinition:o,structureId:m}),{positionAssignments:l}=Pt({structure:d}),g=l?.find(({drawPosition:x})=>x===t)?.bye,I=u.drawPositions?.filter(Boolean),S=l?.filter(x=>I?.includes(x.drawPosition)),h=l?.find(({drawPosition:x})=>x===t),T=r?.find(x=>x!==t),E=(T&&S?.find(({drawPosition:x})=>x===T))?.bye,A=g&&E;if(A&&console.log({isByeAdvancedBye:A}),I?.length>1&&g&&!E)return M({result:{error:Yc},stack:c});let N=I?.find(x=>x!==t),D=A,R=[...(u.drawPositions??[]).filter(Boolean),void 0,void 0].slice(0,2),U=R.map(x=>!x&&!D||x===t?(D=!0,t):x).sort(Zt);if(!D)return console.log("@@@@@@@",{advancingAssignmentIsBye:h,drawPositionToAdvance:t,existingAssignments:S}),M({result:{error:Yc},stack:c});let b=l?.find(({drawPosition:x})=>x===N)?.bye,C=l?.find(({drawPosition:x})=>x===t)?.bye;Object.assign(u,{matchUpStatus:C||b?"BYE":zt,score:void 0,winningSide:void 0,drawPositions:U});let v=u.drawPositions.find(x=>!R.includes(x));Pe({method:c,color:"brightyellow",changedDrawPosition:v,pairedDrawPositionIsBye:b,drawPositionIsBye:C}),It({tournamentId:n?.tournamentId,matchUp:u,eventId:a?.eventId,context:c,drawDefinition:o});let{targetLinks:{loserTargetLink:w},targetMatchUps:{loserMatchUp:L,loserTargetDrawPosition:F}}=er({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:o});if(b||C){let x=b?t:N;if(x)EE({drawPositionToAdvance:x,matchUpId:i.matchUpId,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:o,matchUpsMap:s});else if(C&&w&&L)if(L.feedRound)d0({loserTargetDrawPosition:F,tournamentRecord:n,loserTargetLink:w,drawDefinition:o,loserMatchUp:L,matchUpsMap:s});else{let G=1-i.roundPosition%2,V=L.drawPositions[G],B=Or({structureId:w.target.structureId,drawPosition:V,tournamentRecord:n,drawDefinition:o,event:a});if(B.error)return B}}}function d0({loserTargetDrawPosition:t,tournamentRecord:e,loserTargetLink:r,drawDefinition:n,loserMatchUp:o,matchUpsMap:i,event:s}){let{roundNumber:a}=o;Pe({method:"assignFedDrawPositionBye",color:"cyan",loserTargetDrawPosition:t});let p=(i?.mappedMatchUps??{})[o.structureId].matchUps,{initialRoundNumber:m}=Zs({drawPosition:t,matchUps:p});if(m===a){let d=Or({structureId:r.target.structureId,drawPosition:t,tournamentRecord:e,drawDefinition:n,event:s});if(d.error)return d}}function AE({positionAssignments:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:n,structure:o,event:i}){let{matchUps:s}=ht({drawDefinition:r,matchUpsMap:n,structure:o,event:i});s.forEach(a=>{let u=t.filter(({drawPosition:p})=>a.drawPositions?.includes(p)).filter(p=>p.bye).length;a.winningSide||(Object.assign(a,{matchUpStatus:u?"BYE":zt}),It({tournamentId:e?.tournamentId,context:"modifyRoundRobinMatchUpsStatus",eventId:i?.eventId,drawDefinition:r,matchUp:a}))})}function Au(t){let{inContextDrawMatchUps:e,participantId:r,drawPosition:n}=t,{tournamentRecord:o,drawDefinition:i,structureId:s,matchUpsMap:a,event:c}=t,{structure:u}=tt({drawDefinition:i,structureId:s}),m=(se({drawDefinition:i,structure:u}).positionAssignments??[]).find(g=>r&&g.participantId===r||n&&g.drawPosition===n);if(m&&r&&!n&&(n=m?.drawPosition),!n)return{error:Ta};r||(r=m?.participantId);let{activeDrawPositions:d}=Xi({drawDefinition:i,structureId:s});return d.includes(n)?{error:qc}:(e||({matchUps:e}=te({inContext:!0,drawDefinition:i,matchUpsMap:a})),vb({inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,structureId:s,drawPosition:n,matchUpsMap:a,event:c}).drawPositionCleared?(hn({tournamentId:o?.tournamentId,drawDefinition:i,structure:u,event:c}),{...P,participantId:r}):{error:_D})}function vb({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,matchUpsMap:o,structureId:i,event:s}){let{structure:a}=tt({drawDefinition:r,structureId:i});if(!a)return{error:Nt};let c=se({drawDefinition:r,structure:a}).positionAssignments??[],u=c.some(h=>{if(h.drawPosition===n)return delete h.participantId,delete h.qualifier,delete h.bye,!0});if(a.structureType===de)return AE({positionAssignments:c,tournamentRecord:e,drawDefinition:r,matchUpsMap:o,structure:a}),{drawPositionCleared:u,...P};let p={isCollectionMatchUp:!1},{matchUps:m}=ht({drawDefinition:r,matchUpFilters:p,matchUpsMap:o,structure:a,event:s}),{roundProfile:d,roundMatchUps:l}=Ue({matchUps:m}),g=(d&&Object.keys(d))?.map(h=>st(h)),I=hq({roundNumbers:g,roundProfile:d,positionAssignments:c,drawPosition:n}),S=Tq(I);return S?.forEach(({roundNumber:h,targetDrawPosition:T,relevantPair:y})=>{let E=l?.[h].find(A=>Re(A.drawPositions?.filter(Boolean),y.filter(Boolean)));E&&(Sq({inContextDrawMatchUps:t,targetDrawPosition:T,tournamentRecord:e,drawDefinition:r,structureId:i,roundNumber:h,matchUpsMap:o}),l0({inContextDrawMatchUps:t,positionAssignments:c,tournamentRecord:e,drawDefinition:r,targetMatchUp:E,drawPosition:n,matchUpsMap:o,structure:a,event:s}))}),{tasks:S,drawPositionCleared:u,positionAssignments:c}}function Sq({inContextDrawMatchUps:t,targetDrawPosition:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,roundNumber:i,structureId:s}){let{structure:a}=tt({drawDefinition:n,structureId:s});if(!a)return{error:Nt};if(a.structureType===de)return;o=o||Ie({drawDefinition:n});let u=(o?.mappedMatchUps??{})[s].matchUps,{initialRoundNumber:p}=Zs({drawPosition:e,matchUps:u}),m=u?.filter(l=>l.roundNumber>=i&&l.roundNumber!==p&&l.drawPositions?.includes(e)),d=Pt({drawDefinition:n,structureId:s}).positionAssignments??[];return m?.forEach(l=>l0({drawPosition:e,targetMatchUp:l,inContextDrawMatchUps:t,positionAssignments:d,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,structure:a})),{...P}}function l0({inContextDrawMatchUps:t,positionAssignments:e,tournamentRecord:r,drawDefinition:n,targetMatchUp:o,drawPosition:i,matchUpsMap:s,structure:a,event:c}){let u="removeDrawPosition",p=o.drawPositions?.slice(),m=o.matchUpStatus,d=o.winningSide;s=s??Ie({drawDefinition:n});let f=s.mappedMatchUps[a.structureId].matchUps,{initialRoundNumber:g}=Zs({drawPosition:i,matchUps:f});if(o.roundNumber&&g&&o.roundNumber>g){let A=(o.drawPositions??[]).map(N=>N===i?void 0:N);o.drawPositions=A}yq({inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,targetMatchUp:o,drawPosition:i,event:c,stack:u});let I=er({matchUpId:o.matchUpId,inContextDrawMatchUps:t,drawDefinition:n}),{targetLinks:{winnerTargetLink:S},targetMatchUps:{loserMatchUp:h,winnerMatchUp:T,loserMatchUpDrawPositionIndex:y}}=I,E=Eq({initialDrawPositions:p,initialMatchUpStatus:m,initialWinningSide:d,positionAssignments:e,tournamentRecord:r,drawDefinition:n,targetMatchUp:o,drawPosition:i,event:c,stack:u});if(h&&h.structureId!==I.matchUp.structureId&&!E){let A=Aq({loserMatchUpDrawPositionIndex:y,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,loserMatchUp:h,matchUpsMap:s,event:c,stack:u});if(A?.error)return A}return T&&T.structureId!==I.matchUp.structureId&&(S.target.feedProfile,ln),{...P}}function hq({roundNumbers:t,roundProfile:e,positionAssignments:r,drawPosition:n}){let o=n;return t?.map(i=>{let a=e?.[i]?.pairedDrawPositions?.find(I=>I.includes(o)),c=a?.find(I=>I!==o),u=r.find(I=>I.drawPosition===c),p=e?.[i+1],m=u?.bye,d=p?.pairedDrawPositions?.find(I=>I.includes(c)),l=m&&d&&p?.drawPositions?.includes(c),g=a&&{pairedDrawPositionByeAdvancedPair:!l&&d,pairedDrawPosition:c,targetDrawPosition:o,relevantPair:a,roundNumber:i};return l&&(o=c),g}).filter(i=>i?.targetDrawPosition)}function Tq(t){return t?.reduce((e,r)=>{let{roundNumber:n,relevantPair:o,targetDrawPosition:i,pairedDrawPosition:s,pairedDrawPositionByeAdvancedPair:a}=r,c={roundNumber:n,targetDrawPosition:i,relevantPair:o},u=a&&{roundNumber:n+1,targetDrawPosition:s,relevantPair:a,subsequentRoundRemoval:!0},p=[c,u].filter(Boolean);return e.concat(...p)},[])}function yq({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,targetMatchUp:n,drawPosition:o,event:i,stack:s}){if(n.matchUpType!==xt)return;let u=(t?.find(p=>p.matchUpId===n.matchUpId)?.sides??[]).reduce((p,m,d)=>m.drawPosition===o?d:p,void 0);u!==void 0&&n.sides?.[u]?.lineUp&&(delete n.sides?.[u].lineUp,It({tournamentId:e?.tournamentId,context:`${s}-TEAM`,eventId:i?.eventId,matchUp:n,drawDefinition:r}))}function Eq({initialDrawPositions:t,initialMatchUpStatus:e,initialWinningSide:r,positionAssignments:n,tournamentRecord:o,drawDefinition:i,targetMatchUp:s,drawPosition:a,event:c,stack:u}){let m=n.filter(({drawPosition:g})=>s.drawPositions?.includes(g)).filter(g=>g.bye).length,d=m&&"BYE"||s.matchUpStatus&&Ye(s.matchUpStatus)&&s.matcHUpStatus||zt;s.matchUpStatus=d,s.matchUpStatus&&Ye(s.matchUpStatus)&&(s.winningSide=void 0);let l=t?.find(g=>!s.drawPositions?.includes(g));return t?.includes(a)&&e===s.matchUpStatus&&r===s.winningSide||(l&&Pe({method:u,color:"brightyellow",removedDrawPosition:l}),It({tournamentId:o?.tournamentId,context:`${u}-${a}`,eventId:c?.eventId,matchUp:s,drawDefinition:i})),m}function Aq({loserMatchUpDrawPositionIndex:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,loserMatchUp:o,matchUpsMap:i,event:s,stack:a}){let{drawPositions:c,roundNumber:u}=o;if(u===1){let g=c[t];vb({structureId:o.structureId,drawPosition:g,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:i});return}let p=Math.min(...c.filter(Boolean)),m=Pq({loserMatchUpDrawPosition:p,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,loserMatchUp:o,matchUpsMap:i,event:s});if(m.error)return M({result:m,stack:a});let l=(i?.mappedMatchUps??{})[o.structureId].matchUps,{initialRoundNumber:f}=Zs({drawPosition:p,matchUps:l});f===1&&(Pe({method:a,color:"brightyellow",loserMatchUpDrawPosition:p}),vb({structureId:o.structureId,drawPosition:p,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:i}))}function Pq({loserMatchUpDrawPosition:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,loserMatchUp:o,matchUpsMap:i,event:s}){let{structure:a}=tt({structureId:o.structureId,drawDefinition:n}),{positionAssignments:c}=Pt({structure:a});if(c?.find(p=>p.drawPosition===t)?.bye){let p=Au({drawPosition:t,structureId:o.structureId,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:i,event:s});if(p.error)return p}return{...P}}function Ji({drawDefinition:t,stages:e}){if(!t)return{error:$};let r=(t?.structures??[]).filter(o=>!e?.length||o.stage&&e.includes(o.stage)),n=pt(r.map(o=>{let{positionAssignments:i}=Pt({structure:o});return i?i.map(gt):[]}).flat().filter(Boolean));return{...P,assignedParticipantIds:n}}function no(t){let e=(t?.entries??[]).filter(Boolean).reduce((n,o)=>{let{entryStage:i,entryStatus:s}=o,a=`_${i||W}${s||""}`;return n[a]||(n[a]=[]),n[a].push(o),n},{}),r=n=>Number.isNaN(Number(n))?1/0:n;return Object.keys(e).flatMap(n=>e[n].sort((o,i)=>r(o.entryPosition)-r(i.entryPosition)).map((o,i)=>{let s=i+1;return{...o,entryPosition:s}}))}function ta(t){return[qi,Gr].includes(t)}function Xl({autoEntryPositions:t=!0,ignoreAssignment:e,tournamentRecord:r,drawDefinition:n,participantIds:o,entryStatus:i,entryStage:s,extension:a,eventSync:c,drawId:u,stage:p,event:m}){let d=Nq({participantIds:o,drawDefinition:n,entryStatus:i,entryStage:s,extension:a,event:m});if(d)return d;let l="modifyEntriesStatus",f=[],g=Dq({event:m,stage:p}),I=r?.participants??[];if(!Uq({participantIds:o,tournamentParticipants:I,entryStatus:i,event:m}))return{error:Qg};let S=m&&Bt({event:m}).flightProfile,h=S?.flights?.find(U=>U.drawId===u),T=Rq({assignedParticipantIds:g,ignoreAssignment:e,participantIds:o,entryStatus:i,entryStage:s,extension:a,stage:p}),y=({flight:U,drawDefinition:b})=>{m&&(m.entries=no({entries:m.entries??[]})),U&&(U.drawEntries=no({entries:U.drawEntries})),b&&(b.entries=no({entries:b.entries}))},E=({flight:U,drawDefinition:b})=>{let C="updateDrawEntries";if(U){let _=T(U.drawEntries);if(_.error)return M({result:_,stack:C})}if(b){let _=T(b.entries);if(_.error)return M({result:_,stack:C});f.includes(b.drawId)||f.push(b.drawId)}return{...P}},A=m?.entries?.find(({entryPosition:U})=>U)??(h?.drawEntries?.find(({entryPosition:U})=>U)||n?.entries?.find(({entryPosition:U})=>U));if(t&&!A&&y({flight:h,drawDefinition:n}),h||n){let U=E({flight:h,drawDefinition:n});if(U.error)return M({result:U,stack:l})}let N=m?.drawDefinitions?.map(({drawId:U})=>U)??[],D=S?.flights?.filter(U=>!N.includes(U.drawId))??[];for(let U of D){let b=U&&E({flight:U,drawDefinition:void 0});if(b?.error)return M({result:b,stack:l})}let R=S?.flights?.length===1&&(m?.drawDefinitions?.length??0)<=S?.flights?.length;if(!h&&!n&&i&&Sb.includes(i))return{error:TU};if(!h&&!n||i===Mn||c&&R){let U=T(m?.entries);if(U?.error)return M({result:U,stack:l});if(i===Mn){let b=bq({updateEntryStatus:T,participantIds:o,flightProfile:S,event:m});if(b)return M({result:{error:b},stack:l})}}t&&y({flight:h,drawDefinition:n});for(let U of m?.drawDefinitions??[])f.length&&!f.includes(U.drawId)||Ft({tournamentId:r.tournamentId,eventId:m?.eventId,drawDefinition:U});return{...P}}function Nq({participantIds:t,drawDefinition:e,entryStatus:r,entryStage:n,extension:o,event:i}){if(!t||!Array.isArray(t))return{error:Hr,method:"modifyEntriesStatus",participantIds:t};if(!e&&!i)return{error:le};if(r&&!hb.includes(r))return{error:Qg};if(n&&!ou.includes(n))return{error:cc};let s="modifyEntriesStatus";if(!r&&!o)return M({result:{error:nt},info:"Missing entryStatus",stack:s});if(o&&!Yn({extension:o,requiredAttributes:["name"]}))return M({result:{error:O},info:"Invalid extension",context:{extension:o},stack:s})}function Dq({event:t,stage:e}){let r=[];return t?.drawDefinitions?.forEach(n=>{let o=Ji({stages:e&&[e],drawDefinition:n}).assignedParticipantIds??[];r.push(...o)}),r}function Uq({participantIds:t,tournamentParticipants:e,entryStatus:r,event:n}){return t.every(o=>{let i=ui({tournamentParticipants:e,participantId:o})?.participantType;return!(i&&[lt,ur].includes(i)&&ta(r))&&!(r&&n?.eventType&&i===St&&[Lt,Ze].includes(n.eventType)&&[Zr,...td].includes(r))})}function Rq({assignedParticipantIds:t,ignoreAssignment:e,participantIds:r,entryStatus:n,entryStage:o,extension:i,stage:s}){return a=>{let c=(a??[]).filter(m=>!s||!m.entryStage||s===m.entryStage).filter(({participantId:m})=>r.includes(m)),u=m=>n&&t.includes(m.participantId)&&!(td.includes(m.entryStatus)&&td.includes(n));return c.every(m=>u(m)&&!e?!1:(n&&(m.entryStatus=n,delete m.entryPosition),o&&(m.entryStage=o,delete m.entryPosition),i&&(i.value?ut({element:m,extension:i}):dr({element:m,name:i.name})),!0))?{...P}:{error:Pa}}}function bq({updateEntryStatus:t,participantIds:e,flightProfile:r,event:n}){let o=new Set(e);for(let i of r?.flights??[]){let s=t(i.drawEntries);if(s.error)return s.error;i.drawEntries=i.drawEntries.filter(({participantId:a})=>!o.has(a))}for(let i of n?.drawDefinitions??[]){let s=t(i.entries);if(s.error)return s.error;i.entries=i.entries?.filter(({participantId:a})=>!o.has(a))}}function Ob(t){let e=X(t,[{ratings:!0,[Ge]:qr}]);if(e.error)return e;let r=t.matchUpType&&[Ct,Rt].includes(t.matchUpType)?t.matchUpType:Ct,n=Object.keys(Ke),o=t.targetRatingType&&n.includes(t.targetRatingType)?t.targetRatingType:"ELO",i=t.ratings[r]?t.ratings[r].reduce((d,l)=>d.includes(l.scaleName)?d:d.concat(l.scaleName),[]):[];if(!i)return{error:fe};let s=t.ratings[r]?.find(d=>d.scaleName===o)??t.ratings[r]?.[0];if(i[0]===o)return s;let a=s?.scaleName,c=Ke[s?.scaleName]?.accessor,u=c&&s.scaleValue[c]||s?.scaleValue,p=Up({sourceRatingType:a,sourceRating:u}),m=lL({targetRatingType:o,sourceRating:p});return m?{convertedRating:m,sourceRating:u}:{error:O}}function f0({participantResults:t,sides:e,score:r}){let n=e?.find(({sideNumber:a})=>a===1),o=e?.find(({sideNumber:a})=>a===2),i=n?.participant?.ratings,s=o?.participant?.ratings;if(i?.[Ct]&&s?.[Ct]){let a="ELO",{convertedRating:c}=Ob({ratings:i,targetRatingType:a}),{convertedRating:u}=Ob({ratings:s,targetRatingType:a}),{side1pressure:p,side2pressure:m}=Cq({side1ConvertedRating:c,side2ConvertedRating:u,score:r});p&&t[n?.participantId].pressureScores.push(p),m&&t[o?.participantId].pressureScores.push(m);let d=Math.max(...Ke["ELO"].range),l=xg((u-c)/d),f=xg((c-u)/d);t[n?.participantId].ratingVariation.push(l),t[o?.participantId].ratingVariation.push(f)}}function Cq({side1ConvertedRating:t,side2ConvertedRating:e,score:r}){let n=Math.max(t,e),o=Math.min(t,e),i=Math.abs(t-e),s=Ke["ELO"].range,a=Math.max(...s),c=(a-n)*0,p=(n+c)/a*i,m=r?.sets?.reduce((T,y)=>T+(y?.side1Score??0),0),d=r?.sets?.reduce((T,y)=>T+(y.side2Score??0),0),l=t>e?2:1,f=(m||0)*(o+(l===1?p:0)),g=(d||0)*(o+(l===2?p:0)),I=f+g,S=I?xg(f/I):0,h=I?xg(g/I):0;return{side1pressure:S,side2pressure:h}}function pS({winningSide:t,matchUpFormat:e=xn,matchUpStatus:r,tallyPolicy:n,score:o}){let i=[0,0],s=o?.sets,a=typeof t=="number"&&t-1,c=oe(e),u=_b(c?.bestOf??1);if(typeof a=="number"&&(r===Mt&&n?.setsCreditForDefaults||r===vt&&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===De&&(+i[1-a]===u&&(i[1-a]-=1),n?.setsCreditForRetirements&&(i[a]=u)),i}function PE({matchUpFormat:t=xn,winningSide:e,matchUpStatus:r,tallyPolicy:n,score:o}){let{sets:i}=o??{};if(!i)return[0,0];let s=typeof e=="number"&&e-1,a=oe(t),c=a?.bestOf??1,u=_b(c),p=a?.setFormat?.tiebreakAt||0,m=[[],[]];if(typeof s=="number"&&(r===Mt&&n?.gamesCreditForDefaults||r===vt&&n?.gamesCreditForWalkovers)){let d=a?.setFormat?.setTo||0,l=u*d;m[s].push(l)}else i.forEach((d,l)=>{let g=(d.setNumber||l+1)>u&&a?.finalSetFormat?"finalSetFormat":"setFormat",I=a?.[g]?.based,S=a?.[g].tiebreakSet,{side1Score:h,side2Score:T}=d;g0(I)&&!S&&(m[0].push(st(h||0)),m[1].push(st(T||0))),S&&d.winningSide&&n?.gamesCreditForTiebreakSets!==!1&&m[d.winningSide-1].push(1)});if(r===De&&typeof s=="number"){let d=i.length>u&&a?.finalSetFormat?"finalSetFormat":"setFormat",l=a?.[d];if(g0(l.based)){let f=l?.setTo||0,g=h=>{if(!(!a||h===""))return+h===p-1||+h===p?st(p||0)+1:+h<p?f:p},I=pS({winningSide:e,score:{sets:i},matchUpStatus:r,matchUpFormat:t,tallyPolicy:n});if(m.map(h=>h[s]<=h[1-s]).reduce((h,T)=>h+(T?1:0),0)>I[1-s]){let h=m[s].length,T=g(m[1-s][h-1]);T&&(m[s][h-1]=T)}u>m[s].length&&n?.gamesCreditForRetirements&&m[s].push(f)}}return[m[0].reduce((d,l)=>d+l,0),m[1].reduce((d,l)=>d+l,0)]}function NE({matchUpFormat:t,score:e}){let r=t?oe(t):void 0,n=r?.bestOf??1,o=_b(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(I0(m)){let{side1Score:d,side2Score:l}=a;d&&(s[0]+=st(d||0)),l&&(s[1]+=st(l||0))}else a.side1TiebreakScore&&(s[0]+=st(a.side1TiebreakScore||0)),a.side2TiebreakScore&&(s[1]+=st(a.side2TiebreakScore||0)),(a.side1TiebreakScore||a.side2TiebreakScore)&&a.winningSide&&(i[a.winningSide-1]+=1)}),{pointsTally:s,tiebreaksTally:i}}function _b(t){return t&&Math.ceil(t/2)||1}function I0(t){return t==="P"}function g0(t){return!I0(t)}function S0({participantResults:t,groupingTotal:e,matchUpFormat:r,tallyPolicy:n,totalGames:o,perPlayer:i,totalSets:s}){let a=(r&&oe(r))??{},c=a.bestOf,u=c&&Math.ceil(c/2)||1,p=a.setFormat?.setTo,m=Math.pow(10,n?.precision||3);Object.keys(t).forEach(d=>{let l=t[d].setsWon,f=t[d].setsLost,g=n?.groupTotalSetsPlayed||e==="setsPct"?s:i*(u||0)||l+f,I=Math.round(l/g*m)/m;(I===1/0||Number.isNaN(I))&&(I=g);let S=t[d].tieMatchUpsWon,h=t[d].tieMatchUpsLost,T=S+h,y=Math.round(S/T*m)/m;(y===1/0||Number.isNaN(y))&&(y=S);let E=t[d].matchUpsWon,A=t[d].matchUpsLost,N=E+A,D=Math.round(E/N*m)/m;(D===1/0||Number.isNaN(D))&&(D=E);let R=t[d].gamesWon||0,U=t[d].gamesLost||0,b=(i||0)*(u||0)*(p||0),C=n?.groupTotalGamesPlayed||e==="gamesPct"?o:Math.max(b,R+U),_=Math.round(R/C*m)/m;(_===1/0||Number.isNaN(_))&&(_=0);let v=t[d].pointsWon+t[d].pointsLost,w=Math.round(t[d].pointsWon/v*m)/m;(w===1/0||Number.isNaN(w))&&(w=0),t[d].setsWon=l,t[d].setsLost=f,t[d].setsPct=I,t[d].tieMatchUpsWon=S,t[d].tieMatchUpsPct=y,t[d].matchUpsPct=D,t[d].gamesWon=R,t[d].gamesLost=U,t[d].gamesPct=_,t[d].pointsPct=w,t[d].result=`${t[d].matchUpsWon}/${t[d].matchUpsLost}`})}function Vp({participantIds:t,pressureRating:e,groupingTotal:r,matchUpFormat:n,tallyPolicy:o,perPlayer:i,matchUps:s}){let a={},c=o?.excludeMatchUpStatuses??[],u=Mq({matchUps:s,excludeMatchUpStatuses:c,participantIds:t}),{totalSets:p,totalGames:m}=vq({filteredMatchUps:u,excludeMatchUpStatuses:c});for(let d of u??[]){let{matchUpStatus:l,tieMatchUps:f,tieFormat:g,score:I,winningSide:S,sides:h}=d,T=g&&d._disableAutoCalc&&g.collectionDefinitions.every(({scoreValue:A})=>A),y=S&&Fq(d),E=S&&kq(d);!y&&!E?i=Oq({participantResults:a,manualGamesOverride:T,matchUpStatus:l,tieMatchUps:f,perPlayer:i,score:I,sides:h}):(Pu(a,y),Pu(a,E),i=xq({winningParticipantId:y,losingParticipantId:E,manualGamesOverride:T,participantResults:a,pressureRating:e,matchUpFormat:n,matchUpStatus:l,tieMatchUps:f,tallyPolicy:o,winningSide:S,perPlayer:i,matchUp:d,score:I,sides:h})),T&&Lq({participantResults:a,score:I,sides:h})}return S0({participantResults:a,groupingTotal:r,matchUpFormat:n,tallyPolicy:o,totalGames:m,perPlayer:i,totalSets:p}),{participantResults:a}}function Mq({matchUps:t,excludeMatchUpStatuses:e,participantIds:r}){return t?.filter(n=>(n.tieMatchUps||!e.includes(n.matchUpStatus))&&(!r?.length||Yt(r,[Jl(n,0),Jl(n,1)]).length===2))}function vq({filteredMatchUps:t,excludeMatchUpStatuses:e}){let n=t?.flatMap(({score:a,tieMatchUps:c})=>c?c.filter(({matchUpStatus:u})=>!e.includes(u)).flatMap(({score:u})=>u?.sets?.length??0):a?.sets?.length??0)?.reduce((a,c)=>a+c,0),o=a=>a?.sets?.reduce((c,u)=>c+(u?.side1Score??0)+(u?.side2Score??0),0)??0,s=t?.flatMap(({score:a,tieMatchUps:c})=>c?c.filter(({matchUpStatus:u})=>!e.includes(u)).flatMap(({score:u})=>o(u)):o(a))?.reduce((a,c)=>a+c,0);return{totalSets:n,totalGames:s}}function Oq({participantResults:t,manualGamesOverride:e,matchUpStatus:r,tieMatchUps:n,perPlayer:o,score:i,sides:s}){if(r&&Ot.includes(r)){let a=Jl({sides:s},0),c=Jl({sides:s},1);a&&(Pu(t,a),t[a].matchUpsCancelled+=1),c&&(Pu(t,c),t[c].matchUpsCancelled+=1)}else if(n?.length){o=0;for(let a of n)a.winningSide&&_q({participantResults:t,tieMatchUp:a,sides:s}),T0({score:a.score,manualGamesOverride:e,participantResults:t,sides:s})}else T0({manualGamesOverride:e,participantResults:t,score:i,sides:s});return o}function _q({participantResults:t,tieMatchUp:e,sides:r}){let n=r?.find(({sideNumber:i})=>i===e.winningSide)?.participantId,o=r?.find(({sideNumber:i})=>i===e.winningSide)?.participantId;n&&o&&(Pu(t,n),Pu(t,o),t[n].tieMatchUpsWon+=1,t[o].tieMatchUpsLost+=1,re(Ct)(e.matchUpType)?(t[n].tieSinglesWon+=1,t[o].tieSinglesLost+=1):re(Rt)(e.matchUpType)&&(t[n].tieDoublesWon+=1,t[o].tieDoublesLost+=1))}function xq({winningParticipantId:t,losingParticipantId:e,manualGamesOverride:r,participantResults:n,pressureRating:o,matchUpFormat:i,matchUpStatus:s,tieMatchUps:a,tallyPolicy:c,winningSide:u,perPlayer:p,matchUp:m,score:d,sides:l}){if(a?.length){p=0;for(let f of a)f.winningSide&&wq({winningParticipantId:t,losingParticipantId:e,participantResults:n,tieMatchUp:f,winningSide:u}),y0({matchUpFormat:f.matchUpFormat,matchUpStatus:f.matchUpStatus,matchUpType:f.matchUpType,score:f.score,sides:f.sides,winningParticipantId:t,losingParticipantId:e,manualGamesOverride:r,participantResults:n,isTieMatchUp:!0,pressureRating:o,tallyPolicy:c,winningSide:u});E0({winningParticipantId:t,losingParticipantId:e,participantResults:n,matchUpStatus:s})}else y0({matchUpFormat:m.matchUpFormat??i,matchUpType:m.matchUpType,isTieMatchUp:void 0,winningParticipantId:t,manualGamesOverride:r,losingParticipantId:e,participantResults:n,pressureRating:o,matchUpStatus:s,tallyPolicy:c,winningSide:u,score:d,sides:l});return p}function wq({winningParticipantId:t,losingParticipantId:e,participantResults:r,tieMatchUp:n,winningSide:o}){let{matchUpType:i}=n,s=re(Rt)(i),a=re(Ct)(i),c=n.winningSide===o,u=c?t:e,p=c?e:t;h0(r,u,"Won",a,s),h0(r,p,"Lost",a,s)}function h0(t,e,r,n,o){e&&(t[e][`tieMatchUps${r}`]+=1,n&&(t[e][`tieSingles${r}`]+=1),o&&(t[e][`tieDoubles${r}`]+=1))}function Lq({participantResults:t,score:e,sides:r}){let n=e?.sets?.reduce((a,c)=>a+(c?.side1Score??0),0),o=e?.sets?.reduce((a,c)=>a+(c.side2Score??0),0),i=r?.find(({sideNumber:a})=>a===1)?.participantId,s=r?.find(({sideNumber:a})=>a===2)?.participantId;Pu(t,i),Pu(t,s),i&&(t[i].gamesWon+=n,t[i].gamesLost+=o),s&&(t[s].gamesWon+=o,t[s].gamesLost+=n)}function Fq(t){let e=t.winningSide-1;return Jl(t,e)}function kq(t){let e=1-(t.winningSide-1);return Jl(t,e)}function Jl(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 Pu(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 T0({manualGamesOverride:t,participantResults:e,score:r,sides:n}){let{sets:o}=r??{},i=[[],[]],s=[0,0];for(let c of o??[]){let{winningSide:u,side1Score:p,side2Score:m}=c;u&&(s[u-1]+=1),i[0].push(st(p||0)),i[1].push(st(m||0))}let a=[i[0].reduce((c,u)=>c+u,0),i[1].reduce((c,u)=>c+u,0)];n.forEach((c,u)=>{let{participantId:p}=c;p&&(Pu(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 y0({winningParticipantId:t,manualGamesOverride:e,losingParticipantId:r,participantResults:n,pressureRating:o,matchUpFormat:i,matchUpStatus:s,isTieMatchUp:a,matchUpType:c,tallyPolicy:u,winningSide:p,score:m,sides:d}){let l=p&&p-1,f=1-l;o&&c===Ct&&f0({participantResults:n,sides:d,score:m}),a||E0({winningParticipantId:t,losingParticipantId:r,participantResults:n,matchUpStatus:s});let g=pS({matchUpStatus:s,matchUpFormat:i,tallyPolicy:u,winningSide:p,score:m}),I=PE({matchUpStatus:s,matchUpFormat:i,tallyPolicy:u,winningSide:p,score:m}),{pointsTally:S}=NE({score:m,matchUpFormat:i});t&&(n[t].setsWon+=g[l],n[t].setsLost+=g[f],e||(n[t].gamesWon+=I[l],n[t].gamesLost+=I[f]),n[t].pointsWon+=S[l],n[t].pointsLost+=S[f]),r&&(n[r].setsWon+=g[f],n[r].setsLost+=g[l],e||(n[r].gamesWon+=I[f],n[r].gamesLost+=I[l]),n[r].pointsWon+=S[f],n[r].pointsLost+=S[l])}function E0({winningParticipantId:t,losingParticipantId:e,participantResults:r,matchUpStatus:n}){e&&(n===vt&&(r[e].walkovers+=1),n===Mt&&(r[e].defaults+=1),n===De&&(r[e].retirements+=1),Ye(n)&&(r[e].allDefaults+=1),r[e].matchUpsLost+=1),t&&(r[t].matchUpsWon+=1),e&&t&&(r[e].defeats.push(t),r[t].victories.push(e))}function Gq(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 Vq(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)}Gq(t,r,n,o)}n.push("----------------------")}function A0({matchUps:t,order:e,report:r}){let n={};t.forEach(({sides:i})=>{i.forEach(s=>{s.participantId&&s.participant&&(n[s.participantId]=s.participant.participantName)})});let o=[];return Array.isArray(r)&&r.forEach((i,s)=>{Vq(i,s,n,o)}),o.push("Final Order:"),e.forEach(i=>{let{participantId:s,resolved:a}=i,c=i.groupOrder||i.provisionalOrder;o.push(`${c}: ${n[s]} => resolved: ${!!a}`)}),o.join(`\r
|
|
4
4
|
`)}function xb({participantResults:t,participantIds:e,attribute:r}){return wb({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 wb(t){return(t.participantIds||Object.keys(t.participantResults)).reduce((r,n,o)=>(r.push({participantId:n,i:o,results:t.participantResults[n]}),r),[])}var Bq=[{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}],Lb={matchUpsPct:20,tieMatchUpsPct:16,pointsPct:4,gamesPct:8,setsPct:12};function Fb(t){let{requireCompletion:e=!0,participantResults:r,subOrderMap:n,tallyPolicy:o}=t,i=[];if(e&&!Wq(t))return{};let s=["tieMatchUpsWon","tieSinglesWon","tieDoublesWon","matchUpsWon","pointsWon","gamesWon","setsWon","gamesPct","setsPct","pointsPct","matchUpsPct"].includes(o?.groupOrderKey)?o.groupOrderKey:"matchUpsWon",a=xb({participantResults:r,attribute:s});i.push({attribute:s,groups:a});let p=Object.keys(a).map(h=>Number.parseFloat(h)).sort((h,T)=>T-h).map(h=>a[h]).map(h=>{let T=P0({participantIds:h,...t});return i.push(...T.report??[]),T.order}).flatMap((h,T)=>h.map(y=>y.resolved?y:{...y,subGroup:[T].concat(...y.subGroup??[])})),m,d=0,l=1,f;p.forEach((h,T)=>{T&&(h.resolved||f&&!h.resolved)&&(l+=1),f=h.resolved;let y=Number.parseInt(h.subGroup?.join("")||0);h.resolved?(h.position=T+1,l=h.position):(m&&y>m&&(l+=d,d=0),h.position=l,d+=1),m=y});let g=p.map(({position:h})=>h),I=mn(g);return p.forEach(h=>{let{participantId:T,position:y}=h??{},E=r[T];h.GEMscore=S(E);let A=I[y];h?.position!==void 0&&(A>1&&(h.ties=A,n&&(h.subOrder=n[T])),h.rankOrder=y,h.groupOrder=y+(h.subOrder||1)-1)}),{groupOrder:p,report:i.flat(1/0).filter(Boolean)};function S(h){return(Array.isArray(o?.GEMscore)?Object.keys(Lb).filter(E=>o.GEMscore.includes(E)):Object.keys(Lb)).map(E=>(h[E]||0)*Math.pow(10,Lb[E].toFixed(3))).reduce((E,A)=>E+A,0)}}function Wq({participantResults:t,participantsCount:e}){let n=wb({participantResults:t}).filter(o=>e-1===o.results.matchUpsWon+o.results.matchUpsLost+o.results.matchUpsCancelled);return e===n.length}function Hq({disableHeadToHead:t,participantIds:e,matchUpFormat:r,groupTotals:n,tallyPolicy:o,attribute:i,idsFilter:s,matchUps:a,reversed:c}){let{participantResults:u}=Vp({participantIds:s&&e,groupingTotal:n&&i,matchUpFormat:r,tallyPolicy:o,matchUps:a}),p=xb({participantResults:u,participantIds:e,attribute:i}),m=[{attribute:i,reversed:c,groups:p,idsFilter:s,groupTotals:n}],d;return Object.keys(p).length>1&&e.length&&(d=Object.keys(p).map(g=>Number.parseFloat(g)).sort((g,I)=>c?g-I:I-g).map(g=>p[g]).map(g=>{let I=P0({participantResults:u,disableHeadToHead:t,participantIds:g,matchUpFormat:r,tallyPolicy:o,matchUps:a});return m.push(...I.report??[]),I.order}).flatMap((g,I)=>g.map(S=>S.resolved?S:{...S,subGroup:[I].concat(...S.subGroup??[])}))),{order:d,report:m}}function P0({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=Yq({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||Bq).filter(m=>{let d=!(Le(m.maxParticipants)&&r?.length>m.maxParticipants);return d||s.push(m),d});return s.length&&a.push({excludedDirectives:s,participantIds:r}),p.every(({attribute:m,reversed:d,idsFilter:l,groupTotals:f,disableHeadToHead:g})=>(c=Hq({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 Yq({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 ea({policyDefinitions:t,generateReport:e,pressureRating:r,matchUpFormat:n,matchUps:o=[],subOrderMap:i,perPlayer:s}){if(!o?.length||!Rr(o))return{error:Bn};let a=pt(o.map(({structureId:y})=>y));if(a.length!==1)return M({result:{error:O,info:"Maximum one structureId"},stack:"tallyParticipantResults",context:{structureIds:a}});let c=o.filter(y=>y&&y.matchUpStatus!=="BYE"),u=c.length&&pt(c.flatMap(({drawPositions:y})=>y)).length,p=c.filter(y=>Js({matchUp:y})).length===c.length;p||(s=0);let m=o.every(({matchUpType:y,tieMatchUps:E})=>y===xt&&E?.every(A=>Js({matchUp:A}))),d=t?.[vI],l=o.filter(y=>Js({matchUp:y})??y.matchUpType===xt),{participantResults:f}=Vp({matchUps:l,pressureRating:r,matchUpFormat:n,tallyPolicy:d,perPlayer:s}),g,I,{groupOrder:S,report:h}=Fb({matchUps:l,participantResults:f,participantsCount:u,matchUpFormat:n,subOrderMap:i,tallyPolicy:d});if(r&&jq({participantResults:f}),p&&S)g=h,I=S,S.forEach(y=>{let{participantId:E,groupOrder:A,rankOrder:N,subOrder:D,ties:R,GEMscore:U}=y,b=f[E];Object.assign(b,{groupOrder:A,rankOrder:N,GEMscore:U,subOrder:D,ties:R})});else{let{groupOrder:y,report:E}=Fb({requireCompletion:!1,participantResults:f,participantsCount:u,matchUpFormat:n,tallyPolicy:d,subOrderMap:i,matchUps:o});g=E,I=y,y&&y.forEach(A=>{let{participantId:N,groupOrder:D,subOrder:R,ties:U,GEMscore:b}=A,C=f[N];Object.assign(C,{provisionalOrder:D,GEMscore:b,subOrder:R,ties:U})})}let T={completedTieMatchUps:m,readableReport:"",participantResults:f,bracketComplete:p,order:[],report:g};if((p||m)&&(T.order=I),e||je({tally:!0})){let y=A0({matchUps:o,report:g,order:I});je({tally:!0})&&console.log(y),T.readableReport=y}return T}function jq({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 N0({publishedSeeding:t,usePublishState:e,withSeeding:r,participant:n,event:o}){let i={},s=m=>[ci,Eo,o.eventType,m].join("."),a=Object.assign({},...(n.timeItems??[]).filter(({itemType:m})=>m.split(".")[1]===Eo).map(({itemType:m,itemValue:d})=>({[m]:d}))),c=(t?.stageSeedingScaleNames&&Object.values(t?.stageSeedingScaleNames)||Array.isArray(t?.seedingScaleNames)&&t.seedingScaleNames||[]).map(s),u=Yt(Object.keys(a),c);if(!!(!e||!Object.keys(a).length&&!t?.drawIds?.length||u.length)&&u.length){if(t?.stageSeedingScaleNames){let m=Object.keys(t.stageSeedingScaleNames).map(l=>{let f=s(t.stageSeedingScaleNames[l]),g=a[f];return[l,g]}).filter(l=>l[1]).map(l=>({[l[0]]:{seedValue:l[1]}})),d=Object.assign({},...m);i.seedAssignments=d}else if(u){let m=u.map(d=>a[d]);i.seedValue=m.pop()}}else if(!e&&typeof r=="object"){let m=Object.keys(r).map(l=>{let f=s(r[l]),g=a[f];return[l,g]}).filter(l=>l[1]).map(l=>({[l[0]]:{seedValue:l[1]}})),d=Object.assign({},...m);i.seedAssignments=d}else{let{categoryName:m,ageCategoryCode:d}=o.category??{},l=[d,o.eventId,m].filter(Boolean),f;for(let g of l){let I={eventType:o.eventType,scaleType:Eo,scaleName:g},S=Po({scaleAttributes:I,participant:n});if(S.scaleItem){f=S.scaleItem;break}}if(f&&(!e||t?.published&&!t?.published?.drawIds?.length)){let I=f.scaleValue;i.seedValue=I}}return i}function Zl({positionAssignments:t}){let e=(t??[]).filter(Vr(sr)).map(i=>{let{extension:s}=ot({element:i,name:du}),a=st(s?.value),c=!isNaN(a)&&a;return c&&{participantId:i.participantId,subOrder:c}}).filter(Boolean),r=e.map(({subOrder:i})=>i),n=mn(r);return{subOrderMap:Object.assign({},...e.filter(({subOrder:i})=>n[i]===1).map(({participantId:i,subOrder:s})=>({[i]:s})))}}function D0({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({},...TI(m??[])):{},l=Object.assign(d,{entryPosition:p,entryStatus:c,entryStage:u,ranking:s,eventId:i});r.events[i]=et(l,!1,!1,!0),n&&(e&&(r.events[i].seedAssignments=e),o&&(r.events[i].seedValue=o))}function Uc(t){let e=X(t,[{[rt]:!0}]);if(e.error)return e;let{tournamentRecord:r,status:n=br}=t,o=`${qo}.${$o}`;return q(_l({tournamentRecord:r,itemType:o})?.timeItem?.itemValue?.[n],!1,!0)}function U0(t){let{tournamentId:e}=t??{};return!!e}function Cr({event:t,status:e=br}){let r=`${qo}.${$o}`;return xp({itemType:r,event:t})?.timeItem?.itemValue?.[e]}function Bp({drawDetails:t,drawId:e,ignoreEmbargo:r=!1}){let n=t?.[e]?.publishingDetail;return r?!!n?.published:ro(n)}function ra(t){let{tournamentRecord:e,drawDefinition:r,eventIds:n,eventId:o,drawIds:i,drawId:s,event:a}=t??{};if(e&&!U0(e))return{error:O};if(o&&!a)return{error:Wr};if(Array.isArray(n)&&n?.length){let d={};for(let l of n){if(!wt(l))return{error:O};let f=_e({tournamentRecord:e,eventId:l})?.event;if(!f)return{error:Wr};let g=kb({event:f});d[l]=g}return{...P,publishState:d}}if(a)return qq({event:a,drawId:s,drawIds:i,drawDefinition:r});let c={},{publishedEventIds:u,tournamentPublished:p}=$q({publishState:c,tournamentRecord:e}),m=[];return e&&Kq({tournamentPublished:p,publishedEventIds:u,tournamentRecord:e,publishState:c,embargoes:m}),zq({tournamentRecord:e,embargoes:m}),m.length&&(c.embargoes=m),{...P,publishState:c}}function qq({event:t,drawId:e,drawIds:r,drawDefinition:n}){let o=kb({event:t}),i={};if(e)return n?{publishState:{status:{published:!!o.status.publishedDrawIds?.includes(e),drawDetail:o.status.drawDetails?.[e]},...P}}:{error:Mr};if(Array.isArray(r)&&r?.length){let s=t.drawDefinitions?.map(Tc)??[];for(let a of r){if(!wt(a))return{error:O};if(!s.includes(a))return{error:Mr};i[a]={status:{published:!!o.status.publishedDrawIds.includes(a),drawDetail:o.status.drawDetails?.[a]}}}}else i=o;return{...P,publishState:i}}function $q({publishState:t,tournamentRecord:e}){let r=[],n=!1;for(let o of e?.events??[]){let i=kb({event:o});t[o.eventId]=i,i.status.published&&(r.push(o.eventId),n=!0);for(let{drawId:s}of o.drawDefinitions??[]){let a=i.status?.publishedDrawIds?.includes(s);a&&(t[s]={status:{published:a}})}}return{publishedEventIds:r,tournamentPublished:n}}function Kq({publishState:t,tournamentRecord:e,tournamentPublished:r,publishedEventIds:n,embargoes:o}){let i=Uc({tournamentRecord:e});return t.tournament=i??{},(i?.orderOfPlay?.published||i?.participants?.published)&&(r=!0),t.tournament.status={published:r,publishedEventIds:n},i?.orderOfPlay?.embargo&&o.push({type:"orderOfPlay",embargo:i.orderOfPlay.embargo,embargoActive:Uo(i.orderOfPlay)}),i?.participants?.embargo&&o.push({type:"participants",embargo:i.participants.embargo,embargoActive:Uo(i.participants)}),r}function zq({tournamentRecord:t,embargoes:e}){for(let r of t?.events??[]){let o=Cr({event:r})?.drawDetails??{};for(let[i,s]of Object.entries(o))Qq({drawId:i,detail:s,embargoes:e})}}function Qq({drawId:t,detail:e,embargoes:r}){e?.publishingDetail?.embargo&&r.push({type:"draw",id:t,embargo:e.publishingDetail.embargo,embargoActive:Uo(e.publishingDetail)});for(let[n,o]of Object.entries(e?.stageDetails??{}))o?.embargo&&r.push({type:"stage",id:`${t}:${n}`,embargo:o.embargo,embargoActive:Uo(o)});for(let[n,o]of Object.entries(e?.structureDetails??{}))o?.embargo&&r.push({type:"structure",id:n,embargo:o.embargo,embargoActive:Uo(o)}),Xq({structureId:n,structureDetail:o,embargoes:r})}function Xq({structureId:t,structureDetail:e,embargoes:r}){if(e?.scheduledRounds)for(let[n,o]of Object.entries(e.scheduledRounds))o?.embargo&&r.push({type:"scheduledRound",id:`${t}:round${n}`,embargo:o.embargo,embargoActive:Uo(o)})}function kb({event:t}){let e=Cr({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(Tc)??[])n[a]||(n[a]={publishingDetail:{published:!1}});let o=n&&Object.keys(n).length&&Object.keys(n).filter(a=>Bp({drawDetails:n,drawId:a,ignoreEmbargo:!0})),i=o?.length?o:e.drawIds??[];if(i?.length&&!o?.length)for(let a of i)n[a]={publishingDetail:{published:!0}};let s=i?.length>0;return{status:{publishedDrawIds:i,publishedSeeding:r,drawDetails:n,published:s}}}function DE(t){let{participantMap:e,participantId:r,matchUpStatus:n,roundPosition:o,structureId:i,matchUpType:s,roundNumber:a,matchUpId:c,potential:u,schedule:p,drawId:m,score:d}=t;if(!p||!Object.keys(p).length)return;n==="BYE"||e[r].scheduleItems.push({...p,scheduledDate:mt(p?.scheduledDate),scheduledTime:$t(p?.scheduledTime),checkScoreHasValue:ue({score:d}),matchUpStatus:n,roundPosition:o,structureId:i,matchUpType:s,roundNumber:a,matchUpId:c,potential:u,drawId:m})}function R0({finishingPositionRange:t={winner:[],loser:[]},collectionPosition:e,participantMap:r,finishingRound:n,participantWon:o,collectionId:i,matchUpStatus:s,participantId:a,stageSequence:c,roundNumber:u,structureId:p,matchUpId:m,drawId:d,stage:l}){let f=r[a],g=y=>Math.abs(y[0]-y[1]);f.structureParticipation[p]||(f.structureParticipation[p]={rankingStage:l,walkoverWinCount:0,defaultWinCount:0,stageSequence:c,winCount:0,structureId:p,drawId:d});let I=f.structureParticipation[p],{winner:S,loser:h}=t,T=o?S:h;o&&(I.winCount+=1,s===vt&&(I.walkoverWinCount+=1),s===Mt&&(I.defaultWinCount+=1)),T&&(!I.finishingPositionRange||g(T)<g(I.finishingPositionRange))&&(I.finishingPositionRange=T),n&&((!I.finishingRound||n<I.finishingRound)&&(I.finishingMatchUpId=m,I.finishingRound=n,I.roundNumber=u),n===1&&(I.participantWon=o)),e&&(I.lineParticipation||(I.lineParticipation=[]),I.lineParticipation.push({collectionPosition:e,collectionId:i,won:o}))}function Gb(t){let{withScheduleItems:e,scheduleAnalysis:r,withTeamMatchUps:n,participantMap:o,withOpponents:i,withMatchUps:s,withEvents:a,withDraws:c,finishingPositionRange:u,finishingRound:p,matchUpStatus:m,stageSequence:d,roundNumber:l,structureId:f,score:g,stage:I,withRankingProfile:S,collectionPosition:h,tieWinningSide:T,roundPosition:y,matchUpTieId:E,matchUpSides:A,collectionId:N,matchUpType:D,winningSide:R,matchUpId:U,schedule:b,eventId:C,drawId:_,sides:v}=t,w=i&&v?.length===2&&Object.assign({},...v.map(({sideNumber:L},F)=>{let x=v[1-F].participantId;return L&&{[L]:x}}).filter(Boolean));for(let L of v){let{participantId:F,sideNumber:x,bye:k}=L;if(k)continue;let G=R===x,V=H=>{let K=o[H]?.participant,Y=K?.participantType,J=[{participantId:H,participantType:Y}];if(Y!==ur)for(let ct of K?.individualParticipantIds??[]){let Et=o[ct]?.participant;J.push({participantType:Et?.participantType,participantId:ct})}return J},B=(H,K)=>{if(s){if(o[H].matchUps[U]={participantWon:G,matchUpType:D,structureId:f,sideNumber:x,matchUpId:U,eventId:C,drawId:_,stage:I},i){let Y=V(K);o[H].matchUps[U].opponentParticipantInfo=Y}N&&(o[H].matchUps[U].collectionId=N)}i&&K&&(o[H].opponents[K]={participantId:K,matchUpId:U,eventId:C,drawId:_}),S&&R&&R0({finishingPositionRange:u,collectionPosition:h,participantMap:o,participantWon:G,collectionId:N,finishingRound:p,matchUpStatus:m,participantId:H,stageSequence:d,roundNumber:l,structureId:f,matchUpId:U,drawId:_,stage:I}),(r||e)&&DE({participantMap:o,participantId:H,matchUpStatus:m,roundPosition:y,matchUpType:D,roundNumber:l,structureId:f,matchUpId:U,schedule:b,drawId:_,score:g})},z=({participant:H,partnerParticipantId:K})=>{let Y=(J,ct)=>{J&&(J.partnerParticipantIds??=[],J.partnerParticipantIds.includes(ct)||J.partnerParticipantIds.push(ct))};c&&Y(H?.draws?.[_],K),a&&Y(H?.events?.[C],K),s&&Y(H?.matchUps?.[U],K)};if(F&&o[F]){let H=w?.[x];B(F,H);let K=o[F]?.participant.participantType===lt,Y=o[F]?.participant.individualParticipantIds??[];E&&Jq({individualParticipantIds:Y,tieWinningSide:T,withTeamMatchUps:n,participantMap:o,matchUpSides:A,matchUpTieId:E,sideNumber:x,participantId:F,withDraws:c,eventId:C,drawId:_}),K&&Zq({individualParticipantIds:Y,opponentParticipantId:H,participantMap:o,matchUpSides:A,participantId:F,sideNumber:x,withEvents:a,addMatchUp:B,addPartner:z,eventId:C}),R&&t$({individualParticipantIds:Y,participantMap:o,participantWon:G,matchUpStatus:m,participantId:F,matchUpType:D})}}}function Jq({individualParticipantIds:t,tieWinningSide:e,withTeamMatchUps:r,participantMap:n,matchUpSides:o,matchUpTieId:i,sideNumber:s,participantId:a,withDraws:c,eventId:u,drawId:p}){if(r){let m=d=>n[d].matchUps[i]={participantWon:e===s,matchUpId:i,matchUpType:xt,sideNumber:s};m(a),t.forEach(m)}if(c&&!n[a].draws[p]){let m=o.find(f=>f.sideNumber===s)?.participant?.participantId,d=n[m]?.draws?.[p]?.entryStatus,l=f=>n[f].draws[p]={entryStatus:d,eventId:u,drawId:p};l(a),t.forEach(l)}}function Zq({individualParticipantIds:t,opponentParticipantId:e,participantMap:r,matchUpSides:n,participantId:o,sideNumber:i,withEvents:s,addMatchUp:a,addPartner:c,eventId:u}){if(t.forEach(p=>r[p]&&a(p,e)),t.forEach((p,m)=>{let d=t[1-m],l=r[p];l&&c({participant:l,partnerParticipantId:d})}),s&&n){let p=n.find(m=>m.sideNumber===i)?.participant?.participantId;if(p){let m=r[p]?.events[u];m?(r[o].events[u]={...m},t.forEach(d=>r[d].events[u]={...m})):console.log("Missing teamEntry",{eventId:u,teamParticipantId:p})}}}function t$({individualParticipantIds:t,participantMap:e,participantWon:r,matchUpStatus:n,participantId:o,matchUpType:i}){let s=a=>{r?(e[a].counters[i].wins+=1,e[a].counters.wins+=1,n===vt&&(e[a].counters[i].walkoverWins+=1,e[a].counters.walkoverWins+=1),n===Mt&&(e[a].counters[i].defaultWins+=1,e[a].counters.defaultWins+=1)):(e[a].counters[i].losses+=1,e[a].counters.losses+=1,n===vt&&(e[a].counters[i].walkovers+=1,e[a].counters.walkovers+=1),n===Mt&&(e[a].counters[i].defaults+=1,e[a].counters.defaults+=1))};s(o),t.forEach(s)}function Wp(t,e){return(t||"").localeCompare(e||"")}function C0(t){let{participantFilters:e,convertExtensions:r,policyDefinitions:n,tournamentRecord:o,usePublishState:i,contextFilters:s,matchUpFilters:a,participantMap:c,contextProfile:u,withPotentialMatchUps:p,withRankingProfile:m,withScheduleItems:d,scheduleAnalysis:l,withTeamMatchUps:f,withStatistics:g,withOpponents:I,withMatchUps:S,withSeeding:h,withEvents:T,withDraws:y}=t,E=e?.participantIds,A=x=>{let k=[x];return c[x]?.participant.individualParticipantIds?.forEach(G=>k.push(G)),k.some(G=>!E?.length||E.includes(G))?k:[]},N={withMatchUps:S||m,withEvents:T||m,withDraws:y||m,withPotentialMatchUps:p,withRankingProfile:m,withScheduleItems:d,scheduleAnalysis:l,withTeamMatchUps:f,withStatistics:g,participantMap:c,withOpponents:I,withSeeding:h},D=[],R={},U=[],b={},C={},_={},v={},w={},L=({eventType:x,scaleNames:k,participantId:G})=>c[G]?.participant?.rankings?.[x]?.find(V=>k.includes(V.scaleName))?.scaleValue;for(let x of o?.events??[])e?.eventIds&&!e.eventIds.includes(x.eventId)||e$({convertExtensions:r,eventsPublishStatuses:b,derivedEventInfo:C,derivedDrawInfo:_,participantMap:c,getRanking:L,withOpts:N,event:x,getRelevantParticipantIds:A,withPotentialMatchUps:p,withRankingProfile:m,withScheduleItems:d,scheduleAnalysis:l,withTeamMatchUps:f,policyDefinitions:n,tournamentRecord:o,withStatistics:g,rrContainerInfo:w,rrGroupMatchUps:v,mappedMatchUps:R,contextFilters:s,matchUpFilters:a,contextProfile:u,withOpponents:I,usePublishState:i,withMatchUps:S,withSeeding:h,withEvents:T,withDraws:y,matchUps:U});let F=c$(v,w,m);if(g||m||l){let x=p$({rrFinishingPositions:F,withRankingProfile:m,scheduleAnalysis:l,withStatistics:g,derivedDrawInfo:_,participantMap:c});D.push(...x)}return{participantIdsWithConflicts:D,eventsPublishStatuses:b,derivedEventInfo:C,derivedDrawInfo:_,mappedMatchUps:R,participantMap:c,matchUps:U}}function e$({convertExtensions:t,eventsPublishStatuses:e,derivedEventInfo:r,derivedDrawInfo:n,participantMap:o,getRanking:i,withOpts:s,event:a,getRelevantParticipantIds:c,withPotentialMatchUps:u,withRankingProfile:p,withScheduleItems:m,scheduleAnalysis:d,withTeamMatchUps:l,policyDefinitions:f,tournamentRecord:g,withStatistics:I,rrContainerInfo:S,rrGroupMatchUps:h,mappedMatchUps:T,contextFilters:y,matchUpFilters:E,contextProfile:A,withOpponents:N,usePublishState:D,withMatchUps:R,withSeeding:U,withEvents:b,withDraws:C,matchUps:_}){let{drawDefinitions:v=[],extensions:w=[],wheelchairClass:L,eventType:F,eventName:x,category:k,entries:G,eventId:V,gender:B}=a,{flightProfile:z}=Bt({event:a}),H=z?.flights??[],K=ra({event:a}).publishState;K&&(e[V]=K);let Y=K?.status?.publishedSeeding;if(b||U||p){let ct=t?Object.assign({},...TI(w??[])):{};r[V]={...ct,wheelchairClass:L,eventName:x,eventType:F,category:k,eventId:V,gender:B};let Et=[k?.categoryName,k?.ageCategoryCode].filter(Boolean);for(let Ht of G){let{participantId:Ut}=Ht;if(!Ut||!o[Ut])continue;let pe=i({eventType:F,scaleNames:Et,participantId:Ut}),ye,Jt;if(U){let zr=o[Ut].participant;({seedAssignments:ye,seedValue:Jt}=N0({publishedSeeding:Y,usePublishState:D,withSeeding:U,participant:zr,event:a}))}let pr=zr=>{if(o[zr]?.events?.[V])return;let so=o[zr];D0({convertExtensions:t,seedAssignments:ye,participant:so,withSeeding:U,seedValue:Jt,eventId:V,ranking:pe,entry:Ht})};pr(Ut),(o[Ut].participant.individualParticipantIds??[]).forEach(pr)}}let J=e?.[V]?.publishedSeeding;if(C||p||U){let ct=pt([...v.map(Tc),...H.map(Tc)]);for(let Et of ct)n$({drawDefinitions:v,participantMap:o,derivedDrawInfo:n,eventPublishedSeeding:J,usePublishState:D,withRankingProfile:p,withSeeding:U,withDraws:C,eventType:F,category:k,eventId:V,flights:H,drawId:Et,getRanking:i})}if(p||d||l||I||N||R||C){let ct=!!d||u,Et=vn({afterRecoveryTimes:!!d,policyDefinitions:f,tournamentRecord:g,inContext:!0,participantMap:o,contextFilters:y,matchUpFilters:E,contextProfile:A,nextMatchUps:ct,event:a})?.matchUps??[];for(let Ht of Et)o$({getRelevantParticipantIds:c,withScheduleItems:m,tournamentRecord:g,drawDefinitions:v,scheduleAnalysis:d,withRankingProfile:p,rrContainerInfo:S,rrGroupMatchUps:h,mappedMatchUps:T,participantMap:o,nextMatchUps:ct,withOpts:s,matchUp:Ht});_.push(...Et)}}function b0(t){return t?Object.assign({},...t.map(({participantId:e,seedValue:r,seedNumber:n})=>({[e]:{seedValue:r,seedNumber:n}}))):void 0}function r$({participantMap:t,id:e,participantId:r,eventId:n,eventType:o,drawId:i,mainSeedingMap:s,qualifyingSeedingMap:a,seedingPublished:c,withSeeding:u}){let p=u&&c,m=p?{}:void 0,d=p?s?.[r]?.seedValue||s?.[r]?.seedNumber:void 0,l=d?s?.[r]:void 0,f=p?a?.[r]?.seedValue||a?.[r]?.seedNumber:void 0,g=f?a?.[r]:void 0;m&&d&&(m[W]=l),m&&f&&(m[Z]=g);let I=d||f;return I&&(t[e].participant.seedings[o]||(t[e].participant.seedings[o]=[]),l&&t[e].participant.seedings[o].push({...l,scaleName:i}),g&&t[e].participant.seedings[o].push({...g,scaleName:i}),m&&(t[e].events[n].seedAssignments||(t[e].events[n].seedAssignments={}),Object.keys(m).forEach(S=>t[e].events[n].seedAssignments[S]=m[S]))),{seedAssignments:m,seedValue:I}}function n$({drawDefinitions:t,participantMap:e,derivedDrawInfo:r,eventPublishedSeeding:n,usePublishState:o,withRankingProfile:i,withSeeding:s,withDraws:a,eventType:c,category:u,eventId:p,flights:m,drawId:d,getRanking:l}){let f=t.find(G=>G.drawId===d),g=[u?.categoryName,u?.ageCategoryCode].filter(Boolean),{structures:I=[],drawOrder:S,drawName:h,drawType:T}=f??{},y=m?.find(G=>G.drawId===d),E=f?.entries||y?.drawEntries,A=y?.flightNumber,N=(f?.structures??[]).sort((G,V)=>Hi(G,V)).map(({structureId:G,structures:V})=>[G,...(V??[]).map(({structureId:B})=>B)]).flat(1/0),D,R,U,b,C=0,_=new Set(I.filter(({stage:G,stageSequence:V})=>G===W&&V===1||G===Z).flatMap(G=>{let{positionAssignments:V}=Pt({structure:G}),{seedAssignments:B,stageSequence:z,stage:H}=G;return H===W?(C=V?.length??0,U=V,b=B):z===1&&(D=V,R=B),V}).map(({participantId:G})=>G).filter(Boolean)),v=b0(b),w=b0(R),L=f?E.filter(({participantId:G})=>_.has(G)):E,F=!o||n?.published&&(n?.drawIds?.length===0||n?.drawIds?.includes(d));for(let G of L){if(!e[G.participantId])continue;let{entryStatus:V,entryStage:B,entryPosition:z,participantId:H}=G,K=l({participantId:H,scaleNames:g,eventType:c}),Y=J=>{if(!e[J]||e[J].draws?.[d])return;let{seedAssignments:ct,seedValue:Et}=r$({participantMap:e,id:J,participantId:H,eventId:p,eventType:c,drawId:d,mainSeedingMap:v,qualifyingSeedingMap:w,seedingPublished:F,withSeeding:s});(a||i)&&(e[J].draws[d]=et({seedAssignments:ct,entryPosition:z,entryStatus:V,entryStage:B,seedValue:Et,eventId:p,ranking:K,drawId:d},!1,!1,!0))};[Gr,qi].includes(V)||(Y(H),(e[H].participant.individualParticipantIds??[])?.forEach(Y))}let x=(f?.structures??[]).reduce((G,V)=>(G.includes(V.stage)||G.push(V.stage),G),[]),k=(f?.links??[]).length;r[d]={qualifyingPositionAssignments:D,qualifyingSeedAssignments:R,mainPositionAssignments:U,qualifyingSeedingMap:w,mainSeedAssignments:b,orderedStructureIds:N,mainSeedingMap:v,flightNumber:A,linksCount:k,drawOrder:S,drawName:h,drawType:T,drawSize:C,drawId:d,stages:x}}function o$({getRelevantParticipantIds:t,withScheduleItems:e,tournamentRecord:r,drawDefinitions:n,scheduleAnalysis:o,withRankingProfile:i,rrContainerInfo:s,rrGroupMatchUps:a,mappedMatchUps:c,participantMap:u,nextMatchUps:p,withOpts:m,matchUp:d}){let{finishingPositionRange:l,potentialParticipants:f,tieMatchUps:g=[],sides:I=[],winningSide:S,matchUpType:h,matchUpId:T,eventId:y,drawId:E,collectionId:A,containerStructureId:N,stageSequence:D,finishingRound:R,matchUpStatus:U,roundPosition:b,roundNumber:C,structureId:_,schedule:v,score:w,stage:L}=d;if(c[T]=d,i&&N&&_&&E&&(a[_]||(a[_]=[]),a[_].push(d),!s[N])){let x=n.find(k=>k.drawId===E);x&&(s[N]={drawDefinition:x,drawId:E})}let F={finishingPositionRange:l,containerStructureId:N,finishingRound:R,stageSequence:D,roundPosition:b,collectionId:A,roundNumber:C,structureId:_,schedule:v,eventId:y,drawId:E,score:w,stage:L};Gb({tournamentRecord:r,drawDefinitions:n,...F,...m,matchUpStatus:U,winningSide:S,matchUpType:h,matchUpId:T,sides:I});for(let x of g){let{winningSide:k,sides:G=[],matchUpId:V,collectionPosition:B,collectionId:z,matchUpStatus:H,matchUpType:K}=x;Gb({...F,...m,winningSide:k,tieWinningSide:S,matchUpTieId:T,matchUpId:V,sides:G,collectionId:z,collectionPosition:B,matchUpSides:I,matchUpStatus:H,matchUpType:K})}Array.isArray(f)&&(p||o||e)&&i$({getRelevantParticipantIds:t,potentialParticipants:f,withScheduleItems:e,tournamentRecord:r,scheduleAnalysis:o,participantMap:u,matchUpStatus:U,roundPosition:b,structureId:_,matchUpType:h,roundNumber:C,matchUpId:T,schedule:v,eventId:y,drawId:E,score:w})}function i$({getRelevantParticipantIds:t,potentialParticipants:e,withScheduleItems:r,tournamentRecord:n,scheduleAnalysis:o,participantMap:i,matchUpStatus:s,roundPosition:a,structureId:c,matchUpType:u,roundNumber:p,matchUpId:m,schedule:d,eventId:l,drawId:f,score:g}){e.flat().map(gt).filter(Boolean)?.forEach(S=>{t(S)?.forEach(T=>{i[T]&&(i[T].potentialMatchUps[m]=et({tournamentId:n?.tournamentId,matchUpId:m,eventId:l,drawId:f}))}),(o||r)&&DE({potential:!0,participantMap:i,participantId:S,matchUpStatus:s,roundPosition:a,structureId:c,matchUpType:u,roundNumber:p,matchUpId:m,schedule:d,drawId:f,score:g})})}function s$({drawPositionsCount:t,containerStructureId:e,bracketsCount:r,playoffStructure:n,drawDefinition:o,bracketSize:i,order:s}){if(t===i&&s)return[s,s];if(r>1&&s&&!n)return[1,r];if(r>1&&s&&n){let a=o.links?.find(c=>c.source.structureId===e)?.source?.finishingPositions;if(a){let c=a.length*r;if(a.includes(s))return[1,c];let u=(i-s)*r;return[c+1,t-u]}}}function a$({containedStructure:t,rrGroupMatchUps:e,drawPositionsCount:r,containerStructureId:n,bracketsCount:o,playoffStructure:i,drawDefinition:s,drawPositions:a}){let c=t.structureId,u=e[c];if(!u?.length)return;let p=t.positionAssignments?.length,{subOrderMap:m}=Zl({positionAssignments:t.positionAssignments}),d=ea({matchUps:u,subOrderMap:m});if(d?.participantResults)for(let[l,f]of Object.entries(d.participantResults)){let g=f.groupOrder||f.provisionalOrder;if(!g)continue;let I=s$({drawPositionsCount:r,containerStructureId:n,bracketsCount:o,playoffStructure:i,drawDefinition:s,bracketSize:p,order:g});I&&(a[l]=I)}}function c$(t,e,r){let n={};if(!r)return n;for(let[o,i]of Object.entries(e)){let{drawDefinition:s,drawId:a}=i,c=s.structures?.find(l=>l.structureType===de&&l.stage===W&&l.stageSequence===1);if(!c?.structures)continue;let u=c.structures,p=u.length,m=u.reduce((l,f)=>l+(f.positionAssignments?.length||0),0),d=s.structures?.find(l=>l.stage===Vt);n[a]||(n[a]={});for(let l of u)a$({containedStructure:l,rrGroupMatchUps:t,drawPositionsCount:m,containerStructureId:o,bracketsCount:p,playoffStructure:d,drawDefinition:s,drawPositions:n[a]})}return n}function u$({scheduleItems:t,potentialMatchUps:e,scheduleAnalysis:r}){let n=Tt(r)?r.scheduledMinutesDifference:0,o={},i=t.reduce((s,a)=>{let{scheduledDate:c,scheduledTime:u}=a;return s[c]||(s[c]=[]),u&&s[c].push(a),s},{});Object.values(i).forEach(s=>s.sort(ny));for(let s of t){let{typeChangeTimeAfterRecovery:a,timeAfterRecovery:c,scheduledDate:u,scheduledTime:p}=s,m=i[u],d=jt(p);for(let l of m){if(l.matchUpId===s.matchUpId||Ye(l.matchUpStatus)&&!l.checkScoreHasValue)continue;let I=s.matchUpType!==l.matchUpType&&a||c,S=s.drawId===l.drawId,h=e[s.matchUpId]&&e[l.matchUpId],T=jt(l.scheduledTime),y=Math.abs(T-d),E=T>=d;if((n&&!Number.isNaN(n)?y<=n:E&&jt(l.scheduledTime)<jt(I))&&!(h&&S)&&E){let N=[s.matchUpId,l.matchUpId].sort(Wp).join("|");o[N]={priorScheduledMatchUpId:s.matchUpId,matchUpIdWithConflict:l.matchUpId}}}}return o}function p$({rrFinishingPositions:t,withRankingProfile:e,scheduleAnalysis:r,withStatistics:n,derivedDrawInfo:o,participantMap:i}){let s=[],a=Object.values(i);for(let c of a){let{wins:u,losses:p,[Ct]:{wins:m,losses:d},[Rt]:{wins:l,losses:f}}=c.counters,g=(I,S,h)=>{let T=S+h,y=S,E=T&&y/T;c.statistics[I]={denominator:T,numerator:y,statValue:E,statCode:I}};n&&(g(wl,u,p),g(`${wl}.${Ct}`,m,d),g(`${wl}.${Rt}`,l,f)),e&&m$({participantAggregator:c,derivedDrawInfo:o,rrFinishingPositions:t}),r&&d$({participantAggregator:c,scheduleAnalysis:r,participantMap:i,participantIdsWithConflicts:s})}return s}function m$({participantAggregator:t,derivedDrawInfo:e,rrFinishingPositions:r}){let n=(o=[])=>Math.abs(o[0]-o[1]);for(let o of Object.keys(t.draws)){let{orderedStructureIds:i=[],flightNumber:s}=e[o]??{};if(!t.structureParticipation||!i.length)continue;let a,c=0,u=i.map(p=>{let m=t.structureParticipation[p];if(!m)return;a||(a=m?.finishingPositionRange),n(a)>n(m?.finishingPositionRange)&&(a=m?.finishingPositionRange);let d=m.stage!==Z;return d&&(c+=1),et({...m,participationOrder:d?c:void 0,flightNumber:s})}).filter(Boolean);if(t.draws[o]){let p=t.participant.participantId,m=r[o]?.[p];m&&(a=m),t.draws[o].finishingPositionRange=a,t.draws[o].structureParticipation=u}}}function d$({participantAggregator:t,scheduleAnalysis:e,participantMap:r,participantIdsWithConflicts:n}){let o=t.scheduleItems??[],i=t.potentialMatchUps??{};t.scheduleConflicts=u$({scheduleAnalysis:e,scheduleItems:o,potentialMatchUps:i});let s=t.participant.participantId;Object.keys(t.scheduleConflicts).length&&n.push(s),r[s].scheduleConflicts=t.scheduleConflicts}function Hp({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=Ba(l)&&e?.events?.filter(y=>l?.includes(y.eventId))||e?.events||[],I=o&&l$({drawEntryStatuses:o,tournamentEvents:g}),S=s&&f$({eventEntryStatuses:s,tournamentEvents:g}),h=i!==void 0&&[!0,!1].includes(i)&&g.reduce((y,E)=>y.concat(...(E.drawDefinitions??[]).map(A=>qy({drawDefinition:A}).allPositionedParticipantIds).filter(Boolean)),[]),T=y=>n?.reduce((E,A)=>{let{accessor:N,value:D}=A,{values:R}=Bi({element:y,accessor:N});return E&&R?.includes(D)},!0);if(r=r?.filter(y=>{let E=Jr({element:y,itemType:fu})?.timeItem?.itemValue,{participantRoleResponsibilities:A,participantType:N,participantRole:D,participantId:R,person:U}=y,b=Array.isArray(f)&&f?.length&&U?.sex&&f.includes(U.sex);return d?f&&b||i&&h.includes(R)||i===!1&&!h.includes(R)||I?.includes(R)||S?.includes(R)||p?.includes(R)||m&&E===m||u&&N&&Ba(u)&&u.includes(N)||a&&D&&Ba(a)&&a.includes(D)||c&&Ba(A)&&Ba(c)&&c.find(C=>A?.includes(C))||n?.length&&Ba(n)&&T(y):(!f||b)&&(i===void 0||i&&h.includes(R)||i===!1&&!h.includes(R))&&(!I||I.includes(R))&&(!S||S.includes(R))&&(!p||p.includes(R))&&(!m||E===m)&&(!u||N&&Ba(u)&&u.includes(N))&&(!a||D&&Ba(a)&&a.includes(D))&&(!c||Ba(A)&&Ba(c)&&c.find(C=>A?.includes(C)))&&(!n?.length||Ba(n)&&T(y))}),g.length&&l){let y=new Set(g.filter(E=>l.includes(E.eventId)).flatMap(E=>{let A=(E.entries??[]).map(D=>D.participantId);if(re(Dt)(E.eventType))return A;let N=(e?.participants??[]).filter(D=>A.includes(D.participantId)).flatMap(D=>D.individualParticipantIds);return A.concat(...N)}));r=r?.filter(E=>y.has(E.participantId))}return r}function Ba(t){return t&&Array.isArray(t)&&t.length}function l$({drawEntryStatuses:t,tournamentEvents:e}){let r=({entryStatus:n})=>Array.isArray(t)?t.includes(n):!0;return pt(e.reduce((n,o)=>{let{flightProfile:i}=Bt({event:o}),s=i?.flights?.flatMap(({drawEntries:c})=>Array.isArray(c)?c.filter(r).map(gt):[])??[],a=o.drawDefinitions?.map(({entries:c})=>c?c.filter(r).map(gt):[])??[];return n.concat(...s,...a)},[]))}function f$({eventEntryStatuses:t,tournamentEvents:e}){return pt(e.reduce((r,n)=>{let o=(n.entries??[]).filter(({entryStatus:i})=>Array.isArray(t)?t.includes(i):!0).map(gt);return r.concat(...o)},[]))}function bt(t){let{withIndividualParticipants:e,participantFilters:r={},withPotentialMatchUps:n,withRankingProfile:o,convertExtensions:i,policyDefinitions:s,withScheduleItems:a,tournamentRecord:c,scheduleAnalysis:u,withSignInStatus:p,withTeamMatchUps:m,withScaleValues:d,usePublishState:l,withStatistics:f,contextFilters:g,matchUpFilters:I,contextProfile:S,withOpponents:h,withMatchUps:T,internalUse:y,withSeeding:E,withEvents:A,withDraws:N,withISO2:D,withIOC:R}=t,U="getParticipants";if(!c)return M({stack:U,result:{error:j}});(T||o)&&tn({tournamentRecord:c});let b=eE({convertExtensions:i,tournamentRecord:c,withSignInStatus:p,withScaleValues:d,internalUse:y,withISO2:D,withIOC:R}),{participantMap:C}=b,_=C0({withMatchUps:T??o,withEvents:A??o,withDraws:N??o,withPotentialMatchUps:n,participantFilters:r,withRankingProfile:o,convertExtensions:i,withScheduleItems:a,policyDefinitions:s,tournamentRecord:c,scheduleAnalysis:u,withTeamMatchUps:m,usePublishState:l,withStatistics:f,contextFilters:g,matchUpFilters:I,participantMap:C,withOpponents:h,contextProfile:S,withSeeding:E}),{participantIdsWithConflicts:v,eventsPublishStatuses:w,derivedEventInfo:L,derivedDrawInfo:F,mappedMatchUps:x}=_,k=_.matchUps;C=_.participantMap;let G=u??n,V=({potentialMatchUps:ct,scheduleConflicts:Et,scheduleItems:Ht,participant:Ut,statistics:pe,opponents:ye,matchUps:Jt,events:pr,draws:Kn})=>{let zr=Object.values(Kn),so=Object.values(ye);return h&&zr?.forEach(Zo=>{Zo.opponents=so.filter(ti=>ti.drawId===Zo.drawId)}),et({...Ut,scheduleConflicts:u?Object.values(Et):void 0,draws:N||o?zr:void 0,events:A||o?Object.values(pr):void 0,matchUps:T||o?Object.values(Jt):void 0,opponents:h?so:void 0,potentialMatchUps:G?Object.values(ct):void 0,statistics:f?Object.values(pe):void 0,scheduleItems:a?Ht:void 0},!1,!1,!0)},B=new Map;for(let ct of Object.keys(C))B.set(ct,V(C[ct]));let z=[...B.values()],K=s?.[xa]?.participant,Y=Hp({participants:z,participantFilters:r,tournamentRecord:c});if(e){let ct=Tt(e)?e:void 0;for(let Et of Y)for(let Ht of Et.individualParticipantIds??[]){Et.individualParticipants??=[];let Ut=B.get(String(Ht)),pe=ct?hs({template:ct,source:Ut}):Ut;Et.individualParticipants.push(pe)}}let J=K?Y.map(ct=>hs({source:ct,template:K})):Y;return{participantMap:t.returnParticipantMap!==!1?C:void 0,mappedMatchUps:t.returnMatchUps!==!1?x:void 0,matchUps:t.returnMatchUps!==!1?k:void 0,missingParticipantIds:b.missingParticipantIds,participantIdsWithConflicts:v,eventsPublishStatuses:w,derivedEventInfo:L,derivedDrawInfo:F,participants:J,...P}}function Zi(t){let{tournamentRecord:e,scaleAttributes:r,participantId:n}=t,o=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!n)return{error:We};let{participant:i,tournamentId:s}=Do({tournamentRecords:o,tournamentRecord:e,participantId:n});return i?{...Po({participant:i,scaleAttributes:r}),tournamentId:s}:{error:ee}}function O0(t,e){let r=t.startDate||e?.startDate,n=t.endDate||e?.endDate;return!r||!n?{error:Sw}:!Me(r)||!Me(n)?{error:ae}:{startDate:r,endDate:n}}function M0(t,e){let r=new Date(mt(t)),n=new Date(mt(e)),o=n.getFullYear()-r.getFullYear(),i=n.getMonth()-r.getMonth();return(i<0||i===0&&n.getDate()<r.getDate())&&o--,o}function v0(t,e,r){return!(e!==void 0&&t<e||r!==void 0&&t>r)}function g$(t){return/^C\d{1,2}-\d{1,2}$/.test(t.ageCategoryCode||"")}function I$(t,e,r,n){if(g$(e))return{valid:!0};let o=e.ageMin,i=e.ageMax;if(e.ageCategoryCode&&!o&&!i){let m=gs({consideredDate:r,category:e});m.error||(o=m.ageMin,i=m.ageMax)}if(!o&&!i)return{valid:!0};let s=t.person?.birthDate;if(!s)return{valid:!1,reason:"Missing birthDate",details:{requiredMin:o,requiredMax:i}};let a=M0(s,r),c=M0(s,n),u=v0(a,o,i),p=v0(c,o,i);if(!u){let m=[o===void 0?null:`min: ${o}`,i===void 0?null:`max: ${i}`].filter(Boolean).join(", ");return{valid:!1,reason:`Age ${a} at event start (${r}) outside range [${m}]`,details:{birthDate:s,ageAtStart:a,ageAtEnd:c,requiredMin:o,requiredMax:i}}}if(!p){let m=[o===void 0?null:`min: ${o}`,i===void 0?null:`max: ${i}`].filter(Boolean).join(", ");return{valid:!1,reason:`Age ${c} at event end (${n}) outside range [${m}]`,details:{birthDate:s,ageAtStart:a,ageAtEnd:c,requiredMin:o,requiredMax:i}}}return{valid:!0}}function S$(t,e,r,n){if(!e.ratingMin&&!e.ratingMax)return{valid:!0};if(!e.ratingType)return{valid:!0};let o={scaleType:"RATING",scaleName:e.ratingType,eventType:r.eventType},{scaleItem:i}=Zi({tournamentRecord:n,participantId:t.participantId,scaleAttributes:o});if(!i?.scaleValue)return{valid:!1,reason:`Missing ${e.ratingType} rating`,details:{ratingType:e.ratingType,requiredMin:e.ratingMin,requiredMax:e.ratingMax}};let s;if(typeof i.scaleValue=="object"){let a=Bi({element:i.scaleValue,accessor:i.scaleValue?.accessor});if(a===void 0)return{valid:!1,reason:`Cannot extract rating value from ${e.ratingType} scale item`,details:{ratingType:e.ratingType,requiredMin:e.ratingMin,requiredMax:e.ratingMax}};s=a}else s=i.scaleValue;return e.ratingMin!==void 0&&s<e.ratingMin?{valid:!1,reason:`${e.ratingType} rating ${s} below minimum ${e.ratingMin}`,details:{ratingType:e.ratingType,ratingValue:s,requiredMin:e.ratingMin,requiredMax:e.ratingMax}}:e.ratingMax!==void 0&&s>e.ratingMax?{valid:!1,reason:`${e.ratingType} rating ${s} above maximum ${e.ratingMax}`,details:{ratingType:e.ratingType,ratingValue:s,requiredMin:e.ratingMin,requiredMax:e.ratingMax}}:{valid:!0}}function Vb(t){let e=t.person;if(!e)return t.participantOtherName||t.participantName||"Unknown";let r=e.standardGivenName||e.passportGivenName,n=e.standardFamilyName||e.passportFamilyName;return[r,n].filter(Boolean).join(" ")||t.participantOtherName||t.participantName||"Unknown"}function Bb(t,e,r,n,o,i){let s=I$(t,e,n,o),a=S$(t,e,r,i);if(!s.valid||!a.valid){let c={participantId:t.participantId,participantName:Vb(t),rejectionReasons:[]};return s.valid||c.rejectionReasons.push({type:"age",reason:s.reason,details:s.details??{}}),a.valid||c.rejectionReasons.push({type:"rating",reason:a.reason,details:a.details??{}}),c}return null}function Nu({participantId:t,drawDefinition:e,entryStatus:r,entryStage:n}){if(!e)return{error:$};let o=e.entries?.find(i=>i.participantId===t&&(!r||r===i.entryStatus)&&(!n||n===i.entryStage));return t&&o}function Wb({stage:t,drawDefinition:e}){return!!(t===Fe||CL({stage:t,drawDefinition:e}))}function h$({relevantLinks:t,drawDefinition:e,provisionalPositioning:r,roundQualifiersCounts:n}){let o=0;for(let i of t){let s=tt({structureId:i.source.structureId,drawDefinition:e})?.structure;if(s?.stage===Z){let a=i.source.roundNumber,c=i.target.roundNumber,u;if(s.structureType===de){let p=s.structures?.length??0,m=i.source.finishingPositions?.length??0;u=p*m}else a===0&&i.source.qualifyingPositions?u=i.source.qualifyingPositions:u=ht({matchUpFilters:{roundNumbers:[a]},structure:s,afterRecoveryTimes:!1,provisionalPositioning:r,inContext:!1}).matchUps?.length||0;n[c]||(n[c]=0),n[c]+=u,o+=u}}return o}function Yp(t){let{provisionalPositioning:e,drawDefinition:r,structureId:n}=t;if(!r)return{error:$};let o={};if(!n)return{qualifiersCount:0,roundQualifiersCounts:o};let{structure:i}=tt({drawDefinition:r,structureId:n}),s=r.links?.filter(c=>c?.target?.structureId===i?.structureId),a=0;return s?.length&&(a=h$({relevantLinks:s,drawDefinition:r,provisionalPositioning:e,roundQualifiersCounts:o})),{qualifiersCount:a,roundQualifiersCounts:o}}function Hb({stage:t,drawDefinition:e,stageSequence:r,tournamentRecord:n,event:o}){let i=e?.structures?.filter(s=>s.stage===t&&(!r||s.stageSequence===r));if(i?.length)return i.reduce((s,a)=>a.structureType===de?s+(a.structures?.reduce((c,u)=>c+(u.positionAssignments?.length??0),0)??0):s+(a.positionAssignments?.length??0),0);if(t===W&&n){let{constraints:s}=XI({tournamentRecord:n,event:o});if(s?.drawSize)return s.drawSize}return 0}function _0(t){let{provisionalPositioning:e,drawDefinition:r,stageSequence:n,stage:o,tournamentRecord:i,event:s}=t,a=Hb({stage:o,drawDefinition:r,stageSequence:n,tournamentRecord:i,event:s}),c=r?.structures?.find(p=>p.stage===o&&(!n||p.stageSequence===n)),{qualifiersCount:u}=Yp({structureId:c?.structureId,provisionalPositioning:e,drawDefinition:r,stageSequence:n,stage:o});return a&&a-(u??0)}function Yb({entryStatus:t=kr,tournamentRecord:e,drawDefinition:r,stageSequence:n,event:o,stage:i}){let{constraints:s}=XI({tournamentRecord:e,event:o});if(t===Zr){if(!s)return{positionsAvailable:1/0,...P};if(s.maxAlternates===void 0)return{positionsAvailable:1/0,...P};let f=nE({entryStatus:Zr,drawDefinition:r,stage:i});return f<s.maxAlternates?{positionsAvailable:s.maxAlternates-f,...P}:{error:hU}}if(!r?.structures?.some(f=>f.stage===i))return{positionsAvailable:1/0,...P};let c=_0({drawDefinition:r,stageSequence:n,stage:i}),u=nE({entryStatus:Lp,drawDefinition:r,stage:i}),p=nE({entryStatus:kr,drawDefinition:r,stage:i}),m=u+p,d=c>0&&m>=c,l=c-m;if(i!==Fe&&d)return{error:Xg};if(t===Lp){if(!s)return m<c?{...P}:{error:Xg};let f=s.maxWildcards??c;return u<f?{...P}:{error:Xg}}return{positionsAvailable:l,...P}}var T$=new Set([Ni,Bs]);function yn(t){return!!t&&T$.has(t)}function tf(t){let e=X(t,[{[Kt]:!0,[Cy]:!0}]);if(e.error)return e;let{suppressDuplicateEntries:r=!0,entryStatus:n=kr,entryStageSequence:o,entryStage:i=W,ignoreStageSpace:s,drawDefinition:a,entryPosition:c,participant:u,roundTarget:p,extensions:m,extension:d,drawType:l,event:f}=t,g="addDrawEntry";if(!yn(l)&&!Wb({stage:i,drawDefinition:a}))return M({result:{error:cc},stack:g});let I=Yb({stageSequence:o,stage:i,drawDefinition:a,entryStatus:n});if(!s&&!I.success&&(!l||!yn(l)))return{error:I.error};if(d&&!Yn({extension:d}))return M({result:{error:O},info:"Invalid extension",context:{extension:d},stack:g});let S=t.participantId||u?.participantId;if(!S)return M({result:{error:We},stack:g});let h=n===Ys&&Nu({participantId:S,drawDefinition:a,entryStatus:n}),T=i===Fe&&Nu({participantId:S,drawDefinition:a,entryStage:i}),y=Nu({participantId:S,drawDefinition:a}),E=n!==Ys&&i!==Fe&&y;if(E)return r?(at({payload:{drawId:a.drawId,eventId:f?.eventId,error:nl,participantId:S},topic:Ky}),{...P}):M({result:{error:nl},context:{participantId:S},stack:g});if(h||T)return M({context:{invalidEntry:E,invalidLuckyLoser:h,invalidVoluntaryConsolation:T},result:{error:_m},stack:g});let A=et({entryStageSequence:o,participantId:S,entryPosition:c,entryStatus:n,entryStage:i,extensions:m});return d&&ut({element:A,extension:d}),p&&ut({extension:{name:bn,value:p},element:A}),a.entries??=[],a.entries.push(A),Ft({drawDefinition:a}),{...P}}function x0(t){let e="addDrawEntries",{suppressDuplicateEntries:r=!0,entryStatus:n=kr,autoEntryPositions:o=!0,ignoreStageSpace:i,participantIds:s,drawDefinition:a,stageSequence:c,stage:u=W,roundTarget:p,extension:m,event:d}=t,l=yn(a.drawType);if(!u)return{error:Wg};if(!a)return{error:$};if(!Array.isArray(s))return{error:_r};if(!l&&!Wb({stage:u,drawDefinition:a}))return{error:cc};if(m&&!Yn({extension:m}))return M({result:{error:O},info:"Invalid extension",context:{extension:m},stack:e});let f=Yb({drawDefinition:a,stageSequence:c,entryStatus:n,stage:u});if(!i&&!f.success&&!l)return{error:f.error};let g=f.positionsAvailable??0;if(!i&&!l&&u!==Fe&&g<s.length)return{error:zg};let I=[],S=a.drawId,h=d?.eventId,T=s.reduce((y,E)=>{let A=n===Ys&&Nu({participantId:E,drawDefinition:a,entryStatus:n}),N=u===Fe&&Nu({entryStage:u,drawDefinition:a,participantId:E}),D=Nu({participantId:E,drawDefinition:a});return n!==Ys&&u!==Fe&&D&&(I.push(E),r&&at({payload:{error:nl,participantId:E,eventId:h,drawId:S},topic:Ky})),A||N?y.concat(E):y},[]);return I.length&&!r?M({context:{eventId:h,drawId:S,duplicateEntries:I},result:{error:nl},stack:e}):(s.filter(y=>y&&!T.includes(y)).forEach(y=>{let E={entryStageSequence:c,entryStage:u,participantId:y,entryStatus:n};m&&ut({element:E,extension:m}),p&&ut({extension:{name:bn,value:p},element:E}),a.entries??=[],a.entries.push(E)}),o&&(a.entries=no({entries:a.entries})),Ft({drawDefinition:a}),T?.length||I?.length?{info:"some participantIds could not be added",participantIdsNotAdded:T,duplicateEntries:I,...P}:{...P})}function mS({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:Mo};if(!m)return{error:Wr};if(!p)return{error:Nn};let d=(m.entries??[]).map(gt);if(o.filter(I=>!d.includes(I)).length)return{error:jD};if(i){let I=x0({stageSequence:r,suppressDuplicateEntries:t,autoEntryPositions:e,stage:c,ignoreStageSpace:n,participantIds:o,drawDefinition:i,entryStatus:s,roundTarget:a,extension:u});if(I.error)return I}let{flightProfile:f}=Bt({event:m}),g=f?.flights.find(I=>I.drawId===p);return g?.drawEntries&&(o.forEach(I=>{let S=s===Ys&&jb({participantId:I,entryStatus:s,flight:g}),h=c===Fe&&jb({participantId:I,entryStage:c,flight:g});!(s!==Ys&&c!==Fe&&jb({flight:g,participantId:I}))&&!S&&!h&&g.drawEntries.push({participantId:I,entryStatus:s,entryStage:c})}),e&&(g.drawEntries=no({entries:g.drawEntries}))),{...P}}function jb({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 Du({autoEntryPositions:t=!0,participantIds:e=[],entryStatuses:r,stage:n,event:o}){let i="removeEventEntries";if(!o?.eventId)return{error:le};if(!Array.isArray(e)||e.some(m=>!wt(m)))return M({result:{error:Hr},stack:i});let s=(o.drawDefinitions??[]).flatMap(m=>Ji({drawDefinition:m}).assignedParticipantIds??[]),a=(r?.length&&o.entries?.filter(m=>m.entryStatus&&r.includes(m.entryStatus))||[]).map(gt).filter(m=>!s.includes(m)),c=(n&&o.entries?.filter(m=>m.entryStage&&m.entryStage===n)||[]).map(gt).filter(m=>!s.includes(m));if(e.length?e=e.filter(m=>(!r?.length||a.includes(m))&&(!n||c.includes(m))):a.length&&c.length?e=Yt(a,c):a.length?e=a:c.length&&(e=c),e?.length&&s.some(m=>e.includes(m)))return M({result:{error:Pa},stack:i});if(!e?.length)return{...P,participantIdsRemoved:[]};let u=[];o.entries=(o.entries??[]).filter(m=>{let d=!e.includes(m?.participantId);return d||u.push(m.participantId),d}),t&&(o.entries=no({entries:o.entries}));let{flightProfile:p}=Bt({event:o});return p?.flights?.forEach(m=>{m.drawEntries=(m.drawEntries??[]).filter(d=>!e.includes(d.participantId))}),o.drawDefinitions?.forEach(m=>{m.entries=(m.entries??[]).filter(d=>!e.includes(d.participantId))}),{...P,participantIdsRemoved:u}}var qb={[He]:{policyName:"matchUpActionsDefault",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[],disabledActions:[]}],participants:{enforceCategory:!0,enforceGender:!0},processCodes:{substitution:["RANKING.IGNORE","RATING.IGNORE"]},substituteAfterCompleted:!1,substituteWithoutScore:!1}},Ns=qb;function y$(t,e,r,n){return e.gender&&r&&!(nn(e.gender)||Oo(e.gender))&&Ar(e.gender)!==Ar(t.person?.sex)?(n.push({participantId:t.participantId,sex:t.person?.sex}),!1):!0}function E$({participantIds:t,typedParticipantIds:e,checkTypedParticipants:r}){return t.filter(n=>!r||e.includes(n))}function A$({tournamentRecord:t,participantIds:e,event:r,entryStatus:n,genderEnforced:o,mismatchedGender:i}){function s(m,d,l){return re(Ct)(d.eventType)&&m.participantType===St&&!ta(l)}function a(m,d,l){return d.eventType===Rt&&m.participantType===lt&&!ta(l)}function c(m,d,l,f,g){return d.eventType===Rt&&m.participantType===St&&ta(l)?d.gender&&f&&!(nn(d.gender)||Oo(d.gender))&&Ar(d.gender)!==Ar(m.person?.sex)?(g.push({participantId:m.participantId,sex:m.person?.sex}),!1):!0:!1}function u(m,d,l){return d.eventType===EI&&[St,lt].includes(m.participantType)&&!ta(l)}function p(m,d,l){return d.eventType===_t&&(m.participantType===_t||ta(l)&&m.participantType===St)}return t?.participants?.filter(m=>e.includes(m.participantId)?s(m,r,n)?y$(m,r,o,i):a(m,r,n)||c(m,r,n,o,i)||u(m,r,n)?!0:p(m,r,n):!1).map(m=>m.participantId)??[]}function P$(t,e,r,n,o){let i=[];for(let s of t.individualParticipantIds??[]){let a=e.participants?.find(u=>u.participantId===s);if(!a)continue;let c=Bb(a,r.category,r,n,o,e);c&&i.push(c)}return i.length?{participantId:t.participantId,participantName:Vb(t),rejectionReasons:i.flatMap(s=>s.rejectionReasons.map(a=>({...a,reason:`${s.participantName}: ${a.reason}`})))}:null}function N$(t){return(t.participantType===lt||t.participantType===_t)&&!!t.individualParticipantIds?.length}function D$({typedParticipantIds:t,categoryRejections:e,tournamentRecord:r,startDate:n,endDate:o,event:i}){let s=[];for(let a of t){let c=r.participants?.find(u=>u.participantId===a);if(c)if(i.category){let u=N$(c)?P$(c,r,i,n,o):Bb(c,i.category,i,n,o,r);u?e.push(u):s.push(a)}else s.push(a)}return s}function U$({enforceCategory:t,event:e,tournamentRecord:r,typedParticipantIds:n,categoryRejections:o}){if(t&&e.category&&r){let i=O0(e,r);if(!("error"in i)){let{startDate:s,endDate:a}=i;return D$({typedParticipantIds:n,tournamentRecord:r,event:e,startDate:s,endDate:a,categoryRejections:o})}}return n}function R$({validParticipantIds:t,existingIds:e,entryStatus:r,entryStage:n,extensions:o,extension:i,roundTarget:s,entryStageSequence:a,addedParticipantIdEntries:c,event:u}){t.forEach(p=>{if(!e.has(p)){let m=et({participantId:p,entryStatus:r,entryStage:n,extensions:o});i&&ut({element:m,extension:i}),s&&ut({extension:{name:bn,value:s},element:m}),a&&(m.entryStageSequence=a),c.push(m.participantId),u.entries?.push(m)}})}function b$({tournamentRecord:t,removedEntries:e,event:r}){if(r.eventType&&[si,Ze].includes(r.eventType)){let n=new Set((r.entries??[]).map(c=>c.participantId)),o=(r.entries??[]).filter(c=>ta(c.entryStatus)).map(c=>c.participantId),i=t?.participants??[],s=new Set(i.filter(c=>n.has(c.participantId)&&c.participantType&&[lt,_t].includes(c.participantType)).map(c=>c.individualParticipantIds).flat(1/0)),a=o.filter(c=>s.has(c));a.length&&(e.push(...a),Du({participantIds:a,autoEntryPositions:!1,event:r}))}}function C$(t,e){if(!Array.isArray(t.participantIds))return M({result:{error:_r},stack:e});let r=pt(t.participantIds??[]);return t.event?r?.length?t.event?.eventId?{participantIds:r}:{error:Wr}:M({result:{error:Mo},stack:e}):{error:le}}function M$({policyDefinitions:t,tournamentRecord:e,event:r,enforceGender:n}){let o=ft({tournamentRecord:e,event:r}).appliedPolicies??{},i=t?.[He]??o?.[He]??Ns[He],s=(n??i?.participants?.enforceGender)!==!1;return{matchUpActionsPolicy:i,genderEnforced:s}}function v$(t,e,r){return t&&(!Array.isArray(t)||!t.every(n=>Yn({extension:n})))||e&&!Yn({extension:e})?M({context:et({extension:e,extensions:t}),result:{error:O},info:"Invalid extension(s)",stack:r}):null}function jn(t){let{suppressDuplicateEntries:e=!0,entryStatus:r=kr,autoEntryPositions:n=!0,enforceCategory:o=!1,enforceGender:i=!0,entryStageSequence:s,policyDefinitions:a,entryStage:c=W,tournamentRecord:u,ignoreStageSpace:p,drawDefinition:m,roundTarget:d,extensions:l,extension:f,drawId:g,event:I}=t,S="addEventEntries",h=C$(t,S);if("error"in h)return h;let T="participantIds"in h?h.participantIds:[],y=v$(l,f,S);if(y)return y;let{genderEnforced:E}=M$({policyDefinitions:a,tournamentRecord:u,event:I,enforceGender:i}),A=[],N=[],D=!!u,R=[],U,b=A$({tournamentRecord:u,participantIds:T,event:I,entryStatus:r,genderEnforced:E,mismatchedGender:R}),C=[];b=U$({enforceCategory:o,event:I,tournamentRecord:u,typedParticipantIds:b,categoryRejections:C});let _=E$({participantIds:T,typedParticipantIds:b,checkTypedParticipants:D});I.entries??=[];let v=new Set(I.entries.map(x=>x.participantId||x.participant?.participantId));if(R$({validParticipantIds:_,existingIds:v,entryStatus:r,entryStage:c,extensions:l,extension:f,roundTarget:d,entryStageSequence:s,addedParticipantIdEntries:A,event:I}),g&&!ta(c)){let x=mS({participantIds:_,suppressDuplicateEntries:e,autoEntryPositions:n,entryStageSequence:s,ignoreStageSpace:p,drawDefinition:m,entryStatus:r,roundTarget:d,entryStage:c,extension:f,drawId:g,event:I});x.error&&(U=x.error)}if(b$({event:I,tournamentRecord:u,removedEntries:N}),_.length!==T.length)return M({context:et({categoryRejections:C.length?C:void 0,mismatchedGender:R.length?R:void 0,gender:I.gender}),result:{error:_r},stack:S});n&&(I.entries=no({entries:I.entries??[]}));let L=A.length,F=N.length;return M({result:{...P,addedEntriesCount:L,removedEntriesCount:F,...C.length&&{context:et({categoryRejections:C})}},stack:S,info:U})}var $b="ADMINISTRATION",O$="CAPTAIN",_$="COACH",Ve="COMPETITOR",x$="DIRECTOR",w$="HOSPITALITY",Kb="MEDIA",zb="MEDICAL",dS="OFFICIAL",Qb="OTHER",Xb="SECURITY",L$="STRINGER",F$="SUPERVISOR",k$="TRANSPORT",G$="VOLUNTEER",ef={ADMINISTRATION:$b,CAPTAIN:O$,COACH:_$,COMPETITOR:Ve,DIRECTOR:x$,HOSPITALITY:w$,MEDIA:Kb,MEDICAL:zb,OFFICIAL:dS,OTHER:Qb,SECURITY:Xb,STRINGER:L$,SUPERVISOR:F$,TRANSPORT:k$,VOLUNTEER:G$};function lS({addIndividualParticipantsToEvents:t,individualParticipantIds:e,groupingParticipantId:r,tournamentRecord:n,suppressErrors:o}){let i="removeIndividualParticipantIds";if(!n)return M({result:{error:j},stack:i});if(!r||!e)return M({result:{error:nt},stack:i});let a=(n.participants??[]).find(m=>m.participantId===r);if(!a)return M({result:{error:ee},stack:i});if(![_t,$r].includes(a.participantType))return M({result:{participantType:a.participantType,error:Dn},stack:i});let c=w0({individualParticipantIds:e,groupingParticipant:a,tournamentRecord:n,suppressErrors:o}),{removed:u,error:p}=c;if(p)return M({result:c,stack:i});if(t)for(let m of n.events??[]){let d=new Set((m.entries??[]).map(({participantId:l})=>l).filter(Boolean));if(d.has(r)){let l=u?.filter(f=>!d.has(f));jn({participantIds:l,entryStatus:Gr,tournamentRecord:n,event:m})}}return u&&at({topic:tr,payload:{tournamentId:n.tournamentId,participants:[a]}}),{...P,...c}}function w0({individualParticipantIds:t=[],groupingParticipant:e,tournamentRecord:r,suppressErrors:n,mappedMatchUps:o,participants:i}){let s=[];if(!e)return{removed:s};let a=[],c=[];i||({participants:i,mappedMatchUps:o}=bt({withMatchUps:!0,tournamentRecord:r,withEvents:!0}));let p=i?.find(({participantId:f})=>f===e.participantId)?.events?.map(({eventId:f})=>f),m=new Set(t),d=(e.individualParticipantIds??[]).filter(f=>m.has(f)?V$({groupingParticipantEventIds:p,mappedMatchUps:o,participantId:f,participants:i})?(c.push(f),!0):(s.push(f),B$({groupingParticipantId:e.participantId,tournamentRecord:r,participantId:f}),!1):(a.push(f),!0));e.individualParticipantIds=d;let l={groupingParticipantId:e.participantId,cannotRemove:c,notRemoved:a,removed:s};return c.length&&!n&&{...l,cannotRemove:c,error:Om}||l}function V$({groupingParticipantEventIds:t,mappedMatchUps:e,participantId:r,participants:n}){return n?.find(i=>i.participantId===r)?.matchUps.filter(({eventId:i})=>t.includes(i)).map(({matchUpId:i})=>e?.[i]).filter(({winningSide:i,score:s})=>i||ue({score:s}))?.length>0}function B$({groupingParticipantId:t,tournamentRecord:e,participantId:r}){for(let n of e.events??[])for(let o of n.drawDefinitions??[])W$({drawDefinition:o,groupingParticipantId:t,participantId:r}),H$({drawDefinition:o,tournamentRecord:e,participantId:r})}function W$({drawDefinition:t,groupingParticipantId:e,participantId:r}){let{extension:n}=ot({element:t,name:Vo}),o=n?.value[e];n&&o&&(n.value[e]=o.filter(i=>i.participantId!==r),ut({element:t,extension:n}),yc({drawDefinition:t}))}function H$({drawDefinition:t,tournamentRecord:e,participantId:r}){let n=rr({drawDefinition:t,inContext:!1}).matchUps??[];for(let o of n)for(let i of o.sides??[]){let s=i.lineUp??[];s.find(c=>c.participantId===r)&&(i.lineUp=s.filter(c=>c.participantId!==r),It({tournamentId:e?.tournamentId,drawDefinition:t,matchUp:o}))}}function cd({participantRole:t=Ve,individualParticipantIds:e=[],groupingTypes:r=[ur,$r],tournamentRecord:n}){if(!n)return{error:j};let o=n.participants??[],{participants:i,mappedMatchUps:s}=bt({withMatchUps:!0,tournamentRecord:n,withEvents:!0}),a=0;return o.filter(c=>(c.participantRole===t||!c.participantRole)&&c.participantType&&r.includes(c.participantType)).forEach(c=>{let{removed:u}=w0({groupingParticipant:c,individualParticipantIds:e,tournamentRecord:n,mappedMatchUps:s,participants:i});u&&a++}),a?P:{error:fU}}function Ds(t){let e=X(t,[{[rt]:!0},{participantIds:!0,[Ge]:ke,[jr]:Mo}]);if(e.error)return e;let{addIndividualParticipantsToEvents:r,tournamentRecord:n,participantIds:o}=t,i=n.participants?.length||0;if(!i)return{...P};let s=(n.events??[])?.filter(({eventType:f})=>f===Oe).map(f=>f?.drawDefinitions?.map(({drawId:g})=>g)).flat(1/0),a=bt({participantFilters:{participantIds:o},tournamentRecord:n,withDraws:!0}).participants??[],c=f=>{let I=(qt({matchUpFilters:{drawIds:f,matchUpTypes:[Rt]},tournamentRecord:n}).matchUps??[]).flatMap(({sides:S})=>S?.map(({participantId:h})=>h??[])).filter(Boolean);return Yt(I,o)},u=s?.length?c(s):[],p=a.filter(f=>f.draws?.filter(g=>(!s?.length||!s?.includes(g.drawId))&&g.positionAssignments).length);if(u?.length||p.length)return{error:Pa};let m={},d={};for(let f of n.events??[]){let g=Du({participantIds:o,event:f});if(g.error)return g;m[f.eventId]=g.participantIdsRemoved}n.participants=(n.participants??[]).filter(f=>{let g=o.includes(f.participantId)||f.participantType===lt&&f.individualParticipantIds?.some(I=>o.includes(I));if(!g&&f.participantType===Oe&&f.individualParticipantIds?.some(I=>o.includes(I))&&(f.individualParticipantIds=f.individualParticipantIds.filter(I=>!o.includes(I))),g&&r&&f.participantType&&[lt,_t].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(cd({individualParticipantIds:o,tournamentRecord:n}),r)for(let f of n.events??[]){let I=m[f.eventId].map(S=>d[S]??[]).flat();jn({participantIds:I,entryStatus:Gr,tournamentRecord:n,event:f})}return l&&at({payload:{participantIds:o,tournamentId:n.tournamentId},topic:VI}),l?{...P,participantsRemovedCount:l}:{error:Om}}function UE({selected:t=!0,drawDefinition:e,entryStatuses:r,drawId:n,event:o,stage:i}){let s=o.entries??[];if(n){let{flightProfile:c}=Bt({event:o}),u=c?.flights?.find(p=>p.drawId===n);u?s=u.drawEntries:e.entries&&(s=e?.entries)}let a=s.filter(c=>(!r?.length||!c.entryStatus||r.includes(c.entryStatus))&&(!i||!c.entryStage||c.entryStage===i)&&(!t||c.entryStatus&&yr.includes(c.entryStatus)));return{entries:s,stageEntries:a}}function Jb({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,stage:i,event:s}){let a="destroyGroupEntry",c=dt({tournamentRecord:e,participantId:n,event:s},[rt,sr,ce]);if(c.error)return c;if(!s.eventType||![si,Ze].includes(s.eventType))return M({result:{error:zn},stack:a});let u=e.participants??[],p=u.find(T=>T.participantId===n);if(!p)return M({result:{error:ee},stack:a});if(!p.participantType||![lt,ur].includes(p.participantType)||p.participantType===ur&&s.eventType!==Ze||p.participantType===lt&&s.eventType!==si)return{error:Dn};let d=(s.entries??[]).find(T=>T.participantId===n);if(!d)return{error:jT};let{stageEntries:l}=UE({selected:!1,drawDefinition:r,drawId:o,event:s,stage:i}),f=l.map(gt),g=u.filter(({participantId:T})=>f.includes(T)).map(({individualParticipantIds:T})=>T).flat().filter(Boolean),I=p.individualParticipantIds?.filter(T=>us(T,g).length===1),S=Du({participantIds:[n],event:s});if(S.error||I?.length&&(S=jn({participantIds:I,entryStatus:Gr,entryStage:d.entryStage,tournamentRecord:e,drawDefinition:r,drawId:o,event:s}),S.error))return S;let h;return t&&Ds({participantIds:[n],tournamentRecord:e}).success&&(h=!0),{...P,participantRemoved:h}}function fS({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,event:i}){return Jb({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,event:i})}function Zb(t){if(!t.tournamentRecord)return{error:j};let{participantIds:e,...r}=t,n=0,o=[];for(let i of e){let s=Jb({participantId:i,...r});s.success&&(n+=1),s.error&&o.push(s.error)}return n?{destroyedCount:n,...P}:{error:o}}function jp(t){let{tournamentRecord:e,replaceWithBye:r,drawDefinition:n,destroyPair:o,entryStatus:i,matchUpsMap:s,drawId:a}=t,c="removeDrawPositionAssignment",u=Au(t);if(u.error)return M({result:u,stack:c});let{participantId:p}=u,{drawPosition:m,event:d,structureId:l}=t,f=ft({tournamentRecord:e,drawDefinition:n,event:d}).appliedPolicies??{};if([Zr,Mn].includes(i)&&p){let{tournamentRecord:S}=t,{participant:h}=Do({tournamentRecord:S,participantId:p}),{participantType:T,individualParticipantIds:y}=h??{};if(o&&T===lt){let E=fS({tournamentRecord:S,drawDefinition:n,participantId:p,event:d});if(E.error)return M({result:E,stack:c});y&&Xl({participantIds:y,tournamentRecord:S,drawDefinition:n,entryStatus:i,drawId:a,event:d})}else Xl({participantIds:[p],tournamentRecord:S,drawDefinition:n,entryStatus:i,drawId:a,event:d})}if(r){let S=Or({tournamentRecord:e,drawDefinition:n,drawPosition:m,structureId:l,matchUpsMap:s,event:d});if(S.error)return M({result:S,stack:c})}let{structure:g}=tt({drawDefinition:n,structureId:l});return Ol({structure:g,drawPositions:[m]}),Ec({appliedPolicies:f,drawDefinition:n,positionAction:{name:"removeDrawPositionAssignment",replaceWithBye:r,drawPosition:m,entryStatus:i,structureId:l}}),u}function tC(t){return Object.assign(t,{entryStatus:Mn}),jp(t)}var Ko=({finishingPosition:t=Ss,hasExistingDrawDefinition:e,qualifyingRoundNumber:r,structureAbbreviation:n,seedAssignments:o=[],stageSequence:i=1,qualifyingOnly:s,structureOrder:a,seedingProfile:c,matchUpFormat:u,structureType:p,structureName:m,matchUps:d=[],matchUpType:l,structureId:f,roundOffset:g,roundLimit:I,stageOrder:S,structures:h,tieFormat:T,stage:y})=>{let E={structureId:f??it(),structureAbbreviation:n,finishingPosition:t,seedAssignments:o,matchUpFormat:u,stageSequence:i,structureName:m};(s||e&&T)&&(E.tieFormat=T),a&&(E.structureOrder=a),p&&(E.structureType=p),c&&(typeof c=="string"?E.seedingProfile=c:typeof c=="object"&&typeof c.positioning=="string"&&(E.seedingProfile=c.positioning)),l&&(E.matchUpType=l),g&&(E.roundOffset=g),S&&(E.stageOrder=S),I&&(E.roundLimit=I),y&&(E.stage=y),r&&(E.qualifyingRoundNumber=r);let A=d.flatMap(({drawPositions:N})=>N).filter(Boolean);return h?E.structures=h:(E.matchUps=d,E.positionAssignments=pt(A).sort((N,D)=>N-D).map(N=>({drawPosition:N}))),E},lr=Ko;function RE(t){return wt(t)?t.split(" ").map(e=>e.split("").map((r,n)=>n?r.toLowerCase():r.toUpperCase()).join("")).join(" "):t}function xe(t){return wt(t)?RE(t.replace(/_/g," ")):""}function gS({structureName:t=xe(Fe),structureAbbreviation:e,drawDefinition:r,matchUpType:n,structureId:o}){if(!r)return{error:$};let i=lr({stage:Fe,structureAbbreviation:e,structureName:t,matchUps:[],structureId:o,matchUpType:n});return r.structures??=[],r.structures.push(i),Ft({drawDefinition:r,structureIds:[i.structureId]}),{...P}}function Y$({size:t}){let e=[t],r=t;for(;r/2===Math.floor(r/2);)r=r/2,e.push(r);return e.includes(1)||e.push(1),e.sort(Zt),e.reverse(),e}function L0({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 F0({positioning:t,size:e}){let r=Y$({size:e}),n=[],o=[],i=d=>d[0],s=d=>d[d.length-1],a=(d,l)=>(t&&[iu,Hm,Li].includes(t)&&l%2?s(d):i(d))||i(d),c=(d,l)=>{if(d.every(f=>!o.includes(f))){let f=a(d,l);return o.push(f),f}},u=d=>{let l=d.filter(f=>!o.includes(f));if(l.length)return o.push(...l),l},p=(d,l)=>{let f=a(d,l);if(!o.includes(f))return o.push(f),f},m=Q(1,e+1);for(let d of r)if(d===1){let l=he(m,2),f=l.map(c).filter(Boolean);f.length&&n.push(f);let g=l.flatMap(u).filter(Boolean);g.length&&n.push(g)}else{let f=he(m,d).map(p).filter(Boolean);f.length&&n.push(f)}return{divisions:r,divisionGroupings:n}}function IS({drawPositions:t}){if(!t?.length)return{error:jc};let e=o=>t.filter(i=>i!==o).map(i=>[o,i]),r=[].concat(...(t??[]).map(e)),n=pt(r.map(SS)).map(o=>o.split("|").map(i=>+i));return{groupMatchUps:r,uniqueMatchUpGroupings:n}}function SS(t=[]){return!Array.isArray(t)||!t.length?"":[...t].sort(Zt).join("|")}function eC({groupSize:t,drawPositionOffset:e}){if(!t)return[];let r=m=>[...Array(m)].map((d,l)=>l),n=r(2*Math.round(t/2)+1).slice(1),o=r(n.length-1).map(()=>[]),i=n.slice(0,n.length/2),s=n.slice(n.length/2);n.slice(1).forEach((m,d)=>{i.forEach((I,S)=>{o[d].push([i[S],s[S]])});let l=i.shift(),f=i.pop(),g=s.shift();i=[l,g,...i].filter(Boolean),s=[...s,f].filter(Boolean)});let a=i.shift(),c=i.pop(),u=s.shift();i=[a,u,...i].filter(Boolean),s=[...s,c].filter(Boolean);let p=m=>m[0].reduce((d,l)=>d+l);return[...o].reverse().sort((m,d)=>p(m)-p(d)).map(m=>m.filter(d=>d.every(l=>l<=t)).map(d=>{let l=d.map(f=>f+e);return SS(l)}))}function j$({rounds:t,hash:e}){return t?.length?t?.reduce((r,n,o)=>n.includes(e)?o+1:r,void 0):{error:nt}}var k0={getRoundRobinGroupMatchUps:IS,determineRoundNumber:j$,drawPositionsHash:SS,groupRounds:eC};function Rc(t){let{hasExistingDrawDefinition:e,groupNameBase:r="Group",playoffAttributes:n,stageSequence:o=1,structureOptions:i,appliedPolicies:s,qualifyingOnly:a,seedingProfile:c,stage:u=W,matchUpType:p,roundTarget:m,structureId:d,groupNames:l,tieFormat:f,drawSize:g,idPrefix:I,isMock:S,uuids:h}=t,T=t.structureName??n?.["0"]?.name??xe(W),{groupCount:y,groupSize:E}=q$({structureOptions:i,appliedPolicies:s,drawSize:g}),A=po,N,D=Q(1,y+1).map(U=>{let b=$$({groupSize:E,structureOrder:U,matchUpType:p,drawSize:g,idPrefix:I,isMock:S});N=Array.isArray(b)?Math.max(...b.map(({roundNumber:_})=>_??0)):0;let C=l?.[U-1]??`${r} ${U}`;return Ko({structureId:h?.pop(),hasExistingDrawDefinition:e,structureType:su,finishingPosition:A,qualifyingOnly:a,structureOrder:U,structureName:C,tieFormat:f,matchUps:b,stage:u})}),R=Ko({structureId:d??h?.pop(),hasExistingDrawDefinition:e,structureType:de,finishingPosition:A,seedingProfile:c,structureName:T,stageSequence:o,structures:D,tieFormat:f,stage:u});return m&&ut({extension:{name:bn,value:m},element:R}),{structures:[R],maxRoundNumber:N,groupCount:y,links:[],groupSize:E,...P}}function q$({appliedPolicies:t,structureOptions:e,drawSize:r}){let n=e?.groupSize,o=e?.groupSizeLimit||8,{validGroupSizes:i}=ud({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 ud(t){let{groupSizeLimit:e=10,drawSize:r=0}=t??{},n=Q(3,e+1).filter(o=>{let i=Math.ceil(r/o),s=i*o-r,a=Math.ceil(r/i),c=Math.ceil(s/i);return(!s||s<o)&&a===o&&a>=3&&c<2});return{...P,validGroupSizes:n}}function $$({structureOrder:t,matchUpType:e,groupSize:r,drawSize:n,idPrefix:o,isMock:i,uuids:s}){let a=(t-1)*r,c=Q(1+a,r+1+a),u=IS({drawPositions:c}).uniqueMatchUpGroupings??[],p=eC({groupSize:r,drawPositionOffset:a});return u.map(l).sort((f,g)=>(f.roundNumber??1/0)-(g.roundNumber??1/0));function d(f){return p.reduce((g,I,S)=>I.includes(f)?S+1:g,void 0)}function l(f){let g=SS(f),I=d(g),S=[1,n],h=K$({structureOrder:t,drawPositions:f,roundNumber:I,idPrefix:o,uuids:s}),T={matchUpStatus:I?zt:"BYE",matchUpType:e,finishingPositionRange:{winner:S,loser:S},drawPositions:f,roundNumber:I,matchUpId:h};return i&&(T.isMock=!0),T}}function K$({structureOrder:t,drawPositions:e,roundNumber:r,idPrefix:n,uuids:o}){return n?`${n}-${t}-${r}-DP-${e.join("-")}`:o?.pop()||it()}function hS(t){let{roundRobinGroupsCount:e,participantsCount:r,cluster:n}=t;if(!yt(r))return{seedBlocks:void 0,...M({result:{error:O},context:{participantsCount:r},stack:"getSeedBlocks"})};let o=Pi(r);if(e){let l=Math.min(e,o),f=[],g=1;for(Q(0,l).forEach(()=>{f.push([g]),g++});g<o;){let I=Q(g,g+l);g+=l,f.push(I)}return{...P,seedBlocks:f}}let i=Q(1,o+1),s=[],a=o/2;for(;a>1;){let l=he(i,a),f=l.length;l.forEach((g,I)=>{let S,h=I<f/2,T=I%2===0,y=g[0],E=g[g.length-1];n&&f>4?f===8?S=h?E:y:S=T?y:E:S=h?y:E,Re(g,s)||s.push(S)}),a=a/2}let c=i.filter(l=>!s.includes(l));for(;c.length;)c.length%2===0?s.push(c.pop()):s.push(c.shift());let u=Q(0,20).map(l=>Math.pow(2,l));u.unshift(1);let p=u.indexOf(o),m=0,d=[];return Q(0,p).forEach(l=>{d.push(s.slice(m,m+u[l])),m+=u[l]}),{...P,seedBlocks:d}}function TS({roundRobinGroupsCount:t,drawSize:e}){let r="getSeedGroups";if(!yt(e))return{seedGroups:void 0,...M({result:{error:O},context:{drawSize:e},stack:r})};if(t){if(!yt(t))return{seedGroups:void 0,...M({context:{roundRobinGroupsCount:t},result:{error:O},stack:r})};let n=1,o=Math.floor(e/t);return{seedGroups:Q(0,o).map(()=>{let s=Q(n,n+t);return n+=t,s})}}else{let{seedBlocks:n}=hS({participantsCount:e,roundRobinGroupsCount:t}),o=0;return{seedGroups:(n??[]).map(s=>(s??[]).map(()=>(o+=1,o)))}}}function bE({roundRobinGroupsCount:t,participantsCount:e}){if(t){let{validGroupSizes:o}=ud({drawSize:e});if(!o?.map(a=>Math.ceil(e/a))?.includes(t))return M({context:{roundRobinGroupsCount:t},result:{error:O}})}let{seedGroups:r}=TS({drawSize:e,roundRobinGroupsCount:t}),n=r?.map(o=>Math.min(...o))??[];return{...P,seedingThresholds:n}}function Uu(t){if(!t)return 1/0;if(yt(t))return st(t);let e=t.split("-")[0];return yt(e)?st(e):1/0}function hi({provisionalPositioning:t,returnAllProxies:e,appliedPolicies:r,seedingProfile:n,drawDefinition:o,allPositions:i,structure:s,random:a}){let c=[];if(!s)return{error:_i};let{matchUps:u,roundMatchUps:p}=ht({matchUpFilters:{roundNumbers:[1]},provisionalPositioning:t,structure:s}),{seedAssignments:m}=Ur({provisionalPositioning:t,returnAllProxies:e,drawDefinition:o,structure:s}),{positionAssignments:d}=se({structure:s}),l=d?.length,f=m?.length??0,g=[],S=Object.keys(p).map(k=>Number.parseInt(k)).sort((k,G)=>k-G).map(k=>{let G=p[k].map(B=>B.drawPositions).flat(1/0).filter(Boolean),V=G.filter(B=>!g.includes(B));return g=g.concat(...G),V}).filter(k=>k.length).reverse(),h=S.pop()??[],T=h&&Math.min(...h)-1||0;n=n??r?.seeding?.seedingProfile;let y=h?.length||0,E=S.filter(k=>k.filter(G=>G<=f).length),{stage:A,structureType:N,roundLimit:D}=s,R=N===de,U=!R&&S?.length,b=!R&&A===Z&&D,C=E.flat(1/0),_=U?C?.length:0,v=i?l:f,w=Pc({drawDefinition:o,structure:s,matchUps:u}),L=w?0:!U&&v||v&&C.length<v&&v-C.length||0;if(b){let k=s?.matchUps?s.matchUps.filter(({roundNumber:V})=>V===s.roundLimit).length:0,G=h.length/k;if(!U){let V=md(n),B=he(h,G),z=1,H=Q(0,B[0].length).map(()=>{let K=Q(z,z+B.length);return z+=B.length,K});({validSeedBlocks:c}=G0({drawPositionBlocks:B,nonRandom:n?.nonRandom,positioning:V,seedGroups:H,random:a}))}}else R?{validSeedBlocks:c}=z$({nonRandom:n?.nonRandom,seedingProfile:n,structure:s,random:a}):U?c=E.map(k=>({seedNumbers:k,drawPositions:k})):w&&he(h,2).map((G,V)=>({drawPositions:[G[0]],seedNumbers:[V+1]})).forEach(G=>c.push(G));if(!R&&!w&&!b){let{blocks:k}=Q$({drawPositionOffset:T,seedNumberOffset:_,seedCountGoal:L,seedingProfile:n,baseDrawSize:y});k.forEach(G=>c.push(G))}let x=c.flatMap(k=>k.drawPositions).reduce((k,G)=>h?.includes(G)&&k,!0);return!w&&!U&&!R&&!x?{error:BD,validSeedBlocks:[],isContainer:R,isFeedIn:U}:{isLuckyStructure:w,validSeedBlocks:c,isContainer:R,isFeedIn:U}}function z$({seedingProfile:t,structure:e,nonRandom:r,random:n}){let o=e.structures??[],i=o.length,s=Pt({structure:e})?.positionAssignments,a=md(t),c=s?.length??0,{seedGroups:u}=TS({roundRobinGroupsCount:i,drawSize:c}),p=o.map(m=>Pt({structure:m}).positionAssignments?.map(d=>d.drawPosition));return G0({drawPositionBlocks:p,positioning:a,seedGroups:u,nonRandom:r,random:n})}function G0({drawPositionBlocks:t,positioning:e,seedGroups:r,nonRandom:n,random:o}){let i=[],{divisionGroupings:s}=F0({size:r.length,positioning:e}),a=[];return r.forEach((c,u)=>{let p=L0({blockPattern:s,index:u});c.forEach((m,d)=>{let l=u%2?t.length-d-1:d,g=t[l].slice().filter((S,h)=>p.includes(h+1)&&S);e!==Li?g=n?g:ar(g,o):u%2&&g.reverse();let I=g.find(S=>!a.includes(S));I&&(a.push(I),i.push({drawPositions:[I],seedNumbers:[m]}))})}),{validSeedBlocks:i}}function Q$(t){let{drawPositionOffset:e=0,roundRobinGroupsCount:r,seedNumberOffset:n=0,seedingProfile:o,seedCountGoal:i,baseDrawSize:s}=t,a,c=[],{seedBlocks:u}=hS({cluster:[iu,Hm].includes(md(o)),participantsCount:s,roundRobinGroupsCount:r});a=0;for(let p of u){if(a+1>i)break;let m=p.map(l=>l+e),d=X$(a+1,p.length).map(l=>+l+n);a+=p.length,c.push({drawPositions:m,seedNumbers:d})}return{blocks:c}}function X$(t,e){return Array.from(new Array(e),(r,n)=>n+t)}function pd({appliedPolicies:t,drawDefinition:e,seedBlockInfo:r,drawPosition:n,structureId:o,seedNumber:i}){let{structure:s}=tt({drawDefinition:e,structureId:o});t??=ft({drawDefinition:e}).appliedPolicies;let a=r?.validSeedBlocks;return!a&&s&&(a=hi({appliedPolicies:t,drawDefinition:e,structure:s})?.validSeedBlocks),t?.seeding?.validSeedPositions?.ignore?!0:t?.seeding?.validSeedPositions?.strict?(a.find(m=>m.seedNumbers.includes(i))?.drawPositions??[]).includes(n):a.flatMap(u=>u.drawPositions).includes(n)}function CE(t){let{provisionalPositioning:e,drawDefinition:r,seedingProfile:n,seedBlockInfo:o,structureId:i,randomize:s,random:a}=t,{structure:c}=tt({drawDefinition:r,structureId:i}),{seedAssignments:u}=Ur({returnAllProxies:t.returnAllProxies,provisionalPositioning:e,drawDefinition:r,structure:c}),{positionAssignments:p}=se({structure:c}),d=p?.filter(k=>k.participantId??k.bye??k.qualifier)?.map(k=>k.drawPosition).filter(Boolean),{appliedPolicies:l}=ft({drawDefinition:r}),g=((o?.validSeedBlocks||c&&hi({returnAllProxies:t.returnAllProxies,provisionalPositioning:e,appliedPolicies:l,drawDefinition:r,seedingProfile:n,structure:c})?.validSeedBlocks)??[]).find(k=>k.drawPositions.filter(V=>!d?.includes(V)).length),I=u?.map(k=>k.participantId).filter(Boolean),S=p?.map(k=>k.participantId).filter(Boolean),h=I?.filter(k=>S?.includes(k)),T=I?.filter(k=>!S?.includes(k)),y=u?.filter(k=>T?.includes(k.participantId)),E=u?.filter(k=>!k.participantId),N=(y?.length&&y.length>0?y.length:E?.length??0)&&g?.drawPositions.filter(k=>!d?.includes(k))||[],D=s?ar(N,a):N,R=[],U=D.map(()=>{let G=x(y,R)?.participantId;return G&&R.push(G),G}).filter(Boolean),b=u?.filter(k=>h?.includes(k.participantId)).map(k=>k.seedNumber),_=(g?.seedNumbers??[]).filter(k=>!b?.includes(k)),v=u?.filter(k=>_.includes(k.seedNumber)).map(k=>k.participantId),w=l?.seeding?.duplicateSeedNumbers;return{nextSeedBlock:g,unplacedSeedParticipantIds:(typeof w=="boolean"?w:!0)?U:v,unplacedSeedNumbers:_,unfilledPositions:D,unplacedSeedAssignments:y};function x(k,G){let V=k.filter(K=>!G.includes(K.participantId)),B=Math.min(...V.map(K=>Uu(K.seedValue))),z=V.filter(K=>Uu(K.seedValue)===B);return ar(z,a).pop()}}function md(t){if(typeof t=="string")return t;if(typeof t=="object")return t.positioning}function Wa({provisionalPositioning:t,tournamentRecord:e,drawDefinition:r,seedingProfile:n,participantId:o,seedBlockInfo:i,structureId:s,seedNumber:a,seedValue:c,eventId:u,event:p}){let m="assignSeed",{structure:d}=tt({drawDefinition:r,structureId:s}),{positionAssignments:l}=se({structure:d}),f=Ur({provisionalPositioning:t,drawDefinition:r,structure:d}).seedAssignments,g=f.map(A=>A.seedNumber),I=Nu({drawDefinition:r,participantId:o});if(o&&!I)return M({result:{error:Hr},context:{participantId:o},stack:m});let S=p?Bt({event:p}).flightProfile?.flights?.length:0,h=S&&S>1,y=l?.find(A=>A.participantId===o)?.drawPosition;if(y&&!pd({drawPosition:y,drawDefinition:r,seedBlockInfo:i,structureId:s,seedNumber:a}))return M({result:{error:Fg},context:{assignedDrawPosition:y},info:"invalid seed position",stack:m});g.includes(a)||f.push({seedNumber:a,seedValue:c});let E;return f.forEach(A=>{A.participantId===o&&A.seedNumber!==a&&(A.participantId=void 0),A.seedNumber===a&&(A.participantId=o,!n?.groupSeedingThreshold&&!h&&(A.seedValue=c??a),E=!0)}),E?(vl({tournamentId:e?.tournamentId,drawDefinition:r,structure:d,eventId:u}),{...P}):M({result:{error:VD},stack:m})}function rf({inContextTargetMatchUp:t,drawPositionSideIndex:e,teamParticipantId:r,tournamentRecord:n,drawDefinition:o,matchUp:i,event:s}){let a=t?.sides?.[e]?.sideNumber,c=a&&i.sides?.find(d=>d.sideNumber===a),{extension:u}=ot({element:o,name:Vo}),p=u?.value??{},m=q(p[r],!1,!0);if(c)i?.sides?.forEach(d=>{d.sideNumber===a&&(d.lineUp=m)});else{i.sides=[1,2].map(l=>({...i.sides?.find(g=>g.sideNumber===l)??{},sideNumber:l}));let d=i.sides.find(l=>l.sideNumber===a);d&&(d.lineUp=m)}It({tournamentId:n?.tournamentId,context:"updateSidLineUp",eventId:s?.eventId,drawDefinition:o,matchUp:i})}function ME(t){let{sourceMatchUp:e}=t,{targetMatchUp:r,structure:n,matchUpsMap:o,drawPosition:i}=t,s=r.roundNumber>1&&r.roundNumber-1,a=jo({structureId:n.structureId,matchUpsMap:o});Pe({method:"getPairedPreviousMatchUpIsDoubleExit",color:"brightcyan",keyColors:{structureId:"brightyellow",sourceMatchUpId:"brightmagenta"},structureId:n.structureId?.slice(0,8),targetMatchUpId:r.matchUpId,targetRound:[r.roundNumber,r.roundPosition],previousRoundNumber:s,sourceMatchUpId:e?.matchUpId,sourceStructureId:e?.structureId?.slice(0,8),sourceRound:e?[e.roundNumber,e.roundPosition]:void 0,drawPosition:i,structureMatchUpCount:a?.length}),e&&e.structureId!==n.structureId&&i?(Pe({method:"getPairedPreviousMatchUpIsDoubleExit",color:"cyan",info:"cross_structure_sourceMatchUp_resolving_in_target",originalSourceId:e?.matchUpId,originalSourceStructure:e?.structureId?.slice(0,8),targetStructure:n.structureId?.slice(0,8)}),e=a.find(({drawPositions:f,roundNumber:g})=>g===s&&f?.includes(i)),Pe({method:"getPairedPreviousMatchUpIsDoubleExit",color:"cyan",info:"resolved_cross_structure_sourceMatchUp",resolvedMatchUpId:e?.matchUpId,resolvedRound:e?[e.roundNumber,e.roundPosition]:void 0,resolvedStatus:e?.matchUpStatus})):!e&&i&&(e=a.find(({drawPositions:f,roundNumber:g})=>g===s&&f?.includes(i)),Pe({method:"getPairedPreviousMatchUpIsDoubleExit",color:"cyan",info:"resolved_sourceMatchUp_from_drawPosition",resolvedMatchUpId:e?.matchUpId,resolvedRound:e?[e.roundNumber,e.roundPosition]:void 0,resolvedStatus:e?.matchUpStatus}));let c=e?.roundPosition,u=c%2?1:-1,p=c+u,m=s&&a.find(({roundNumber:f,roundPosition:g})=>f===s&&g===p),d=m?.matchUpStatus,l=[Qt,ge].includes(d);return Pe({method:"getPairedPreviousMatchUpIsDoubleExit",color:l?"brightred":"brightgreen",keyColors:{pairedMatchUpId:"brightcyan",isDoubleExit:l?"brightred":"brightgreen"},sourceRoundPosition:c,offset:u,pairedRoundPosition:p,pairedMatchUpId:m?.matchUpId,pairedRound:m?[m.roundNumber,m.roundPosition]:void 0,pairedStatus:d,isDoubleExit:l}),{pairedPreviousMatchUp:m,pairedPreviousMatchUpIsDoubleExit:l}}function V0({drawPosition:t,drawPositions:e}){let r=!1,n=!!e?.includes(t);return{updatedDrawPositions:n?e??[]:[...e,void 0,void 0].slice(0,2).map(s=>!s&&!n?(n=!0,r=!0,t):s).sort(Zt).filter(Boolean),positionAdded:r,positionAssigned:n}}function vE({structureId:t,matchUpsMap:e,matchUp:r}){let n=r?.roundPosition,o=n%2?1:-1,i=n+o;return{pairedPreviousMatchUp:jo({matchUpsMap:e,structureId:t}).find(({roundNumber:c,roundPosition:u})=>c===r?.roundNumber&&u===i)}}function OE({inContextDrawMatchUps:t,sourceMatchUpStatus:e,sourceMatchUpId:r,matchUpsMap:n,matchUp:o}){let i=t.find(a=>a.matchUpId===r),{pairedPreviousMatchUp:s}=vE({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=wt(p)||!isNaN(p)?{code:p}:p;return m.sideNumber===u?{...m,previousMatchUpStatus:e}:m})}}function nf({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 bc({inContextDrawMatchUps:t,sourceMatchUpStatus:e,tournamentRecord:r,sourceMatchUpId:n,drawDefinition:o,matchUpStatus:i,drawPosition:s,matchUpsMap:a,matchUpId:c,event:u}){let p="assignMatchUpDrawPosition";a??=Ie({drawDefinition:o});let m=t??te({inContext:!0,drawDefinition:o,matchUpsMap:a}).matchUps??[],d=m.find(F=>F.matchUpId===c),l=d?.structureId,f=o?.structures?.find(F=>F.structureId===l);if(!f)return{error:Nt};let g=a?.drawMatchUps?.find(F=>F.matchUpId===c),I=g?.drawPositions??[],{positionAdded:S,positionAssigned:h,updatedDrawPositions:T}=V0({drawPositions:I,drawPosition:s}),{positionAssignments:y}=Pt({drawDefinition:o,structure:f}),A=y?.filter(F=>T.includes(F.drawPosition))?.find(({bye:F})=>F),N=g?.matchUpStatus&&Ye(g.matchUpStatus)&&T.filter(Boolean).length<2;i=J$({isByeMatchUp:A,matchUpStatus:i,isDoubleExitExit:N,matchUp:g});let D=!!(Ye(g?.matchUpStatus)&&g?.winningSide);g&&S&&Z$({updatedDrawPositions:T,sourceMatchUpStatus:e,isPropagatedExit:D,isDoubleExitExit:N,tournamentRecord:r,inContextMatchUp:d,sourceMatchUpId:n,drawDefinition:o,matchUpStatus:i,drawPosition:s,matchUpsMap:a,matchUpId:c,matchUp:g,stack:p});let R=er({inContextDrawMatchUps:m,inContextMatchUp:d,drawDefinition:o,matchUpId:c}),{targetMatchUps:{winnerMatchUp:U,loserMatchUp:b,loserTargetDrawPosition:C},targetLinks:{loserTargetLink:_}}=R,v=an(o?.drawType),w=t3({inContextDrawMatchUps:m,positionAssigned:h,isPropagatedExit:D,tournamentRecord:r,inContextMatchUp:d,drawDefinition:o,matchUpStatus:i,winnerMatchUp:U,drawPosition:s,isByeMatchUp:A,isLuckyDraw:v,matchUpsMap:a,matchUp:g,structure:f});if(w?.error)return w;g?.matchUpType===xt&&e3({inContextDrawMatchUps:m,positionAssignments:y,tournamentRecord:r,drawDefinition:o,drawPosition:s,matchUp:g});let L=r3({updatedDrawPositions:T,loserTargetDrawPosition:C,tournamentRecord:r,loserTargetLink:_,drawDefinition:o,structureId:f.structureId,isByeMatchUp:A,loserMatchUp:b,matchUpsMap:a,event:u});return L?.error?L:h?{...P}:M({result:{error:Yc},context:{drawPosition:s},stack:p})}function J$({isByeMatchUp:t,matchUpStatus:e,isDoubleExitExit:r,matchUp:n}){return t&&"BYE"||e||r&&n.matchUpStatus||n?.matchUpStatus&&[Qt,ge].includes(n.matchUpStatus)&&n.matchUpStatus||zt}function Z$({updatedDrawPositions:t,sourceMatchUpStatus:e,isPropagatedExit:r,isDoubleExitExit:n,tournamentRecord:o,inContextMatchUp:i,sourceMatchUpId:s,drawDefinition:a,matchUpStatus:c,drawPosition:u,matchUpsMap:p,matchUpId:m,matchUp:d,stack:l}){let f=te({inContext:!0,drawDefinition:a,matchUpsMap:p}).matchUps??[],g=n&&nf({inContextDrawMatchUps:f,drawPosition:u,matchUpId:m})||r&&d.winningSide||void 0;d?.matchUpStatusCodes&&OE({inContextDrawMatchUps:f,sourceMatchUpStatus:e,sourceMatchUpId:s,matchUpsMap:p,matchUp:d}),Object.assign(d,{drawPositions:t,winningSide:g,matchUpStatus:r?d?.matchUpStatus:c}),It({tournamentId:o?.tournamentId,eventId:i?.eventId,context:l,drawDefinition:a,matchUp:d})}function t3({inContextDrawMatchUps:t,positionAssigned:e,isPropagatedExit:r,tournamentRecord:n,inContextMatchUp:o,drawDefinition:i,matchUpStatus:s,winnerMatchUp:a,drawPosition:c,isByeMatchUp:u,isLuckyDraw:p,matchUpsMap:m,matchUp:d,structure:l}){if(e&&u&&!p){if(a)if(["BYE",Qt,ge].includes(s)){let f=bc({matchUpId:a.matchUpId,inContextDrawMatchUps:t,tournamentRecord:n,drawDefinition:i,drawPosition:c,matchUpsMap:m});if(f.error)return f}else{let{structureId:f}=a;f!==l.structureId&&console.log("winnerMatchUp in different structure... participant is in different targetDrawPosition")}}else if(e&&r){if(a){let f=bc({matchUpId:a.matchUpId,inContextDrawMatchUps:t,tournamentRecord:n,drawDefinition:i,drawPosition:c,matchUpsMap:m});if(f.error)return f}}else if(a&&o&&!o.feedRound){let{pairedPreviousMatchUpIsDoubleExit:f}=ME({targetMatchUp:d,drawPosition:c,matchUpsMap:m,structure:l});if(f){let g=bc({matchUpId:a.matchUpId,inContextDrawMatchUps:t,tournamentRecord:n,drawDefinition:i,drawPosition:c,matchUpsMap:m});if(g.error)return g}}}function e3({inContextDrawMatchUps:t,positionAssignments:e,tournamentRecord:r,drawDefinition:n,drawPosition:o,matchUp:i}){let s=t?.find(({matchUpId:p})=>p===i.matchUpId),c=(s?.sides??[]).reduce((p,m,d)=>m.drawPosition===o?d:p,void 0),u=e?.find(p=>p.drawPosition===o)?.participantId;u&&c!==void 0&&rf({inContextTargetMatchUp:s,drawPositionSideIndex:c,teamParticipantId:u,tournamentRecord:r,drawDefinition:n,matchUp:i})}function r3({updatedDrawPositions:t,loserTargetDrawPosition:e,tournamentRecord:r,loserTargetLink:n,drawDefinition:o,structureId:i,isByeMatchUp:s,loserMatchUp:a,matchUpsMap:c,event:u}){if(n?.linkCondition!==Wn||t.filter(Boolean).length!==2||s)return;if(jo({structureId:i,matchUpsMap:c}).filter(({drawPositions:l,roundNumber:f})=>f===1&&Re(l,t)).every(({matchUpStatus:l})=>[ie,De].includes(l))&&a){let{structureId:l}=a,f=Or({drawPosition:e,tournamentRecord:r,drawDefinition:o,structureId:l,matchUpsMap:c,event:u});if(f.error)return f}}function _E({inContextDrawMatchUps:t,drawDefinition:e,assignments:r,matchUpsMap:n,structure:o}){let s=ji({drawDefinition:e})?.containedStructures?.[o.structureId]?.map(({structureId:m})=>m)??[];s.push(o?.structureId);let a=r?.map(({drawPosition:m})=>m)??[],c=t?.filter(m=>s.includes(m.structureId)&&Yt(m.drawPositions??[],a).length)??[],u=c.map(({matchUpId:m})=>m),p=n?.drawMatchUps?.filter(m=>u.includes(m.matchUpId))??[];return{drawPositions:a,matchUps:p,targetMatchUps:c}}function of({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}=ad({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 Ri(t){return`${t} must be an array`}function sf({lineUp:t,tieFormat:e}){let r=[];if(!Array.isArray(t))return r.push(Ri("lineUp")),{valid:!1,errors:r,error:O};let n=t.every(s=>{if(typeof s!="object")return r.push("lineUp entries must be objects"),!1;let{participantId:a,collectionAssignments:c}=s;return a?typeof a!="string"?(r.push("participantIds must be strings"),!1):Array.isArray(c)?c.every(u=>{if(typeof u!="object")return r.push("collectionAssignments must be objects"),!1;let{collectionPosition:p}=u;return typeof p!="number"?(r.push("collectionPosition must be a number"),!1):!0}):(r.push(Ri("collectionAssignments")),!1):(r.push("Missing participantId"),!1)}),o=pt(t.map(gt)).length===t.length;return o||r.push("Duplicated participantId(s)"),{valid:n&&o,errors:r,error:r.length?O:void 0}}function Us({drawDefinition:t,participantId:e,tieFormat:r,lineUp:n}){if(typeof t!="object")return{error:$};if(typeof e!="string")return{error:We};let o=sf({lineUp:n,tieFormat:r});if(!o.valid)return o;let{extension:i}=ot({element:t,name:Vo}),s=i?.value??{};return s[e]=of({lineUp:n}),ut({element:t,extension:{name:Vo,value:s}}),yc({drawDefinition:t}),{...P}}function yS({inContextDrawMatchUps:t,inheritance:e=!0,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,assignments:i,structure:s,event:a}){if(!n)return{error:$};let{drawPositions:c,matchUps:u,targetMatchUps:p}=_E({inContextDrawMatchUps:t,matchUpsMap:o,assignments:i,structure:s});for(let m of p)m.matchUpType===Ir&&(m.sides??[]).forEach((d,l)=>{if(d?.drawPosition&&c?.includes(d.drawPosition)){let f=u.find(({matchUpId:g})=>g===m.matchUpId);if(f?.sides?.[l]){if(delete f.sides[l].lineUp,e===!1){let g=m.tieFormat,I=d.participantId;g&&I&&Us({drawDefinition:n,participantId:I,lineUp:[],tieFormat:g})}It({tournamentId:r?.tournamentId,context:"resetLineUps",eventId:a?.eventId,drawDefinition:n,matchUp:f})}}});return{...P}}function On({provisionalPositioning:t,inContextDrawMatchUps:e,isQualifierPosition:r,sourceMatchUpStatus:n,tournamentRecord:o,drawDefinition:i,seedingProfile:s,participantId:a,seedBlockInfo:c,drawPosition:u,matchUpsMap:p,structureId:m,event:d}){let l="assignDrawPosition";if(!a&&!r)return M({result:{error:We},stack:l});p=p??Ie({drawDefinition:i}),e||({matchUps:e}=te({inContext:!0,drawDefinition:i,matchUpsMap:p}));let f=tt({drawDefinition:i,structureId:m});if(f.error)return M({result:f,stack:l});let{structure:g}=f;if(!g)return{error:Nt};if(Ae({structure:g}))return M({result:{error:cr},stack:l});let{seedAssignments:I}=Ur({provisionalPositioning:t,drawDefinition:i,structure:g}),h=I?.find(C=>C.participantId===a)?.seedNumber,{appliedPolicies:T}=ft({tournamentRecord:o,drawDefinition:i,structure:g,event:d});if(h&&!pd({seedNumber:h,appliedPolicies:T,drawDefinition:i,seedBlockInfo:c,drawPosition:u,structureId:m}))return M({result:{error:Fg},context:{drawPosition:u},stack:l});let E=se({structure:g}).positionAssignments??[],A=E?.find(C=>C.drawPosition===u);if(!A)return M({result:{error:ps},context:{drawPosition:u},stack:l});if(E?.map(gt).includes(a))return M({result:{error:Pa},context:{drawPosition:u},stack:l});let{containsParticipant:D,containsBye:R}=Ql(A);if(R){let C=Au({inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,drawPosition:u,structureId:m,matchUpsMap:p,event:d});if(C.error)return M({result:C,stack:l})}if(D&&A.participantId!==a){let{activeDrawPositions:C}=Xi({drawDefinition:i,structureId:m});if(C.includes(u))return M({result:{error:qc},stack:l});yS({assignments:[A],inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,matchUpsMap:p,structure:g})}A.participantId=a,r&&(A.qualifier=!0),n3({provisionalPositioning:t,tournamentRecord:o,drawDefinition:i,seedingProfile:s,participantId:a,structureId:m,structure:g,event:d}),g.structureType===de?o3({inContextDrawMatchUps:e,positionAssignments:E,positionAssignment:A,tournamentRecord:o,drawDefinition:i,participantId:a,matchUpsMap:p,structure:g}):i3({provisionalPositioning:t,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:o,drawDefinition:i,drawPosition:u,matchUpsMap:p,structure:g,event:d});let U=i.entries?.find(C=>C.participantId===a),b=d?.entries?.find(C=>C.participantId===a);return!U&&b&&tf({entryStatus:b.entryStatus,entryStage:g.stage,ignoreStageSpace:!0,drawDefinition:i,participantId:a,event:d}),hn({tournamentId:o?.tournamentId,drawDefinition:i,structure:g,event:d}),{positionAssignments:E,...P}}function n3({provisionalPositioning:t,tournamentRecord:e,drawDefinition:r,seedingProfile:n,participantId:o,structureId:i,structure:s,event:a}){if(!(s.stage===W&&(!s.stageSequence||s.stageSequence>1))&&!(s.stage&&[me,Vt].includes(s.stage)))return;let u=s.stage===Z?Z:W,d=(r.structures?.find(l=>l?.stage===u&&l?.stageSequence===1)?.seedAssignments??[]).find(l=>l.participantId===o);d?.participantId&&Wa({eventId:a?.eventId,participantId:d.participantId,seedNumber:d.seedNumber,seedValue:d.seedValue,provisionalPositioning:t,tournamentRecord:e,drawDefinition:r,seedingProfile:n,structureId:i,event:a})}function o3({inContextDrawMatchUps:t,positionAssignments:e,positionAssignment:r,tournamentRecord:n,drawDefinition:o,participantId:i,matchUpsMap:s,structure:a}){AE({positionAssignments:e,tournamentRecord:n,drawDefinition:o,matchUpsMap:s,structure:a});let{drawPositions:c,matchUps:u,targetMatchUps:p}=_E({assignments:[r],inContextDrawMatchUps:t,drawDefinition:o,matchUpsMap:s,structure:a});if(c&&u?.length===1&&u[0].matchUpType===xt){let d=(p?.[0].sides??[]).reduce((l,f,g)=>c?.includes(f.drawPosition)?g:l,void 0);rf({inContextTargetMatchUp:p[0],teamParticipantId:i,matchUp:u[0],drawPositionSideIndex:d,tournamentRecord:n,drawDefinition:o})}}function i3({provisionalPositioning:t,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:n,drawDefinition:o,drawPosition:i,matchUpsMap:s,structure:a,event:c}){let u={isCollectionMatchUp:!1},{matchUps:p}=ht({provisionalPositioning:t,matchUpFilters:u,drawDefinition:o,matchUpsMap:s,structure:a,event:c}),{roundMatchUps:m}=Ue({matchUps:p}),{initialRoundNumber:d}=Zs({drawPosition:i,matchUps:p}),l=d&&m?.[d].find(f=>f.drawPositions?.includes(i));if(l){let f=bc({matchUpId:l.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:n,drawDefinition:o,drawPosition:i,matchUpsMap:s});if(f.error)return M({stack:"assignDrawPositionToMatchUps",context:{drawPosition:i},result:f})}return{...P}}function af(t){let{participantIdAttributeName:e="participantId",isQualifierPosition:r,positionActionName:n,tournamentRecord:o,drawDefinition:i,participantId:s,drawPosition:a,structureId:c,event:u}=t,p="positionParticipantAction";if(!i)return{error:$};let m=ft({tournamentRecord:o,drawDefinition:i,event:u}).appliedPolicies??{},{inContextDrawMatchUps:d,matchUpsMap:l}=t;l||(l=Ie({drawDefinition:i}),Object.assign(t,{matchUpsMap:l})),d||({matchUps:d}=te({inContext:!0,drawDefinition:i,matchUpsMap:l}),Object.assign(t,{inContextDrawMatchUps:d}));let{positionAssignments:f}=Pt({drawDefinition:i,structureId:c}),g=f?.find(y=>y.drawPosition===a);if(g?.participantId){let y=g.participantId,E=On({inContextDrawMatchUps:d,tournamentRecord:o,drawDefinition:i,participantId:s,drawPosition:a,structureId:c,matchUpsMap:l,event:u});return E.success?T({appliedPolicies:m,removedParticipantId:y}):M({result:E,stack:p})}let I=Au({inContextDrawMatchUps:d,tournamentRecord:o,drawDefinition:i,drawPosition:a,structureId:c,matchUpsMap:l,event:u});if(I.error)return M({result:I,stack:p});let S=I.participantId,h=On({inContextDrawMatchUps:d,isQualifierPosition:r,tournamentRecord:o,drawDefinition:i,participantId:s,drawPosition:a,structureId:c,matchUpsMap:l,event:u});if(!h.success)return M({result:h,stack:p});return T({appliedPolicies:m,removedParticipantId:S});function T({appliedPolicies:y,removedParticipantId:E}){let{structure:A}=tt({drawDefinition:i,structureId:c});Ol({drawPositions:[a],structure:A});let N={[e]:s,name:n,drawPosition:a,structureId:c};return Ec({appliedPolicies:y,drawDefinition:i,positionAction:N}),M({context:{removedParticipantId:E},result:{...P},stack:p})}}function B0({luckyLoserParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o}){return af({positionActionName:"luckyLoserDrawPositionAssignment",participantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o})}function rC(t){return B0(t)}function xE({params:t,modMap:e,structure:r}){let{tournamentRecord:n,drawDefinition:o,event:i}=t;for(let s of r.matchUps)e[s.matchUpId]&&(s.roundNumber=e[s.matchUpId],It({tournamentId:n?.tournamentId,eventId:i?.eventId,drawDefinition:o,matchUp:s}))}function wE(t,e){let r=[{drawDefinition:!0,structureId:!0}];Array.isArray(e)&&r.push(...e);let n=X(t,r);if(n.error)return n;let o=tt(t);if(o.error)return o;let i=o.structure;if(!Ae({structure:i}))return M({result:{error:Co,message:"structure must be adHoc"}});let{roundMatchUps:a=[],roundNumbers:c}=Ue({matchUps:i?.matchUps});return c?.length?{valid:!0,structure:i,roundMatchUps:a,roundNumbers:c}:{error:Bn}}function nC(t){let e=wE(t,[{targetRoundNumber:!0,roundNumber:!0,[Ge]:iL}]);if(e.error)return e;let{structure:r,roundMatchUps:n,roundNumbers:o}=e,{targetRoundNumber:i,roundNumber:s}=t;if(!o?.includes(s)||!o?.includes(i))return M({result:{error:O},info:"roundNumbers must be valid rounds"});let a=i>s,c=a?Q(s+1,i+1):Q(i,s),u={};return c.forEach(p=>(n?.[p]??[]).forEach(({matchUpId:m})=>{u[m]=p-(a?1:-1)})),n?.[s]?.forEach(({matchUpId:p})=>u[p]=i),xE({params:t,modMap:u,structure:r}),{...P}}function oC({structurePositionAssignments:t,provisionalPositioning:e,tournamentRecord:r,drawDefinition:n,event:o}){if(!n)return{error:$};if(!Array.isArray(t))return{error:O};let i="setPositionAssignments";for(let a of t){let{structureId:c,positionAssignments:u}=a;if(!u)continue;let p=tt({drawDefinition:n,structureId:c});if(p.error)return p;let m=p.structure;if(!m)return{error:Nt};let d=Pt({structure:m}).positionAssignments?.map(({drawPosition:I})=>I),l=u?.map(({drawPosition:I})=>I);if(Yt(d,l).length!==d?.length)return M({result:{error:O},info:"drawPositions do not match",stack:i});let f=Ie({drawDefinition:n}),{matchUps:g}=te({inContext:!0,drawDefinition:n,matchUpsMap:f});for(let I of u??[]){let{drawPosition:S,participantId:h,bye:T,qualifier:y}=I;if(T){let E=Or({tournamentRecord:r,drawDefinition:n,drawPosition:S,matchUpsMap:f,structureId:c,structure:m,event:o});if(E?.error)return E}else if(y)u.forEach(E=>{E.drawPosition===S&&(E.qualifier=!0,delete E.participantId,delete E.bye)});else if(h){let E=On({provisionalPositioning:e,inContextDrawMatchUps:g,tournamentRecord:r,drawDefinition:n,participantId:h,drawPosition:S,matchUpsMap:f,structureId:c,event:o});if(E?.error)return E}}hn({tournamentId:r?.tournamentId,drawDefinition:n,structure:m,event:o})}let s=t.map(({structureId:a})=>a);return Ft({tournamentId:r?.tournamentId,eventId:o?.eventId,drawDefinition:n,structureIds:s}),{...P}}function iC(t){let e=wE(t,[{roundNumbers:!0,[Ge]:ke,[$e]:s=>s.length===2&&s.every(Le)}]);if(e.error)return e;let{structure:r,roundMatchUps:n,roundNumbers:o}=e;if(!t.roundNumbers.every(s=>o?.includes(s)))return M({result:{error:O,message:"roundNumbers must be valid rounds"}});let i={};return t.roundNumbers.forEach((s,a)=>(n?.[s]??[]).forEach(({matchUpId:c})=>{i[c]=t.roundNumbers[1-a]})),xE({params:t,modMap:i,structure:r}),{...P}}function cf({roundPosition:t,roundNumber:e,idPrefix:r,uuids:n}){return r?`${r}-${e}-${t}`:n?.pop()||it()}function W0({includeMatchUpType:t,drawPosition:e,roundNumber:r,matchUpType:n,idPrefix:o,matchUps:i,isMock:s,uuids:a,nodes:c,fed:u}){let p=c.length,m=e?e-p:void 0,d=Q(0,p).map(g=>m?m+g:void 0),l=[];for(let g=0;g<p;g++){let I=d.shift(),S={drawPosition:I,fed:u+1,feed:!0},h=c[g];h.roundNumber=r-1;let T=cf({roundPosition:h.roundPosition,roundNumber:r,idPrefix:o,uuids:a}),y={roundPosition:h.roundPosition,drawPositions:[I],matchUpStatus:zt,roundNumber:r,matchUpId:T};t&&(y.matchUpType=n),s&&(y.isMock=!0),i.push(y);let E={children:[h,S]};l.push(E)}let f=e?e-p:void 0;return{roundNodes:l,matchUps:i,drawPosition:f}}function dd({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=cf({roundPosition:p,roundNumber:r,idPrefix:o,uuids:s}),I={roundPosition:p,children:[l,f],matchUpId:g};u.push(I);let S={drawPositions:I.children.map(h=>h?.drawPosition).filter(Boolean),matchUpStatus:zt,matchUpId:I.matchUpId,roundPosition:p,roundNumber:r};t&&e&&(S.matchUpType=e),i&&(S.isMock=!0),n.push(S),p++,c+=2}return{roundNodes:u,matchUps:n}}function bi(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=s3({drawSize:i}),S=I.length,h=0;if(r?.length)h=r.reduce((x,k)=>x+k,0);else if(e){let x=e-i;r=I.filter(k=>k<=x?(x-=k,!0):!1),h=r.reduce((k,G)=>k+G,0),n=r.length}else o>=S?n=0:u&&(n=S-u,o=0),r=I.filter((x,k)=>u&&!n||n&&k>=o+n||k<o?0:x),h=r.reduce((x,k)=>x+k,0),n=r.length;let T=[...I,...r].sort((x,k)=>k-x),y=T.length,A=[...(c??[]).map(x=>x-1),...(s??[]).map(x=>y-x)].map(x=>T[x]).reduce((x,k)=>x+k,0);h=h-A;let N=0,D=[],R,U=1,C=Q(0,i).map((x,k)=>({drawPosition:k+1+h})),_=h+1;for(let x of I){if({roundNodes:R,matchUps:D}=dd({matchUpType:m,roundNumber:U,idPrefix:d,matchUps:D,isMock:l,nodes:C,uuids:f}),U++,r.includes(x)){let k=mn(r)[x],G=Q(0,k),V=y+1-U,B=s?.includes(V)??c?.includes(U);G.forEach(()=>{({roundNodes:R,matchUps:D,drawPosition:_}=W0({drawPosition:!B&&_||void 0,nodes:R,matchUpType:m,roundNumber:U,idPrefix:d,matchUps:D,isMock:l,uuids:f,fed:N})),U++,N+=1})}C=R}y!==U-1&&console.log("ERROR");let v=i-h;D=Nc({finishingPositionOffset:p?v:a,positionsFed:h,roundsCount:y,matchUps:D,fmlc:g});let L=R?.length?R[0]:R;return L&&(L.roundNumber=U-1,L.matchUps=D),{draw:L,matchUps:D,roundsCount:y};function F(x){let k=rl(x);return k>x?k/2:k}}function s3({drawSize:t}){let e=Math.ceil(Math.log(t)/Math.log(2));return Q(0,e).reverse().map(n=>Math.pow(2,n))}function Er({finishingPositionOffset:t,finishingPositionLimit:e,qualifyingRoundNumber:r,qualifyingPositions:n,matchUpType:o,roundLimit:i,idPrefix:s,drawSize:a,isMock:c,uuids:u}){if(isNaN(a)||a<2||n&&a<=n)return{matchUps:[],roundsCount:0};if(n&&(!en(a)||a%n)){let I=n;for(;I<a;)I=2*I;a=I}let p=n&&!(a%2)&&(!isNaN(n)||r&&!isNaN(r))&&(a/n===Math.round(a/n)||r&&a/r===Math.round(a/r));if(!en(a)&&!p)return{matchUps:[],roundsCount:0};let m=Q(1,a+1).map(I=>({drawPosition:I})),d,l=[],f=1;for({roundNodes:d,matchUps:l}=dd({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}=dd({nodes:d,matchUpType:o,roundNumber:f,idPrefix:s,matchUps:l,isMock:c,uuids:u}),f++;let g=f-1;return l=Nc({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 Ru(t){let{finishingPositionOffset:e=0,addNameBaseToAttributeName:r,playoffStructureNameBase:n,finishingPositionNaming:o,finishingPositionLimit:i,playoffAttributes:s,stageSequence:a=1,exitProfile:c="0",exitProfileLimit:u,roundOffsetLimit:p,roundOffset:m=0,drawDefinition:d,staggeredEntry:l,sequenceLimit:f,childStage:g,stage:I=W,drawSize:S,idPrefix:h,isMock:T,uuids:y}=t;if(!(!s||!u||s?.[c])||S<2||f&&a>f)return{};let A=[],N=[],D=[],R=t.matchUpType??d?.matchUpType,U=e+1,b=e+S,C=`${U}-${b}`,_=s?.[c],v=n&&`${n} `||"",w=s?.[C]??o?.[C],L=t.structureName||w?.name||_?.name&&(r?`${v}${_?.name}`:_.name)||`${v}${C}`,F=w?.abbreviation??_?.abbreviation,x=t.structureId??_?.structureId??y?.pop(),k={idPrefix:h&&`${h}-${L}-RP`,finishingPositionOffset:e,matchUpType:R,drawSize:S,isMock:T,uuids:y},{matchUps:G}=l?bi(k):Er(k),V=lr({structureAbbreviation:F,stageSequence:a,structureName:L,matchUpType:R,roundOffset:m,structureId:x,matchUps:G,stage:I});A.push(...G),N.push(V);let B=Math.ceil(Math.log(S)/Math.log(2)),z=p?Math.min(p-m,B):(!i||U<i)&&B||0;return S>2&&Q(1,z+1).forEach(K=>H(K)),{structureId:V.structureId,matchUps:A,structureName:L,structures:N,links:D,...P};function H(K){let Y=S/Math.pow(2,K);if(Y<2)return;let J=S/Math.pow(2,K)+e;if(i&&J+1>i)return;let{structures:ct,structureId:Et,matchUps:Ht,links:Ut}=Ru({finishingPositionOffset:J,exitProfile:`${c}-${K}`,roundOffset:m+K,stageSequence:a+1,stage:g??I,drawSize:Y,addNameBaseToAttributeName:r,playoffStructureNameBase:n,finishingPositionNaming:o,finishingPositionLimit:i,playoffAttributes:s,exitProfileLimit:u,roundOffsetLimit:p,drawDefinition:d,sequenceLimit:f,childStage:g,matchUpType:R,idPrefix:h,uuids:y});if(V.structureId&&Et){let pe={linkType:ir,source:{roundNumber:K,structureId:V.structureId},target:{roundNumber:1,feedProfile:qe,structureId:Et}};Ut&&V&&Ut.push(pe),Ut?.length&&D.push(...Ut)}return ct?.length&&N.push(...ct),Ht?.length&&A.push(...Ht),{structureId:Et,childLinks:Ut,structures:N}}}function H0({q1Structure:t,eliminatorStructure:e,q2Structure:r,finalStructure:n}){return[{linkType:Pr,source:{roundNumber:1,structureId:t.structureId},target:{feedProfile:qe,roundNumber:1,structureId:n.structureId}},{linkType:ir,source:{roundNumber:1,structureId:t.structureId},target:{feedProfile:qe,roundNumber:1,structureId:r.structureId}},{linkType:Pr,source:{roundNumber:1,structureId:e.structureId},target:{feedProfile:qe,roundNumber:1,structureId:r.structureId}},{linkType:Pr,source:{roundNumber:1,structureId:r.structureId},target:{feedProfile:qe,roundNumber:1,structureId:n.structureId}}]}function LE({finishingPositionOffset:t=0,stage:e=W,structureName:r,matchUpType:n,idPrefix:o,drawSize:i,isMock:s,uuids:a}){if(i!==4)return{error:ni,info:"PAGE_PLAYOFF requires exactly 4 participants"};let c=[],{matchUps:u}=Er({idPrefix:o&&`${o}-q1`,drawSize:2,matchUpType:n,isMock:s,uuids:a}),p=Ko({structureName:r?`${r} Qualifier 1`:"Qualifier 1",structureAbbreviation:"Q1",structureId:a?.pop(),matchUps:u,stageSequence:1,matchUpType:n,stage:e});c.push(p);let{matchUps:m}=Er({finishingPositionOffset:t+2,idPrefix:o&&`${o}-el`,drawSize:2,matchUpType:n,isMock:s,uuids:a}),d=Ko({structureName:r?`${r} Eliminator`:"Eliminator",structureAbbreviation:"EL",structureId:a?.pop(),matchUps:m,stageSequence:2,matchUpType:n,stage:e});c.push(d);let{matchUps:l}=Er({finishingPositionOffset:t+1,idPrefix:o&&`${o}-q2`,drawSize:2,matchUpType:n,isMock:s,uuids:a}),f=Ko({structureName:r?`${r} Qualifier 2`:"Qualifier 2",structureAbbreviation:"Q2",structureId:a?.pop(),stage:Vt,matchUps:l,stageSequence:3,matchUpType:n});c.push(f);let{matchUps:g}=Er({finishingPositionOffset:t,idPrefix:o&&`${o}-fi`,drawSize:2,matchUpType:n,isMock:s,uuids:a}),I=Ko({structureName:r?`${r} Final`:"Final",structureAbbreviation:"F",structureId:a?.pop(),matchUps:g,stage:Vt,stageSequence:4,matchUpType:n});c.push(I);let S=H0({eliminatorStructure:d,q1Structure:p,q2Structure:f,finalStructure:I});return{structures:c,links:S,...P}}function uf({drawDefinition:t,matchUpsMap:e,structureId:r}){let n=tt({drawDefinition:t,structureId:r});if(n.error)return M({result:n});let{matchUps:o}=ht({structure:n.structure,matchUpsMap:e});return{...Ue({matchUps:o}),matchUps:o,matchUpsMap:e}}function sC({finishingPositions:t,drawDefinition:e,structureId:r}){let{roundProfile:n}=uf({drawDefinition:e,structureId:r});return(n&&Object.keys(n))?.reduce((i,s)=>(Y0(n?.[s]).forEach(c=>{t.forEach(u=>{a3({position:u,rangeDefinition:c})&&(i[u]={roundNumber:s})})}),i),{})}function a3({position:t,rangeDefinition:e}){if(!Array.isArray(e)||e.reduce((i,s)=>i||isNaN(s),!1))return!1;let[r,n]=e;return Q(r,(n||r)+1).includes(t)}function Y0(t){return[pt(t?.finishingPositionRange?.loser??[]),pt(t?.finishingPositionRange?.winner??[])]}function j0(t){return Y0(t).map(e=>Q(e[0],e[1]&&e[1]+1||e[0]+1))}function bu({drawDefinition:t,structureIds:e,matchUpsMap:r}){if(e&&!Array.isArray(e))return{error:O,context:{structureIds:e}};if(!t)return{error:$};e=e??(t.structures??[]).filter(a=>a.stage!==Z).map(({structureId:a})=>a);let n=e.map(a=>{let{roundProfile:c}=uf({drawDefinition:t,matchUpsMap:r,structureId:a});return(c&&Object.values(c))?.map(j0).flat()}).flat(),o=n.filter(a=>a?.length===1).sort(Zt).flat();return{positionsNotPlayedOff:pt(n.flat()).filter(a=>!o.includes(a)),positionsPlayedOff:o}}function FE({excludeRoundNumbers:t=[],playoffPositions:e=[],drawDefinition:r,structureId:n}){let o=dt({drawDefinition:r,structureId:n},[Kt,mo]);if(o.error)return o;if(!e)return{error:nt,info:"missing playoffPositions"};let i=bu({drawDefinition:r});if(i.error)return i;let s=i.positionsPlayedOff,a=e.filter(T=>!s.includes(T)),c=sC({finishingPositions:a,drawDefinition:r,structureId:n}),p=Object.values(c).reduce((T,y)=>T.includes(y.roundNumber)?T:T.concat(y.roundNumber),[]).map(T=>st(T)).filter(T=>!t.includes(T)),m=sC({finishingPositions:s,drawDefinition:r,structureId:n}),d=m?Object.values(m):[],l=m?d.reduce((T,y)=>T.includes(y.roundNumber)?T:T.concat(y.roundNumber),[]).map(T=>st(T)):[],f=p.filter(T=>!l.includes(T)).sort(Zt),{roundProfile:g}=uf({drawDefinition:r,structureId:n}),I=f.map(T=>{let y=g?.[T].finishingPositionRange.loser,[E,A]=y??[0,0];return Q(E,(A||E)+1)}).flat().sort(Zt),{playoffRoundsRanges:S}=c3({playoffSourceRounds:f,roundProfile:g}),h=[...f,...l];return{playoffPositionsReturned:I,playedOffSourceRounds:l,playoffRoundsRanges:S,playoffSourceRounds:f,sourceRounds:h,roundProfile:g}}function c3({playoffSourceRounds:t,roundProfile:e}){return{playoffRoundsRanges:t.map(n=>{let o=e[n].finishingPositionRange.loser,[i,s]=o,a=Q(i,(s||i)+1);return{finishingPositionRange:o.join("-"),finishingPositions:a,roundNumber:n}})}}function qp({drawDefinition:t,structureId:e}){if(!t)return{error:$};let{matchUps:r,matchUpsMap:n}=rr({inContext:!0,drawDefinition:t}),{positionsNotPlayedOff:o,positionsPlayedOff:i}=bu({drawDefinition:t,matchUpsMap:n}),{structures:s}=Sn({drawDefinition:t}),a=s.filter(u=>!e&&u.stage!==Fe||u.structureId===e),c={};for(let u of a){let p=u?.structureId,m=u3({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 u3({playoffPositions:t,drawDefinition:e,structure:r,matchUps:n}){let o=r?.structureId,{links:i}=ka({drawDefinition:e,structureId:o});if(r.structureType===de||r.structures){let l=Pt({structure:r})?.positionAssignments?.length,f=r.structures.length,g=(l??0)/f,I=i.source?.flatMap(({source:U})=>U?.finishingPositions??[])??[],S=Q(1,g+1).filter(U=>!I.includes(U)),h=n.find(U=>U.containerStructureId===o&&U.finishingPositionRange)?.finishingPositionRange?.winner||[0,1],T=i?.source.map(({target:U})=>U.structureId),{positionsPlayedOff:y=[],positionsNotPlayedOff:E=[]}=bu({structureIds:T,drawDefinition:e}),A=new Set([...y,...E]),N=Q(h[0],h[1]+1).filter(U=>!A.has(U)),D=he(N,N.length/S.length),R=S.map((U,b)=>{let C=D[b],_=[Math.min(...C??[]),Math.max(...C??[])].join("-");return{finishingPosition:U,finishingPositions:C,finishingPositionRange:_}});return{positionsNotPlayedOff:N,playoffFinishingPositionRanges:R,finishingPositionsAvailable:S,finishingPositionsPlayedOff:I,positionsPlayedOff:y,groupCount:f,groupSize:g}}let s=i?.source?.filter(l=>l.linkCondition!==Wn).map(l=>l.source?.roundNumber)??[],a=i?.source?.filter(l=>l.linkCondition===Wn).map(l=>l.source?.roundNumber)??[],c=FE({excludeRoundNumbers:s,playoffPositions:t,drawDefinition:e,structureId:o}),u=c?.playoffSourceRounds?[...c?.playoffSourceRounds??[]]:void 0,p=[...c?.playoffRoundsRanges??[]],{roundProfile:m,error:d}=c;for(let l of a){let f=i?.source.find(T=>T.source.roundNumber===l),g=f?.target.roundNumber,I=f?.target.structureId,S=n.filter(({roundNumber:T,structureId:y})=>y===I&&T===g),h=S.filter(({sides:T})=>T.find(y=>y.participantFed&&!y.participantId)).length;if(u&&h===S.length){u.push(l);let T=m?.[l]?.finishingPositionRange?.loser;if(T){let y=Math.min(...T),E=y+h,A=Q(y,E),N={finishingPositionRange:[y,E-1].join("-"),finishingPositions:A,roundNumber:l};p.push(N)}}}return u&&u.sort(Zt),p.sort((l,f)=>l.roundNumber-f.roundNumber),{playoffRounds:u,playoffRoundsRanges:p,error:d}}function q0({playoffGroups:t,drawDefinition:e,structureId:r}){if(!e)return{error:$};if(!wt(r)||!Array.isArray(t))return{error:O};let n=t.map(({finishingPositions:a})=>a).flat();return{positionRangeMap:qp({drawDefinition:e,structureId:r}).playoffFinishingPositionRanges?.filter(a=>n.includes(a.finishingPosition))?.reduce((a,c)=>(a[c.finishingPosition]=c,a),{})}}function pf({playoffGroups:t,groupCount:e,groupSize:r}){if(!Array.isArray(t)||!t.length)return{error:O,valid:!1,info:"playoffGroups must be a non-empty array"};if(!e||e<1)return{error:O,valid:!1,info:"groupCount must be >= 1"};if(!r||r<1)return{error:O,valid:!1,info:"groupSize must be >= 1"};let n={};for(let a=1;a<=r;a++)n[a]=0;let o=e*r,i=0,s=!1;for(let a of t){let{finishingPositions:c,bestOf:u,rankBy:p,remainder:m}=a;if(m){let l=p3({hasBestOf:s,totalAvailable:o,totalClaimed:i});if(l.error)return l;i+=o-i;continue}if(!Array.isArray(c)||!c.length)return{error:O,valid:!1,info:"Each playoffGroup must have non-empty finishingPositions"};for(let l of c)if(l<1||l>r)return{error:O,valid:!1,info:`finishingPosition ${l} out of range [1, ${r}]`};let d=e*c.length;if(u===void 0){let l=m3({finishingPositions:c,groupCount:e,consumptionMap:n});if(l?.error)return l;i+=d}else{let l=d3({finishingPositions:c,guaranteedCount:d,consumptionMap:n,totalAvailable:o,groupCount:e,groupSize:r,bestOf:u,rankBy:p});if(l?.error)return l;s=!0,i+=u}}return i>o?{info:`Total claimed participants (${i}) exceeds available (${o})`,error:ni,valid:!1}:{valid:!0,consumptionMap:n}}function p3({hasBestOf:t,totalAvailable:e,totalClaimed:r}){if(!t)return{error:ni,valid:!1,info:"A remainder group must appear after at least one bestOf group"};let n=e-r;return n<2?{error:ni,valid:!1,info:`Remainder group would have insufficient participants (${n}), minimum 2 required`}:{}}function m3({finishingPositions:t,groupCount:e,consumptionMap:r}){for(let n of t){let o=e-r[n];if(o<2)return{error:ni,valid:!1,info:`finishingPosition ${n} has insufficient remaining participants (${o}) for a standard playoff group (minimum 2 required)`};r[n]+=o}return{}}function d3({finishingPositions:t,guaranteedCount:e,consumptionMap:r,totalAvailable:n,groupCount:o,groupSize:i,bestOf:s,rankBy:a}){if(typeof s!="number"||s<1)return{error:O,valid:!1,info:"bestOf must be a positive number"};if(s<e)return{info:`bestOf (${s}) cannot be less than guaranteed count (${e}) for finishingPositions [${t}] with ${o} groups`,error:ni,valid:!1};if(s>n)return{info:`bestOf (${s}) exceeds total available participants (${n})`,error:ni,valid:!1};if(a!==void 0&&a!==Su)return{info:`Unsupported rankBy value: '${a}'. Currently only '${Su}' is supported.`,error:O,valid:!1};for(let u of t)r[u]+=o;let c=s-e;if(c>0){let u=l3({remainder:c,finishingPositions:t,groupCount:o,groupSize:i,consumptionMap:r,bestOf:s});if(u?.error)return u}return{}}function l3({remainder:t,finishingPositions:e,groupCount:r,groupSize:n,consumptionMap:o,bestOf:i}){let s=t,a=[...e].sort(Zt),c=Math.max(...a)+1;for(;s>0&&c<=n;){let u=r-o[c],p=Math.min(s,u);o[c]+=p,s-=p,c++}return s>0?{info:`bestOf (${i}) requires more participants than available from remaining finishing positions`,error:ni,valid:!1}:{}}function kE(t){let{finishingPositionOffset:e=0,playoffAttributes:r,stageSequence:n=1,staggeredEntry:o,structureName:i,stage:s=W,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?bi(l):Er(l),g=lr({structureName:i||r?.["0"]?.name||xe(W),structureId:c||d?.pop(),stageSequence:n,matchUpType:a,matchUps:f,stage:s}),I=[g],S=[];if(p>2){let h=p/2,{matchUps:T}=Er({finishingPositionOffset:e+h,idPrefix:u&&`${u}-c`,drawSize:h,matchUpType:a,isMock:m}),y=xe(me),E=r?.["0-1"]?.name??t.consolationStructureName??(i?`${i} ${y}`:y),A=lr({structureName:E,matchUps:T,structureId:d?.pop(),stage:me,stageSequence:1,matchUpType:a});I.push(A);let N={linkType:ir,source:{roundNumber:1,structureId:g.structureId},target:{roundNumber:1,feedProfile:qe,structureId:A.structureId}};S.push(N)}return{...P,structures:I,links:S}}function GE({consolationStructure:t,roundOffset:e=0,mainStructure:r,roundsCount:n,feedPolicy:o,fmlc:i}){let a=t.matchUps.reduce((p,m)=>(m.drawPositions??[]).filter(Boolean).length&&!p.includes(m.roundNumber)?p.concat(m.roundNumber):p,[]),c=o?.roundGroupedOrder??[],u=o?.roundFeedProfiles;return Q(1+e,n+1+e).map(p=>{let m=u?.[p-1]?u[p-1]:p%2&&qe||Fi,d=p-e<=2?p-e:(p-e-2)*2+2,l={linkType:ir,source:{roundNumber:p,structureId:r.structureId},target:{feedProfile:m,roundNumber:d,structureId:t.structureId}},f=c[p-1];return f&&(l.target.groupedOrder=f),je()&&(l.source.structureName=r.structureName,l.target.structureName=t.structureName),p===2&&i&&(l.linkCondition=Wn,l.target.feedProfile=qe),a.includes(d)?l:void 0}).filter(Boolean)}function VE(t){let{playoffStructureNameBase:e,finishingPositionOffset:r,stageSequence:n=1,playoffAttributes:o,structureNameMap:i,staggeredEntry:s,stage:a=W,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?bi(f):Er(f),S=t.structureName??o?.["0"]?.name??xe(W),h=Ko({structureId:u||l?.pop(),structureName:S,stageSequence:n,matchUpType:c,matchUps:g,stage:a}),T=[h],y=[];if(p>2){let N=[0,2].slice(0,p/16).map((D,R)=>{let U=R+1,{consolationStructure:b}=f3({idPrefix:m&&`${m}-c${R}`,structureId:l?.pop(),playoffStructureNameBase:e,playoffAttributes:o,structureNameMap:i,stageSequence:U,roundOffset:D,matchUpType:c,drawSize:p,isMock:d,index:R,uuids:l});T.push(b);let C=GE({consolationStructure:b,roundsCount:2,mainStructure:h,roundOffset:D});return{consolationStructure:b,links:C}}).map(D=>D.links).flat();if(y.push(...N),p>=4&&p<=16||p>32){let{matchUps:D}=Er({idPrefix:m&&`${m}-p3t4`,finishingPositionOffset:2,drawSize:2,matchUpType:c,isMock:d}),R=o?.["3-4"]?.name??xe(Vt),U=i?.[R]||R,b=e?`${e} ${U}`:U,C=Ko({structureId:l?.pop(),matchUps:D,stageSequence:2,stage:Vt,structureName:b,matchUpType:c}),_={linkType:ir,source:{roundNumber:I-1,structureId:h.structureId},target:{structureId:C.structureId,feedProfile:qe,roundNumber:1}};T.push(C),y.push(_)}}return{structures:T,links:y,...P}}function f3({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}=bi({finishingPositionOffset:d,baseDrawSize:d,isConsolation:!0,feedRounds:1,matchUpType:i,idPrefix:a,isMock:u,uuids:m}),I=p===0&&r?.["0-1"]?.name||p===1&&r?.["0-3"]?.name||`${xe(me)} ${p+1}`,S=n?.[I]||I,h=t?`${t} ${S}`:S;return{consolationStructure:Ko({matchUps:l,stage:me,structureName:h,stageSequence:e,matchUpType:i,structureId:s}),consolationRoundsCount:f}}function Cu(t){let{finishingPositionOffset:e,stageSequence:r=1,playoffAttributes:n,feedsFromFinal:o,staggeredEntry:i,structureName:s,stage:a=W,structureId:c,matchUpType:u,skipRounds:p,feedRounds:m,idPrefix:d,drawSize:l,isMock:f,uuids:g,fmlc:I}=t,S=t.feedPolicy||t.policyDefinitions?.[uu]||t.appliedPolicies?.[uu],h={finishingPositionOffset:e,matchUpType:u,skipRounds:p,drawSize:l,idPrefix:d,isMock:f,uuids:g},{matchUps:T}=i?bi(h):Er(h),y=lr({structureName:s||n?.["0"]?.name||xe(W),structureId:c||g?.pop(),stageSequence:r,matchUpType:u,matchUps:T,stage:a}),E=[y],A=[],N=l/2,{matchUps:D,roundsCount:R}=bi({finishingPositionOffset:N,idPrefix:d&&`${d}-c`,isConsolation:!0,feedsFromFinal:o,baseDrawSize:N,matchUpType:u,feedRounds:m,skipRounds:p,isMock:f,uuids:g,fmlc:I});if(l>2){let U=n?.["0-1"]?.name??xe(me),b=t.playoffStructureNameBase?`${t.playoffStructureNameBase} ${U}`:U,C=lr({matchUps:D,structureId:g?.pop(),stage:me,stageSequence:1,structureName:b,matchUpType:u});E.push(C);let _=GE({consolationStructure:C,mainStructure:y,roundsCount:R,feedPolicy:S,fmlc:I});A.push(..._)}return{...P,structures:E,links:A}}var g3=new Set([wo,Vs,au,va,Is,Oa]),I3=new Set([xo,Sp,qm]);function mf({requireSequential:t=!0,playoffMatchUpFormat:e,playoffAttributes:r,sourceStructureId:n,policyDefinitions:o,stageSequence:i,drawDefinition:s,playoffGroups:a,matchUpType:c,feedPolicy:u,groupCount:p,groupSize:m,idPrefix:d,isMock:l,uuids:f}={}){let g=u||o?.[uu],I="processPlayoffGroups",S=0,h=[],T=[],y=[];if(a?.some(b=>b.bestOf!==void 0||b.remainder)&&m){let b=pf({playoffGroups:a,groupCount:p,groupSize:m});if(!b.valid)return M({result:{error:b.error||ni},context:{info:b.info},stack:I})}let A=a?.filter(b=>!b.remainder),{error:N,positionRangeMap:D}=q0({structureId:n,playoffGroups:A,drawDefinition:s});if(N)return M({result:{error:N},stack:I});if(!(!D||A?.every(b=>{let{finishingPositions:C=[]}=b;if(!C.length)return!1;let _=[...C].sort(Zt).map((v,w)=>(C[w+1]||v)-v).every(v=>v<2);return(!t||_)&&C.every(v=>D[v])})))return M({context:{validFinishingPositions:Object.values(D)},result:{error:O},stack:I});let U=0;for(let b of a){let{bestOf:C,rankBy:_,remainder:v}=b;if(v){let H=S3({finishingPositionOffset:S,playoffMatchUpFormat:e,sourceStructureId:n,stageSequence:i,totalClaimed:U,playoffGroup:b,matchUpType:c,groupCount:p,groupSize:m,idPrefix:d,isMock:l,uuids:f});T.push(H.structure),y.push(H.link),h.push(H.target),S+=H.remainderCount,U+=H.remainderCount;continue}let w=b.finishingPositions??[],L=D&&w.flatMap(H=>D[H]?.finishingPositions??[]),F=C??p*w.length;U+=F;let x=Pi(F),k=x===2&&Nr||b.drawType||Nr;L&&(S=Math.min(...L)-1);let G=D3({positionsPlayedOff:L,playoffGroup:b}),B={...{addNameBaseToAttributeName:b.addNameBaseToAttributeName,playoffStructureNameBase:b.playoffStructureNameBase,finishingPositionNaming:b.finishingPositionNaming,finishingPositionLimit:b.finishingPositionLimit,structureId:b.structureId??f?.pop(),playoffAttributes:b.playoffAttributes,structureNameMap:b.structureNameMap,sequenceLimit:b.sequenceLimit,structureName:G},idPrefix:d&&`${d}-po`,appliedPolicies:o,finishingPositionOffset:S,stage:Vt,stageSequence:i,matchUpType:c,drawSize:x,isMock:l,uuids:f},z=({playoffStructures:H,playoffLinks:K})=>{let[Y]=H,J=Mu({playoffStructureId:Y.structureId,finishingPositions:w,sourceStructureId:n,bestOf:C,rankBy:_});y.push(J,...K),T.push(...H),h.push({structureId:Y.structureId,finishingPositions:w}),S+=F};if(k===Nr)h3({finishingPositionOffset:S,playoffMatchUpFormat:e,finishingPositions:w,sourceStructureId:n,participantsInDraw:F,stageSequence:i,playoffGroup:b,structureName:G,matchUpType:c,drawSize:x,idPrefix:d,bestOf:C,rankBy:_,isMock:l,uuids:f,finishingPositionTargets:h,structures:T,links:y}),S+=F;else if(I3.has(k)){let H=T3({finishingPositionOffset:S,finishingPositions:w,sourceStructureId:n,playoffAttributes:r,playoffDrawType:k,stageSequence:i,playoffGroup:b,drawSize:x,idPrefix:d,bestOf:C,rankBy:_,isMock:l,uuids:f,finishingPositionTargets:h,structures:T,links:y});if(H)return H;S+=F}else if(g3.has(k))y3({finishingPositionOffset:S,finishingPositions:w,sourceStructureId:n,playoffDrawType:k,playoffGroup:b,structureName:G,matchUpType:c,drawSize:x,idPrefix:d,bestOf:C,rankBy:_,isMock:l,uuids:f,feedPolicy:g,finishingPositionTargets:h,structures:T,links:y}),S+=F;else if(k===hr){let{structures:H,links:K}=Rc({...B,structureOptions:b.structureOptions||{groupSize:4}});z({playoffStructures:H,playoffLinks:K})}else if(k===Ma){let{structures:H,links:K}=kE(B);z({playoffStructures:H,playoffLinks:K})}else if(k===PI){let{structures:H,links:K}=VE(B);z({playoffStructures:H,playoffLinks:K})}else if(k===jm){let H=E3({finishingPositionTargets:h,participantsInDraw:F,sourceStructureId:n,finishingPositions:w,drawDefinition:s,playoffGroup:b,structures:T,params:B,links:y,stack:I});if(H)return H}else k===Ni&&N3({finishingPositions:w,stageSequence:i,structureName:G,playoffGroup:b,groupSize:m,uuids:f,updateStructureAndLinks:z})}return{finishingPositionTargets:h,positionRangeMap:D,structures:T,links:y}}function S3({finishingPositionOffset:t,playoffMatchUpFormat:e,sourceStructureId:r,stageSequence:n,totalClaimed:o,playoffGroup:i,matchUpType:s,groupCount:a,groupSize:c,idPrefix:u,isMock:p,uuids:m}){let l=a*c-o,f=Pi(l),g=Array.from({length:c},(y,E)=>E+1),I=i.structureName||"Remainder Playoff",{matchUps:S}=Er({finishingPositionLimit:t+l,idPrefix:u&&`${u}-po`,finishingPositionOffset:t,matchUpType:s,drawSize:f,isMock:p,uuids:m}),h=lr({structureId:i.structureId??m?.pop(),matchUpFormat:e,stage:Vt,structureName:I,stageSequence:n,matchUps:S}),T=Mu({playoffStructureId:h.structureId,finishingPositions:g,sourceStructureId:r,remainder:!0});return{structure:h,target:{structureId:h.structureId,finishingPositions:g},remainderCount:l,link:T}}function h3({finishingPositionOffset:t,playoffMatchUpFormat:e,finishingPositions:r,sourceStructureId:n,participantsInDraw:o,stageSequence:i,playoffGroup:s,structureName:a,matchUpType:c,drawSize:u,idPrefix:p,bestOf:m,rankBy:d,isMock:l,uuids:f,finishingPositionTargets:g,structures:I,links:S}){let{matchUps:h}=Er({finishingPositionLimit:t+o,idPrefix:p&&`${p}-po`,finishingPositionOffset:t,matchUpType:c,drawSize:u,isMock:l,uuids:f}),T=lr({structureId:s.structureId??f?.pop(),matchUpFormat:e,stage:Vt,structureName:a,stageSequence:i,matchUps:h});I.push(T);let y=Mu({playoffStructureId:T.structureId,finishingPositions:r,sourceStructureId:n,bestOf:m,rankBy:d});S.push(y),g.push({structureId:T.structureId,finishingPositions:r})}function T3({finishingPositionOffset:t,finishingPositions:e,sourceStructureId:r,playoffAttributes:n,playoffDrawType:o,stageSequence:i,playoffGroup:s,drawSize:a,idPrefix:c,bestOf:u,rankBy:p,isMock:m,uuids:d,finishingPositionTargets:l,structures:f,links:g}){let I={playoffAttributes:s.playoffAttributes??n,playoffStructureNameBase:s.playoffStructureNameBase,structureId:s.structureId??d?.pop(),structureName:s.structureName,idPrefix:c&&`${c}-po`,addNameBaseToAttributeName:!0,finishingPositionOffset:t,stage:Vt,roundOffset:0,stageSequence:i,drawSize:a,isMock:m,uuids:d};o===xo?Object.assign(I,{playoffAttributes:s?.playoffAttributes??n??NI,roundOffsetLimit:3}):o===Sp&&Object.assign(I,{playoffAttributes:s?.playoffAttributes??n??DI,roundOffsetLimit:2});let S=Ru(I);if(S.error)return S;if(S.links?.length&&g.push(...S.links),S.structures?.length&&f.push(...S.structures),f.sort(Hi),S.structureId){let h=Mu({playoffStructureId:S.structureId,finishingPositions:e,sourceStructureId:r,bestOf:u,rankBy:p});g.push(h),l.push({structureId:S.structureId,finishingPositions:e})}}function y3({finishingPositionOffset:t,finishingPositions:e,sourceStructureId:r,playoffDrawType:n,playoffGroup:o,structureName:i,matchUpType:s,feedPolicy:a,drawSize:c,idPrefix:u,bestOf:p,rankBy:m,isMock:d,uuids:l,finishingPositionTargets:f,structures:g,links:I}){let S=[l?.pop(),l?.pop()],h={playoffStructureNameBase:o.playoffStructureNameBase,structureId:o.structureId??l?.pop(),playoffAttributes:o.playoffAttributes,idPrefix:u&&`${u}-po`,finishingPositionOffset:t,uuids:S,stage:Vt,structureName:i,matchUpType:s,feedPolicy:a,drawSize:c,isMock:d},T={[wo]:{fmlc:!0,feedRounds:1},[Oa]:{feedRounds:1},[au]:{feedsFromFinal:3},[va]:{feedsFromFinal:2},[Is]:{feedsFromFinal:1}};Object.assign(h,T[n]??{});let{structures:y,links:E}=Cu(h),[A]=y,N=Mu({playoffStructureId:A.structureId,finishingPositions:e,sourceStructureId:r,bestOf:p,rankBy:m});I.push(N,...E),g.push(...y),f.push({structureId:A.structureId,finishingPositions:e})}function E3({finishingPositionTargets:t,participantsInDraw:e,sourceStructureId:r,finishingPositions:n,drawDefinition:o,playoffGroup:i,structures:s,params:a,links:c,stack:u}){if(e!==4)return M({result:{error:ni},context:{info:"PAGE_PLAYOFF requires exactly 4 participants"},stack:u});let p=o?.structures?.find(d=>d.structureId===r);return p&&!p.structures&&!p.structureType?A3({finishingPositionTargets:t,sourceStructureId:r,drawDefinition:o,playoffGroup:i,structures:s,params:a,links:c}):P3({finishingPositionTargets:t,sourceStructureId:r,finishingPositions:n,playoffGroup:i,structures:s,params:a,links:c,stack:u})}function A3({finishingPositionTargets:t,sourceStructureId:e,drawDefinition:r,playoffGroup:n,structures:o,params:i,links:s}){let a=n.structureName,{matchUpType:c,isMock:u,uuids:p,idPrefix:m,finishingPositionOffset:d=0}=i,l=Vt,{matchUps:f}=Er({finishingPositionOffset:d+2,idPrefix:m&&`${m}-el`,drawSize:2,matchUpType:c,isMock:u,uuids:p}),g=lr({structureName:a?`${a} 3-4 Playoff`:"3-4 Playoff",structureAbbreviation:"EL",structureId:p?.pop(),matchUps:f,stageSequence:1,matchUpType:c,stage:l}),{matchUps:I}=Er({finishingPositionOffset:d+1,idPrefix:m&&`${m}-q2`,drawSize:2,matchUpType:c,isMock:u,uuids:p}),S=lr({structureName:a?`${a} Playoff Qualifier`:"Playoff Qualifier",structureAbbreviation:"Q2",structureId:p?.pop(),matchUps:I,stageSequence:2,matchUpType:c,stage:l}),{matchUps:h}=Er({finishingPositionOffset:d,idPrefix:m&&`${m}-fi`,drawSize:2,matchUpType:c,isMock:u,uuids:p}),T=lr({structureName:a?`${a} Final`:"Playoff Final",structureAbbreviation:"F",structureId:p?.pop(),matchUps:h,stageSequence:3,matchUpType:c,stage:l});o.push(g,S,T);let E=r?.structures?.find(D=>D.structureId===e)?.matchUps||[],A=E.length?Math.max(...E.map(D=>D.roundNumber)):1,N=A-1;s.push({linkType:ir,source:{structureId:e,roundNumber:N},target:{feedProfile:qe,roundNumber:1,structureId:g.structureId}},{linkType:Pr,source:{structureId:e,roundNumber:A},target:{feedProfile:qe,roundNumber:1,structureId:T.structureId}},{linkType:ir,source:{structureId:e,roundNumber:A},target:{feedProfile:qe,roundNumber:1,structureId:S.structureId}},{linkType:Pr,source:{structureId:g.structureId,roundNumber:1},target:{feedProfile:qe,roundNumber:1,structureId:S.structureId}},{linkType:Pr,source:{structureId:S.structureId,roundNumber:1},target:{feedProfile:qe,roundNumber:1,structureId:T.structureId}}),t.push({structureId:g.structureId,finishingPositions:[3,4]})}function P3({finishingPositionTargets:t,sourceStructureId:e,finishingPositions:r,playoffGroup:n,structures:o,params:i,links:s,stack:a}){let c=LE({...i,structureName:n.structureName});if(c.error)return M({result:c,stack:a});o.push(...c.structures),s.push(...c.links);let u=c.structures.find(m=>m.structureAbbreviation==="Q1"),p=c.structures.find(m=>m.structureAbbreviation==="EL");if(r.length>=2&&u&&p){let m=Math.ceil(r.length/2),d=r.slice(0,m),l=r.slice(m);s.push(Mu({playoffStructureId:u.structureId,finishingPositions:d,sourceStructureId:e}),Mu({playoffStructureId:p.structureId,finishingPositions:l,sourceStructureId:e})),t.push({structureId:u.structureId,finishingPositions:d},{structureId:p.structureId,finishingPositions:l})}else u&&p&&(s.push(Mu({playoffStructureId:u.structureId,finishingPositions:r,sourceStructureId:e}),Mu({playoffStructureId:p.structureId,finishingPositions:r,sourceStructureId:e})),t.push({structureId:u.structureId,finishingPositions:r},{structureId:p.structureId,finishingPositions:r}))}function N3({finishingPositions:t,stageSequence:e,structureName:r,playoffGroup:n,groupSize:o,uuids:i,updateStructureAndLinks:s}){!t.length&&o&&t.push(...Array.from({length:o},(c,u)=>u+1));let a=lr({structureId:n.structureId??i?.pop(),structureName:n.structureName||r||"Playoff",finishingPosition:wl,stage:Vt,stageSequence:e,matchUps:[]});s({playoffStructures:[a],playoffLinks:[]})}function D3({positionsPlayedOff:t,playoffGroup:e}){let r=t&&`${Math.min(...t)}-${Math.max(...t)}`;return e.structureName||r&&e.playoffAttributes?.[r]?.name||e.playoffAttributes?.["0"]?.name}function Mu({playoffStructureId:t,finishingPositions:e,sourceStructureId:r,remainder:n,bestOf:o,rankBy:i}){let s={structureId:r,finishingPositions:e};return o!==void 0&&(s.bestOf=o,s.rankBy=i||Su),n&&(s.remainder=!0),{linkType:fn,source:s,target:{structureId:t,feedProfile:ln,roundNumber:1}}}function $0(t){let{drawDefinition:e,structureOptions:r,requireSequential:n}=t,o={structureName:xe(W),...t,stage:W},{structures:i,groupCount:s,groupSize:a}=Rc(o);if(s<1)return{error:ni};let c=r?.playoffGroups||[{finishingPositions:[1],structureName:xe(Vt)}],[u]=i,{structures:p,links:m}=mf({sourceStructureId:u.structureId,requireSequential:n,drawDefinition:e,playoffGroups:c,groupCount:s,groupSize:a,...t});return p&&i.push(...p),{...P,structures:i,links:m}}function K0({mainStructure:t,consolationStructure:e,deciderStructure:r}){let o=e.matchUps.reduce((p,m)=>(m.drawPositions??[]).filter(Boolean).length&&!p.includes(m.roundNumber)?p.concat(m.roundNumber):p,[]),i=t.matchUps.reduce((p,m)=>!p||m.roundNumber>p?m.roundNumber:p,void 0),s=e.matchUps.reduce((p,m)=>!p||m.roundNumber>p?m.roundNumber:p,void 0),a=o.map((p,m)=>{let l=o.indexOf(p)%2?qe:Fi,f=1+m;return{linkType:ir,source:{roundNumber:f,structureId:t.structureId},target:{feedProfile:l,roundNumber:p,structureId:e.structureId}}}),c={linkType:Pr,source:{roundNumber:s,structureId:e.structureId},target:{feedProfile:qe,roundNumber:i,structureId:t.structureId}},u=[{linkType:Pr,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:qe,roundNumber:1,structureId:r.structureId}},{linkType:ir,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:qe,roundNumber:1,structureId:r.structureId}}];return[...a,c,...u]}function z0({structureName:t,matchUpType:e,idPrefix:r,drawSize:n,isMock:o,uuids:i}){let s=[],{matchUps:a}=bi({linkFedFinishingRoundNumbers:[1],drawSize:n+1,matchUpType:e,idPrefix:r,isMock:o}),c=Ko({structureName:t||xe(W),structureId:i?.pop(),stageSequence:1,stage:W,matchUpType:e,matchUps:a});s.push(c);let u=n/2,{matchUps:p}=bi({finishingPositionOffset:u,idPrefix:r&&`${r}-c`,drawSize:n-1,isConsolation:!0,matchUpType:e,isMock:o,uuids:i}),m=Ko({structureName:xe(UR),matchUps:p,structureId:i?.pop(),stage:me,stageSequence:2,matchUpType:e});s.push(m);let{matchUps:d}=Er({idPrefix:r&&`${r}-p1t2`,drawSize:2,matchUpType:e,isMock:o}),l=Ko({structureName:xe(DR),matchUps:d,structureId:i?.pop(),stageSequence:3,stage:Vt,matchUpType:e});s.push(l);let f=K0({mainStructure:c,consolationStructure:m,deciderStructure:l});return{structures:s,links:f,...P}}function BE(t){let{qualifyingRoundNumber:e,finishingPositionOffset:r,qualifyingPositions:n,matchUpType:o,idPrefix:i,drawSize:s,isMock:a,uuids:c}=t;if(!yt(s)||s<2)return{matchUps:[],roundsCount:0};if(en(s))return Er(t);let u=WE(s),p=u.shift(),m=Q(1,(p?.participantsCount||0)+1).map(I=>({drawPosition:I})),d=[],l=1;({matchUps:d}=dd({roundNumber:l,matchUpType:o,idPrefix:i,matchUps:d,isMock:a,nodes:m,uuids:c})),l++;let f=t.roundLimit||e;for(let I of u){let S=I.participantsCount/2,h=Q(1,S+1);n&&S===n&&(f=l-1);let T=h.map(y=>{let E=cf({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=Nc({finishingPositionOffset:r,lucky:!0,roundsCount:g,roundLimit:f,matchUps:d}),f&&(d=d.filter(I=>I.roundNumber<=f)),{matchUps:d,roundsCount:g,roundLimit:f}}function WE(t){let e=st(t),r=e%2?e+1:e,n=!!(Math.ceil(r/2)%2),o=[{participantsCount:r,preFeedRound:n}];for(;r>2;){let i=Math.ceil(r/2),s=i===1,a=!!(!s&&i%2);r=!s&&a?i+1:i;let c=!!(r!==2&&Math.ceil(r/2)%2);o.push({participantsCount:r,preFeedRound:c,feedRound:a})}return o}function aC(t){let{finishingPositionOffset:e=0,playoffAttributes:r=UI,stageSequence:n=1,exitProfile:o="0",roundOffsetLimit:i=3,roundOffset:s=0,childStage:a=Vt,stage:c=W,matchUpType:u,structureId:p,drawSize:m,idPrefix:d,isMock:l,uuids:f}=t;if(!(!r||r[o])||m<2)return{};let I=[],S=[],h=r[o],T=t.structureName||h?.name||`${e+1}-${e+m}`,y=h?.abbreviation,E=p??h?.structureId??f?.pop(),{matchUps:A}=BE({finishingPositionOffset:e,matchUpType:u,drawSize:m,idPrefix:d&&`${d}-${T}-RP`,isMock:l,uuids:f}),N=lr({structureAbbreviation:y,structureName:T,stageSequence:n,matchUpType:u,roundOffset:s,structureId:E,matchUps:A,stage:c});I.push(N);let D=U3(m),R=D.length,U=Math.min(i-s,R);for(let b=0;b<U;b++){let{roundNumber:C,childSize:_}=D[b];if(_<2)continue;let v=e+R3(m,C),w=`${o}-${C}`,L=aC({finishingPositionOffset:v,exitProfile:w,roundOffset:s+C,stageSequence:n+1,drawSize:_,stage:a,playoffAttributes:r,roundOffsetLimit:i,childStage:a,matchUpType:u,idPrefix:d,isMock:l,uuids:f});if(L.structureId&&N.structureId){let F={linkType:ir,source:{roundNumber:C,structureId:N.structureId},target:{roundNumber:1,feedProfile:qe,structureId:L.structureId}};S.push(F)}L.structures?.length&&I.push(...L.structures),L.links?.length&&S.push(...L.links)}return{structureId:N.structureId,structures:I,links:S,...P}}function U3(t){if(en(t)){let n=Math.ceil(Math.log(t)/Math.log(2)),o=[];for(let i=1;i<=n;i++){let s=t/Math.pow(2,i);s>=2&&o.push({roundNumber:i,childSize:s})}return o}let e=WE(t),r=[];for(let n=0;n<e.length-1;n++){let o=e[n],i=o.participantsCount/2,s=o.preFeedRound?i-1:i;s>=2&&r.push({roundNumber:n+1,childSize:s})}return r}function R3(t,e){if(en(t))return t/Math.pow(2,e);let r=WE(t);return e<r.length?Math.ceil(r[e].participantsCount/2):1}function df(t){let{playoffAttributes:e,stageSequence:r=1,stage:n=W,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??ft(t),m=t.policyDefinitions?.[uu]||p?.[uu];t.skipRounds=t.skipRounds||s<=4&&(m?.feedFromMainFinal?0:1)||0;let d=t.structureName??e?.["0"]?.name??xe(W),l=()=>{let{matchUps:g}=Er(t);return{structures:[lr({stageSequence:r,structureName:d,matchUpType:i,structureId:u,tieFormat:o,matchUps:g,stage:n})],links:[],...P}};return{generators:{[Ni]:()=>({structures:[lr({finishingPosition:po,stageSequence:r,structureName:d,matchUps:[],matchUpType:i,structureId:u,stage:n})],links:[],...P}),[Bs]:()=>{let g=lr({finishingPosition:po,stageSequence:r,structureName:d,matchUps:[],matchUpType:i,structureId:u,stage:n});return s&&(g.positionAssignments=Array.from({length:s},(I,S)=>({drawPosition:S+1}))),{structures:[g],links:[],...P}},[ai]:()=>{let{matchUps:g}=BE(t);return{structures:[lr({stageSequence:r,structureName:d,matchUpType:i,structureId:u,matchUps:g,stage:n})],links:[],...P}},[Nr]:()=>l(),[Gs]:()=>z0(t),[xo]:()=>Ru({...t,childStage:Vt,roundOffsetLimit:3,playoffAttributes:e??NI}),[Sp]:()=>Ru({...t,childStage:Vt,roundOffsetLimit:2,playoffAttributes:e??DI}),[ki]:()=>aC({...t,childStage:Vt,roundOffsetLimit:t.roundOffsetLimit??3,playoffAttributes:e??UI}),[jm]:()=>LE(t),[qm]:()=>Ru({...t,childStage:Vt}),[pc]:()=>{let{matchUps:g}=bi({drawSize:s,uuids:a,matchUpType:i});return{structures:[lr({stageSequence:r,structureName:d,matchUpType:i,structureId:u,stage:W,tieFormat:o,matchUps:g})],links:[],...P}},[Ma]:()=>kE(t),[wo]:()=>Cu({...t,feedRounds:1,fmlc:!0}),[NR]:()=>Cu({...t,feedRounds:1}),[Py]:()=>Cu({...t,feedsFromFinal:1}),[Ny]:()=>Cu({...t,feedsFromFinal:2}),[Dy]:()=>Cu({...t,feedsFromFinal:3}),[Vs]:()=>Cu(t),[AI]:()=>VE(t),[hr]:()=>Rc(t),[Tr]:()=>$0(t)}}}function HE({element:t}){if(!t)return{error:O};if(!t.timeItems)return{};if(!Array.isArray(t.timeItems))return{error:O};let e=(r,n)=>(o,i)=>(i[r]&&(o[i[r]]=i[n]),o);return t.timeItems.reduce(e("itemType","itemValue"),{})}function oo(t){let{duplicateValues:e=!0,creationTime:r=!0,removePriorValues:n,timeItem:o}=t;if(!o)return{error:eI};let i=Jy(t);if(i.error)return i;if(!(Tt(o)&&wt(o.itemType)&&Object.keys(o).includes("itemValue")))return{error:tI};if(o.itemDate&&typeof o.itemDate=="string"&&!Me(o.itemDate))return{error:ae};if(!i.timeItems)i.timeItems=[];else if(b3({element:i,duplicateValues:e,timeItem:o}))return{...P};if(o.itemSubTypes&&!o.itemSubTypes.length&&delete o.itemSubTypes,r){let c=new Date().toISOString();Object.assign(o,{createdAt:c})}return n&&(i.timeItems=i.timeItems.filter(({itemType:c})=>o.itemType!==c)),n&&!o.itemValue||i.timeItems.push(o),{...P}}function b3({element:t,duplicateValues:e,timeItem:r}){let{itemType:n,itemSubTypes:o,itemValue:i}=r,s=n&&Jr({itemSubTypes:o,itemType:n,element:t})?.timeItem;return s&&JSON.stringify(s?.itemValue)===JSON.stringify(i)&&!e}function ES({creationTime:t=!0,removePriorValues:e,tournamentRecord:r,duplicateValues:n,participantId:o,timeItem:i}){if(!r)return{error:j};if(!o)return{error:We};let s=Do({tournamentRecord:r,participantId:o});return s.error?s:oo({element:s.participant,removePriorValues:e,duplicateValues:n,creationTime:t,timeItem:i})}function vu(t){let{removePriorValues:e,tournamentRecord:r,duplicateValues:n,creationTime:o,timeItem:i}=t;if(!r)return{error:j};let s=oo({element:r,removePriorValues:e,duplicateValues:n,creationTime:o,timeItem:i});if(s.error)return s;let a=HE({element:r});return at({payload:{parentOrganisation:r.parentOrganisation,tournamentId:r.tournamentId,timeItemValues:a},topic:mi}),s}function Rs(t){let{removePriorValues:e,duplicateValues:r,creationTime:n,timeItem:o,event:i}=t;return i?oo({removePriorValues:e,duplicateValues:r,element:i,creationTime:n,timeItem:o}):{error:Wr}}function AS(t){return NS({...t,itemType:"attachConsolationStructures"})}function PS(t){return NS({...t,itemType:"attachPlayoffStructures"})}function NS({itemType:t="attachStructures",matchUpModifications:e,tournamentRecord:r,drawDefinition:n,structures:o,links:i=[],event:s}){let a="attachStructures";if(!n)return{error:$};if(!Array.isArray(o)||!Array.isArray(i))return M({result:{error:O},stack:a});let c=S=>[S.source.structureId,S.source.roundNumber||S.source.finishingPositions?.join("|"),S.target.roundNumber].join("|"),u=n.links?.map(c);if(i.some(S=>{let h=c(S);return u?.includes(h)}))return M({result:{error:aI},info:"playoff structure exists",stack:a});if(i.length){let S=new Set([...n.structures?.map(({structureId:T})=>T)??[],...o.map(({structureId:T})=>T)]),h=i.filter(T=>!S.has(T.source.structureId)||!S.has(T.target.structureId));if(h.length)return M({result:{error:Co},info:"links reference non-existent structures",context:{invalidLinks:h.map(T=>({source:T.source.structureId,target:T.target.structureId}))},stack:a})}i.length&&n.links?.push(...i);let m=new Set(o.map(({structureId:S})=>S)),d=n.structures?.map(({structureId:S})=>S);n.structures=(n.structures??[]).map(S=>m.has(S.structureId)?o.find(({structureId:h})=>h===S.structureId):S);let l=o?.filter(({structureId:S})=>!d?.includes(S));l.length&&n.structures.push(...l),Ps({drawDefinition:n});let f=o.map(S=>ht({structure:S})?.matchUps??[]).flat();Ho({tournamentId:r?.tournamentId,eventId:s?.eventId,drawDefinition:n,matchUps:f});let g=o.map(({structureId:S})=>S);if(Ft({drawDefinition:n,structureIds:g}),e?.length){let S={};e.forEach(T=>{let y=T.matchUp?.matchUpId;y&&(S[y]=T)});let h=T=>{T.matchUps.forEach(y=>{if(S[y.matchUpId]){let{tieMatchUps:E,...A}=S[y.matchUpId].matchUp;if(Object.assign(y,A),E?.length){let N={};E.forEach(D=>S[D.matchUpId]=D),y.tieMatchUps.forEach(D=>Object.assign(D,N[D.matchUpId]))}S[y.matchUpId].matchUp=y,It(S[y.matchUpId])}})};n.structures.forEach(T=>{if(d?.includes(T.structureId))if(T.structures)for(let y of T.structures)h(y);else h(T)})}let I=l.map(Vr("structureId"));if(r){let h={itemValue:{structureIds:g,drawId:n.drawId},itemType:t};oo({element:r,timeItem:h})}return{...P,addedStructureIds:I}}function cC({structureName:t,structureType:e=Ni,drawSize:r=2,matchUpFormat:n,matchUpType:o}){let i={stage:me,stageSequence:1,structureName:t||xe(me),drawSize:r,matchUpFormat:n,matchUpType:o},{generators:s,error:a}=df(i);if(a)return{error:a};let c=s[e];if(!c)return{error:rp};let u=c();return u.error?u:{...P,structures:u.structures}}function uC({drawDefinition:t,structureId:e,structureName:r,structureType:n=Ni,drawSize:o=2,matchUpFormat:i,matchUpType:s,links:a=[]}){if(!t)return{error:$};if(e||(e=t.structures?.find(d=>d.stage===W)?.structureId),!e)return{error:_i};let{structure:c}=tt({drawDefinition:t,structureId:e});if(!c)return{error:_i};let u=cC({structureName:r,structureType:n,drawSize:o,matchUpFormat:i,matchUpType:s||t.matchUpType});if(u.error)return u;let p=u.structures?.[0];if(!p)return{error:rp};let m=a.map(d=>({linkType:ir,source:{roundNumber:d.sourceRoundNumber,structureId:e},target:{roundNumber:d.targetRoundNumber,feedProfile:qe,structureId:p.structureId}}));return AS({drawDefinition:t,structures:[p],links:m})}function pC({drawDefinition:t,participantId:e,preferences:r}){if(!t)return{error:$};if(!e)return{error:Hr};if(!Array.isArray(r))return{error:O};let{extension:n}=ot({element:t,name:Vi});if(!n?.value)return{error:fe,info:"No active draft found"};let o=n.value;if(o.status==="COMPLETE")return{error:O,info:"Draft is already complete"};if(!o.tiers?.find(u=>u.participantIds?.includes(e)))return{error:Hr,info:"Participant not in any draft tier"};let s=new Set(o.unassignedDrawPositions);for(let u of r)if(!s.has(u))return{error:ps,info:`Draw position ${u} is not available`};let a=o.preferencesCount??3,c=r.slice(0,a);return o.preferences[e]=c,o.status==="SEEDS_PLACED"&&(o.status="COLLECTING_PREFERENCES"),ut({element:t,extension:{name:Vi,value:o}}),{...P}}function mC({alternateParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o,event:i}){return af({positionActionName:"alternateDrawPositionAssignment",participantIdAttributeName:"alternateParticipantid",participantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o,event:i})}function DS({targetMatchUpIds:t,drawDefinition:e}){if(!e)return{error:$};if(!Array.isArray(t)||!t.length)return{error:O};let{exitProfiles:r}=Gl({drawDefinition:e}),n=e.structures??[],o={},i=0;for(let s of n){let a=r?.[s.structureId]??[];if(s.structures?.length)for(let c of s.structures)i+=Q0({exitProfiles:a,structure:c,parentStructure:s,targetMatchUpIds:t,idMap:o});i+=Q0({exitProfiles:a,targetMatchUpIds:t,structure:s,idMap:o})}if(Object.keys(o).length)for(let s of n){J0(s,o);for(let a of s.structures??[])J0(a,o)}return{...P,remappedCount:i}}function Q0({parentStructure:t,targetMatchUpIds:e,exitProfiles:r,structure:n,idMap:o}){let i=0,s=t?.stage??n.stage,a=t?.stageSequence??n.stageSequence;for(let c of n.matchUps??[]){let u=X0({stageSequence:a,roundPosition:c.roundPosition,roundNumber:c.roundNumber,structureId:n.structureId,parentStructureId:t?.structureId,stage:s,targetMatchUpIds:e,exitProfiles:r});u&&u.matchUpId!==c.matchUpId&&(o[c.matchUpId]=u.matchUpId,c.matchUpId=u.matchUpId,i++);for(let p of c.tieMatchUps??[]){let m=X0({stageSequence:a,roundPosition:p.roundPosition,roundNumber:p.roundNumber,structureId:n.structureId,parentStructureId:t?.structureId,stage:s,targetMatchUpIds:e,exitProfiles:r});m&&m.matchUpId!==p.matchUpId&&(o[p.matchUpId]=m.matchUpId,p.matchUpId=m.matchUpId,i++)}}return i}function X0({parentStructureId:t,targetMatchUpIds:e,stageSequence:r,roundPosition:n,exitProfiles:o,structureId:i,roundNumber:s,stage:a}){return e.find(c=>c.roundNumber!==s||c.roundPosition!==n?!1:c.structureId?c.structureId===i||c.structureId===t:c.exitProfile?o.includes(c.exitProfile):!(c.stage&&c.stage!==a||c.stageSequence&&c.stageSequence!==r))}function J0(t,e){let r=n=>{n.winnerMatchUpId&&e[n.winnerMatchUpId]&&(n.winnerMatchUpId=e[n.winnerMatchUpId]),n.loserMatchUpId&&e[n.loserMatchUpId]&&(n.loserMatchUpId=e[n.loserMatchUpId]);for(let o of n.tieMatchUps??[])r(o)};for(let n of t.matchUps??[])r(n)}function $p({targetRoundNumber:t,finishingPosition:e,drawDefinition:r,structureId:n,linkType:o}){let{links:i}=ka({drawDefinition:r,structureId:n})??{},a=(i?.target??[]).filter(({linkType:u})=>u===o).filter(({target:u})=>!t||t===u.roundNumber).map(u=>{let p=u.source.structureId,{structure:m}=tt({structureId:p,drawDefinition:r});if(!(e&&m?.finishingPosition!==e))return u}).filter(Boolean);return{sourceStructureIds:a.map(({source:u})=>u.structureId),relevantLinks:a}}function US({qualifyingParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o}){return af({positionActionName:"qualifierDrawPositionAssignment",participantId:t,isQualifierPosition:!0,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o})}function YE({drawDefinition:t,structureId:e}){if(!t)return{error:$};let{structure:r}=tt({drawDefinition:t,structureId:e}),n=(t?.links??[]).filter(i=>i.source?.structureId===e).map(i=>i.target?.structureId);return{playoffStructures:(t?.structures??[]).filter(i=>n.includes(i.structureId)),structure:r}}function RS({withStageGrouping:t,stageSequences:e,stageSequence:r,roundTarget:n,stages:o,event:i,stage:s}){if(!i)return{error:le};let a={},c=[];for(let u of i.drawDefinitions??[]){let{structures:p,stageStructures:m}=Sn({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 jE({withStageGrouping:t,tournamentRecord:e,stageSequences:r,stageSequence:n,roundTarget:o,stages:i,stage:s}){if(!e)return{error:j};let a={},c=[];for(let u of e.events??[]){let{structures:p,stageStructures:m}=RS({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 Ro(t){if(!t?.drawDefinition)return!1;let e=Gp(t),r=e?.includesTeamMatchUps,{completedMatchUps:n,pendingMatchUps:o,upcomingMatchUps:i}=e??{};return r&&(n=n?.filter(({matchUpType:a})=>a===xt),o=o?.filter(({matchUpType:a})=>a===xt),i=i?.filter(({matchUpType:a})=>a===xt)),!!(n?.length&&!o?.length&&!i?.length)}function qE(t){let{drawDefinition:e,structureId:r}=t;if(!e)return{error:$};let{playoffStructures:n}=YE({drawDefinition:e,structureId:r});if(!n?.length)return!1;let o=e?.entries?.filter(c=>c?.entryStatus&&yr.includes(c.entryStatus))?.length??0,i=0;return(n??[]).reduce((c,u)=>!!((Pt({structure:u}).positionAssignments??[])?.filter(d=>(d.participantId&&i++,d?.bye??d?.participantId)).length&&c),!!n.length)||i===o}var Z0=(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 dC({targetRoundNumber:t=1,tournamentRecord:e,drawDefinition:r,event:n,randomList:o}){let i=X({drawDefinition:r,event:n,tournamentRecord:e},[{[Kt]:!0,[ce]:!0,[rt]:!0}]);if(i.error)return i;let s=[],a=[],c=r.structures?.find(h=>h.stage===W&&h.stageSequence===1);if(!c)return M({result:{error:Vg}});let m=(ft({tournamentRecord:e,drawDefinition:r,structure:c,event:n}).appliedPolicies??{})[Zn]?.requireCompletedStructures,{qualifierPositions:d,positionAssignments:l}=se({structure:c});if(!d.length)return M({result:{error:Jg}});let f=Q(0,d.length);o&&(f=Z0(f,o));let g=l.map(h=>h.participantId).filter(Boolean),{relevantLinks:I}=$p({structureId:c.structureId,targetRoundNumber:t,linkType:Pr,drawDefinition:r})??{},{relevantLinks:S}=$p({structureId:c.structureId,targetRoundNumber:t,linkType:fn,drawDefinition:r})??{};return C3({eliminationSourceLinks:I,requireCompletedStructures:m,assignedParticipantIds:g,qualifyingParticipantIds:a,drawDefinition:r}),M3({roundRobinSourceLinks:S,assignedParticipantIds:g,qualifyingParticipantIds:a,drawDefinition:r}),a.length?(f.forEach((h,T)=>{let y=a[T],E=d[h].drawPosition;y&&US({qualifyingParticipantId:y,structureId:c.structureId,drawPosition:E,tournamentRecord:e,drawDefinition:r})?.success&&s.push({participantId:y,drawPosition:E})}),M({result:et({...P,assignedParticipants:s})})):M({result:{error:dU}})}function C3({eliminationSourceLinks:t,requireCompletedStructures:e,assignedParticipantIds:r,qualifyingParticipantIds:n,drawDefinition:o}){for(let i of t){let s=o.structures?.find(p=>p.structureId===i.source.structureId);if(s?.stage!==Z)continue;let a=Ro({structureId:i.source.structureId,drawDefinition:o});if(e&&!a)continue;let c=s.qualifyingRoundNumber,{matchUps:u}=ht({matchUpFilters:{...c&&{roundNumbers:[c]},isCollectionMatchUp:!1,hasWinningSide:!0},afterRecoveryTimes:!1,inContext:!0,structure:s});for(let p of u){let m=p.matchUpStatus==="BYE"&&p.sides?.find(({participantId:l})=>l),d=p.sides.find(l=>l?.sideNumber===p.winningSide);if(d||m){let{participantId:l}=d||(m??{});l&&!r.includes(l)&&n.push(l)}}}}function M3({roundRobinSourceLinks:t,assignedParticipantIds:e,qualifyingParticipantIds:r,drawDefinition:n}){for(let o of t){let i=n?.structures?.find(u=>u.structureId===o.source.structureId);if(i?.stage!==Z||!Ro({structureId:o.source.structureId,drawDefinition:n}))continue;let{positionAssignments:a}=Pt({structure:i}),c=a?.map(u=>{let p=u.participantId,m=ot({element:u,name:Bo}).extension?.value;return m?{participantId:p,groupOrder:m?.groupOrder}:{}}).filter(({groupOrder:u,participantId:p})=>u===1&&!e.includes(p)).map(({participantId:u})=>u)??[];c&&r.push(...c)}}function $E({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=$E({accessors:s,significantCharacters:t,value:c});n.push(...u)});else if(r=r[o],s.length){let a=$E({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 KE({targetParticipantIds:t,policyAttributes:e,idCollections:r,participants:n}){if(!Array.isArray(e))return{error:WT};if(!Array.isArray(n))return{error:zc};let o={};return t.forEach(i=>{let s=n.find(c=>c.participantId===i),{values:a}=lC({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 lC({policyAttributes:t,idCollections:e,participants:r,participant:n}){if(!Array.isArray(t))return{error:WT};if(!n)return{error:Aa};let o=[];return t.forEach(s=>{let{directive:a,groupings:c,key:u,significantCharacters:p}=s??{};if(u){let m=u.split(".");o.push(...$E({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 fC({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}=lC({participants:e,policyAttributes:r,idCollections:n,participant:s});return{...i,values:a}})}function eF({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 rF(t){let{unfilledPositions:e,chunkedDrawPositions:r}=t,n=eF(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=tF(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=tF(c);return!s.includes(u)}}}function nF(t){let{unfilledPositions:e,chunkedDrawPositions:r}=t,n=eF(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 tF(t){return Number(t%2?t+1:t-1)}function oF({allGroups:t,participantId:e}){return Object.keys(t).filter(r=>t[r].includes(e))}function iF({selectedParticipantGroups:t,participantIdGroups:e,positionAssignments:r,drawPositionChunks:n,unfilledPositions:o,isRoundRobin:i}){let s=n.map(a=>i?nF({groupsToAvoid:t,chunkedDrawPositions:a,participantIdGroups:e,positionAssignments:r,unfilledPositions:o}):rF({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 zE({positionAssignments:t,participantIds:e}){let r=t.map(n=>n.participantId);return e.filter(n=>!r.includes(n))}function sF({useSpecifiedGroupKey:t=!1,targetParticipantIds:e,largestFirst:r=!0,allGroups:n,groupKey:o,random:i}){let s=Object.assign({},...Object.keys(n).map(m=>[m,n[m].filter(d=>e.includes(d))]).filter(m=>m[1].length).map(([m,d])=>({[m]:d}))),a=Object.keys(s).reduce((m,d)=>s[d].length>m?s[d].length:m,0),c=Object.keys(s).filter(m=>s[m].length===a),u=r?Pn(c,i):Pn(Object.keys(s),i);return o=t&&s[o]?.length?o:u,{participantId:o&&s[o]?Pn(s[o],i):Pn(e,i),groupKey:o}}function aF({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 cF({candidatePositionAssignments:t,unseededParticipantIds:e,participantIdGroups:r,drawPositionChunks:n,drawPositionGroups:o,pairedPriority:i,allGroups:s,groupKey:a,random:c}){let p=o.reduce((U,b)=>b.length>U?b.length:U,0)<=2,m=zE({positionAssignments:t,participantIds:e}),d=aF({positionAssignments:t,drawPositionGroups:o}),{participantId:l,groupKey:f}=sF({targetParticipantIds:m,useSpecifiedGroupKey:p,allGroups:s,groupKey:a,random:c}),g=oF({participantId:l,allGroups:s}),I=iF({positionAssignments:t,isRoundRobin:p,selectedParticipantGroups:g,participantIdGroups:r,drawPositionChunks:n,unfilledPositions:d}),{unassigned:S,unpaired:h,pairedNoConflict:T}=I,y=T?.length&&T[0],E=h?.length&&h[0],A=i&&y?y:E,N=i?E:y,D=A?.length&&A||N?.length&&N,R;if(D?.length){let U=Sr(D,c);R=Sr(U,c)}else{let U=Sr(S[0],c);R=Sr(U,c)}return{newGroupKey:f,selectedParticipantId:l,targetDrawPosition:R}}function bS({isRoundRobin:t,groupedParticipants:e}){let r=[];return t?e.forEach(n=>{let o=n.map(a=>a.drawPosition),i=IS({drawPositions:o}).uniqueMatchUpGroupings??[],s=Object.assign({},...n.map(a=>({[a.drawPosition]:a})));i.forEach(a=>{Re(s[a[0]].values??[],s[a[1]].values??[])&&(r.push(a),n.conflict=!0)})}):e.forEach(n=>{Re(n[0]?.values??[],n[1]?.values??[])&&(r.push(n),n.conflict=!0)}),r}function v3(t,e){let r=t.find(n=>n.includes(e));if(r)return r.find(n=>n!==e)}function uF(t,e){return t.find(r=>r.drawPosition===e)}function O3({moveableParticipant:t,possibleDrawPosition:e,positionedParticipants:r,drawPositionGroups:n,isRoundRobin:o,getAvoidanceConflicts:i}){let s=v3(n,e),a=uF(r,s),u=i({isRoundRobin:o,groupedParticipants:[[t,a]]}),m=[uF(r,e),a],d=i({isRoundRobin:o,groupedParticipants:[m]});return!u.length&&!d.length}function pF({positionedParticipants:t,potentialDrawPositions:e,drawPositionGroups:r,avoidanceConflicts:n,isRoundRobin:o}){return n.flatMap(i=>{let s=i.map(c=>c.drawPosition);return i.filter(c=>e.includes(c.drawPosition)).map(c=>{let p=e.filter(m=>!s?.includes(m)).filter(m=>O3({moveableParticipant:c,possibleDrawPosition:m,positionedParticipants:t,drawPositionGroups:r,isRoundRobin:o,getAvoidanceConflicts:bS}));if(p.length)return{drawPosition:c.drawPosition,possibleDrawPositions:p}}).filter(Boolean)})}function gC(t){let{initialPositionAssignments:e,participantsWithGroupings:r,opponentsToPlaceCount:n,unseededByePositions:o,drawPositionGroups:i,policyAttributes:s,idCollections:a,allGroups:c,random:u}=t,p=[],m,d=Math.min(...(i??[]).map(y=>y?.length).filter(Boolean)),l=d>2,f=q(e,!1,!0).filter(y=>!y.qualifier),g=e.filter(y=>!y.participantId&&!y.qualifier&&(!y.bye||o?.includes(y.drawPosition))).map(y=>y.drawPosition);Q(0,n).forEach(()=>{let{newGroupKey:y,selectedParticipantId:E,targetDrawPosition:A}=cF({...t,candidatePositionAssignments:f,allGroups:c,groupKey:m});m=y,f.forEach(N=>{N.drawPosition===A&&(N.participantId=E)})});let I=fC({candidatePositionAssignments:f,participantsWithGroupings:r,policyAttributes:s,idCollections:a}),S=he(I,d),h=bS({groupedParticipants:S,isRoundRobin:l}),T=0;for(;T<20&&h.length;){let y=pF({positionedParticipants:I,potentialDrawPositions:g,avoidanceConflicts:h,drawPositionGroups:i,isRoundRobin:l});if(y.length){let E=_3({candidatePositionAssignments:f,swapOptions:y,random:u});E.error&&console.log({result:E}),I=fC({candidatePositionAssignments:f,participantsWithGroupings:r,policyAttributes:s,idCollections:a}),S=he(I,d),h=bS({groupedParticipants:S,isRoundRobin:l}),T++}else T=20}return f.forEach(y=>{if(y.bye&&y.participantId){let E=GT;p.push(E)}if(y.qualifier&&y.participantId){let E=GT;p.push(E)}}),{positionAssignments:f,conflicts:h.length,groupedParticipants:S,errors:p}}function _3({candidatePositionAssignments:t,swapOptions:e,random:r}){let n=Sr(e,r);if(!n)return{error:{message:"No swap options"}};let o=n.drawPosition,i=Sr(n.possibleDrawPositions,r),s=t.find(p=>p.drawPosition===o),a=t.find(p=>p.drawPosition===i)??{},c={participantId:a?.participantId,qualifier:a?.qualifier,bye:a?.bye},u={participantId:s.participantId,qualifier:s.qualifier,bye:s.bye};return Object.assign(s,c),Object.assign(a,u),{...P}}function mF({provisionalPositioning:t,unseededParticipantIds:e,inContextDrawMatchUps:r,unseededByePositions:n,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,participants:a,matchUpsMap:c,structureId:u,avoidance:p,drawSize:m,event:d,random:l}){if(!p)return{error:tU};let{candidatesCount:f=1,policyAttributes:g,targetDivisions:I}=p,{roundsToSeparate:S}=p,h="randomUnseededSeparation",{structure:T}=tt({drawDefinition:i,structureId:u}),{matchUps:y}=ht({provisionalPositioning:t,matchUpsMap:c,structure:T,event:d});if(I&&en(I)&&!S){let B=sw(I)||0,z=y.reduce((H,K)=>Math.max(Number(K.roundNumber),H),0);S=z<B?1:z-B+1}let{positionAssignments:E}=se({structure:T}),A=_p({participantsProfile:{convertExtensions:!0},deepCopy:!1,participants:a}).participantsWithGroupings,N=E?.filter(B=>!B.participantId),D=E?.map(B=>B.drawPosition),R=T?.structureType===de,U=R?{structure:T,matchUps:y,allDrawPositions:D,roundsToSeparate:S}:{matchUps:y,allDrawPositions:D,roundsToSeparate:S},{drawPositionGroups:b,drawPositionChunks:C}=R?x3(U):w3(U),_={groupParticipants:a.filter(B=>B.participantType===$r).map(B=>B.participantId),teamParticipants:a.filter(B=>B.participantType===_t).map(B=>B.participantId),pairParticipants:a.filter(B=>B.participantType===lt).map(B=>B.participantId)},v=KE({targetParticipantIds:e,policyAttributes:g,idCollections:_,participants:a});if(v.error)return M({result:v,stack:h});let w=Object.assign({},...e.map(B=>{let z=Object.keys(v).filter(H=>(v[H]??[]).includes(B));return{[B]:z}})),L=zE({participantIds:e,positionAssignments:E});if(L.length>(N?.length||0))return{error:Zg};let F,x=L.length,k=Q(0,f).map(()=>gC({initialPositionAssignments:E,participantsWithGroupings:A,unseededParticipantIds:e,opponentsToPlaceCount:x,pairedPriority:!1,unseededByePositions:n,participantIdGroups:w,drawPositionChunks:C,drawPositionGroups:b,policyAttributes:g,idCollections:_,allGroups:v,drawSize:m,random:l}));if(F=k.reduce((B,z)=>!B||(z.conflicts||0)<(B.conflicts||0)?z:B,void 0),!F||F.conflicts){let B=Q(0,f).map(()=>gC({initialPositionAssignments:E,participantsWithGroupings:A,unseededParticipantIds:e,opponentsToPlaceCount:x,pairedPriority:!0,unseededByePositions:n,participantIdGroups:w,drawPositionChunks:C,drawPositionGroups:b,policyAttributes:g,idCollections:_,allGroups:v,drawSize:m,random:l}));F=k.concat(...B).filter(H=>!H.errors?.length).reduce((H,K)=>!H||(K.conflicts||0)<(H.conflicts||0)?K:H,void 0)}if(!F)return{error:xm};let G=new Set((Pt({structure:T})?.positionAssignments??[]).filter(B=>B.participantId).map(B=>B.participantId)),V=F.positionAssignments.filter(B=>!G.has(B.participantId));for(let B of V)if(B.bye){let z=Or({tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,event:d,...B});if(z.error)return M({result:z,stack:h})}else if(B.participantId){let z=On({automaticPlacement:!0,inContextDrawMatchUps:r,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,event:d,...B});if(z.error)return M({result:z,stack:h,context:{assignment:B}})}return{...P}}function x3(t){let{structure:{structures:e}}=t,r=e.map(n=>n.positionAssignments.map(o=>o.drawPosition));return{drawPositionGroups:r,drawPositionChunks:[r]}}function w3({allDrawPositions:t,roundsToSeparate:e,matchUps:r}){let n=r.filter(d=>d.roundNumber===1).map(d=>d.drawPositions),o=n.flat().sort(Zt),i=Math.max(...o),s=t.filter(d=>d>i),a=o.length,u=Q(a===2?1:2,a).filter(d=>d===rl(d)),m=u.slice(0,e||u.length).reverse().map(d=>he(o,d));return s.length&&console.log({fedDrawPositions:s}),{drawPositionGroups:n,drawPositionChunks:m}}function dF({provisionalPositioning:t,inContextDrawMatchUps:e,unseededByePositions:r,multipleStructures:n,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,participants:a,matchUpsMap:c,structureId:u,structure:p,drawSize:m,event:d,random:l}){let f="positionUnseededParticipants";p||({structure:p}=tt({drawDefinition:i,structureId:u})),u||({structureId:u}=p);let{positionAssignments:g}=se({structure:p}),{seedAssignments:I}=Ur({provisionalPositioning:t,drawDefinition:i,structure:p}),S=I?.map(C=>C.participantId).filter(Boolean),{stage:h,stageSequence:T}=p,y=h===Z?ot({element:p,name:bn})?.extension?.value:void 0,A=Ki({provisionalPositioning:t,drawDefinition:i,stageSequence:T,entryStatuses:$i,structureId:u,roundTarget:y,stage:h}),D=A.filter(C=>!S?.includes(C.participantId)).map(C=>C.participantId),R=g?.filter(C=>!C.participantId&&!C.bye&&!C.qualifier).map(C=>C.drawPosition);if(!n&&D.length>(R?.length||0))return M({result:{error:Zg},context:{unseededParticipantsCount:D.length,unfilledDrawPositionsCount:R?.length},stack:f});let{appliedPolicies:U}=ft({tournamentRecord:o,drawDefinition:i,event:d}),b=U?.[fc];if(p.stage===Vt){let C=A.reduce((_,v)=>(_[v.groupingValue]||(_[v.groupingValue]=[]),_[v.groupingValue].push(v.participantId),_),{});Object.keys(C).length&&(b??={policyName:"Playoff Avoidance"},b.policyAttributes??=[],b.policyAttributes.push({groupings:C}))}return b&&a?mF({provisionalPositioning:t,unseededParticipantIds:D,inContextDrawMatchUps:e,unseededByePositions:r,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,participants:a,matchUpsMap:c,structureId:u,avoidance:b,drawSize:m,entries:A,random:l}):L3({provisionalPositioning:t,unseededParticipantIds:D,inContextDrawMatchUps:e,unfilledDrawPositions:R,multipleStructures:n,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,drawSize:m,event:d,random:l})}function L3({provisionalPositioning:t,unseededParticipantIds:e,inContextDrawMatchUps:r,unfilledDrawPositions:n,multipleStructures:o,tournamentRecord:i,drawDefinition:s,seedBlockInfo:a,matchUpsMap:c,structureId:u,drawSize:p,event:m,random:d}){let l=p>2?ar(n,d):n.reverse();for(let f of e){let g=l.pop();if(!o||g){let I=On({provisionalPositioning:t,inContextDrawMatchUps:r,tournamentRecord:i,drawDefinition:s,seedBlockInfo:a,participantId:f,drawPosition:g,matchUpsMap:c,structureId:u,event:m});if(I?.error&&console.log("!!!!!",{result:I}),I?.error)return M({result:I,stack:"randomUnseededDistribution"})}}return{...P}}function lF(t){let{random:e}=t,r=t.structure??tt(t).structure,n="positionQualifiers",o=[];if(r.stage===me)return M({result:{error:cc},stack:n});let{unplacedRoundQualifierCounts:i,positionAssignments:s,roundDrawPositions:a}=F3(t);for(let c of Object.keys(i)){let u=s?.filter(p=>a[c].includes(p.drawPosition)&&!p.participantId&&!p.qualifier&&!p.bye).map(p=>p.drawPosition);if(i[c]>(u||0))return M({result:{error:Jg},context:{unfilledDrawPositions:u},stack:n});Q(0,i[c]).forEach(()=>{let p=Sr(u,e);o.push(p),s?.forEach(m=>{m.drawPosition===p&&(m.qualifier=!0,delete m.participantId,delete m.bye)})})}return{...P,qualifierDrawPositions:o}}function F3({drawDefinition:t,structure:e,structureId:r,qualifiersCount:n}){e||({structure:e}=tt({drawDefinition:t,structureId:r})),r||({structureId:r}=e);let{positionAssignments:o}=se({structure:e}),{stage:i,stageSequence:s}=e,{qualifiersCount:a,roundQualifiersCounts:c}=Yp({drawDefinition:t,stageSequence:s,structureId:r,stage:i}),u=a||n||0,p=Object.keys(c??{}).length?c:u?{1:u}:{},d=(p?Object.keys(p):[]).map(y=>st(y)),{matchUps:l}=ht({structure:e}),{roundProfile:f}=Ue({matchUps:l}),g=Object.assign({},...d.filter(y=>f?.[y]).map(y=>({[y]:f?.[y]?.drawPositions?.filter(Boolean)??[]}))),I=o?.filter(y=>y.qualifier).map(y=>y.drawPosition),S=(u??0)-(I?.length??0),h=I?.length;return{unplacedRoundQualifierCounts:Object.assign({},...d.map(y=>{let E=o?.filter(A=>A.qualifier&&g[y]?.drawPositions?.includes(A.drawPosition)).map(A=>A.drawPosition);return{[y]:(p?.[y]??0)-(E?.length??0)}})),unplacedQualifiersCount:S,placedQualifiersCount:h,roundQualifiersCounts:p,positionAssignments:o,roundDrawPositions:g,qualifiersCount:u}}function IC({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:r,appliedPolicies:n,validSeedBlocks:o,drawDefinition:i,seedingProfile:s,seedBlockInfo:a,participants:c,groupsCount:u,structureId:p,matchUpsMap:m,structure:d,random:l,event:f}){let g=[],I=[],S=0;if(d||({structure:d}=tt({drawDefinition:i,structureId:p})),p||(p=d?.structureId),n??=ft({drawDefinition:i}).appliedPolicies,!o){let h=d&&hi({provisionalPositioning:t,appliedPolicies:n,drawDefinition:i,seedingProfile:s,structure:d,random:l});h?.error&&I.push(h.error),o=h?.validSeedBlocks}return u=u??o?.length??0,Q(0,u).forEach(()=>{if(S<(u||0)){let h=k3({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:i,seedingProfile:s,seedBlockInfo:a,participants:c,structureId:p,matchUpsMap:m,random:l,event:f});h?.success&&(S++,g.push(...h.seedPositions??[])),h.error&&I.push({seedPositionError:h.error})}}),I.length?{error:I}:{...P,seedPositions:g}}function k3({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,seedingProfile:o,seedBlockInfo:i,participants:s,structureId:a,matchUpsMap:c,random:u,event:p}){let{unplacedSeedParticipantIds:m,unfilledPositions:d}=CE({provisionalPositioning:t,randomize:!0,drawDefinition:n,seedingProfile:o,seedBlockInfo:i,structureId:a,random:u,event:p}),{appliedPolicies:l}=ft({drawDefinition:n}),f=l?.[fc];f?.policyAttributes&&s&&m?.length>2&&G3({unplacedSeedParticipantIds:m,unfilledPositions:d,policyAttributes:f.policyAttributes,participants:s});let g=[];for(let I of m){let S=d.pop();if(!S)return{error:Ta};g.push(S);let h=On({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,seedingProfile:o,participantId:I,seedBlockInfo:i,drawPosition:S,matchUpsMap:c,structureId:a,event:p});if(!h.success)return h}return{...P,seedPositions:g}}function G3({unplacedSeedParticipantIds:t,unfilledPositions:e,policyAttributes:r,participants:n}){let o=KE({targetParticipantIds:t,policyAttributes:r,participants:n});if("error"in o)return;let s=Object.values(o).filter(l=>l.length>1);if(!s.length)return;let a=e.length;if(a<2)return;let c=Math.max(...e),u=Math.min(a,Math.max(2,s.length)),p=Math.ceil(c/u),m=l=>Math.floor((l-1)/p),d=t.map((l,f)=>{let g=e[a-1-f];return g===void 0?f:m(g)});for(let l of s){if(l.length<2)continue;let f=l.map(y=>t.indexOf(y)).filter(y=>y>=0);if(f.length<2)continue;let g=f.map(y=>d[y]);if(!(g.length!==new Set(g).size))continue;let S=new Set(l),h=t.map((y,E)=>S.has(y)?-1:E).filter(y=>y>=0),T=new Set;for(let y of f){let E=d[y];if(!T.has(E)){T.add(E);continue}let A=h.find(N=>!T.has(d[N]));if(A!==void 0){let N=t[y];t[y]=t[A],t[A]=N;let D=d[y];d[y]=d[A],d[A]=D,T.add(d[y]);let R=h.indexOf(A);R>=0&&h.splice(R,1)}}}}function fF({provisionalPositioning:t,drawDefinition:e,structure:r}){let{positionAssignments:n}=se({structure:r}),{seedAssignments:o}=Ur({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 gF({orderedSortedFirstRoundSeededDrawPositions:t,validSeedBlocks:e,byesToPlace:r,random:n}){let o=n??Math.random,i=[];e.forEach(a=>V3(a,r,i,t,o));let s=i.map(a=>Array.isArray(a)?ar(a,n):a).flat(1/0);return OT(r)&&e.map(c=>c.seedNumbers[0]).includes(r)?t:s}function V3(t,e,r,n,o){if(e-r.length>t.drawPositions.length)r.push(...t.drawPositions);else{let s=SC(he(t.drawPositions,2));B3(s,r,n,o)}}function B3(t,e,r,n){let o,i=r[e.length];for(;o=CS(t,i,n);)e.push(o),i=r[e.length]}function CS(t,e,r){return Array.isArray(t)&&t.length!==2?t.pop():Array.isArray(t[0])?H3(t,e,r):W3(t,e,r)}function W3(t,e,r){return t.includes(e)?t.indexOf(e)?t.pop():t.shift():Math.round(r())?t.pop():t.shift()}function H3(t,e,r){let n=t[0].flat(1/0).length,o=t[1].flat(1/0).length;if(n===o){let i=t[0].flat(1/0).includes(e)?t[0]:t[1];return CS(e?i:t[Math.round(r())],e,r)}return n<o?CS(t[1],e,r):CS(t[0],e,r)}function SC(t){let e=Math.floor(t.length/2);return t.length>2?[SC(t.slice(0,e)),SC(t.slice(e))]:t}function SF({provisionalPositioning:t,relevantMatchUps:e,appliedPolicies:r,drawDefinition:n,seedingProfile:o,seedBlockInfo:i,byesToPlace:s,structure:a}){i||(i=hi({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=fF({provisionalPositioning:t,drawDefinition:n,structure:a})??[],l=pt([].concat(...e.map(E=>E.drawPositions))),f=d.filter(E=>l.includes(E.drawPosition)),g=(E,A)=>Uu(E.seedValue)-Uu(A.seedValue),S=m.reduce((E,A)=>{let N=f.filter(D=>A.drawPositions?.includes(D.drawPosition)).sort(g);return E.concat(...N)},[]).map(E=>E.drawPosition),h=gF({orderedSortedFirstRoundSeededDrawPositions:S,validSeedBlocks:m,byesToPlace:s}),T=IF({orderedSeedDrawPositions:S,relevantMatchUps:e}).slice(0,s),y=IF({orderedSeedDrawPositions:h,relevantMatchUps:e}).slice(0,s);return{strictSeedOrderByePositions:T,blockSeedOrderByePositions:y,isLuckyStructure:u,positionedSeeds:d,isContainer:p,isFeedIn:c}}function IF({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 hF({provisionalPositioning:t,seedOrderByePositions:e,isLuckyStructure:r,appliedPolicies:n,drawDefinition:o,seedLimit:i,structure:s,isFeedIn:a,random:c}){let u=n?.seeding?.seedingProfile,p=s.stage===Z,{positionAssignments:m}=se({structure:s}),d=m?.filter(L=>L.participantId).map(L=>L.drawPosition),l={isCollectionMatchUp:!1},{matchUps:f,roundMatchUps:g}=ht({provisionalPositioning:t,matchUpFilters:l,structure:s}),I=g?.[1]??[],S=s.structureType===de?f:I,h=pt(S.flatMap(L=>L.drawPositions)),T=Math.min(...h)-1,y=d?.filter(L=>h.includes(L)),E=L=>{let F=Math.ceil(L.length/2),x=[L.slice(0,F),L.slice(F)],k=x.map(J=>J.flat(1/0).flat().length),G=Math.min(...k.flat(1/0)),V=Math.max(...k.flat(1/0)),B=k.indexOf(V),z=G!==V,H=ar(x,c),[K,Y]=!G||z?[x[B],x[1-B]]:[H[0],H[1]];return{greaterHalf:K,lesserHalf:Y}},A=L=>{let{greaterHalf:F,lesserHalf:x}=E(L),{greaterHalf:k,lesserHalf:G}=E(F),B=ar(k.flat(1/0),c).pop(),z=k.flat().filter(K=>K!==B);return{newlyFilteredChunks:[...x,...G,z],drawPosition:B}},N=L=>!e.includes(L),D=L=>!y?.includes(L),R=L=>{let x=he(L.sort(Zt),Math.ceil(L.length/4)).map(V=>V.filter(D)),k=x.flat(1/0).flat().length,G=[];for(let V=0;V<k;V++){let{newlyFilteredChunks:B,drawPosition:z}=A(x);G.push(z),x=B}return G},{validSeedBlocks:U}=hi({provisionalPositioning:t,allPositions:!0,appliedPolicies:n,drawDefinition:o,structure:s}),b=U?.map(L=>L.drawPositions?.map(F=>F+T)),C;if(a){let L=h.length,{seedBlocks:F}=hS({cluster:[iu,Hm].includes(md(u)),participantsCount:L});C=F.map(k=>k.map(G=>G+T)).map(R).filter(k=>k.length)}else p?C=b?.map(L=>L.filter(D)):C=b?.map(R).filter(L=>L.length);let _=S.map(L=>L.drawPositions).map(L=>L?.sort((F,x)=>F-x)).filter(L=>L?.[0]+1===L?.[1]),v=L=>_.reduce((F,x)=>x.includes(L)?x.reduce((k,G)=>G===L?k:G,void 0):F,void 0),w=C.map(L=>L.map(v)).flat(1/0).filter(D).filter(N).filter(Boolean);if(p&&!s.structures){let L=i%4,F=w.slice(0,L),x=g[s.roundLimit]?.length,k=he(w.slice(L),x).flatMap(G=>ar(G,c));w=F.concat(k)}return{unseededByePositions:w}}function TF({provisionalPositioning:t,drawDefinition:e,matchUpsMap:r,structure:n,event:o}){let i={isCollectionMatchUp:!1},{matchUps:s,roundMatchUps:a}=ht({afterRecoveryTimes:!1,provisionalPositioning:t,drawDefinition:e,matchUpFilters:i,matchUpsMap:r,structure:n,event:o}),c=a?.[1]??[],u=n?.structureType===de,p=u?s:c,m=u?n?.structures?.length||0:s.length,{structureId:d,stage:l,stageSequence:f}=n,g=Ki({entryStatuses:yr,provisionalPositioning:t,drawDefinition:e,stageSequence:f,structureId:d,stage:l}),{qualifiersCount:I}=Yp({provisionalPositioning:t,drawDefinition:e,stageSequence:f,structureId:d,stage:l}),S=g.length+(I??0),{positionAssignments:h,unassignedPositions:T}=se({structure:n}),y=T?.map(U=>U.drawPosition),E=h?.filter(U=>U.bye).length,A=h?.filter(U=>U.bye).map(U=>U.drawPosition),N=p.map(U=>U.drawPositions).filter(U=>U?.reduce((b,C)=>!A?.includes(C)&&b,!0)).flat(1/0).filter(U=>y?.includes(U)),D=h?.length,R=D?D-S:0;return R>m&&n.stageSequence===1&&n.stage!==me&&(R=m),{placedByes:E,byesCount:R,relevantMatchUps:p,placedByePositions:A,roundMatchUps:a,positionsToAvoidDoubleBye:N}}function hC({provisionalPositioning:t,tournamentRecord:e,appliedPolicies:r,drawDefinition:n,seedBlockInfo:o,seedingProfile:i,matchUpsMap:s,structureId:a,structure:c,seedLimit:u,seedsOnly:p,event:m,random:d}){c||({structure:c}=tt({drawDefinition:n,structureId:a})),a||(a=c?.structureId);let l=!(c?.structures??c?.stage===Z),{byesCount:f,placedByes:g,relevantMatchUps:I}=TF({provisionalPositioning:t,drawDefinition:n,matchUpsMap:s,structure:c,event:m}),S=f-(g||0);if(S<=0)return{...P};if(an(n.drawType)){let _=(I??[]).flatMap(L=>L.drawPositions??[]).filter(Boolean),v=new Set(c?.positionAssignments?.filter(L=>L.participantId).map(L=>L.drawPosition)??[]),w=_.filter(L=>!v.has(L)).slice(0,S);for(let L of w){let F=Or({provisionalPositioning:t,tournamentRecord:e,drawDefinition:n,drawPosition:L,matchUpsMap:s,structureId:a,structure:c,event:m});if(F?.error)return F}return{...P,byeDrawPositions:w}}let{strictSeedOrderByePositions:h,blockSeedOrderByePositions:T,isLuckyStructure:y,isFeedIn:E}=SF({provisionalPositioning:t,relevantMatchUps:I,appliedPolicies:r,drawDefinition:n,seedingProfile:i,seedBlockInfo:o,byesToPlace:S,structure:c}),A=c?.structureType&&[de,su].includes(c.structureType)&&r?.seeding?.containerByesIgnoreSeeding,N=l&&T?.length?T:h,{unseededByePositions:D}=hF({provisionalPositioning:t,seedOrderByePositions:N,isLuckyStructure:y,appliedPolicies:r,drawDefinition:n,seedLimit:u,structure:c,isFeedIn:E,random:d}),R=_=>_%2,U=(_,v)=>(_??[]).every(w=>R(w)?v!==w+1:v!==w-1),b=N.flat();if(!p)for(;D.length;){let _=D.find(v=>U(b,v));_?(b.push(_),D=D.filter(v=>v!==_)):(b.push(...D),D=[])}A&&(b=ar(b,d),je({ignoreSeededByes:A})&&console.log({byePositions:b}));let C=b.slice(0,S);for(let _ of C){let v=Or({provisionalPositioning:t,tournamentRecord:e,drawDefinition:n,drawPosition:_,matchUpsMap:s,structureId:a,structure:c,event:m});if(v?.error)return v}return{...P,unseededByePositions:D,byeDrawPositions:C}}function MS(t,e){return e||cI(),M({result:t,stack:"automatedPositioning"})}function Y3(t,e){return e||cI(),t}function j3(t,e,r,n){let o=tt({drawDefinition:e,structureId:r});if(o.error)return{error:o.error};let i=o.structure;if(!i)return{error:Nt};let s=t.appliedPolicies||ft({drawDefinition:e,structure:i,event:n})?.appliedPolicies,{qualifiersCount:a}=Yp({stageSequence:i.stageSequence,provisionalPositioning:t.provisionalPositioning,stage:i.stage,drawDefinition:e,structureId:r}),c=a||t.qualifiersCount||0,u=$i,p=Ki({stageSequence:i.stageSequence,provisionalPositioning:t.provisionalPositioning,stage:i.stage,placementGroup:t.placementGroup,drawDefinition:e,entryStatuses:u,structureId:r});return{structure:i,appliedPolicies:s,qualifiersCount:c,entries:p}}function q3({placeByes:t,provisionalPositioning:e,tournamentRecord:r,appliedPolicies:n,drawDefinition:o,seedBlockInfo:i,matchUpsMap:s,structure:a,seedLimit:c,seedsOnly:u,event:p,structureSeedingProfile:m,seedingProfile:d,inContextDrawMatchUps:l,participants:f,positioningReport:g,random:I}){let S=t?hC({provisionalPositioning:e,tournamentRecord:r,appliedPolicies:n,drawDefinition:o,seedBlockInfo:i,matchUpsMap:s,structure:a,seedLimit:c,seedsOnly:u,random:I,event:p}):void 0;if(S?.error)return{error:S.error};let h=S?.unseededByePositions;return g.push({action:"positionByes",unseededByePositions:h}),S=IC({seedingProfile:m?{positioning:m}:d,provisionalPositioning:e,inContextDrawMatchUps:l,tournamentRecord:r,appliedPolicies:n,validSeedBlocks:i.validSeedBlocks,drawDefinition:o,seedBlockInfo:i,participants:f,matchUpsMap:s,structure:a,random:I,event:p}),S.error?{error:S.error}:(g.push({seedPositions:S.seedPositions,action:"positionSeedBlocks"}),{unseededByePositions:h})}function $3({drawType:t,structureSeedingProfile:e,seedingProfile:r,provisionalPositioning:n,inContextDrawMatchUps:o,tournamentRecord:i,appliedPolicies:s,validSeedBlocks:a,drawDefinition:c,seedBlockInfo:u,participants:p,matchUpsMap:m,structure:d,event:l,placeByes:f,seedLimit:g,seedsOnly:I,positioningReport:S,random:h}){let T;if(!an(t)){let A=IC({seedingProfile:e?{positioning:e}:r,provisionalPositioning:n,inContextDrawMatchUps:o,tournamentRecord:i,appliedPolicies:s,validSeedBlocks:a,drawDefinition:c,seedBlockInfo:u,participants:p,matchUpsMap:m,structure:d,random:h,event:l});if(A.error)return{error:A.error};S.push({action:"positionSeedBlocks",seedPositions:A.seedPositions})}let y=f?hC({provisionalPositioning:n,tournamentRecord:i,appliedPolicies:s,drawDefinition:c,seedBlockInfo:u,matchUpsMap:m,structure:d,seedLimit:g,seedsOnly:I,random:h,event:l}):void 0;return y?.error?{error:y.error}:(T=y?.unseededByePositions,S.push({action:"positionByes",byeDrawPositions:y?.byeDrawPositions,unseededByePositions:T}),{unseededByePositions:T})}function K3({seedsOnly:t,inContextDrawMatchUps:e,tournamentRecord:r,appliedPolicies:n,validSeedBlocks:o,drawDefinition:i,seedBlockInfo:s,participants:a,matchUpsMap:c,structure:u,positionQualifiers:p,positionUnseededParticipants:m,provisionalPositioning:d,unseededByePositions:l,multipleStructures:f,qualifiersCount:g,structureId:I,drawSize:S,event:h,positioningReport:T,conflicts:y,random:E}){if(t)return{};let A=p({inContextDrawMatchUps:e,tournamentRecord:r,appliedPolicies:n,validSeedBlocks:o,drawDefinition:i,qualifiersCount:g,seedBlockInfo:s,participants:a,matchUpsMap:c,structure:u,random:E});return A.error?{error:A.error}:(A.conflicts&&(y.qualifierConflicts=A.conflicts),T.push({action:"positionQualifiers",qualifierDrawPositions:A.qualifierDrawPositions}),A=m({provisionalPositioning:d,inContextDrawMatchUps:e,unseededByePositions:l,multipleStructures:f,tournamentRecord:r,drawDefinition:i,seedBlockInfo:s,participants:a,matchUpsMap:c,structureId:I,structure:u,drawSize:S,random:E,event:h}),A.error?{error:A.error}:(A.conflicts&&(y.unseededConflicts=A.conflicts),T.push({action:"positionUnseededParticipants"}),{}))}function Ou(t){let{drawDefinition:e}=t,{applyPositioning:r=!0,provisionalPositioning:n,multipleStructures:o,placeByes:i=!0,tournamentRecord:s,seedingProfile:a,structureId:c,seedLimit:u,seedsOnly:p,drawType:m,drawSize:d,random:l,event:f}=t,g=[];r||(KU(),e=q(e,!1,!0));let{structure:I,appliedPolicies:S,qualifiersCount:h,entries:T,error:y}=j3(t,e,c,f);if(y)return MS(y,r);if(!T?.length&&!h)return Y3({...P},r);let E=t.matchUpsMap??Ie({drawDefinition:e}),A=t.inContextDrawMatchUps??te({inContext:!0,drawDefinition:e,matchUpsMap:E})?.matchUps,N=hi({provisionalPositioning:n,appliedPolicies:S,drawDefinition:e,seedingProfile:a,structure:I,random:l});if(N.error)return MS(N,r);let{validSeedBlocks:D}=N;g.push({validSeedBlocks:D});let R=t.participants||(s?bt({withIndividualParticipants:!0,convertExtensions:!0,tournamentRecord:s})?.participants:[]),U;if(md(I.seedingProfile||a)===Li){let v=q3({placeByes:i,provisionalPositioning:n,tournamentRecord:s,appliedPolicies:S,drawDefinition:e,seedBlockInfo:N,matchUpsMap:E,structure:I,seedLimit:u,seedsOnly:p,event:f,structureSeedingProfile:I.seedingProfile,seedingProfile:a,inContextDrawMatchUps:A,participants:R,positioningReport:g,random:l});if(v?.error)return MS(v.error,r);U=v.unseededByePositions}else{let v=$3({drawType:m,structureSeedingProfile:I.seedingProfile,seedingProfile:a,provisionalPositioning:n,inContextDrawMatchUps:A,tournamentRecord:s,appliedPolicies:S,validSeedBlocks:D,drawDefinition:e,seedBlockInfo:N,participants:R,matchUpsMap:E,structure:I,event:f,placeByes:i,seedLimit:u,seedsOnly:p,positioningReport:g,random:l});if(v?.error)return MS(v.error,r);U=v.unseededByePositions}let b={},C=K3({seedsOnly:p,inContextDrawMatchUps:A,tournamentRecord:s,appliedPolicies:S,validSeedBlocks:D,drawDefinition:e,seedBlockInfo:N,participants:R,matchUpsMap:E,structure:I,positionQualifiers:lF,positionUnseededParticipants:dF,provisionalPositioning:n,unseededByePositions:U,multipleStructures:o,qualifiersCount:h,structureId:c,drawSize:d,event:f,positioningReport:g,conflicts:b,random:l});if(C?.error)return MS(C.error,r);let{positionAssignments:_}=Pt({drawDefinition:e,structure:I});return Ft({drawDefinition:e,structureIds:[c]}),r||cI(),{positionAssignments:_,conflicts:b,...P,positioningReport:g}}function Ha(t){let{applyPositioning:e=!0,provisionalPositioning:r,tournamentRecord:n,drawDefinition:o,seedingProfile:i,structureId:s,placeByes:a,seedsOnly:c,random:u}=t;if(!o)return{error:Mr};if(!Ro({drawDefinition:o,structureId:s})&&!r)return{error:Lg};let m=YE({drawDefinition:o,structureId:s}).playoffStructures?.sort((f,g)=>FI(f)-FI(g)),d=[],l=[];if(m)for(let f of m){let{structureId:g}=f,I=Ou({structureId:g,provisionalPositioning:r,applyPositioning:e,tournamentRecord:n,drawDefinition:o,seedingProfile:i,placeByes:a,seedsOnly:c,random:u});if(I.error)return I;I.positionAssignments&&d.push({positionAssignments:I.positionAssignments,structureId:g}),I.positioningReport&&l.push(I.positioningReport)}return{...P,structurePositionAssignments:d,positioningReports:l}}function TC({validation:t=!0,tournamentRecord:e,drawDefinition:r,participantId:n,structureId:o,seedValue:i,event:s}){if(!r)return{error:$};if(!o)return{error:dn};let a=(e?.participants??[]).find(l=>l.participantId===n);if(e&&!a)return{error:Hr};let{structure:c}=tt({drawDefinition:r,structureId:o});if(!c)return{error:Nt};if(!(!t||Le(i)||i===void 0||i===""||typeof i=="string"&&i.split("-").every(l=>Le(l)&&st(l)>0)))return{error:O};let{seedAssignments:p}=Ur({drawDefinition:r,structure:c}),m=p?.map(l=>l.seedNumber),d=p?.find(l=>l.participantId===n);if(d){let l=typeof i=="string"?i.includes("-")&&i.split("-").map(f=>parseInt(f)).join("-")||parseInt(i)>0&&parseInt(i)||"":i&&i>0&&i||"";d.seedValue=l}else{let f={seedNumber:Math.max(0,...m??[])+1,participantId:n};i&&(f.seedValue=i),c.seedAssignments??=[],c.seedAssignments.push(f)}return vl({tournamentId:e?.tournamentId,eventId:s?.eventId,drawDefinition:r,structure:c}),{...P}}function yC({drawDefinition:t,orderMap:e}){return t?((typeof e!="object"||!Object.values(e).every(r=>yt(r)))&&M({result:{error:O},context:{orderMap:e}}),t.structures??=[],t.structures.forEach(r=>{let n=e[r.structureId];n&&(r.structureOrder=n)}),t.structures.sort((r,n)=>Wc(r.structureOrder)-Wc(n.structureOrder)),{...P}):{error:$}}function Kp({drawDefinition:t}){let e=t.structures??[],r=t.links??[],n=new Map,o=I=>{let S=n.get(I)||n.set(I,{drawSources:[],drawTargets:[],progeny:[],sources:[],targets:[]})&&n.get(I);if(S&&!S?.stage){let h=e.find(T=>T.structureId===I);S.stage=h?.stage}return S},i={},s={},a=z3({links:r,initStructureProfile:o,sourceStructureIds:i,hasDrawFeedProfile:s});Q3(n);let c=Z3(n),u=a.length;Q(0,Math.ceil(u/2)).forEach(()=>{a=Q(0,u).map(I=>{let S=a[I],h=a.reduce((T,y)=>Re(S,y)?T.concat(...y):T,[])??[];return pt(S.concat(...h))})});let p=a[0],m=(I,S)=>Yt(I,S).length===I.length,d=a.slice(1).reduce((I,S)=>I&&m(S,p),!0),l=[p].filter(Boolean),f=[p].filter(Boolean);t5({structures:e,structureGroups:l,linkCheck:f});let g=d&&f.length===1;return!r?.length&&e.length===1&&o(e[0].structureId),{structureProfiles:Object.fromEntries(n),allStructuresLinked:g,maxQualifyingDepth:c,sourceStructureIds:i,hasDrawFeedProfile:s,structureGroups:l}}function z3({links:t,initStructureProfile:e,sourceStructureIds:r,hasDrawFeedProfile:n}){return t.map(o=>{let i=o.source.structureId,s=o.target.structureId,a=e(i),c=e(s);return[Fi,qe,Ym,Li].includes(o.target.feedProfile)?(a?.targets.push(s),c?.sources.push(i)):o.target.feedProfile===ln&&(c?.drawSources.push(i),a?.drawTargets.push(s)),n[s]=n[s]||o.target.feedProfile===ln,r[s]=pt([...r[s]??[],i]).filter(Boolean),[o.source.structureId,o.target.structureId]})}function Q3(t){for(let e of t.keys()){let r=t.get(e);r&&(X3(r,t),J3(r,t))}}function X3(t,e){let r=t.targets??[];for(;r.length;){let n=r.pop(),o=n&&e[n];o?.targets?.length?r.push(...o.targets):o&&(t.rootStage=o.stage)}t.rootStage??=t.stage}function J3(t,e){if(t.targets?.length)return;let r=t.sources??[];for(;r.length;){let n=r.pop(),o=n&&e[n];if(o?.sources?.length){for(let i of o.sources)t.progeny?.includes(i)||t.progeny?.push(i);r.push(...o.sources)}}}function Z3(t){let e=0;for(let r of t.keys()){let n=t.get(r);if(n?.rootStage!==Z)continue;let o=[n.drawTargets?.[0]],i=0;for(;o.length;){i+=1;let s=o.pop(),a=s?t.get(s):void 0;a?.drawTargets?.length&&o.push(a.drawTargets[0])}n.distanceFromMain=i,i>e&&(e=i)}return e}function t5({structures:t,structureGroups:e,linkCheck:r}){t.forEach(n=>{let{structureId:o,stage:i}=n;e.find(a=>a.includes(o))||(e.push([o]),i!==Fe&&r.push([o]))})}function QE({drawDefinition:t}){let{maxQualifyingDepth:e,structureProfiles:r}=Kp({drawDefinition:t});for(let n of t.structures){let o=r[n.structureId];o.distanceFromMain&&(n.stageSequence=e+1-o.distanceFromMain)}return{...P}}function vS(t){let e=X(t,[{[rt]:!0,[Kt]:!0}]);if(e.error)return e;let{tournamentRecord:r,drawDefinition:n,structure:o,link:i}=t;return e5({tournamentId:r.tournamentId,drawDefinition:n,structure:o,link:i})}function e5(t){let e=X(t,[{[Kt]:!0,[mc]:!0},{link:!0,[Ge]:qr,[RD]:kg}]);if(e.error)return e;let{drawDefinition:r,tournamentId:n,structure:o,eventId:i,link:s}=t,a=s.target.structureId,c=tt({drawDefinition:r,structureId:a});if(c.error)return M({stack:"attachQualifyingStructure",context:{targetStructureId:a},result:c});r.structures??=[],r.links??=[],r.structures.push(o),r.links.push(s),QE({drawDefinition:r});let u=ht({structure:o})?.matchUps??[];return Ho({drawDefinition:r,tournamentId:n,matchUps:u,eventId:i}),Ft({drawDefinition:r,structureIds:[o.structureId]}),{...P}}function EC({drawDefinition:t,structureDetails:e}){if(!Array.isArray(e))return{error:O};if(!t)return{error:$};let r=Object.assign({},...e.map(n=>{if(!Tt(n))return;let{structureId:o,structureName:i}=n??{};if(!(!o||!i))return{[o]:i}}).filter(Boolean));if(!Object.values(r).length)return{error:nt};for(let n of t.structures??[]){let o=r[n.structureId];if(o&&(n.structureName=o),n.structures)for(let i of n.structures){let s=r[i.structureId];s&&(i.structureName=s)}}return{...P}}function OS({drawDefinition:t,timeItem:e}){if(!t)return{error:Mr};if(!e)return{error:eI};let r=e&&Object.keys(e),n=["itemType","itemValue"];if(!(n.filter(s=>r.includes(s)).length===n.length))return{error:tI};t.timeItems??=[];let i=new Date().toISOString();return Object.assign(e,{createdAt:i}),t.timeItems.push(e),yc({drawDefinition:t}),{...P}}function yF({positionAssignments:t,participantFactors:e,random:r}){if(!e||!t)return{error:nt};let n=q(e,!1,!0),o=t.map(({drawPosition:g})=>g),i=t.filter(g=>!g.participantId&&!g.bye&&!g.qualifier).map(hL),s,a=!0;for(;a;)({drawPositionResolutions:s,remainingPreferences:a,participantPreferences:n}=r5({participantPreferences:n,drawPositionResolutions:s,random:r}));let c=new Set(Object.keys(s).map(g=>st(g))),u=i.filter(g=>!c.has(g)),p=Object.keys(n),d=Q(1,((g,I)=>Math.log(I)/Math.log(g))(2,o?.length||0)+1).map(g=>Math.pow(2,g)),l={};for(let g of d){let I=he(o,g).filter(T=>Re(T,u)),S={};if(p.forEach(T=>{I.forEach(y=>{let E=y.join("|");Re(y,e[T].preferences)&&(S[E]||(S[E]=[]),S[E].push(T))})}),ar(Object.keys(S),r).forEach(T=>{let y=S[T].filter(E=>p.includes(E));for(;y.length;){let E=Sr(y,r),A=T.split("|").map(N=>st(N)).filter(N=>u.includes(st(N)));if(A.length){let N=Sr(A,r);u=u.filter(R=>R!==N),p=p.filter(R=>R!==E),s[N]=E;let D=T.split("|").length;l[D]||(l[D]=0),l[D]+=1}}}),!u.length)break}let f={chunkResolution:l};return p.length&&(p.forEach(g=>{let I=Sr(u,r);I&&(s[I]=g)}),f.randomAssignment=p.length),{drawPositionResolutions:s,report:f}}function r5({participantPreferences:t,drawPositionResolutions:e={},random:r}){let n=Object.keys(t).reduce((a,c)=>{let p=t[c].preferences[0];return p&&(a[p]||(a[p]=[]),a[p].push(c)),a},{}),o=Math.min(...Object.values(n).filter(a=>a.length).map(a=>a.length)),i=Object.keys(n).filter(a=>n[a].length&&o&&n[a].length===o);i.forEach(a=>{let c=n[a],u=Sr(c,r);e[a]=u,delete t[u]});let s;return Object.values(t).forEach(a=>{a.preferences=a.preferences.filter(c=>{let u=!i.includes(c.toString());return u&&(s=!0),u})}),{drawPositionResolutions:e,remainingPreferences:s,participantPreferences:t}}function AC({tournamentRecord:t,drawDefinition:e,applyResults:r=!0,tierIndex:n,random:o,event:i}){if(!e)return{error:$};let{extension:s}=ot({element:e,name:Vi});if(!s?.value)return{error:fe,info:"No active draft found"};let a=s.value;if(a.status==="COMPLETE")return{error:O,info:"Draft is already complete"};let c=a.structureId,{structure:u}=tt({drawDefinition:e,structureId:c});if(!u)return{error:fe,info:"Structure not found"};let{positionAssignments:p}=Pt({drawDefinition:e,structureId:c});if(!p)return{error:fe,info:"No position assignments"};let m=n5({draftState:a,targetTierIndex:n});if(m?.error)return m;let d=p.map(I=>({...I})),l={},f=[];for(let I=0;I<a.tiers.length;I++){let S=a.tiers[I];S.resolved||n!==void 0&&I!==n||(o5({draftState:a,tier:S,tierIndex:I,workingAssignments:d,allResolutions:l,tierReports:f,random:o}),S.resolved=!0)}let g=a5(a,l);if(r){let I=i5({allResolutions:l,tournamentRecord:t,drawDefinition:e,structureId:c,draftState:a,transparencyReport:g,tierReports:f,event:i});if(I)return I}return{...P,drawPositionResolutions:l,tierReports:f,transparencyReport:g}}function n5({draftState:t,targetTierIndex:e}){if(e!==void 0){if(e<0||e>=t.tiers.length)return{error:O,info:"Invalid tier index"};if(t.tiers[e].resolved)return{error:O,info:"Tier already resolved"};for(let r=0;r<e;r++)if(!t.tiers[r].resolved)return{error:O,info:`Tier ${r+1} must be resolved first`}}}function o5({draftState:t,tier:e,tierIndex:r,workingAssignments:n,allResolutions:o,tierReports:i,random:s}){let a=new Set(n.filter(p=>!p.participantId&&!p.bye&&!p.qualifier).map(p=>p.drawPosition)),c={},u=[];for(let p of e.participantIds){let d=t.preferences[p]?.filter(l=>a.has(l));d?.length?c[p]={preferences:d}:u.push(p)}if(Object.keys(c).length){let{drawPositionResolutions:p,report:m}=yF({positionAssignments:n,participantFactors:c});if(p)for(let[d,l]of Object.entries(p)){o[Number(d)]=l;let f=n.find(g=>g.drawPosition===Number(d));f&&(f.participantId=l)}i.push({tierIndex:r,preferenceReport:m,participantsWithoutPreferences:u})}if(u.length){let p=n.filter(l=>!l.participantId&&!l.bye&&!l.qualifier).map(l=>l.drawPosition),m=s??Math.random,d=[...p].sort(()=>m()-.5);for(let l=0;l<u.length&&l<d.length;l++){let f=d[l],g=u[l];o[f]=g;let I=n.find(S=>S.drawPosition===f);I&&(I.participantId=g)}i.push({tierIndex:r,randomAssignment:u.length})}}function i5({allResolutions:t,tournamentRecord:e,drawDefinition:r,structureId:n,draftState:o,transparencyReport:i,tierReports:s,event:a}){let c=[];for(let[m,d]of Object.entries(t)){let l=On({drawPosition:Number(m),participantId:d,tournamentRecord:e,drawDefinition:r,structureId:n,event:a});l.error&&c.push({drawPosition:Number(m),participantId:d,error:l.error})}let u=new Set(Object.keys(t).map(Number));if(o.unassignedDrawPositions=(o.unassignedDrawPositions??[]).filter(m=>!u.has(m)),s5({draftState:o,allResolutions:t}),o.tiers.every(m=>m.resolved)&&(o.status="COMPLETE",o.resolvedAt=new Date().toISOString(),o.transparencyReport=i),ut({element:r,extension:{name:Vi,value:o}}),c.length)return{...P,errors:c,drawPositionResolutions:t,tierReports:s,transparencyReport:i}}function s5({draftState:t,allResolutions:e}){let r={};for(let[n,o]of Object.entries(e))r[o]=Number(n);for(let n of t.tiers){if(!n.resolved||n.resolutions)continue;let o={};for(let i of n.participantIds){let s=r[i];if(s===void 0)continue;let c=(t.preferences[i]??[]).indexOf(s);o[i]={assignedPosition:s,preferenceMatch:c>=0?c+1:null}}n.resolutions=o}}function a5(t,e){let r=[],n={};for(let[o,i]of Object.entries(e))n[i]=Number(o);for(let o of t.tiers)for(let i of o.participantIds){let s=t.preferences[i]??[],a=n[i],c=s.indexOf(a);r.push({participantId:i,preferences:s,assignedPosition:a,preferenceMatch:c>=0?c+1:null})}return r}function PC({tournamentRecord:t,drawDefinition:e,event:r,structureId:n}){if(!e)return{error:$};let o=e.structures?.find(a=>a.stage===Z&&a.structureId===n);if(!o)return{error:Nt};if(o.matchUps?.some(({matchUpStatus:a,score:c})=>ue({score:c})??Ot.includes(a)))return{error:Zc};let s=o.matchUps?.map(({matchUpId:a})=>a)??[];return o.positionAssignments=[],o.seedAssignments=[],o.matchUps=[],wn({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:s,drawDefinition:e}),Ft({tournamentId:t?.tournamentId,eventId:r?.eventId,drawDefinition:e,structureIds:[o.structureId]}),{...P}}function NC(t){let{tournamentRecord:e,drawDefinition:r,structureId:n,event:o}=t,i=X(t,[{drawDefinition:!0,structureId:!0}]);if(i.error)return i;let s=r.structures??[],a=s.find(S=>S.structureId===n);if(!a)return{error:Nt};let c=s.find(({stage:S,stageSequence:h})=>S===W&&h===1),u=n===c?.structureId,p=s.filter(({stage:S})=>S===Z).map(Vr("structureId"));if(u&&!p.length)return{error:bD};let m=p.includes(n),d=c5({isQualifyingStructure:m,structure:a,...t});if(d?.error)return d;let{structureIdsToRemove:l,relatedStructureIdsMap:f}=p5({qualifyingStructureIds:p,isQualifyingStructure:m,isMainStageSequence1:u,mainStageSequence1:c,drawDefinition:r,structureId:n}),{removedMatchUpIds:g,removedStructureIds:I}=m5({relatedStructureIdsMap:f,qualifyingStructureIds:p,isMainStageSequence1:u,mainStageSequence1:c,drawDefinition:r,structureIdsToRemove:l,structureId:n});if(u5({removedMatchUpIds:g,drawDefinition:r}),u){let S=(c.matchUps??[])?.map(Vr("matchUpId"));g.push(...S),c.positionAssignments=[],c.seedAssignments=[],c.matchUps=[],c.extensions&&(c.extensions=[])}return m&&QE({drawDefinition:r}),wn({tournamentId:e?.tournamentId,matchUpIds:g,action:"removeStructure",eventId:o?.eventId,drawDefinition:r}),Ft({drawDefinition:r,eventId:o?.eventId}),{...P,removedMatchUpIds:g,removedStructureIds:I}}function c5({isQualifyingStructure:t,tournamentRecord:e,drawDefinition:r,structureId:n,structure:o,event:i,force:s}){let a=[n];if(t){let p=d=>r.links?.find(l=>l.target.structureId===d),m=p(n)?.source.structureId;for(;m;)a.push(m),m=p(m)?.source.structureId}if(te({matchUpFilters:{structureIds:a},drawDefinition:r}).matchUps?.some(({score:p})=>ue({score:p}))){let p=ft({tournamentRecord:e,drawDefinition:r,structure:o,event:i})?.appliedPolicies;if(!(s??p?.[Qr]?.allowDeletionWithScoresPresent?.structures))return{error:Zc}}return{...P}}function u5({removedMatchUpIds:t,drawDefinition:e}){let{matchUps:r}=te({drawDefinition:e});r?.forEach(n=>{n.winnerMatchUpId&&t.includes(n.winnerMatchUpId)&&delete n.winnerMatchUpId,n.loserMatchUpId&&t.includes(n.loserMatchUpId)&&delete n.loserMatchUpId})}function p5({qualifyingStructureIds:t,isQualifyingStructure:e,isMainStageSequence1:r,mainStageSequence1:n,drawDefinition:o,structureId:i}){let a=(o.structures??[]).map(Vr("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 m5({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(...f5({idBeingRemoved:u,drawDefinition:o}));let p=l5({qualifyingStructureIds:e,isMainStageSequence1:r,idBeingRemoved:u,drawDefinition:o,structureId:s});a.push(...p.removedStructureIds);let m=d5({relatedStructureIdsMap:t,mainStageSequence1:n,idBeingRemoved:u,structureId:s});m?.length&&i.push(...m)}return{removedMatchUpIds:c,removedStructureIds:a}}function d5({idBeingRemoved:t,relatedStructureIdsMap:e,mainStageSequence1:r,structureId:n}){return t&&e.get(t)?.filter(o=>o!==r?.structureId||n===r.structureId)}function l5({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 f5({idBeingRemoved:t,drawDefinition:e}){let{structure:r}=tt({structureId:t,drawDefinition:e}),n=ht({structure:r}).matchUps;return bl(n)}var EF="qualifierDrawPositionAssignment",AF="withdrawParticipantAtDrawPosition",PF="alternateDrawPositionAssignment",NF="luckyLoserDrawPositionAssignment",DC="removeDrawPositionAssignment",XE="swapDrawPositionAssignments",DF="modifyPairAssignment",UF="adHocPositionSwap",RF="modifyParticipantOtherName",UC="assignDrawPosition",bF="removeSeededParticipant",CF="assignDrawPositionBye",MF="modifySeedAssignment",vF="seedWithdrawalCascade",JE="addPenalty",_S="MODIFY_PAIR",ld="QUALIFIER",xS="ALTERNATE",wS="WITHDRAW",na="ASSIGN",ZE="REMOVE",LS="LUCKY",fd="REMOVE_SEED",gd="SWAP",zp="NICKNAME",Ya="SEED_VALUE",ja="PENALTY",RC="SEED_CASCADE";var OF={MODIFY_PAIR_ASSIGNMENT:_S,QUALIFYING_PARTICIPANT:ld,ALTERNATE_PARTICIPANT:xS,WITHDRAW_PARTICIPANT:wS,ASSIGN_PARTICIPANT:na,LUCKY_PARTICIPANT:LS,REMOVE_ASSIGNMENT:ZE,SWAP_PARTICIPANTS:gd,ADD_NICKNAME:zp,REMOVE_SEED:fd,ADD_PENALTY:ja,ASSIGN_BYE:"BYE",SEED_CASCADE:RC,SEED_VALUE:Ya};function bC({tournamentRecord:t,drawDefinition:e,drawPositions:r,structureId:n,event:o}){if(!e)return{error:$};if(!n)return{error:dn};if(r?.length!==2)return{error:O,drawPositions:r};let i=Ie({drawDefinition:e}),{matchUps:s}=te({inContext:!0,drawDefinition:e,matchUpsMap:i}),{structure:a}=tt({drawDefinition:e,structureId:n});if(!a)return{error:Nt};let c=ft({tournamentRecord:t,drawDefinition:e,event:o}).appliedPolicies??{},u;if(a.structureType===de?u=S5({inContextDrawMatchUps:s,tournamentRecord:t,drawDefinition:e,drawPositions:r,matchUpsMap:i,structure:a,event:o}):u=g5({inContextDrawMatchUps:s,tournamentRecord:t,drawDefinition:e,drawPositions:r,matchUpsMap:i,structure:a,event:o}),u.error)return u;if(Ol({structure:a,drawPositions:r}),Ec({appliedPolicies:c,drawDefinition:e,positionAction:{name:XE,drawPositions:r,structureId:n}}),hn({tournamentId:t?.tournamentId,drawDefinition:e,structure:a,event:o}),o.eventType===Ze){let m=ht({matchUpFilters:{matchUpTypes:[Ir]},inContext:!0,structure:a}).matchUps.filter(l=>l.drawPositions?.some(f=>r.includes(f))),d=ht({matchUpFilters:{matchUpTypes:[Ir]},structure:a}).matchUps;m.forEach(l=>{(l.sides??[]).forEach(f=>{let g=f?.drawPosition;if(r.includes(g)){let I=f.participantId,S=d.find(({matchUpId:T})=>T===l.matchUpId),h=l?.sides?.reduce((T,y,E)=>y.drawPosition===g?E:T,void 0);rf({inContextTargetMatchUp:l,drawPositionSideIndex:h,teamParticipantId:I,tournamentRecord:t,drawDefinition:e,matchUp:S,event:o})}})})}return Ft({drawDefinition:e,structureIds:[n]}),{...P}}function g5({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPositions:n,matchUpsMap:o,structure:i,event:s}){let a=i?.positionAssignments.filter(p=>n?.includes(p.drawPosition));if(!a)return{error:O,structure:i,info:"Missing positionAssignments"};if(a.filter(({bye:p})=>p).length===2)return{...P};if(a.filter(({qualifier:p})=>p).length===2)return{...P};let c=a.some(({qualifier:p})=>p);return a.some(({bye:p})=>p)&&!c?_F({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s}):I5({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s})}function _F({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=jp({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o});return l.error||(l=jp({drawPosition:m,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o}),l.error)||(Or({drawPosition:m,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o,event:s}),l=On({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,participantId:p,matchUpsMap:o,event:s}),l.error)?l:{...P}}function I5({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),yS({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:o,assignments:n,structure:i,event:s}),{...P}}function S5({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPositions:n,matchUpsMap:o,structure:i,event:s}){let a=i.structures?.reduce((p,m)=>{let d=m?.positionAssignments.filter(l=>n?.includes(l.drawPosition));return d&&p.push(...d),p},[]);if(a.filter(({bye:p})=>p).length===2)return{...P};if(a.filter(({qualifier:p})=>p).length===2)return{...P};yS({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)_F({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s});else{let p=q(a,!1,!0);a.forEach((m,d)=>{let l=p[1-d].participantId;m.qualifier=p[1-d].qualifier,m.participantId=l})}return{...P}}function CC({tournamentRecord:t,drawDefinition:e,participantId:r,structureId:n}){let o="removeSeededParticipant";if(!t)return{error:j};if(!e)return{error:$};let i=(e.structures??[]).find(a=>a.structureId===n);return i?!i.stage||![W,Z].includes(i.stage)||i.stage===W&&i.stageSequence!==1?M({result:{error:Co},stack:o}):i.seedAssignments?.find(a=>a.participantId===r)?{...P}:M({info:"participant not seeded",result:{error:fe},context:{participantId:r}}):M({result:{error:Nt},stack:o})}function oa({qualifyingPositions:t,targetEntryRound:e=1,finishingPositions:r,sourceRoundNumber:n,sourceStructureId:o,targetStructureId:i,linkType:s=Pr}){return!o||!i?{error:dn}:{link:et({linkType:s,source:{roundNumber:n,structureId:o,qualifyingPositions:t,finishingPositions:r},target:{feedProfile:ln,roundNumber:e,structureId:i}})}}function ts({matchUp:t,tieFormat:e,isMock:r,uuids:n}){let{collectionDefinitions:o}=e??{};return{tieMatchUps:(o??[]).map(s=>Qp({matchUp:t,collectionDefinition:s,uuids:n,isMock:r})).filter(Boolean).flat()}}function Qp({collectionPositionOffset:t=0,collectionDefinition:e,matchUpsLimit:r,matchUp:n,isMock:o,uuids:i}){let{matchUpCount:s,matchUpType:a,collectionId:c,processCodes:u}=e??{},p=r??s??0,m=d=>{if(!o&&!n?.isMock)return i?.pop()??it();let l=e?.collectionId;return i?.pop()??`${n?.matchUpId}-${l}-TMU-${d+1}`};return Q(0,p).map(d=>{let l=t+d+1;return{sides:[{sideNumber:1},{sideNumber:2}],matchUpId:m(d),matchUpStatus:zt,collectionPosition:l,collectionId:c,processCodes:u,matchUpType:a,isMock:o}})}function h5(t,e){return t.drawDefinition?t.drawSize&&!yt(t.drawSize)||t.participantsCount&&!yt(t.participantsCount)||t.qualifyingPositions&&!yt(t.qualifyingPositions)?M({result:{error:O},stack:e}):t.drawSize?t.qualifyingPositions&&t.qualifyingPositions>=t.drawSize?M({result:{error:O},context:{drawSize:t.drawSize,qualifyingPositions:t.qualifyingPositions},stack:e}):null:M({result:{error:$c},context:{drawSize:t.drawSize},stack:e}):M({result:{error:$},stack:e})}function T5(t,e,r){let{structureProfiles:n}=Kp({drawDefinition:t}),o=n[e];return o||M({result:{error:Nt},context:{targetStructureId:e},stack:r})}function y5(t){let{maxRoundNumber:e,structures:r,groupCount:n}=Rc(t);return{qualifiersCount:n,roundLimit:e,structure:r[0],finishingPositions:[1]}}function E5(t){let{drawSize:e,matchUps:r,roundLimit:n,roundsCount:o}=Er(t);n||(n=o);let i=lr({structureName:t.structureName,structureId:t.structureId,qualifyingRoundNumber:n,stage:Z,matchUpFormat:t.matchUpFormat,stageSequence:t.stageSequence,matchUpType:t.matchUpType,roundLimit:n,matchUps:r});t.roundTarget&&ut({extension:{name:bn,value:t.roundTarget},element:i});let s=r?.filter(a=>a.roundNumber===n)?.length??0;return{drawSize:e,structure:i,matchUps:r,roundLimit:n,qualifiersCount:s}}function lf(t){let e="generateQualifyingStructure",r=h5(t,e);if(r)return r;let n=t.drawSize??el(t.participantsCount),{hasExistingDrawDefinition:o,qualifyingRoundNumber:i,qualifyingPositions:s,targetStructureId:a,structureOptions:c,appliedPolicies:u,qualifyingOnly:p,drawDefinition:m,matchUpFormat:d,structureName:l,structureId:f,roundTarget:g,tieFormat:I,drawType:S,idPrefix:h,isMock:T,uuids:y}=t,E=T5(m,a,e);if(E?.error)return E;let A=m.matchUpType,N=1,D=g?`${g}-`:"",R=typeof E=="object"&&"stage"in E&&E.stage===Z,U=u?.[Fo]?.namingConventions?.pre??_L[Fo]?.namingConventions?.pre,b=R&&U?`${U}-`:"",C=l??(D?`${b}${xe(Z)} ${D}`:`${b}${xe(Z)}`),_,v,w,L,F;if(S===hr){let G=y5({structureName:l??C,structureId:f??y?.pop(),hasExistingDrawDefinition:o,stage:Z,structureOptions:c,appliedPolicies:u,qualifyingOnly:p,stageSequence:N,matchUpType:A,roundTarget:g,tieFormat:I,idPrefix:h,drawSize:n,isMock:T,uuids:y});L=G.qualifiersCount,w=G.roundLimit,_=G.structure,F=G.finishingPositions}else{let G=E5({qualifyingRoundNumber:i,qualifyingPositions:s,matchUpType:A,idPrefix:h,drawSize:n,isMock:T,uuids:y,structureName:l??C,structureId:f??y?.pop(),matchUpFormat:d,stageSequence:N,roundTarget:g});n=G.drawSize,_=G.structure,w=G.roundLimit,L=G.qualifiersCount}let x=S===hr?fn:Pr,k=_&&w&&oa({sourceStructureId:_.structureId,sourceRoundNumber:w,targetStructureId:a,finishingPositions:F,linkType:x})?.link;return I&&(v=ht({structure:_})?.matchUps??[],v?.forEach(G=>{let{tieMatchUps:V}=ts({tieFormat:I,matchUp:G,isMock:T});Object.assign(G,{tieMatchUps:V,matchUpType:A})})),{qualifyingDrawPositionsCount:n,qualifiersCount:L,...P,structure:_,link:k}}function MC(t){if(!t.tournamentRecord)return{error:j};let r=A5(t);return r.error,r}function A5(t){if(!t.drawDefinition)return{error:$};if(!t.targetStructureId)return{error:dn};let e=lf(t);if(e.error)return e;let{structure:r,link:n}=e;return!r||!n?{error:O}:vS({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,structure:r,link:n})}function vC({tournamentRecord:t,drawDefinition:e,structureId:r,drawPosition:n,event:o}){if(!e)return{error:$};if(r=r||e.structures?.[0]?.structureId,!r)return{error:O};let{structure:i}=tt({drawDefinition:e,structureId:r});if(!i)return{error:O};if(i.stage!==W||i.stageSequence!==1)return{error:O};if(i.structureType===de)return{error:O};if(Xi({drawDefinition:e,structureId:r}).activeDrawPositions?.length)return{error:O};let{positionAssignments:a}=se({structure:i});if(!a)return{error:O};let{seedAssignments:c}=Ur({drawDefinition:e,structure:i});if(!c?.length)return{error:O};let p=a.find(A=>A.drawPosition===n)?.participantId;if(!p)return{error:O};let m=c.find(A=>A.participantId===p);if(!m)return{error:O};let{validSeedBlocks:d}=hi({drawDefinition:e,structure:i});if(!d?.length)return{error:O};let l=m.seedNumber,f=d.findIndex(A=>A.seedNumbers.includes(l));if(f<0)return{error:O};let g=[],I=n,S=l;for(let A=f+1;A<d.length;A++){let N=d[A],D=c.filter(C=>N.seedNumbers.includes(C.seedNumber)&&C.participantId).sort((C,_)=>C.seedNumber-_.seedNumber);if(!D.length)break;let R=D[0],U=R.participantId,b=a.find(C=>C.participantId===U);if(!b)break;g.push({replacementParticipantId:U,replacementSeedNumber:R.seedNumber,targetSeedNumber:S,sourceDrawPosition:b.drawPosition,targetDrawPosition:I}),I=b.drawPosition,S=R.seedNumber}for(let A of g){let N=a.find(R=>R.drawPosition===A.targetDrawPosition);N&&(N.participantId=A.replacementParticipantId);let D=c.find(R=>R.seedNumber===A.targetSeedNumber);D&&(D.participantId=A.replacementParticipantId)}let h=g.length?g.at(-1)?.sourceDrawPosition:n,T=a.find(A=>A.drawPosition===h);if(T&&(T.participantId=void 0),g.length===0)m.participantId=void 0;else{let A=g.at(-1),N=c.find(D=>D.seedNumber===A?.replacementSeedNumber);N&&(N.participantId=void 0)}let y=e.entries?.find(A=>A.participantId===p);y&&(y.entryStatus=Mn);let E=t?.tournamentId;return hn({drawDefinition:e,tournamentId:E,structure:i,event:o}),vl({eventId:o?.eventId,drawDefinition:e,tournamentId:E,structure:i}),{...P,vacatedDrawPosition:h}}function OC(t){let e=X(t,[{[Kt]:!0,[mo]:!0,[wr]:!0},{[Jw]:!0,[$e]:m=>Number.isInteger(m)&&m>0},{[$e]:m=>Array.isArray(m)&&m.length===2&&m.every(wt),[Lr]:_r,participantIds:!0}]);if(e.error)return e;let{drawDefinition:r,structureId:n,tournamentRecord:o,event:i}=t,{structure:s}=tt({drawDefinition:r,structureId:n});if(!s)return{error:Nt};if(!Ae({structure:s}))return{error:Co};let a=m=>m.sides?.map(d=>d.participantId).some(d=>t.participantIds.includes(d)),c=m=>m.roundNumber===t.roundNumber,u=m=>!ue(m),p=(s?.matchUps??[]).filter(c).filter(u).filter(a);if(p.length!==2)return{error:_r};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,It({tournamentId:o?.tournamentId,eventId:i?.eventId,drawDefinition:r,matchUp:m})}}return Ft({drawDefinition:r,structureIds:[n]}),{...P}}var P5=new Set([vt,Mt,Qt,ge]);function Id({matchUp:t}){if(!t)return{error:Xe};let{winningSide:e,score:r,matchUpStatus:n}=t;if(!e||!r)return{error:O};if(n&&P5.has(n))return{...P,margin:Number.NaN,setRatio:Number.NaN,gameRatio:Number.NaN,pointRatio:Number.NaN,setsWonByLoser:0,setsWonByWinner:0,gameDifferential:0};let o=r.sets??[],i=e===1?2:1,s=o.filter(A=>A.winningSide===e).length,a=o.filter(A=>A.winningSide===i).length,c=s+a,u=c>0?a/c:Number.NaN,p=!1,m=0,d=0;for(let A of o){let N=e===1?A.side1PointScore:A.side2PointScore,D=e===1?A.side2PointScore:A.side1PointScore;N!=null&&(m+=Number(N),p=!0),D!=null&&(d+=Number(D),p=!0)}let l=m+d,f=p&&l>0?d/l:Number.NaN,{games:g}=Fl({score:r}),I=g[e-1],S=g[i-1],h=I+S,T=h>0?S/h:Number.NaN,y=I-S,E;return Number.isFinite(f)?E=f:Number.isFinite(T)?E=T:E=u,{...P,margin:E,setRatio:u,gameRatio:T,pointRatio:f,setsWonByLoser:a,setsWonByWinner:s,gameDifferential:y}}function ff({tournamentRecord:t,drawDefinition:e,structureId:r,cumulativeMargin:n}){if(!e)return{error:$};let o=an(e.drawType);if(r=r||e.structures?.[0]?.structureId,!r)return o?{error:O}:{...P,isLuckyDraw:!1,rounds:[]};let{structure:i}=tt({drawDefinition:e,structureId:r});if(!i)return{error:O};if(!(o||Pc({drawDefinition:e,structure:i})))return{...P,isLuckyDraw:!1,rounds:[]};let a=i.matchUps??[],{roundProfile:c,roundNumbers:u}=Ue({matchUps:a});if(!c||!u?.length)return{...P,isLuckyDraw:!0,rounds:[]};let p=i.positionAssignments??[],m={};for(let f of p)f.drawPosition&&f.participantId&&(m[f.drawPosition]=f.participantId);let d={};if(t?.participants)for(let f of t.participants)f.participantId&&f.participantName&&(d[f.participantId]=f.participantName);let l=u.map(f=>{let g=c[f],I=a.filter(x=>x.roundNumber===f),S=I.filter(x=>Ot.includes(x.matchUpStatus)||x.winningSide||x.matchUpStatus==="BYE").length,h=S===g.matchUpsCount,y=!(g.matchUpsCount===1)&&g.matchUpsCount%2!==0,E=f+1,N=a.filter(x=>x.roundNumber===E).some(x=>!x.drawPositions||x.drawPositions.filter(Boolean).length<2?!0:x.drawPositions.some(k=>{if(!k)return!0;let G=p.find(V=>V.drawPosition===k);return!G?.participantId&&!G?.bye})),D=y&&h&&N,U=(e.links??[]).filter(x=>x.linkType===ir&&x.source.structureId===r&&(x.source.roundNumber||1)===f).map(x=>{let k=x.target.structureId,G=x.target.roundNumber,{structure:V}=tt({drawDefinition:e,structureId:k}),B=V?.positionAssignments??[],z=(V?.matchUps??[]).filter(Y=>Y.roundNumber===G),H=new Set(z.flatMap(Y=>(Y.drawPositions??[]).filter(Boolean))),K=H.size>0&&[...H].some(Y=>B.some(J=>J.drawPosition===Y&&J.participantId));return{targetStructureId:k,targetRoundNumber:G,feedProfile:x.target.feedProfile,losersPlaced:K}}),b={roundNumber:f,matchUpsCount:g.matchUpsCount,completedCount:S,isComplete:h,isPreFeedRound:y,needsLuckySelection:D,nextRoundHasOpenPosition:N,...U.length&&{consolidationLinks:U}},C=(x,k)=>{let G=x.sides?.find(B=>B.sideNumber===k);if(G)return G.participantId||G.participant?.participantId;let V=x.drawPositions?.[k-1];return V?m[V]:void 0},_=(x,k,G)=>x.sides?.find(B=>B.sideNumber===k)?.participant?.participantName||d[G],v=(x,k)=>{let G=C(x,k);if(!G)return;let V=_(x,k,G),B=Id({matchUp:x});return{participantId:G,participantName:V,matchUpId:x.matchUpId,scoreString:x.score?.scoreStringSide1,margin:B.margin??0,gameRatio:Number.isFinite(B.gameRatio)?B.gameRatio:void 0,pointRatio:Number.isFinite(B.pointRatio)?B.pointRatio:void 0,setRatio:Number.isFinite(B.setRatio)?B.setRatio:void 0,gameDifferential:B.gameDifferential??0,setsWonByLoser:B.setsWonByLoser??0}},w=I.filter(x=>x.winningSide),L=[...I].sort((x,k)=>(x.roundPosition||0)-(k.roundPosition||0)),F=[];for(let x of L)if(x.winningSide){let k=v(x,x.winningSide);k&&F.push(k)}else if(x.matchUpStatus==="BYE"){let k=x.drawPositions??[];for(let G of k){if(!G)continue;let V=p.find(B=>B.drawPosition===G);if(V?.participantId&&!V.bye){F.push({participantId:V.participantId,participantName:d[V.participantId],matchUpId:x.matchUpId,margin:0,gameDifferential:0,setsWonByLoser:0});break}}}if(b.advancingWinners=F,y){let x=w.map(k=>{let G=k.winningSide===1?2:1,V=v(k,G);if(!V||!n)return V;let B=a.filter(K=>{if(!K.roundNumber||K.roundNumber>f||!K.winningSide)return!1;let Y=C(K,1),J=C(K,2);return Y===V.participantId||J===V.participantId}),z=0,H=0;for(let K of B){let Y=Id({matchUp:K});if(Number.isFinite(Y.margin)){let J=C(K,1),ct=J===V.participantId&&K.winningSide!==1||J!==V.participantId&&K.winningSide!==2;z+=ct?Y.margin??0:1-(Y.margin??0),H++}}return H>0&&(V.margin=z/H),V}).filter(k=>!!k).sort((k,G)=>(G.margin??0)!==(k.margin??0)?(G.margin??0)-(k.margin??0):(G.setsWonByLoser??0)-(k.setsWonByLoser??0));b.eligibleLosers=x}return b});return{...P,isLuckyDraw:!0,rounds:l}}var xF="luckyDrawAdvancement";function _C({tournamentRecord:t,drawDefinition:e,participantId:r,structureId:n,roundNumber:o,random:i,event:s}){if(!e)return{error:$};if(n=n||e.structures?.[0]?.structureId,!n)return{error:O};let{structure:a}=tt({drawDefinition:e,structureId:n});if(!a)return{error:O};if(!an(e.drawType)&&!Pc({drawDefinition:e,structure:a}))return M({result:{error:O},info:"Not a lucky draw"});let c=ff({tournamentRecord:t,drawDefinition:e,structureId:n});if(c.error)return c;let u=c.rounds?.find(h=>h.roundNumber===o);if(!u?.isComplete)return M({result:{error:O},info:"Round is not complete"});if(u.isPreFeedRound&&u.needsLuckySelection){if(!r)return{error:We};if(!u.eligibleLosers?.find(T=>T.participantId===r))return M({result:{error:O},info:"Participant is not an eligible loser from this round"})}let p=o+1,m=(a.matchUps??[]).filter(h=>h.roundNumber===p).sort((h,T)=>(h.roundPosition||0)-(T.roundPosition||0)),d=u.advancingWinners??[],l=d.map(h=>h.participantId);if(u.isPreFeedRound&&r&&R5({advancingParticipantIds:l,nextRoundMatchUps:m,roundStatus:u,participantId:r,winners:d,random:i}),!m.length)return M({result:{error:O},info:"No matchUps found in next round"});let f=m.length*2;if(l.length!==f)return M({result:{error:O},info:`Expected ${f} advancing participants, got ${l.length}`});let g=a.positionAssignments??[];g=b5({positionAssignments:g,nextRoundMatchUps:m,structure:a,roundNumber:o}),a.positionAssignments=g;let I=U5({nextRoundMatchUps:m,positionAssignments:g});if(I)return I;let S=t?.tournamentId;return C5({advancingParticipantIds:l,positionAssignments:g,nextRoundMatchUps:m,drawDefinition:e,roundNumber:o,roundStatus:u,participantId:r,tournamentId:S,structureId:n,structure:a}),hn({drawDefinition:e,tournamentId:S,structure:a,event:s}),u.isPreFeedRound&&r&&D5({drawDefinition:e,tournamentRecord:t,roundStatus:u,participantId:r,structureId:n,roundNumber:o,event:s}),{...P}}function N5({drawDefinition:t,tournamentRecord:e,targetStructureId:r,targetRoundNumber:n,feedProfile:o,participantIds:i,event:s}){let{structure:a}=tt({drawDefinition:t,structureId:r});if(!a)return{error:O};if(Ae({structure:a})&&a.finishingPosition===po)return{...P};let c=(a.matchUps??[]).filter(d=>d.roundNumber===n).sort((d,l)=>(d.roundPosition||0)-(l.roundPosition||0)),u=a.positionAssignments??[],p=[];a.matchUps??=[],c.length===0?(M5({targetStructure:a,targetStructureId:r,targetRoundNumber:n,participantIds:i,unfilledPositions:p}),c=a.matchUps.filter(d=>d.roundNumber===n).sort((d,l)=>(d.roundPosition||0)-(l.roundPosition||0))):v5({targetMatchUps:c,targetPositionAssignments:u,targetStructure:a,unfilledPositions:p}),o==="BOTTOM_UP"?p.sort((d,l)=>l-d):p.sort((d,l)=>d-l);let m=e?.tournamentId;for(let d=0;d<i.length&&d<p.length;d++){let l=p[d],f=i[d],g=u.find(S=>S.drawPosition===l&&!S.participantId);g?g.participantId=f:u.push({drawPosition:l,participantId:f});let I=c.find(S=>S.drawPositions?.includes(l));I&&It({context:xF,drawDefinition:t,tournamentId:m,structureId:r,matchUp:I})}return a.positionAssignments=u,hn({drawDefinition:t,tournamentId:m,structure:a,event:s}),{...P}}function D5({drawDefinition:t,tournamentRecord:e,roundStatus:r,participantId:n,structureId:o,roundNumber:i,event:s}){let a=(r.eligibleLosers??[]).filter(u=>u.participantId!==n).map(u=>u.participantId);if(!a.length)return;let c=(t.links??[]).filter(u=>u.linkType===ir&&u.source.structureId===o&&(u.source.roundNumber||1)===i);for(let u of c){let p=N5({drawDefinition:t,tournamentRecord:e,targetStructureId:u.target.structureId,targetRoundNumber:u.target.roundNumber,feedProfile:u.target.feedProfile,participantIds:a,event:s});p?.error&&je()&&console.warn("Failed to place discarded losers in consolidation structure:",p.error)}}function U5({nextRoundMatchUps:t,positionAssignments:e}){for(let r of t){let n=r.drawPositions;if(!n?.length)continue;if(n.filter(i=>i?e.some(s=>s.drawPosition===i&&s.participantId):!1).length)return M({result:{error:O},info:"Next round already has participants assigned"});n.some(Boolean)&&(r.drawPositions=[]),r.matchUpStatus&&r.matchUpStatus!=="TO_BE_PLAYED"&&(r.matchUpStatus=void 0,r.winningSide=void 0,r.score=void 0)}}function R5({advancingParticipantIds:t,nextRoundMatchUps:e,roundStatus:r,participantId:n,winners:o,random:i}){let s=r.eligibleLosers?.find(d=>d.participantId===n),a=s?o.findIndex(d=>d.matchUpId===s.matchUpId):-1,c=e.length,u=Math.ceil(c/2);if(a<0||c<=1){t.push(n);return}let p=c*2,m=[];for(let d=0;d<p;d++){let l=Math.floor(d/2),f=a+(d<=a?1:0),g=Math.floor(f/2),I=l<u,S=g<u;I!==S&&m.push(d)}if(m.length){let d=Math.floor((i??Math.random)()*m.length);t.splice(m[d],0,n)}else t.push(n)}function b5({positionAssignments:t,nextRoundMatchUps:e,structure:r,roundNumber:n}){let o=new Set(e.flatMap(s=>(s.drawPositions??[]).filter(Boolean)));if(o.size){let s=[];for(let a of o){let c=t.filter(p=>p.drawPosition===a),u=c.some(p=>!p.participantId&&!p.bye);(c.length>1||u)&&s.push(a)}if(s.length){let a=new Set(s);t=t.filter(c=>!a.has(c.drawPosition))}}let i=new Set((r.matchUps??[]).filter(s=>s.roundNumber&&s.roundNumber<=n).flatMap(s=>s.drawPositions??[]).filter(Boolean));return t=t.filter(s=>s.participantId||s.bye?!0:i.has(s.drawPosition)),t}function C5({advancingParticipantIds:t,positionAssignments:e,nextRoundMatchUps:r,drawDefinition:n,roundNumber:o,roundStatus:i,participantId:s,tournamentId:a,structureId:c,structure:u}){let p=new Set(e.map(g=>g.drawPosition)),m=(u.matchUps??[]).flatMap(g=>g.drawPositions??[]).filter(Boolean),d=[...p,...m],f=(d.length?Math.max(...d):0)+1;for(let g=0;g<r.length;g++){let I=r[g],S=f++,h=f++,T=t[g*2],y=t[g*2+1];I.drawPositions=[S,h];let E={drawPosition:S,participantId:T},A={drawPosition:h,participantId:y};i.isPreFeedRound&&s&&(T===s?E.extensions=[{name:"luckyAdvancement",value:{fromRoundNumber:o}}]:y===s&&(A.extensions=[{name:"luckyAdvancement",value:{fromRoundNumber:o}}])),e.push(E,A),It({context:xF,drawDefinition:n,tournamentId:a,structureId:c,matchUp:I})}u.positionAssignments=e}function M5({targetStructure:t,targetStructureId:e,targetRoundNumber:r,participantIds:n,unfilledPositions:o}){let i=Math.ceil(n.length/2),s=1;for(let a=0;a<i;a++){let c=s++,u=s++,p={matchUpId:`${e}-mu-${a+1}`,roundNumber:r,roundPosition:a+1,drawPositions:[c,u],matchUpStatus:"TO_BE_PLAYED"};t.matchUps.push(p),o.push(c,u)}}function v5({targetMatchUps:t,targetPositionAssignments:e,targetStructure:r,unfilledPositions:n}){for(let o of t)for(let i of o.drawPositions??[]){if(!i)continue;let s=e.find(a=>a.drawPosition===i);!s?.participantId&&!s?.bye&&n.push(i)}if(!n.length){let o=new Set(e.filter(c=>c.participantId).map(c=>c.drawPosition)),i=(r.matchUps??[]).flatMap(c=>c.drawPositions??[]).filter(c=>c&&o.has(c)),s=[...o,...i],a=s.length?Math.max(...s)+1:1;for(let c of t)if(!c.drawPositions?.length||!c.drawPositions.some(Boolean)){let u=a++,p=a++;c.drawPositions=[u,p],n.push(u,p)}}}function wF(t){let e="generateAndPopulateRRplayoffStructures";if(!t.playoffGroups)return M({result:{error:nt},info:"playoffGroups required",stack:e});let{sourceStructureId:r,requireSequential:n,tournamentRecord:o,drawDefinition:i,playoffGroups:s,groupCount:a,groupSize:c,event:u}=t,p=mf({requireSequential:n,sourceStructureId:r,playoffGroups:s,groupCount:a,groupSize:c,...t});if(p.error)return M({result:p,stack:e});let{structures:m=[],links:d=[],finishingPositionTargets:l,positionRangeMap:f}=p,g=l?.flatMap(({finishingPositions:D})=>D).flatMap(D=>f[D].finishingPositions);i.structures.push(...m),i.links.push(...d);let{matchUps:I,matchUpsMap:S}=te({inContext:!0,drawDefinition:i}),h=new Set(m.map(({structureId:D})=>D)),T=I?.filter(({structureId:D})=>h.has(D)).map(Te),y=S?.drawMatchUps?.filter(({matchUpId:D})=>T?.includes(D));if(y?.length){let D=ze({drawDefinition:i,event:u})?.tieFormat;D&&y.forEach(R=>{let{tieMatchUps:U}=ts({isMock:t.isMock,tieFormat:D,matchUp:R});Object.assign(R,{tieMatchUps:U,matchUpType:Ir})})}let{positionAssignments:E}=Pt({structureId:r,drawDefinition:i}),A={};E?.forEach(D=>{let b=ot({element:D,name:Bo})?.extension?.value?.groupOrder;b&&(A[b]||(A[b]=[]),A[b].push(D.participantId))});let N=Ha({provisionalPositioning:t.provisionalPositioning,structureId:r,applyPositioning:!0,event:t.event,tournamentRecord:o,drawDefinition:i});return N.error&&N.error?.code!==Lg.code?M({result:N,stack:e}):{structures:m,links:d,positionsPlayedOff:g,drawDefinition:i,...P}}function gf({positionAssignments:t,tournamentRecord:e,drawDefinition:r,matchUpFormat:n,matchUps:o,event:i}){if(!Rr(o))return{error:O};if(!t)return{error:O};let{policyDefinitions:s}=fo({policyTypes:[vI],tournamentRecord:e,drawDefinition:r,event:i}),{subOrderMap:a}=Zl({positionAssignments:t}),c=o.length?ea({policyDefinitions:s,matchUpFormat:n,subOrderMap:a,matchUps:o}):void 0;if(c?.error)return c;let{participantResults:u={},bracketComplete:p,report:m}=c??{},d=Object.keys(u);return t.forEach(l=>{let{participantId:f}=l;if(d.includes(f)){let g={value:u[f],name:Bo};ut({element:l,extension:g}),u[f].ties||dr({element:l,name:du})}else dr({element:l,name:Bo}),dr({element:l,name:du})}),Ft({drawDefinition:r}),{...P,participantResults:u,bracketComplete:p,report:m}}function tA({matchUps:t,matchUpId:e}){return{matchUp:(t??[]).find(n=>n.matchUpId===e)}}function Wt(t){let e=X(t,[{[Kt]:!0,[wr]:!0}]);if(e.error)return e;let{tournamentParticipants:r,participantsProfile:n,afterRecoveryTimes:o,contextProfile:i,drawDefinition:s,matchUpsMap:a,matchUpId:c,inContext:u,context:p,event:m}=t,{structures:d=[]}=Sn({drawDefinition:s}),l=t.contextContent||i&&eo({contextProfile:i,drawDefinition:s});for(let f of d){let{matchUps:g}=ht({tournamentParticipants:r,participantsProfile:n,afterRecoveryTimes:o,contextContent:l,drawDefinition:s,contextProfile:i,matchUpsMap:a,inContext:u,structure:f,context:p,event:m}),{matchUp:I}=tA({matchUps:g,matchUpId:c});if(I)return{matchUp:I,structure:f}}return{error:Be}}function Sd(t){return!Tt(t)||!t.notes?{error:nt}:Tt(t.element)?!wt(t.notes)&&!t.notes?.testing?{error:O}:(Object.assign(t.element,{notes:t.notes}),{...P}):{error:O}}function FS(t){return Tt(t)?Tt(t.element)?(t.element.notes&&delete t.element.notes,{...P}):{error:O}:{error:nt}}var qa={matchUpStatus:zt,matchUpStatusCodes:[],score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0},matchUpFormat:void 0,winningSide:void 0};function Fn(t){let e="modifyMatchUpScore",r=t.matchUpFormat,n=t.matchUp,o,{matchUpStatusCodes:i,tournamentRecord:s,drawDefinition:a,matchUpStatus:c,removeScore:u,winningSide:p,matchUpId:m,event:d,notes:l,score:f}=t,g=O5({appliedPolicies:t.appliedPolicies,tournamentRecord:s,drawDefinition:a,structure:o,event:d}),I=n.matchUpType===xt,S=_5({isDualMatchUp:I,drawDefinition:a,matchUpId:m,matchUp:n,event:d});if(S?.error)return S;S&&({matchUp:n,structure:o}=S);let h=c&&n?.matchUpStatus===Mt&&c!==Mt;x5({matchUpStatusCodes:i,removeWinningSide:t.removeWinningSide,matchUpStatus:c,matchUpFormat:r,removeScore:u,winningSide:p,matchUp:n,score:f}),!o&&a&&({structure:o}=Wt({drawDefinition:a,matchUpId:m,event:d})),w5({matchUpStatus:c,matchUp:n});let T;(h&&n?.processCodes?.length||c===Mt)&&(T=g?.[Qr]?.processCodes?.incompleteAssignmentsOnDefault);let y=L5({isDualMatchUp:I,tournamentRecord:s,drawDefinition:a,matchUpFormat:r,matchUpId:m,structure:o,matchUp:n,event:d});if(y?.error)return M({result:y,stack:e});if(a&&n.winningSide){let{competitionPolicy:N}=Ao({tournamentRecord:s,drawDefinition:a,event:d});N?.processingGranularity==="PER_MATCHUP"&&Jm({tournamentRecord:s,drawDefinition:a,matchUp:n,event:d})}if(l){let N=Sd({element:n,notes:l});if(N.error)return M({result:N,stack:e})}let E=s?.tournamentId,A=F5({defaultedProcessCodes:T,tournamentRecord:s,drawDefinition:a,matchUpId:m});return A&&vr().topics.includes(Cp)&&EL({tournamentId:E,inContextMatchUp:A}),k5({defaultedProcessCodes:T,inContextMatchUp:A,matchUpStatus:c,matchUp:n}),It({eventId:d?.eventId,context:e,drawDefinition:a,tournamentId:E,matchUp:n}),{...P}}function O5({appliedPolicies:t,tournamentRecord:e,drawDefinition:r,structure:n,event:o}){return t&&Object.keys(t).length?t:ft({policyTypes:[Qr],tournamentRecord:e,drawDefinition:r,structure:n,event:o})?.appliedPolicies}function _5({isDualMatchUp:t,drawDefinition:e,matchUpId:r,matchUp:n,event:o}){if(t&&e){if(r&&n.matchUpId!==r){let i=Wt({drawDefinition:e,matchUpId:r,event:o});return i.matchUp?{matchUp:i.matchUp,structure:i.structure}:{error:Be}}return}n.matchUpId!==r&&console.log("!!!!!")}function x5({matchUpStatusCodes:t,removeWinningSide:e,matchUpStatus:r,matchUpFormat:n,removeScore:o,winningSide:i,matchUp:s,score:a}){r&&new Set([vt,Qt]).has(r)||o?Object.assign(s,{...qa}):a&&(s.score=a),r&&(s.matchUpStatus=r),n&&(s.matchUpFormat=n),t&&(s.matchUpStatusCodes=t),i&&(s.winningSide=i),e&&(s.winningSide=void 0)}function w5({matchUpStatus:t,matchUp:e}){let r=new Set([lu,Wi,Xr]);t&&!e.winningSide&&ue(e)&&!Ot.includes(t)&&!r.has(t)&&(e.matchUpStatus=Cn)}function L5({isDualMatchUp:t,tournamentRecord:e,drawDefinition:r,matchUpFormat:n,matchUpId:o,structure:i,matchUp:s,event:a}){if(s.collectionId)return;let c=i?.structureType===de,u=Ae({structure:i});if(!Pc({drawDefinition:r,structure:i})&&!u&&!c)return;let p=t?"SET1-S:T100":n??s.matchUpFormat??i?.matchUpFormat??r?.matchUpFormat??a?.matchUpFormat,m=t?{matchUpTypes:[xt]}:void 0,d=c&&i.structures.find(g=>g?.matchUps.find(I=>I.matchUpId===o))||i,{matchUps:l}=ht({structure:d,afterRecoveryTimes:!1,tournamentRecord:e,inContext:!0,matchUpFilters:m,drawDefinition:r,event:a});u&&(d.positionAssignments=pt(l.flatMap(g=>(g.sides??[]).map(I=>I.participantId)).filter(Boolean)).map(g=>({participantId:g})));let f=gf({positionAssignments:d.positionAssignments,matchUpFormat:p,tournamentRecord:e,drawDefinition:r,matchUps:l,event:a});return f.error?f:{matchUpFormat:p}}function F5({defaultedProcessCodes:t,tournamentRecord:e,drawDefinition:r,matchUpId:n}){if(!vr().topics.includes(Cp)&&!t)return;let i=Ie({drawDefinition:r});if(i)return te({matchUpFilters:{matchUpIds:[n]},nextMatchUps:!0,tournamentRecord:e,inContext:!0,drawDefinition:r,matchUpsMap:i}).matchUps?.[0]}function k5({defaultedProcessCodes:t,inContextMatchUp:e,matchUpStatus:r,matchUp:n}){if(!(!Array.isArray(t)||!e)&&!e.sides?.every(({participantId:o})=>o))if(r===Mt)n.processCodes=pt([...n.processCodes??[],...t]);else for(let o of t??[]){let i=o&&n?.processCodes?.lastIndexOf(o);n?.processCodes?.splice(i,1)}}function If(t){let{propagateExitStatus:e,matchUpStatusCodes:r,autoCalcDisabled:n,inContextMatchUp:o,matchUpStatus:i,dualMatchUp:s,structure:a,matchUp:c}=t,u=Va({matchUpStatus:i})||[to,Fr].includes(i)&&s||n,p=c?.sides?.map(S=>S.participantId).filter(Boolean).length||o?.sides?.map(S=>S.participantId).filter(Boolean).length,m="attemptToModifyScore";if(!(Ae({structure:a})&&p===1||i===Mt&&p||G5({structure:a,matchUp:c,inContextMatchUp:o})||t.appliedPolicies?.[Qr]?.requireParticipantsForScoring===!1||Ye(i)&&p===1&&e))return M({result:{error:Bg},stack:m});let f=[vt].includes(i),g=u?i:t.winningSide&&ie||Xr,I=Fn({...t,winningSide:t.winningSide,matchUpStatusCodes:(u&&r)??[],matchUpStatus:g,context:m,removeScore:f});return M({result:I,stack:m})}function G5({structure:t,matchUp:e,inContextMatchUp:r}){let{drawPositions:n}=e,{positionAssignments:o}=se({structure:t}),i=o?.filter(a=>n?.includes(a.drawPosition)&&a.participantId),s=r?.sides?.every(a=>a.participantId);return i?.length===2||s}function eA({collectionGroups:t=[]}){let e=Object.assign({},...t.filter(n=>yt(n?.groupValue)&&n?.groupNumber).map(n=>({[n.groupNumber]:{...n,allGroupMatchUpsCompleted:!0,matchUpsCount:0,sideWins:[0,0],values:[0,0]}}))),r=Object.keys(e).map(n=>st(n));return{groupValueGroups:e,groupValueNumbers:r}}function LF({collectionDefinition:t,groupValueNumbers:e,groupValueGroups:r,sideTieValues:n,tieMatchUps:o}){let i=o.filter(h=>h.collectionId===t.collectionId),s=[0,0],a=[0,0],c=i.every(h=>Ot.includes(h.matchUpStatus)),{collectionValueProfiles:u,collectionGroupNumber:p,collectionValue:m,matchUpValue:d,winCriteria:l,scoreValue:f,setValue:g}=t,I=p&&e.includes(p),S=[0,0];i.forEach(h=>{h.winningSide&&(S[h.winningSide-1]+=1)}),V5({collectionDefinition:t,collectionMatchUps:i,sideMatchUpValues:s,collectionValueProfiles:u,matchUpValue:d,scoreValue:f,setValue:g}),a=H5({allCollectionMatchUpsCompleted:c,collectionDefinition:t,sideCollectionValues:a,belongsToValueGroup:I,sideMatchUpValues:s,groupValueGroups:r,collectionGroupNumber:p,collectionValue:m,matchUpValue:d,winCriteria:l,scoreValue:f,setValue:g,sideWins:S}),I?(r[p].sideWins[0]+=S[0]||0,r[p].sideWins[1]+=S[1]||0,r[p].allGroupMatchUpsCompleted=r[p].allGroupMatchUpsCompleted&&c,r[p].matchUpsCount+=i.length):a.forEach((h,T)=>n[T]+=h||0)}function V5({collectionDefinition:t,collectionMatchUps:e,sideMatchUpValues:r,collectionValueProfiles:n,matchUpValue:o,scoreValue:i,setValue:s}){yt(o)?e.forEach(a=>{a.winningSide&&(r[a.winningSide-1]+=o)}):yt(s)?e.forEach(a=>{a.score?.sets?.forEach(c=>{c.winningSide&&(r[c.winningSide-1]+=s)})}):yt(i)?B5({collectionMatchUps:e,sideMatchUpValues:r}):Array.isArray(n)&&W5({collectionMatchUps:e,collectionDefinition:t,sideMatchUpValues:r})}function B5({collectionMatchUps:t,sideMatchUpValues:e}){t.forEach(r=>{r.score?.sets?.forEach(n=>{let{side1TiebreakScore:o=0,side2TiebreakScore:i=0,side1Score:s=0,side2Score:a=0}=n;(r.matchUpStatus===ie||r.winningSide||n.winningSide)&&(s||a?(e[0]+=s,e[1]+=a):(o||i)&&n.winningSide&&(e[n.winningSide-1]+=1))})})}function W5({collectionMatchUps:t,collectionDefinition:e,sideMatchUpValues:r}){t.forEach(n=>{if(n.winningSide){let o=n.collectionPosition,i=j5({collectionDefinition:e,collectionPosition:o});yt(i)&&(r[n.winningSide-1]+=i)}})}function H5({allCollectionMatchUpsCompleted:t,collectionDefinition:e,sideCollectionValues:r,belongsToValueGroup:n,sideMatchUpValues:o,groupValueGroups:i,collectionGroupNumber:s,collectionValue:a,matchUpValue:c,winCriteria:u,scoreValue:p,setValue:m,sideWins:d}){if(yt(a)){let l=Y5({allCollectionMatchUpsCompleted:t,collectionDefinition:e,sideMatchUpValues:o,matchUpValue:c,winCriteria:u,scoreValue:p,setValue:m,sideWins:d});l&&(n?i[s].values[l-1]+=a:r[l-1]+=a)}else n?(i[s].values[0]+=o[0]||0,i[s].values[1]+=o[1]||0):r=o;return r}function Y5({allCollectionMatchUpsCompleted:t,collectionDefinition:e,sideMatchUpValues:r,matchUpValue:n,winCriteria:o,scoreValue:i,setValue:s,sideWins:a}){if(o?.aggregateValue){if(t){if(yt(n||s||i)&&r[0]!==r[1])return r[0]>r[1]?1:2;if(a[0]!==a[1])return a[0]>a[1]?1:2}return}if(o?.valueGoal)return r.reduce((u,p,m)=>p>=o.valueGoal?m+1:u,0);let c=Math.floor(e.matchUpCount/2)+1;return a.reduce((u,p,m)=>p>=c?m+1:u,0)}function j5({collectionDefinition:t,collectionPosition:e}){return(t.collectionValueProfiles??[])?.find(o=>o.collectionPosition===e)?.matchUpValue}function _u(t){let{sideAdjustments:e=[0,0],separator:r="-",drawDefinition:n,matchUpsMap:o,structure:i,matchUp:s,event:a}=t;if(!Array.isArray(e)||e.length!==2||Number.isNaN(e.reduce((I,S)=>I+S)))return{error:O};if(!s)return{error:Xe};let c=ze({matchUp:s,drawDefinition:n,structure:i,event:a})?.tieFormat||t?.tieFormat;if(!c)return{error:ya};let u=or({tieFormat:c});if(u.error)return u;let m=q5(c,s).map((I,S)=>(I||0)+e[S]),d={side1Score:m[0],side2Score:m[1],winningSide:void 0},l=m.join(r),f=m.slice().reverse().join(r),g=K5({drawDefinition:n,matchUpsMap:o,sideScores:m,tieFormat:c,matchUp:s});return g&&(d.winningSide=g),{scoreStringSide1:l,scoreStringSide2:f,winningSide:g,set:d}}function q5(t,e){let r=t?.collectionDefinitions??[],n=e?.tieMatchUps??[],o=[0,0],{groupValueGroups:i,groupValueNumbers:s}=eA(t);for(let a of r)LF({collectionDefinition:a,groupValueNumbers:s,groupValueGroups:i,sideTieValues:o,tieMatchUps:n});for(let a of s){let c=$5(i[a]);c&&(o[c-1]+=i[a].groupValue||0)}return o}function $5(t){let{allGroupMatchUpsCompleted:e,matchUpCount:r,winCriteria:n,sideWins:o,values:i}=t;if(n?.aggregateValue)return e&&i[0]!==i[1]?i[0]>i[1]?1:2:void 0;if(n?.valueGoal)return i.reduce((a,c,u)=>c>=n.valueGoal?u+1:a,void 0);let s=Math.floor(r/2)+1;return o.reduce((a,c,u)=>c>=s?u+1:a,void 0)}function K5({drawDefinition:t,matchUpsMap:e,sideScores:r,tieFormat:n,matchUp:o}){if(!n?.winCriteria)return;let{valueGoal:i,aggregateValue:s,tallyDirectives:a}=n.winCriteria,c=o?.tieMatchUps??[],u;return i?u=z5(r,i):s&&(u=Q5(c,r)),!u&&a&&(u=X5({drawDefinition:t,matchUpsMap:e,matchUp:o})),u}function z5(t,e){return t.map((n,o)=>({sideNumber:o+1,points:n})).find(({points:n})=>n>=e)?.sideNumber}function Q5(t,e){if(t.every(n=>n.matchUpStatus&&Ot.includes(n.matchUpStatus)||n.winningSide)&&e[0]!==e[1])return e[0]>e[1]?1:2}function X5({drawDefinition:t,matchUpsMap:e,matchUp:r}){let n=r.matchUpId,o=r.hasContext?r:e?.drawMatchUps?.[n]||t&&Wt({inContext:!0,drawDefinition:t,matchUpId:n})?.matchUp;if(!o)return;let{completedTieMatchUps:i,order:s}=ea({matchUps:[o]});if(!i||!s?.length)return;let a=s[0].participantId;return o.sides.find(({participantId:c})=>c===a)?.sideNumber}function Cc({inContextDualMatchUp:t,drawDefinition:e,tournamentId:r,dualMatchUp:n,eventId:o}){if(n){t||(t=Wt({matchUpId:n.matchUpId,inContext:!0,drawDefinition:e})?.matchUp);let{extension:i}=ot({element:e,name:Vo}),s=q(i?.value??{},!1,!0),a=({displaySideNumber:c,drawPosition:u,sideNumber:p})=>({drawPosition:u,sideNumber:p,displaySideNumber:c});n.sides=t?.sides?.map(c=>{let u=c.participantId,p=u&&s[u]||void 0,{lineUp:m,...d}=n.sides?.find(({sideNumber:f})=>f===c.sideNumber)??{},l=m?.length?m:p;return{...a(c),...d,lineUp:l}}),It({context:"ensureSidLineUps",matchUp:n,drawDefinition:e,tournamentId:r,eventId:o})}}function nr(t){if(t)return q(t,!1,!0)}function kS(t){let e=X(t,[{[Ee]:!0}]);return e.error?e:Object.keys(t.tournamentRecords).reduce((n,o)=>{n.tournamentIdMap[o]=[];let s=t.tournamentRecords[o].events??[],a=s.map(({eventId:u})=>u),c=s.map(u=>(u.drawDefinitions??[]).map(({drawId:p})=>p)).flat();return n.tournamentIdMap[o].push(...a,...c),n.eventIds.push(...a),n.drawIds.push(...c),n},{eventIds:[],drawIds:[],tournamentIdMap:{}})}function rA({tournamentRecords:t,eventId:e,drawId:r}){let{tournamentIdMap:n}=kS({tournamentRecords:t});return(n?Object.keys(n):[]).find(i=>e&&n?.[i].includes(e)||r&&n?.[i].includes(r))}function ho(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&&rA({tournamentRecords:c,...t});let p=u&&c[u];if(!p)return{error:j};let m=Wt({drawDefinition:r,event:a,matchUpId:s});if(m.error)return m;if(!m.matchUp)return{error:Be};let{matchUp:d,structure:l}=m;if(!d.tieMatchUps)return{error:cr};Cc({tournamentId:p?.tournamentId,eventId:a?.eventId,dualMatchUp:d,drawDefinition:r});let{extension:f}=ot({name:gc,element:d});if(f?.value)if(o)dr({element:d,name:gc});else return{...P,score:d.score};let g=ze({drawDefinition:r,structure:l,matchUp:d,event:a})?.tieFormat;d.tieFormat=nr(g);let I=_u({drawDefinition:r,matchUpsMap:i,structure:l,matchUp:d,event:a}),{winningSide:S,set:h,scoreStringSide1:T,scoreStringSide2:y}=I,E=h?.side1Score||h?.side2Score;if(e&&!d.score&&!E)return{...P};let A={scoreStringSide1:T,scoreStringSide2:y,sets:h?[h]:[]},N=S&&[1,2].includes(S),D=N&&ie||uS({matchUpStatus:n??d.matchUpStatus,tieMatchUps:d.tieMatchUps,winningSide:d.winningSide,score:A})&&Cn||zt,R=!!(d.winningSide&&!N),U=d.tieMatchUps.find(({score:C,winningSide:_,matchUpStatus:v})=>C?.sets?.length&&(C.sets[0].side1Score||C.sets[0].side2Score)||v&&Ot.includes(v)||_),b;if(d.tieFormat&&!N&&!U){let C=ze({drawDefinition:r,structure:l,event:a})?.tieFormat;C&&JSON.stringify(g)===JSON.stringify(C)&&(d.tieFormatId=void 0,d.tieFormat=void 0,b=!0)}return Fn({appliedPolicies:t.appliedPolicies,matchUpStatus:D,score:A,removeWinningSide:R,tournamentRecord:p,drawDefinition:r,removeScore:o,winningSide:S,matchUpId:s,matchUp:d,event:a}),{...P,score:A,removeWinningSide:R,tieFormatRemoved:b,winningSide:S}}function FF({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=J5({winnerMatchUpDrawPositionIndex:t,inContextDrawMatchUps:e,sourceMatchUpStatus:n,winningDrawPosition:o,tournamentRecord:i,winnerTargetLink:s,sourceMatchUpId:a,drawDefinition:c,winnerMatchUp:u,matchUpsMap:m,event:d,stack:l});if(f?.error)return f}else{let f=bc({matchUpId:u.matchUpId,drawPosition:o,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,sourceMatchUpId:a,drawDefinition:c,matchUpsMap:m});if(f.error)return f}return p&&r&&Z5({projectedWinningSide:r,tournamentRecord:i,drawDefinition:c,winnerMatchUp:u,dualMatchUp:p,matchUpsMap:m,stack:l}),{...P}}function J5({winnerMatchUpDrawPositionIndex:t,inContextDrawMatchUps:e,sourceMatchUpStatus:r,winningDrawPosition:n,tournamentRecord:o,winnerTargetLink:i,sourceMatchUpId:s,drawDefinition:a,winnerMatchUp:c,matchUpsMap:u,event:p,stack:m}){let d=c.drawPositions??[],l=d[t],f=i.source.structureId,g=tt({structureId:f,drawDefinition:a});if(g.error)return g;let{structure:I}=g,{positionAssignments:S}=se({structureId:f,drawDefinition:a}),T=S?.find(U=>U.drawPosition===n)?.participantId,y=i.target.structureId,{positionAssignments:E}=se({structureId:y,drawDefinition:a}),N=E?.find(U=>U.participantId===T)?.drawPosition,D=E?.filter(U=>{let b=d.includes(U.drawPosition),C=!U.participantId&&!U.bye&&!U.qualifier;return b&&C}).map(U=>U.drawPosition),R=D?.includes(l);if(T&&i.target.roundNumber===1&&R)On({drawPosition:l,participantId:T,structureId:y,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:o,drawDefinition:a,matchUpsMap:u,event:p});else if(T&&D?.length){let U=D.pop();U&&On({participantId:T,structureId:y,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:o,drawDefinition:a,drawPosition:U,matchUpsMap:u,event:p})}else if(N){let U=bc({drawPosition:N,matchUpId:c.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:o,sourceMatchUpId:s,drawDefinition:a,matchUpsMap:u});if(U.error)return M({result:U,stack:m})}else if(I?.stage!==Z){let U="winner target position unavaiallble";console.log(U),M({stack:m,result:{error:U}})}if(I?.seedAssignments&&I.structureId!==y){let U=I.seedAssignments.find(({participantId:C})=>C===T),b=U?.participantId;U&&b&&Wa({eventId:c?.eventId,structureId:y,...U,tournamentRecord:o,drawDefinition:a,participantId:b})}}function Z5({projectedWinningSide:t,tournamentRecord:e,drawDefinition:r,winnerMatchUp:n,dualMatchUp:o,matchUpsMap:i,stack:s}){let a=o.sides?.find(f=>f.sideNumber===t);if(!a?.lineUp)return;let c=o.roundPosition,u=n.roundPosition,p=c===u&&c!==1||Math.floor(c/2)===u?2:1,m=i?.drawMatchUps?.find(({matchUpId:f})=>f===n.matchUpId),d=[1,2].map(f=>({...m.sides?.find(I=>I.sideNumber===f)??{},sideNumber:f}));m.sides=d;let l=m.sides.find(f=>f.sideNumber===p);if(l){let f=a.lineUp?.filter(g=>g?.participantId);l.lineUp=of({lineUp:f}),It({tournamentId:e?.tournamentId,eventId:n?.eventId,matchUp:m,context:s,drawDefinition:r})}}function kF(t){let{loserMatchUpDrawPositionIndex:e,inContextDrawMatchUps:r,projectedWinningSide:n,propagateExitStatus:o,sourceMatchUpStatus:i,loserDrawPosition:s,tournamentRecord:a,loserTargetLink:c,drawDefinition:u,loserMatchUp:p,dualMatchUp:m,matchUpsMap:d,event:l}=t,f="directLoser",g=c.linkCondition,I=p.drawPositions??[],S=g===Wn&&p.roundNumber===2&&Math.min(...I.filter(Boolean)),h=S||I[e],T=S||I[1-e],y=c.source.structureId,{structure:E}=tt({structureId:y,drawDefinition:u}),{matchUps:A}=ht({afterRecoveryTimes:!1,inContext:!0,drawDefinition:u,structure:E,event:l}),D=A.filter(H=>H.drawPositions?.includes(s)).filter(H=>{let K=H.sides.find(J=>J.drawPosition===s),Y=H.matchUpStatus===vt||H.matchUpStatus===Mt&&!ue(H);return K?.sideNumber===H.winningSide&&!Y}),R=g===Wn&&D.length===0,{positionAssignments:U}=se({structureId:y,drawDefinition:u}),C=U?.find(H=>H.drawPosition===s)?.participantId,_={loserParticipantId:C},v=c.target.structureId,{positionAssignments:w}=se({structureId:v,drawDefinition:u}),L=w?.filter(({drawPosition:H})=>I.includes(H)),F=L?.some(H=>H.participantId&&C&&H.participantId===C),x=o&&[De,vt,Mt].includes(i||"");if(F)return{...P,stack:f};let k=L?.filter(H=>{let K=I.includes(H.drawPosition),Y=!H.participantId&&!H.bye&&!H.qualifier;return K&&Y}).map(H=>H.drawPosition),G=k?.includes(h),V=c.target.roundNumber>1&&k?.length,B=c.target.roundNumber===1&&G,z=t4({fedDrawPositionFMLC:S,isFirstRoundValidDrawPosition:B,loserParticipantId:C,isFeedRound:V,unfilledTargetMatchUpDrawPositions:k,targetDrawPositionIsUnfilled:G,validForConsolation:R,targetMatchUpDrawPosition:h,loserBackdrawPosition:T,targetStructureId:v,inContextDrawMatchUps:r,sourceMatchUpStatus:i,validExitToPropagate:x,propagateExitStatus:o,loserDrawPosition:s,loserTargetLink:c,tournamentRecord:a,drawDefinition:u,matchUpsMap:d,event:l});return z.context&&Object.assign(_,z.context),z.error?M({result:z,stack:f}):z.earlyReturn?z.earlyReturn:(e4({loserParticipantId:C,targetStructureId:v,tournamentRecord:a,drawDefinition:u,loserMatchUp:p,structure:E}),r4({projectedWinningSide:n,tournamentRecord:a,drawDefinition:u,loserMatchUp:p,dualMatchUp:m,matchUpsMap:d,stack:f}),M({result:{...P},stack:f,context:_}))}function t4({fedDrawPositionFMLC:t,isFirstRoundValidDrawPosition:e,loserParticipantId:r,isFeedRound:n,unfilledTargetMatchUpDrawPositions:o,targetDrawPositionIsUnfilled:i,validForConsolation:s,targetMatchUpDrawPosition:a,loserBackdrawPosition:c,targetStructureId:u,inContextDrawMatchUps:p,sourceMatchUpStatus:m,validExitToPropagate:d,propagateExitStatus:l,loserDrawPosition:f,loserTargetLink:g,tournamentRecord:I,drawDefinition:S,matchUpsMap:h,event:T}){let y=()=>{let A=r?On({drawPosition:a,participantId:r,structureId:u,inContextDrawMatchUps:p,sourceMatchUpStatus:m,tournamentRecord:I,drawDefinition:S,matchUpsMap:h,event:T}):{error:We};return!A.error&&d&&l?{context:{progressExitStatus:!0}}:M({result:A,stack:"assignLoserDrawPosition"})};if(t){let A="loserLinkFedFMLC";if(s)return M({result:y(),stack:A});let N=Or({drawPosition:c,structureId:u,tournamentRecord:I,drawDefinition:S,event:T});return M({result:M({result:N,stack:"assignLoserPositionBye"}),stack:A})}if(e)return y();if(r&&(n||o?.length)){o.sort(Zt);let A=o[0],N=On({participantId:r,structureId:u,drawPosition:A,inContextDrawMatchUps:p,sourceMatchUpStatus:m,tournamentRecord:I,drawDefinition:S,matchUpsMap:h,event:T});return N.error?N:d&&l?{earlyReturn:{stack:"directLoser",context:{progressExitStatus:!0,loserParticipantId:r}}}:{...P}}return{context:{loserDrawPosition:f,loserTargetLink:g,targetDrawPositionIsUnfilled:i},error:i?ps:gw}}function e4({loserParticipantId:t,targetStructureId:e,tournamentRecord:r,drawDefinition:n,loserMatchUp:o,structure:i}){if(!i?.seedAssignments||i.structureId===e)return;let s=i.seedAssignments.find(({participantId:c})=>c===t),a=s?.participantId;s&&a&&Wa({eventId:o?.eventId,structureId:e,...s,tournamentRecord:r,drawDefinition:n,participantId:a})}function r4({projectedWinningSide:t,tournamentRecord:e,drawDefinition:r,loserMatchUp:n,dualMatchUp:o,matchUpsMap:i,stack:s}){if(!o||!t)return;let a=o.sides?.find(g=>g.sideNumber===3-t);if(!a?.lineUp)return;let{roundNumber:c,eventId:u}=n,{roundPosition:p}=o,m=c===1?2-p%2:1,d=i?.drawMatchUps?.find(({matchUpId:g})=>g===n.matchUpId),l=[1,2].map(g=>({...d.sides?.find(S=>S.sideNumber===g)??{},sideNumber:g}));d.sides=l;let f=d.sides.find(g=>g.sideNumber===m);f&&(f.lineUp=of({lineUp:a.lineUp}),It({tournamentId:e?.tournamentId,matchUp:d,context:s,drawDefinition:r,eventId:u}))}function nA(t){let e="directParticipants",r=If(t);if(r.error)return M({result:r,stack:e});let n=Va({matchUpStatus:t.matchUpStatus}),{dualWinningSideChange:o,inContextDrawMatchUps:i,projectedWinningSide:s,propagateExitStatus:a,matchUpStatusCodes:c,tournamentRecord:u,drawDefinition:p,matchUpStatus:m,dualMatchUp:d,matchUpsMap:l,winningSide:f,targetData:g,matchUpId:I,structure:S,matchUp:h,event:T}=t,y=!!h.collectionId,E=Ae({structure:S}),A=h.drawPositions,N;if(y){let{matchUpTieId:D,matchUpsMap:R}=t,U=ho({appliedPolicies:t.appliedPolicies,matchUpId:D,tournamentRecord:u,drawDefinition:p,matchUpsMap:R,event:T});if(N=U&&{tieMatchUpResult:U},A=i.find(({matchUpId:C})=>C===D)?.drawPositions,!o)return M({result:{...P,...N},stack:e})}return E?M({result:{...P,...N},stack:e}):A?n4({matchUpStatusIsValid:n,inContextDrawMatchUps:i,projectedWinningSide:s,propagateExitStatus:a,matchUpStatusCodes:c,tournamentRecord:u,drawDefinition:p,drawPositions:A,matchUpStatus:m,dualMatchUp:d,matchUpsMap:l,winningSide:f,targetData:g,matchUpId:I,structure:S,annotate:N,matchUp:h,stack:e,event:T}):M({result:{error:jc},stack:e})}function n4({matchUpStatusIsValid:t,inContextDrawMatchUps:e,projectedWinningSide:r,propagateExitStatus:n,matchUpStatusCodes:o,tournamentRecord:i,drawDefinition:s,drawPositions:a,matchUpStatus:c,dualMatchUp:u,matchUpsMap:p,winningSide:m,targetData:d,matchUpId:l,structure:f,annotate:g,matchUp:I,stack:S,event:h}){let T=r?r-1:m-1,y=1-T,E=a[T],A=a[y],N={},{targetLinks:{loserTargetLink:D,winnerTargetLink:R,byeTargetLink:U},targetMatchUps:{winnerMatchUpDrawPositionIndex:b,loserMatchUpDrawPositionIndex:C,winnerMatchUp:_,loserMatchUp:v,byeMatchUp:w}}=d,L=an(s?.drawType),F=o4(L,I,f),x=!L||!F,k=t&&c||ie;if(_&&x){let G=FF({sourceMatchUpStatus:k,winnerMatchUpDrawPositionIndex:b,sourceMatchUpId:l,inContextDrawMatchUps:e,projectedWinningSide:r,winningDrawPosition:E,tournamentRecord:i,winnerTargetLink:R,drawDefinition:s,winnerMatchUp:_,dualMatchUp:u,matchUpsMap:p,event:h});if(G.error)return M({result:G,stack:S})}if(v&&x){let G=kF({sourceMatchUpStatus:k,sourceMatchUpStatusCodes:o??[],sourceWinningSide:m,loserMatchUpDrawPositionIndex:C,sourceMatchUpId:l,inContextDrawMatchUps:e,projectedWinningSide:r,propagateExitStatus:n,loserDrawPosition:A,tournamentRecord:i,loserTargetLink:D,drawDefinition:s,loserMatchUp:v,winningSide:m,matchUpsMap:p,dualMatchUp:u,event:h});if(G.context?.progressExitStatus&&Object.assign(N,G.context,{sourceMatchUpStatus:k,sourceMatchUpStatusCodes:o??[],loserMatchUp:v,matchUpsMap:p}),G.error)return M({result:G,stack:S})}if(w){let G=w.drawPositions??[],V=Math.min(...G.filter(Boolean)),B=U.target.structureId,z=Or({drawPosition:V,structureId:B,tournamentRecord:i,drawDefinition:s,event:h});if(z.error)return M({result:z,stack:S})}return M({result:{...P,...g},stack:S,context:N})}function o4(t,e,r){return!t||!e.roundNumber||!r?.matchUps?!1:r.matchUps.filter(o=>o.roundNumber===e.roundNumber).length%2!==0}function Sf(t){let e="genPlayoffStructure",r=i4(t,e);if(r.error||r.earlyReturn)return r.earlyReturn??r;let{addNameBaseToAttributeName:n,playoffStructureNameBase:o,finishingPositionNaming:i,finishingPositionLimit:s,availabilityResult:a,sourceStructureId:c,playoffAttributes:u,playoffPositions:p,roundOffsetLimit:m,tournamentRecord:d,exitProfileLimit:l,drawDefinition:f,roundProfiles:g,roundNumbers:I,structure:S,idPrefix:h,isMock:T,event:y,uuids:E}=r,{playoffRoundsRanges:A,playoffRounds:N}=a,{playoffPositionsReturned:D,error:R,playoffSourceRounds:U,playoffRoundsRanges:b}=FE(t);if(R)return M({result:{error:R},stack:e});let C=g?.length&&Object.assign({},...g),_=I||typeof g=="object"&&g.flatMap(Y=>Object.keys(Y)),v=Array.isArray(_)&&_.map(Y=>!Number.isNaN(Number(Y))&&st(Y)).filter(Boolean);if(v){if(!Array.isArray(v))return M({result:{error:O},context:{validRoundNumbers:v},stack:e});v.forEach(Y=>{if(!N?.includes(Y))return M({result:{error:O},context:{roundNumber:Y},stack:e})})}p&&p.forEach(Y=>{if(!D?.includes(Y))return M({result:{error:O},context:{playoffPosition:Y},stack:e})});let w=v||U,L=v?A:b,F=[],x=[],k=an(f.drawType);for(let Y of w??[]){let J=L?.find(pr=>pr.roundNumber===Y);if(!J)return M({result:{error:O},context:{roundNumber:Y},stack:e});let ct=a4({finishingPositionsCount:J.finishingPositions.length,isLuckyDraw:k,roundNumber:Y,structure:S}),Et=Math.min(...J.finishingPositions)-1,Ht=2,Ut=Y&&C?.[Y]&&Ht+C[Y]-1,pe=Ru({exitProfile:`0-${Y}`,addNameBaseToAttributeName:n,playoffStructureNameBase:o,finishingPositionOffset:Et,playoffAttributes:u,exitProfileLimit:l,stage:Vt,roundOffset:0,drawDefinition:f,sequenceLimit:Ut,stageSequence:Ht,drawSize:ct,idPrefix:h,isMock:T,uuids:E,finishingPositionNaming:i,finishingPositionLimit:s,roundOffsetLimit:m});if(pe.error)return M({result:pe,stack:e});let{structures:ye,links:Jt}=pe;if(ye?.length&&F.push(...ye),Jt?.length&&x.push(...Jt),pe.structureId&&Y){let pr={linkType:ir,source:{structureId:c,roundNumber:Y},target:{structureId:pe.structureId,feedProfile:qe,roundNumber:1}};x.push(pr)}}if(!F.length)return M({result:{error:O},info:"No structures generated",stack:e});f.structures.push(...F),f.links.push(...x);let{matchUps:G,matchUpsMap:V}=te({inContext:!0,drawDefinition:f}),B=new Set(F.map(({structureId:Y})=>Y)),z=G?.filter(({structureId:Y})=>B.has(Y)).map(Te),H=V?.drawMatchUps?.filter(({matchUpId:Y})=>z?.includes(Y));if(H?.length){let Y=ze({drawDefinition:f,event:y})?.tieFormat;Y&&H.forEach(J=>{let{tieMatchUps:ct}=ts({matchUp:J,tieFormat:Y,isMock:T});Object.assign(J,{tieMatchUps:ct,matchUpType:xt})})}GF({inContextDrawMatchUps:G,sourceStructureId:c,tournamentRecord:d,drawDefinition:f,matchUpsMap:V,structure:S,event:y}),VF({inContextDrawMatchUps:G,sourceStructureId:c,tournamentRecord:d,drawDefinition:f,event:y});let K=c4({inContextDrawMatchUps:G,sourceStructureId:c,tournamentRecord:d,drawDefinition:f,matchUpsMap:V,params:t,stack:e});return{structures:F,matchUpModifications:K,links:x,drawDefinition:f,...P}}function i4(t,e){if(!t.drawDefinition)return{error:!0,earlyReturn:M({result:{error:$},stack:e})};let r=qp(t);if(r.error)return{error:!0,earlyReturn:M({result:r,stack:e})};let{structureId:n,addNameBaseToAttributeName:o,playoffStructureNameBase:i,finishingPositionNaming:s,finishingPositionLimit:a,playoffAttributes:c,playoffPositions:u,roundOffsetLimit:p,tournamentRecord:m,exitProfileLimit:d,playoffGroups:l,roundProfiles:f,roundNumbers:g,idPrefix:I,isMock:S,event:h,uuids:T}=t,y=q(t.drawDefinition,!1,!0),{structure:E}=tt({structureId:n,drawDefinition:y});return E?E.structureType===de||E.structures?{error:!0,earlyReturn:wF({sourceStructureId:E.structureId,...t,...r,drawDefinition:y})}:l?.length?{error:!0,earlyReturn:s4({sourceStructureId:n,tournamentRecord:m,drawDefinition:y,playoffGroups:l,structure:E,idPrefix:I,isMock:S,event:h,uuids:T,stack:e})}:{addNameBaseToAttributeName:o,playoffStructureNameBase:i,finishingPositionNaming:s,finishingPositionLimit:a,availabilityResult:r,sourceStructureId:n,playoffAttributes:c,playoffPositions:u,roundOffsetLimit:p,tournamentRecord:m,exitProfileLimit:d,drawDefinition:y,roundProfiles:f,roundNumbers:g,structure:E,idPrefix:I,isMock:S,event:h,uuids:T}:{error:!0,earlyReturn:M({result:{error:Nt},stack:e})}}function s4({sourceStructureId:t,tournamentRecord:e,drawDefinition:r,playoffGroups:n,structure:o,idPrefix:i,isMock:s,event:a,uuids:c,stack:u}){let p=mf({requireSequential:!1,matchUpType:a?.eventType,sourceStructureId:t,drawDefinition:r,playoffGroups:n,groupCount:1,idPrefix:i,isMock:s,uuids:c});if(p.error)return M({result:p,stack:u});let{structures:m,links:d}=p;if(!m?.length)return M({result:{error:O},info:"No playoff structures generated",stack:u});r.structures.push(...m),d?.length&&r.links.push(...d);let{matchUps:l,matchUpsMap:f}=te({inContext:!0,drawDefinition:r});return GF({inContextDrawMatchUps:l,sourceStructureId:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:f,structure:o,event:a}),VF({inContextDrawMatchUps:l,sourceStructureId:t,tournamentRecord:e,drawDefinition:r,event:a}),{structures:m,links:d,matchUpModifications:[],drawDefinition:r,...P}}function a4({finishingPositionsCount:t,isLuckyDraw:e,roundNumber:r,structure:n}){let o=t;if(e&&n){let s=(n.matchUps??[]).filter(c=>c.roundNumber===r).length;if(!(s===1)&&s%2!==0){let c=s-1,u=c%2===0?c:c+1,p=1;for(;p<u;)p*=2;o=p}else o=Pi(o)}return o}function GF({inContextDrawMatchUps:t,sourceStructureId:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,structure:i,event:s}){t?.filter(c=>Js({matchUp:c})&&c.structureId===e)?.forEach(c=>{let{matchUpId:u,score:p,winningSide:m}=c,d=er({inContextDrawMatchUps:t,drawDefinition:n,matchUpId:u}),l=nA({inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,winningSide:m,targetData:d,matchUpId:u,structure:i,matchUp:c,score:p,event:s});l.error&&console.log(l.error)})}function VF({inContextDrawMatchUps:t,sourceStructureId:e,tournamentRecord:r,drawDefinition:n,event:o}){t?.filter(s=>s.matchUpStatus==="BYE"&&s.structureId===e)?.forEach(s=>{let{matchUpId:a}=s,c=er({inContextDrawMatchUps:t,drawDefinition:n,matchUpId:a}),{targetLinks:{loserTargetLink:u},targetMatchUps:{loserMatchUpDrawPositionIndex:p,loserMatchUp:m}}=c;if(u&&m){let d=u.target.structureId,l=m.drawPositions[p],f=Or({drawPosition:l,structureId:d,tournamentRecord:r,drawDefinition:n,event:o});f.error&&console.log(f.error)}})}function c4({inContextDrawMatchUps:t,sourceStructureId:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,params:i,stack:s}){let a=[],c=Ps({inContextDrawMatchUps:t,drawDefinition:n,matchUpsMap:o}).goesToMap,{structure:u}=tt({drawDefinition:i.drawDefinition,structureId:e}),{matchUps:p}=ht({structure:u});return p.forEach(m=>{let d=c?.loserMatchUpIds[m.matchUpId];if(d&&m.loserMatchUpId!==d){m.loserMatchUpId=d;let f={tournamentId:r?.tournamentId,eventId:i.event?.eventId,context:s,matchUp:m};a.push(f)}let l=c?.winnerMatchUpIds[m.matchUpId];if(l&&m.winnerMatchUpId!==l){m.winnerMatchUpId=l;let f={tournamentId:r?.tournamentId,eventId:i.event?.eventId,context:s,matchUp:m};a.push(f)}}),a}function GS(t){let{structures:e,links:r,matchUpModifications:n,error:o}=Sf(t);if(o)return{error:o};let i=t.drawDefinition;return PS({tournamentId:t.tournamentRecord?.tournamentId,eventId:t.event?.eventId||t.eventId,matchUpModifications:n,drawDefinition:i,structures:e,links:r})}function bs(t){let e=X(t,[{_anyOf:{[Ee]:!1,[rt]:!1,[Kt]:!1,[ce]:!1},[RI]:!0}]);if(e.error)return e;let r=[],n=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(n){let o=BF(t,n);if(o.error)return o;r.push(...o?.applied??[]),t.drawDefinition&&Ft({drawDefinition:t.drawDefinition,tournamentId:t.tournamentId})}else if(t.tournamentRecords){let o=Object.keys(t.tournamentRecords);if(!o.length)return{error:j};for(let i of o){let s=t.tournamentRecords[i],a=BF(t,s);if(a.error)return a;r.push(...a?.applied??[])}}else return{error:j};return r.length?{...P,applied:r}:{error:HT}}function BF(t,e){let r=ft(t).appliedPolicies??{};e.extensions??=[];let n=[],o=Object.keys(t.policyDefinitions);if(!o.length)return{error:Ea};for(let i of o)if(!r[i]||t.allowReplacement){let s=t.policyDefinitions[i];if(!s)continue;if(!Tt(s))return{error:O};let{policyName:a,...c}=s;if(!c||!Object.keys(c).length||a&&!wt(a))return{error:O};r[i]=t.policyDefinitions[i],n.push(i)}return n?.length?{...ut({element:e,extension:{name:Pp,value:r}}),applied:n}:{applied:n,error:HT}}function VS({tournamentRecord:t,drawDefinition:e,flightProfile:r,drawName:n,drawId:o,event:i}){if(!n||typeof n!="string")return M({result:{error:O},context:{drawName:n}});r||(r=Bt({event:i}).flightProfile);let s=r?.flights?.find(a=>a.drawId===o);if(s){s.drawName=n;let a={name:on,value:{...r,flights:r.flights}};Go({event:i,extension:a})}return e&&(e.drawName=n,Ft({tournamentId:t?.tournamentId,drawDefinition:e})),!s&&!e?{error:$}:{...P,flight:s}}function xC({tournamentRecord:t,drawDefinition:e,drawUpdates:r,drawId:n,event:o}){if(!Tt(r))return{error:O};let i=Bt({event:o}).flightProfile,s=r.drawName&&VS({drawName:r.drawName,tournamentRecord:t,drawDefinition:e,flightProfile:i,drawId:n,event:o});if(s?.error)return s?.error;let a=s?.flight||i?.flights?.find(c=>c.drawId===n);if(!a&&!e)return{error:$};if(a){let c={name:on,value:{...i,flights:i.flights}};Go({event:o,extension:c})}return e&&(r.policyDefinitions&&bs({policyDefinitions:r.policyDefinitions,drawDefinition:e}),Ft({tournamentId:t?.tournamentId,drawDefinition:e})),{...P}}function wC({tournamentRecord:t,removeScheduling:e,removeAssignments:r,drawDefinition:n}){if(!n)return{error:$};let o=an(n.drawType),i=Ie({drawDefinition:n}),s=c=>i?.drawMatchUps?.find(u=>u.matchUpId===c);for(let c of n.structures??[]){let{stage:u}=c;if(u===Fe){u4(c);continue}p4({structure:c,isLuckyDraw:o,removeAssignments:r}),d4({removeScheduling:e,tournamentRecord:t,drawDefinition:n,getRawMatchUp:s,isLuckyDraw:o,matchUpsMap:i,structure:c,removeAssignments:r})}n.entries?.length&&(n.entries=n.entries.filter(c=>c.entryStage!==Fe)),n.extensions=n.extensions.filter(c=>c.name!==mu&&c.name!==Vi);let a=(n.structures??[]).map(({structureId:c})=>c);return Ft({drawDefinition:n,structureIds:a}),{...P}}function u4(t){t.matchUps=[],t.positionAssignments&&(t.positionAssignments=t.positionAssignments.map(e=>(delete e.participantId,e))),t.seedAssignments=[]}function p4({structure:t,isLuckyDraw:e,removeAssignments:r}){let{positionAssignments:n,stage:o,stageSequence:i}=t,s=i===1&&[Z,W].includes(o);e&&n?m4({structure:t,positionAssignments:n,isMainOrQualifyingFirst:s,removeAssignments:r}):n&&(!s||r)&&(t.positionAssignments=n.map(a=>(delete a.participantId,a)),t.seedAssignments=[])}function m4({structure:t,positionAssignments:e,isMainOrQualifyingFirst:r,removeAssignments:n}){let o=new Set((t.matchUps??[]).filter(i=>i.roundNumber===1).flatMap(i=>i.drawPositions??[]).filter(Boolean));r?(t.positionAssignments=e.filter(i=>o.has(i.drawPosition)).map(i=>(n&&(delete i.bye,delete i.participantId),i)),n&&(t.seedAssignments=[])):(t.positionAssignments=[],t.seedAssignments=[])}function d4({removeScheduling:t,tournamentRecord:e,removeAssignments:r,drawDefinition:n,getRawMatchUp:o,isLuckyDraw:i,matchUpsMap:s,structure:a}){let{matchUps:c,isRoundRobin:u}=ht({afterRecoveryTimes:!1,inContext:!0,matchUpsMap:s,structure:a});for(let p of c){let{matchUpId:m,roundNumber:d}=p,l=p.sides??[],f=o(m);f&&(delete f.extensions,delete f.notes,l4({matchUp:f,isLuckyDraw:i,removeAssignments:r,roundNumber:d,sides:l,isRoundRobin:u}),f4({matchUp:f,removeScheduling:t}),It({tournamentId:e?.tournamentId,context:"resetDrawDefinition",drawDefinition:n,matchUp:f}))}}function l4({matchUp:t,isLuckyDraw:e,removeAssignments:r,roundNumber:n,sides:o,isRoundRobin:i}){if(e)!r&&t.matchUpStatus==="BYE"||Object.assign(t,qa),n&&n>1&&(t.drawPositions=[]);else if(t.matchUpStatus!=="BYE"&&Object.assign(t,qa),n&&n>1&&t.drawPositions?.length&&!i){let s=o?.map(({drawPosition:c,participantFed:u})=>!u&&c).filter(Boolean),a=t.drawPositions.map(c=>s.includes(c)?void 0:c);t.drawPositions=a}}function f4({matchUp:t,removeScheduling:e}){e?delete t.timeItems:t.timeItems?.length&&(t.timeItems=t.timeItems.filter(r=>r.itemType&&![Io,li,Ts,iS,Tu,ys,Es,hu].includes(r.itemType)))}function Xp({tournamentRecord:t}){if(!t)return{error:j};let e={positionsNoOutcomes:[],canBePruned:[],matchPlay:[],inactive:[],drawAnalysis:{}},r={};return(t.events?.flatMap(o=>{let i=o.eventId;return r[i]=o,(o?.drawDefinitions??[]).map(s=>({drawDefinition:s,eventId:i}))}).filter(Boolean)).forEach(({drawDefinition:o,eventId:i})=>{let s=0,a=0,c=0,{allStructuresLinked:u}=Kp({drawDefinition:o}),p=r[i],d=(o?.structures??[]).map(E=>{let{stage:A,stageSequence:N,structureId:D}=E,R=Ca[A],{inContextStructureMatchUps:U}=Xi({drawDefinition:o,structureId:D,structure:E,event:p}),b=U?.filter(({winningSide:H})=>H),C=b.filter(Boolean).length||0;a+=C,c+=U.length-a;let _=Math.max(b.filter(({roundNumber:H})=>H===1).map(({roundPosition:H})=>H)),{positionAssignments:v}=Pt({structure:E}),w=v?.filter(({participantId:H})=>H);s+=w?.length??0;let L=(v?.length??0)-(w?.length??0),{roundMatchUps:F,roundProfile:x,roundNumbers:k,maxMatchUpsCount:G}=Ue({matchUps:U}),V=x&&Object.keys(x).filter(H=>!x[H].inactiveRound).map(H=>Number.parseInt(H)),B=x&&Object.keys(x).filter(H=>x[H].inactiveRound).map(H=>Number.parseInt(H)),z=x&&Object.values(x).every(H=>H.inactiveRound);return{positionsAssignedCount:w?.length??0,maxWinningSideFirstRoundPosition:_,unassignedPositionsCount:L,inactiveStructure:z,maxMatchUpsCount:G,inactiveRounds:B,roundMatchUps:F,activeRounds:V,roundNumbers:k,roundProfile:x,structureId:D,stageSequence:N,orderNumber:R,stage:A}}),l=d.find(E=>E.orderNumber===2&&E.stageSequence===1),f=d.filter(({inactiveStructure:E})=>!E).length,{links:g}=ka({structureId:l.structureId,drawDefinition:o}),I=st(l.activeRounds[0])===1&&l.activeRounds.length===1&&f===1,S=d?.every(({inactiveStructure:E})=>E),h=!g.length&&l.activeRounds.length&&(l.roundProfile[1].inactiveCount||l.inactiveRounds.length),T=o.drawId;s&&!a&&e.positionsNoOutcomes.push(T),S&&e.inactive.push(T),I&&e.matchPlay.push(T),h&&e.canBePruned.push(T);let y={matchUpsWithWinningSideCount:a,matchUpsNoOutcomeCount:c,positionsAssignedCount:s,allStructuresLinked:u,structuresData:d,inactiveDraw:S,isMatchPlay:I,drawId:T};e.drawAnalysis[T]=y}),{...P,drawsAnalysis:e}}function LC({matchPlayDrawPositions:t=!0,tournamentRecord:e,drawDefinition:r,drawId:n}){if(!e)return{error:j};if(!r)return{error:$};let o=[],{drawsAnalysis:i}=Xp({tournamentRecord:e});if(i.canBePruned.includes(n)){let s=i.matchPlay.includes(n),a=i.drawAnalysis[n],{structures:[c]}=Sn({stageSequence:1,drawDefinition:r,stage:W}),u=a.structuresData.find(({structureId:l})=>c.structureId===l),p=(c.matchUps??[]).sort((l,f)=>l.roundPosition-f.roundPosition);o=p.filter(({roundNumber:l})=>!u.inactiveRounds.includes(l));let m=o.map(Te),d=p.map(Te).filter(l=>!m.includes(l));if(s){let l=o.filter(({roundNumber:T})=>!u.inactiveRounds.includes(T)).filter(({winningSide:T})=>T),f=l.map(Te),g=m.filter(T=>!f.includes(T));d.push(...g);let S=l.flatMap(T=>T.drawPositions??[]).filter(Boolean).flat(),h=Object.assign({},...S.map((T,y)=>({[T]:y+1})));if(l.forEach(T=>{t?T.drawPositions=T.drawPositions.map(y=>h[y]):delete T.drawPositions}),t){let T=c?.positionAssignments?.filter(y=>S.includes(y.drawPosition)).map(y=>(y.drawPosition=h[y.drawPosition],y));c.positionAssignments=T}else c.positionAssignments=[];c.matchUps=l,o=l}wn({tournamentId:e?.tournamentId,matchUpIds:d,drawDefinition:r}),Ft({drawDefinition:r})}return{...P,matchUps:o}}function WF({isPositionAction:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,loserMatchUp:o,matchUpsMap:i,structureId:s,structure:a,event:c}){if(!r)return{error:$};if(a||({structure:a}=tt({drawDefinition:r,structureId:s})),!a)return{error:Nt};s||({structureId:s}=a);let u="assignDrawPositionQualifier";Pe({method:u,color:"cyan",drawPosition:n}),i??=Ie({drawDefinition:r});let{positionAssignments:p}=Pt({structure:a}),{activeDrawPositions:m}=Xi({drawDefinition:r,structureId:s});if(p?.find(T=>T.drawPosition===n)?.qualifier)return{...P};let l=!!(o&&i.drawMatchUps.some(T=>T.loserMatchUpId===o?.matchUpId&&Ye(T.matchUpStatus)));if(m?.includes(n)&&!l)return{error:qc};let g=p?.find(T=>T.drawPosition===n);if(!g)return{error:ps};let{containsQualifier:I,containsParticipant:S}=Ql(g);if(I)return{...P};let h=ft({tournamentRecord:e,drawDefinition:r,event:c}).appliedPolicies??{};return p?.forEach(T=>{T.drawPosition===n&&(T.qualifier=!0,l&&(T.participantId=void 0,console.log("oddity: invalid participantId on qualifier position cleared")))}),hn({tournamentId:e?.tournamentId,drawDefinition:r,structure:a,event:c}),g4({assignedParticipantId:S,isPositionAction:t,appliedPolicies:h,drawDefinition:r,drawPosition:n,structureId:s,stack:u})}function g4({assignedParticipantId:t,isPositionAction:e,appliedPolicies:r,drawDefinition:n,drawPosition:o,structureId:i,stack:s}){return e&&Ec({appliedPolicies:r,drawDefinition:n,positionAction:{removedParticipantId:t,drawPosition:o,structureId:i,name:s}}),M({result:{...P},stack:s})}function FC({tournamentRecord:t,drawDefinition:e,participantId:r,drawPosition:n,structureId:o,qualifier:i,event:s,bye:a}){if(!e)return{error:$};if(!n)return{error:Ta};if(!o)return{error:dn};if(a){let c=Or({tournamentRecord:t,drawDefinition:e,drawPosition:n,structureId:o,event:s});if(c.error)return c}else if(i){let c=WF({tournamentRecord:t,drawDefinition:e,drawPosition:n,structureId:o,event:s});if(c.error)return c}else{let c=On({participantId:r,tournamentRecord:t,drawDefinition:e,drawPosition:n,structureId:o,event:s});if(c.error)return c}return{...P}}function kC({tournamentRecord:t,drawDefinition:e,scaleAttributes:r,preferencesCount:n=3,tierMethod:o,ascending:i,structureId:s,tierCount:a,event:c,force:u}){if(!e)return{error:$};if(a!==void 0&&a<1)return{error:O};if(n<1)return{error:O};if(!s){let b=e.structures?.filter(C=>C.stage===W);b?.length===1&&(s=b[0].structureId)}if(!s)return{error:dn};let{structure:p}=tt({drawDefinition:e,structureId:s});if(!p)return{error:dn};let{extension:m}=ot({element:e,name:Vi});if(m?.value?.status&&m.value.status!=="COMPLETE"&&!u)return{error:NU};let{positionAssignments:d}=Pt({drawDefinition:e,structureId:s}),l=d?.filter(b=>!b.participantId&&!b.bye&&!b.qualifier).map(b=>b.drawPosition);if(!l?.length)return{error:Xc};let f=p.seedAssignments??[],g=new Set(f.map(b=>b.participantId).filter(Boolean)),I=d?.filter(b=>b.participantId).map(b=>b.participantId)??[],h=e.entries?.filter(b=>!g.has(b.participantId)&&!I.includes(b.participantId))?.map(b=>b.participantId)??[],T=o??"ENTRY_ORDER",y=r??I4(T,c),E=i??T==="RANKING",A=S4({participantIds:h,tierMethod:T,scaleAttributes:y,ascending:E,tournamentRecord:t}),N=a??T4(A.length,g.size),D=Math.min(N,A.length),R=y4(A,D),U={status:"SEEDS_PLACED",structureId:s,preferencesCount:n,tierMethod:T,scaleAttributes:y,ascending:E,tiers:R,preferences:{},unassignedDrawPositions:l};return ut({element:e,extension:{name:Vi,value:U}}),{...P,draftState:U,unassignedDrawPositions:l,tiers:R}}function I4(t,e){if(t==="RANKING")return{scaleType:Jn};if(t==="RATING"){let r=e?.category?.ratingType;return r?{scaleType:Lo,scaleName:r}:void 0}}function S4({participantIds:t,tierMethod:e,scaleAttributes:r,ascending:n,tournamentRecord:o}){if(e==="ENTRY_ORDER"||!r||!o)return t;let i=[],s=[];for(let a of t){let{scaleItem:c}=Zi({tournamentRecord:o,scaleAttributes:r,participantId:a}),u=c?.scaleValue,p=h4(u);p===void 0?s.push(a):i.push({participantId:a,scaleValue:p})}return i.sort((a,c)=>n?a.scaleValue-c.scaleValue:c.scaleValue-a.scaleValue),[...i.map(a=>a.participantId),...s]}function h4(t){if(t!=null){if(typeof t=="number")return t;if(typeof t=="string"){let e=Number.parseFloat(t);return Number.isNaN(e)?void 0:e}if(typeof t=="object")for(let e of Object.values(t)){if(typeof e=="number")return e;if(typeof e=="string"){let r=Number.parseFloat(e);if(!Number.isNaN(r))return r}}}}function T4(t,e){return t<4?1:e>0&&t>=24?3:2}function y4(t,e){let r=[],n=Math.floor(t.length/e),o=t.length%e,i=0;for(let s=0;s<e;s++){let a=n+(s<o?1:0);r.push({participantIds:t.slice(i,i+a),resolved:!1}),i+=a}return r}function oA(t){let e=t.matchUpIds??[],{drawDefinition:r}=t,n=t.structureId??r?.structures?.find(c=>c.matchUps?.some(({matchUpId:u})=>e.includes(u)))?.structureId??r?.structures?.[0]?.structureId;if(!n)return{error:Nt};let o=r.structures?.find(c=>c.structureId===n);if(!o)return{error:Nt};let i=o?.matchUps,s=i?.find(c=>!!c.roundPosition);if(o.structures||s||o.finishingPosition===Ss)return{error:Co};let a=i.filter(({roundNumber:c})=>t.roundNumbers?.includes(c)).map(Te);return e=e.filter(c=>!a.includes(c)),t.roundNumbers&&!e.length&&(e=a),{existingMatchUps:i,matchUpIds:e,structureId:n,structure:o}}function GC(t){let e=X(t,[{[Kt]:!0},{[_a]:{[cu]:!1,roundNumbers:!1},[Lr]:O,[Ge]:ke}]);if(e.error)return e;let{removeIncomplete:r=!1,removeUnAssigned:n=!0,removeCompleted:o=!1,tournamentRecord:i,drawDefinition:s,event:a}=t,c=oA(t);if(c.error)return c;let{structure:u,structureId:p,existingMatchUps:m,matchUpIds:d}=c,l=[],f=m?.filter(({matchUpId:S,score:h,winningSide:T})=>{if(T&&!o)return!1;if(T||ue({score:h})){if(!T&&!r)return!1;l.push(S)}else if(!n)return!1;return d?.includes(S)})??[],g=f.map(Te),I=f.map(({tieMatchUps:S})=>S?.map(Te)).filter(Boolean).flat();if(g.length){u.matchUps=(u.matchUps??[]).filter(({matchUpId:T})=>!g.includes(T)),wn({tournamentId:i?.tournamentId,matchUpIds:[...I,...g],action:"deleteAdHocMatchUps",eventId:a?.eventId,drawDefinition:s});let S=pt(u.matchUps.map(Vr("roundNumber"))),h=lw(S);if(h.length){h.reverse();for(let T of h)u.matchUps.forEach(y=>{y.roundNumber&&y.roundNumber>T&&(y.roundNumber-=1,It({tournamentId:i?.tournamentId,context:["adHoc round deletion"],eventId:a?.eventId,drawDefinition:s,matchUp:y}))})}if(l.length){u.positionAssignments=pt(u.matchUps.flatMap(R=>(R.sides??[]).map(U=>U.participantId)).filter(Boolean)).map(R=>({participantId:R}));let T=u?.matchUpFormat??s?.matchUpFormat??a?.matchUpFormat,E=c.existingMatchUps.some(R=>R.matchUpType===Ir)?{matchUpTypes:[Ir]}:void 0,{matchUps:A}=ht({afterRecoveryTimes:!1,inContext:!0,matchUpFilters:E,structure:u,event:a});Ae({structure:u})&&(u.positionAssignments=pt(A.flatMap(R=>(R.sides??[]).map(U=>U.participantId)).filter(Boolean)).map(R=>({participantId:R})));let D=gf({positionAssignments:u.positionAssignments,tournamentRecord:i,drawDefinition:s,matchUpFormat:T,matchUps:A,event:a});D.error&&console.log(D)}Ft({structureIds:[p],eventId:a?.eventId,drawDefinition:s})}return!g.length&&d.length?{error:Zc}:{...P,deletedMatchUpsCount:[...g,...I].length}}function VC({removeCompletedMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:n,roundNumber:o,event:i}){let s=dt({tournamentRecord:e,drawDefinition:r},[rt,Kt]);if(s.error)return s;if(!o)return M({result:{error:nt},info:"roundNumber required"});let a=tt({drawDefinition:r,structureId:n});if(a.error)return a;let c=a.structure;return c?.structures?{error:Co}:Ae({structure:c})?E4({tournamentId:e.tournamentId,removeCompletedMatchUps:t,eventId:i.eventId,drawDefinition:r,roundNumber:o,structure:c}):(console.log("not implemented"),{...P})}function E4({removeCompletedMatchUps:t,drawDefinition:e,tournamentId:r,roundNumber:n,structure:o,eventId:i}){let s=o?.matchUps??[],a=[],c=[],u=!1;if(s.reduce((m,d)=>{let l=d?.roundNumber;return l?m.includes(l)?m:m.concat(l):m},[]).sort(Zt).includes(n)){let m=s.filter(d=>{let l=d.roundNumber===n&&(!Ot.includes(d.matchUpStatus)||t);return l&&(c.push(d.matchUpId),d.tieMatchUps&&a.push(...d.tieMatchUps.map(Te))),!l});c.length&&(wn({matchUpIds:[...a,...c],drawDefinition:e,tournamentId:r,eventId:i}),m.some(l=>l.roundNumber===n)||(m.forEach(l=>{l.roundNumber>n&&(l.roundNumber-=1,It({drawDefinition:e,tournamentId:r,eventId:i,matchUp:l}))}),u=!0),o.matchUps=m)}return{deletedMatchUpsCount:c.length,roundRemoved:u,...P}}function Jp(t){let{suppressNotifications:e,tournamentRecord:r,drawDefinition:n,matchUps:o,event:i}=t;if(typeof n!="object")return{error:$};let s=t?.structureId;if(!s&&n.structures?.length===1&&(s=n.structures?.[0]?.structureId),typeof s!="string")return{error:dn};if(!Rr(o))return{error:O,info:Ri("matchUps")};let a=n.structures?.find(l=>l.structureId===s);if(!a)return{error:Nt};let u=(a?.matchUps).find(l=>!!l.roundPosition);if(a.structures||u||a.finishingPosition===Ss)return{error:Co};let p=qt({tournamentRecord:r,inContext:!1})?.matchUps?.map(Te)??[],m=o.map(Te);if(Re(p,m))return{error:VU,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||(Ho({tournamentId:r?.tournamentId,matchUps:[...d,...o],eventId:i?.eventId,drawDefinition:n}),Ft({drawDefinition:n,structureIds:[s]})),{...P}}function BC({tournamentRecord:t,drawDefinition:e,drawPosition:r,structureId:n,subOrder:o,event:i}){if(!e)return{error:$};if(!n)return{error:dn};if(!r)return{error:Ta};let{structure:s}=tt({drawDefinition:e,structureId:n});if(!s)return{error:Nt};let a=s;s.structures&&s.structureType===de&&(a=s.structures?.find(g=>g.positionAssignments?.find(I=>I.drawPosition===r)));let c=a?.positionAssignments,u=c?.find(g=>g.drawPosition===r);u&&ut({element:u,extension:{name:du,value:o}});let d=(i?.eventType===xt||e.matchUpType===xt||(i?.tieFormat??e?.tieFormat??s?.tieFormat))&&{matchUpTypes:[xt]},{matchUps:l}=ht({structure:a,afterRecoveryTimes:!1,inContext:!0,matchUpFilters:d,event:i}),f=s?.matchUpFormat??e.matchUpFormat;return gf({positionAssignments:c,tournamentRecord:t,drawDefinition:e,matchUpFormat:f,matchUps:l,event:i}),Ft({drawDefinition:e,structureIds:[n]}),{...P}}var nM={};Gt(nM,{addGoesTo:()=>Ps,allPlayoffPositionsFilled:()=>qE,checkValidEntries:()=>Nf,findDrawDefinition:()=>pA,getAssignedParticipantIds:()=>Ji,getAvailableMatchUpsCount:()=>hf,getAvailablePlayoffProfiles:()=>qp,getDraftState:()=>RA,getDrawDefinitionTimeItem:()=>Zy,getDrawParticipantRepresentativeIds:()=>sA,getDrawStructures:()=>Sn,getDrawTypeCoercion:()=>em,getEligibleVoluntaryConsolationParticipants:()=>iA,getLuckyDrawRoundStatus:()=>ff,getMatchUpsMap:()=>Ie,getParticipantIdFinishingPositions:()=>Ef,getPositionAssignments:()=>xu,getPositionsPlayedOff:()=>bu,getRandomQualifierList:()=>PA,getSeedingThresholds:()=>bE,getSeedsCount:()=>rm,getStructureSeedAssignments:()=>Ur,getSwissChart:()=>UA,getSwissStandings:()=>NA,getTeamLineUp:()=>Xs,getValidGroupSizes:()=>ud,hasLuckyRounds:()=>nS,isAdHoc:()=>Ae,isCompletedStructure:()=>Ro,isValidForQualifying:()=>DA,positionActions:()=>AA,predictDrawCompetitiveBands:()=>Zp,validatePlayoffGroups:()=>pf});function iA({excludedMatchUpStatuses:t=[],includeEventParticipants:e,includeQualifyingStage:r,finishingRoundLimit:n,policyDefinitions:o,roundNumberLimit:i,tournamentRecord:s,drawDefinition:a,matchUpsLimit:c,requirePlay:u,requireLoss:p,allEntries:m,winsLimit:d,event:l}){if(!a)return{error:$};let f=[W,Vt];r&&f.push(Z);let g=P4({includeEventParticipants:e,tournamentRecord:s,drawDefinition:a,stages:f,event:l}),I=Ki({stage:Fe,drawDefinition:a}),S=new Set(I.map(({participantId:b})=>b)),h=N4({excludedMatchUpStatuses:t,includeEventParticipants:e,finishingRoundLimit:n,policyDefinitions:o,roundNumberLimit:i,tournamentRecord:s,drawDefinition:a,matchUpsLimit:c,requirePlay:u,requireLoss:p,allEntries:m,winsLimit:d,event:l}),{participantMatchUps:T,losingParticipants:y,matchUpParticipants:E,participantWins:A}=D4({excludedMatchUpStatuses:h.excludedMatchUpStatuses,finishingRoundLimit:h.finishingRoundLimit,roundNumberLimit:h.roundNumberLimit,requirePlay:h.requirePlay,matchUps:g}),N=Object.keys(y),D=b4({includeEventParticipants:h.includeEventParticipants,requireLoss:h.requireLoss,requirePlay:h.requirePlay,allEntries:h.allEntries,matchUpParticipants:E,losingParticipants:y,tournamentRecord:s,drawDefinition:a,event:l}),R=new Set(N);return{eligibleParticipants:D.filter(b=>A4({voluntaryConsolationEntryIds:S,losingParticipantIdSet:R,participantMatchUps:T,participantWins:A,resolvedPolicy:h,participant:b})).map(b=>({...b,individualParticipants:b.individualParticipantIds?.map(C=>s?.participants?.find(_=>_.participantId===C))})),losingParticipantIds:N,...P}}function A4({voluntaryConsolationEntryIds:t,losingParticipantIdSet:e,participantMatchUps:r,participantWins:n,resolvedPolicy:o,participant:i}){let s=i.participantId,a=o.requireLoss?e.has(s):!0,c=o.requirePlay?(r[s]||0)>=0:!0,u=o.winsLimit?(n[s]||0)<=o.winsLimit:!0,p=o.matchUpsLimit?r[s]<=o.matchUpsLimit:!0,m=!t.has(s);return a&&c&&u&&p&&m}function P4({includeEventParticipants:t,tournamentRecord:e,drawDefinition:r,stages:n,event:o}){let i=o?.eventType?{matchUpTypes:[o.eventType]}:void 0,s=r?.matchUpType?{matchUpTypes:[r.matchUpType]}:void 0;return t&&o?vn({contextFilters:{stages:n},matchUpFilters:i,tournamentRecord:e,inContext:!0,event:o})?.matchUps??[]:rr({contextFilters:{stages:n},matchUpFilters:s,tournamentRecord:e,inContext:!0,drawDefinition:r})?.matchUps??[]}function N4({excludedMatchUpStatuses:t,includeEventParticipants:e,finishingRoundLimit:r,policyDefinitions:n,roundNumberLimit:o,tournamentRecord:i,drawDefinition:s,matchUpsLimit:a,requirePlay:c,requireLoss:u,allEntries:p,winsLimit:m,event:d}){let f=(n??fo({policyTypes:[_y],tournamentRecord:i,drawDefinition:s,event:d}).policyDefinitions)?.[_y],g=t.length&&t||(f?.excludedMatchUpStatuses??[]);return{includeEventParticipants:e??f?.includeEventParticipants,finishingRoundLimit:r??f?.finishingRoundLimit,excludedMatchUpStatuses:g,roundNumberLimit:o??f?.roundNumberLimit,matchUpsLimit:a??f?.matchUpsLimit,requirePlay:c??f?.requirePlay??!0,requireLoss:u??f?.requireLoss??!0,allEntries:p??f?.allEntries,winsLimit:m??f?.winsLimit}}function D4({excludedMatchUpStatuses:t,finishingRoundLimit:e,roundNumberLimit:r,requirePlay:n,matchUps:o}){let i={},s={},a={},c={},u=new Set(t);for(let p of o)U4({matchUp:p,requirePlay:n,finishingRoundLimit:e,roundNumberLimit:r})&&R4({matchUp:p,requirePlay:n,excludedSet:u,participantMatchUps:i,losingParticipants:s,matchUpParticipants:a,participantWins:c});return{participantMatchUps:i,losingParticipants:s,matchUpParticipants:a,participantWins:c}}function U4({matchUp:t,requirePlay:e,finishingRoundLimit:r,roundNumberLimit:n}){return!(e&&t.winningSide&&![1,2].includes(t.winningSide)&&t.matchUpStatus!==Qt||t.finishingRound&&r&&t.finishingRound>=r||t.finishingRound&&n&&t.finishingRound<=n)}function R4({matchUp:t,requirePlay:e,excludedSet:r,participantMatchUps:n,losingParticipants:o,matchUpParticipants:i,participantWins:s}){let a=t.sides?.find(({sideNumber:u})=>t.winningSide&&u===3-t.winningSide),c=t.sides?.find(({sideNumber:u})=>t.winningSide&&u===t.winningSide);if(t.sides?.forEach(u=>{let p=u?.participant?.participantId;p&&(i[p]=u.participant,t.matchUpStatus===Qt&&!e&&(o[p]=u.participant,n[p]||(n[p]=0),(!t.matchUpStatus||!r.has(t.matchUpStatus))&&(n[p]+=1)))}),a?.participant){let u=a.participant.participantId;o[u]=a.participant,n[u]||(n[u]=0),t.matchUpStatus&&!r.has(t.matchUpStatus)&&(n[u]+=1)}if(c?.participant){let u=c.participant.participantId;s[u]||(s[u]=0),s[u]+=1,n[u]||(n[u]=0),t.matchUpStatus&&!r.has(t.matchUpStatus)&&(n[u]+=1)}}function b4({includeEventParticipants:t,matchUpParticipants:e,losingParticipants:r,tournamentRecord:n,drawDefinition:o,requireLoss:i,requirePlay:s,allEntries:a,event:c}){let u=n?.participants&&!s&&!i&&a,p;t&&c?p=c.entries:p=o.entries;let m=new Set([Mn,Gr]),d=u?(p??[]).filter(l=>!m.has(l.entryStatus)).map(({participantId:l})=>l):[];if(u){let l=new Set(d);return(n?.participants??[]).filter(({participantId:f})=>l.has(f))}return Object.values(i?r:e)}function hf(t){let e=X(t,[{drawDefinition:!0}]);if(e.error)return e;let{drawDefinition:r,roundNumber:n}=t,o=t.structureId??(r.structures?.length===1&&r.structures?.[0]?.structureId);if(typeof o!="string")return{error:dn};let i=r.structures?.find(g=>g.structureId===o);if(!i)return{error:Nt};let s,c=(i.matchUps??[])?.reduce((g,I)=>(I.roundPosition&&(s=!0),(I?.roundNumber||0)>g?I.roundNumber:g),0);if(i.structures||s||i.finishingPosition===Ss)return{error:Co};let u=r?.entries?.filter(g=>{let I=g.entryStatus;return yr.includes(I)})??[],p=Math.floor(u?.length/2)||1,m=n??c??1,d=i.matchUps?.filter(g=>g.roundNumber===m)?.length??0,l=p-d,f=l>0?l:0;return{...P,availableMatchUpsCount:f,lastRoundNumber:c,roundMatchUpsCount:p}}function sA({drawDefinition:t}){let e=ot({name:"participantRepresentatives",element:t});return e.error?e:{representativeParticipantIds:e.extension?.value??[]}}function HC(t){let e=Math.min(.999999999,Math.max(1e-9,t));return Math.log(e/(1-e))}function HF(t,e){let r=HC(t.probability)-HC(e.probability),n=e.delta-t.delta,o=n===0?0:r/n,i=o===0?t.delta:t.delta+HC(t.probability)/o;return{k:o,x0:i}}function YF({k:t,x0:e},r){return t===0?.5:1/(1+Math.exp(t*(r-e)))}function Tf(t,e){let[r,n]=e.competitiveAnchors,[o,i]=e.decisiveAnchors;if(!r||!n||!o||!i)return{competitive:0,decisive:0,routine:1};let s=HF(r,n),a=YF(s,t),c=HF({delta:o.delta,probability:1-o.probability},{delta:i.delta,probability:1-i.probability}),u=1-YF(c,t),p=Math.min(1,Math.max(0,a)),m=Math.min(1,Math.max(0,u)),d=1-p-m,l=Math.max(0,d);if(d<0){let f=p+m;return{competitive:p/f,decisive:m/f,routine:0}}return{competitive:p,decisive:m,routine:l}}var C4=new Set([Nr,Gs,wo,Ma,va,Is,xo,ai,ki]),M4=new Set([hr,Uy,Tr]),v4=new Set([Bs]),O4=Hs[gn].predictionModel;function _4(t,e){if(t)return t;if(e){let{policy:r}=go({policyType:gn,tournamentRecord:e});if(r?.predictionModel)return r.predictionModel}return O4}function x4(t){if(C4.has(t))return"BALANCED_BRACKET";if(M4.has(t))return"ROUND_ROBIN";if(v4.has(t))return"MIN_DELTA"}function w4(t){let e=[],r=Math.floor(t.length/2);for(let n=0;n<r;n++)e.push([t[n],t[t.length-1-n]]);return e}function L4(t){let e=[],r=t.length-t.length%2;for(let n=0;n<r;n+=2)e.push([t[n],t[n+1]]);return e}function jF(t){let e=[];for(let r=0;r<t.length;r++)for(let n=r+1;n<t.length;n++)e.push([t[r],t[n]]);return e}function F4(t,e){if(!e||e<2)return jF(t);let r=[];for(let n=0;n<t.length;n+=e){let o=t.slice(n,n+e);o.length>=2&&r.push(...jF(o))}return r}function k4(t,e,r){return e==="BALANCED_BRACKET"?w4(t):e==="ROUND_ROBIN"?F4(t,r):L4(t)}function G4(t){if(t.length===0)return{competitive:0,decisive:0,routine:0};let e=t.reduce((n,o)=>(n.competitive+=o.competitive,n.decisive+=o.decisive,n.routine+=o.routine,n),{competitive:0,decisive:0,routine:0}),r=t.length;return{competitive:e.competitive/r,decisive:e.decisive/r,routine:e.routine/r}}function Zp({tournamentRecord:t,projectionMode:e,predictionModel:r,groupSize:n,ratings:o,drawType:i}){if(!Array.isArray(o)||o.length<2)return{competitive:0,decisive:0,routine:0,error:O};let s=e??(i?x4(i):void 0);if(!s)return{competitive:0,decisive:0,routine:0,error:O};let a=_4(r,t),c=[...o].sort((d,l)=>l-d),u=k4(c,s,n),p=u.map(([d,l])=>Tf(Math.abs(d-l),a));return{...G4(p),perMatchUpPredictions:p,projectionMode:s,projectedPairs:u,expectedMatchCount:u.length}}function qF({tournamentParticipants:t,drawDefinition:e,event:r}){if(!e)return{error:$};let n=te({tournamentParticipants:t,inContext:!0,drawDefinition:e,event:r}),o=q(n.matchUps,!1,!0),i=pt(o.reduce((a,c)=>a.concat(...c.sides.map(u=>u.participantId).filter(Boolean)),[])),s=Object.assign({},...i.map(a=>{let c=o.filter(u=>u.sides.map(m=>m.participantId).filter(Boolean).includes(a));return{[a]:c}}));return{participantIds:i,participantIdMatchUps:s}}function xu({tournamentRecord:t,drawDefinition:e,stage:r=W,structureId:n,structure:o}){if(!t)return{error:j};if(!o&&!e)return{error:$};if(!o&&!n&&e?.structures?.filter(a=>a.stage===r).length===1&&(o=e.structures.find(a=>a.stage===r)),!o&&!n)return{error:dn};let{error:i,positionAssignments:s}=Pt({drawDefinition:e,structureId:n,structure:o});return{positionAssignments:s??[],structureId:o?.structureId,error:i}}function YC({dates:t=[],extension:e}){if(!e)return!1;if(typeof e.value=="boolean"&&e.value)return!0;if(!t.length)return!1;let r=Tt(e.value)?e.value?.dates:void 0;if(Array.isArray(r))return r?.length?!!r.filter(o=>!t.length||t.includes(o)).length:!1}function $F({inContextCourt:t,venue:e}){let{defaultStartTime:r,defaultEndTime:n,dateAvailability:o}=e;if(!(r||n||o?.length))return;let s=t.dateAvailability;if(!s?.length){o?.length?t.dateAvailability=o.map(a=>({...a})):r&&n&&(t.dateAvailability=[{startTime:r,endTime:n}]);return}t.dateAvailability=s.map(a=>{let c=V4({date:a.date,venueDateAvailability:o,defaultStartTime:r,defaultEndTime:n});if(!c)return a;let u=B4(a.startTime,c.startTime),p=W4(a.endTime,c.endTime),m=H4(a.bookings,c.bookings);return{...a,startTime:u,endTime:p,...m.length?{bookings:m}:{}}})}function V4({date:t,venueDateAvailability:e,defaultStartTime:r,defaultEndTime:n}){if(e?.length){if(t){let i=e.find(s=>s.date===t);if(i)return i}let o=e.find(i=>!i.date);if(o)return o}if(r||n)return{startTime:r,endTime:n}}function B4(t,e){return t?e?t>e?t:e:t:e}function W4(t,e){return t?e?t<e?t:e:t:e}function H4(t,e){let r=[];return t?.length&&r.push(...t),e?.length&&r.push(...e),r}function jC({convertExtensions:t,ignoreDisabled:e,venue:r,court:n}){let o={...q(n,t,!0),venueId:r.venueId},{extension:i}=ot({name:lo,element:n});if(e&&i){let s=Tt(i.value)?i.value?.dates:void 0,a=i?.value===!0?[]:o.dateAvailability.map(c=>{let u=c.date;if(!(!u||s.includes(u)))return c}).filter(Boolean);o.dateAvailability=a}return $F({inContextCourt:o,venue:r}),{inContextCourt:o}}function Y4(t,e,r){if(e.length&&!e.includes(t.venueId))return!1;if(r){let{extension:n}=ot({name:lo,element:t});if(n?.value)return!1}return!0}function j4({venue:t,convertExtensions:e,ignoreDisabled:r,dates:n,uniqueVenueIds:o,venues:i,uniqueCourtIds:s,courts:a}){o.includes(t.venueId)||(i.push(q(t,e,!0)),o.push(t.venueId));for(let c of t.courts??[])if(!s.includes(c.courtId)){if(r){let{extension:p}=ot({name:lo,element:c});if(YC({extension:p,dates:n}))continue}let{inContextCourt:u}=jC({convertExtensions:e,ignoreDisabled:r,venue:t,court:c});a.push(u),s.push(c.courtId)}}function kn(t){let{convertExtensions:e,ignoreDisabled:r,venueIds:n=[],dates:o}=t,i=t.tournamentRecords||t.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord}||{},s=[],a=[],c=[],u=[];return Object.keys(i).filter(m=>!t.tournamentId||m===t.tournamentId).forEach(m=>{let d=i[m];for(let l of d.venues??[])Y4(l,n,!!r)&&j4({venue:l,convertExtensions:e,ignoreDisabled:r,dates:o,uniqueVenueIds:s,venues:u,uniqueCourtIds:a,courts:c})}),{courts:c,venues:u,...P}}function q4({convertExtensions:t,tournamentRecord:e,ignoreDisabled:r,dates:n}){if(!e)return{error:kt};let o=q(e.venues??[],t).filter(s=>{if(!r)return s;let{extension:a}=ot({name:lo,element:s});return!a?.value&&s}).filter(Boolean),i=o.reduce((s,a)=>{let c=(a?.courts??[]).filter(u=>{if(!r&&!n?.length)return u;let{extension:p}=ot({name:lo,element:u});return YC({extension:p,dates:n})}).filter(Boolean).map(u=>{let{inContextCourt:p}=jC({convertExtensions:t,ignoreDisabled:r,venue:a,court:u});return p});return c.length?s.concat(c):s},[]);return{venues:o,courts:i}}function hd({tournamentRecords:t,requireCourts:e,dates:r}){return typeof t!="object"||!Object.keys(t).length?{error:kt}:Object.keys(t).reduce((o,i)=>{let s=t[i],{venues:a}=q4({tournamentRecord:s,dates:r});return a?.forEach(c=>{let{venueId:u,courts:p}=c;(!e||p?.length)&&!o.venueIds.includes(u)&&(o.venues.push(c),o.venueIds.push(u))}),o},{venues:[],venueIds:[]})}function aA({event:t}){let{surfaceCategory:e,onlineResources:r,matchUpFormat:n,discipline:o,eventLevel:i,eventName:s,eventType:a,startDate:c,category:u,ballType:p,eventId:m,endDate:d,gender:l,notes:f}=t,g=t.entries?.length??0;return{eventInfo:{drawDefinitionCount:t.drawDefinitions?.length,entriesCount:g,surfaceCategory:e,onlineResources:r,matchUpFormat:n,discipline:o,eventLevel:i,eventName:s,eventType:a,ballType:p,startDate:c,category:u,endDate:d,eventId:m,gender:l,notes:f}}}var $4="IN_PROGRESS",K4="ABANDONED",z4="CANCELLED",Q4="COMPLETED",X4="ACTIVE",qC="tournamentImage",cA={TOURNAMENT_IMAGE_RESOURCE_NAME:qC,IN_PROGRESS:$4,ABANDONED:K4,CANCELLED:z4,COMPLETED:Q4,ACTIVE:X4};var J4={[xa]:{policyName:"Staff Privacy Policy",participant:{contacts:!1,individualParticipants:!1,individualParticipantIds:!1,onlineResources:!1,participantName:!0,participantOtherName:!0,participantId:!0,participantRole:!0,participantRoleResponsibilities:!0,participantStatus:!0,penalties:!1,representing:!0,participantType:!0,person:{addresses:!1,biographicalInformation:!1,birthDate:!1,contacts:!1,nationalityCode:!0,nativeFamilyName:!1,nativeGivenName:!1,onlineResources:!1,otherNames:!0,parentOrganisationId:!1,passportFamilyName:!1,passportGivenName:!1,personId:!1,personOtherIds:!1,previousNames:!1,sex:!1,standardFamilyName:!0,standardGivenName:!0,status:!1,tennisId:!1,wheelchair:!0}}}},KF=J4;function ia(t){let{tournamentRecord:e,withMatchUpStats:r,withStructureDetails:n,withVenueData:o}=t??{};if(!e)return{error:j};let s=(({tournamentId:I,tournamentRank:S,tournamentStatus:h,formalName:T,tournamentName:y,promotionalName:E,onlineResources:A,localTimeZone:N,activeDates:D,startDate:R,endDate:U,hostCountryCode:b,venues:C,notes:_,updatedAt:v})=>({tournamentId:I,tournamentRank:S,tournamentStatus:h,formalName:T,tournamentName:y,promotionalName:E,onlineResources:A,localTimeZone:N,activeDates:D,startDate:R,endDate:U,hostCountryCode:b,venues:C,notes:_,updatedAt:v}))(e),a=e.venues?.find(I=>I.isPrimary);a?.addresses?.length&&(s.tournamentAddress=a.addresses[0]);let u=bt({participantFilters:{participantRoles:[$b,dS,Kb,zb,Xb]},policyDefinitions:KF,tournamentRecord:e})?.participants??[];u&&(s.tournamentContacts=u);let p=e?.onlineResources?.find(I=>I.name===qC&&I.resourceType==="URL")?.identifier;p&&(s.imageUrl=p);let m=ra({tournamentRecord:e})?.publishState,d=m?.tournament?.status?.publishedEventIds??[],l=[];for(let I of e.events??[])if(!t?.usePublishState||d.includes(I.eventId)){let S=aA({event:I}).eventInfo;S&&l.push(S)}s.timeItemValues=HE({element:e}),s.publishState=m?.tournament,s.eventInfo=l;let f=[],g=[];if(r||n)for(let I of e.events??[])for(let S of I.drawDefinitions??[])for(let h of S.structures??[])g.push(...h.matchUps??[]),f.push(et({eventId:I.eventId,eventName:I.eventName,eventType:I.eventType,drawId:S.drawId,drawName:S.drawName,drawType:S.drawType,structureId:h.structureId,structureName:h.structureName,stage:h.stage,stageSequence:h.stageSequence,positionAssignments:h.positionAssignments,seedAssignments:h.seedAssignments,matchUpFormat:h.matchUpFormat}));if(n&&(s.structures=f),r){let I=e.participants?.filter(D=>D.participantType===St).length??0,S=e.participants?.filter(D=>D.participantType===_t).length??0,h=e.events?.length??0,T=g?.filter(D=>D.matchUpStatus!=="BYE"),y=T?.length,E=T?.filter(D=>Ot.includes(D.matchUpStatus)||D.winningSide)?.length,A=T?.filter(D=>Qs({matchUp:D})?.scheduledDate||jl({matchUp:D})?.scheduledTime)?.length,N=y>0?Math.round(E/y*100):0;s.matchUpStats={total:y,completed:E,scheduled:A,percentComplete:N},s.individualParticipantCount=I,s.teamParticipantCount=S,s.eventCount=h}if(o){let{venues:I}=kn({tournamentRecord:e});s.venues=I??[]}return{tournamentInfo:q(et(s),!1,!0),...P}}function uA({publishStatus:t,drawId:e}){return t?.drawDetails?ro(t.drawDetails?.[e]?.publishingDetail):t?.drawIds?t.drawIds.includes(e):!0}var $C="PUBLIC",Z4="ADMIN",zF={PUBLIC_DISPLAY:$C,ADMIN_DISPLAY:Z4};function yf(t){let{tournamentParticipants:e=[],includePositionAssignments:r,policyDefinitions:n,tournamentRecord:o,inContext:i=!0,usePublishState:s,status:a=br,pressureRating:c,refreshResults:u,contextProfile:p,drawDefinition:m,noDeepCopy:d,sortConfig:l,context:f,event:g}=t;if(!m)return{error:$};let{matchUpFormat:I,updatedAt:S,drawType:h,drawName:T,drawId:y}=m,E={matchUpFormat:I,updatedAt:S,drawName:T,drawType:h,drawId:y};E.display=ot({element:m,name:Nl}).extension?.value;let A={},N,D,{allStructuresLinked:R,sourceStructureIds:U,hasDrawFeedProfile:b,structureGroups:C}=Kp({drawDefinition:m});if(!R)return{error:HD};let _=t?.eventPublishState??ra({event:g}).publishState,v=t?.publishStatus??Cr({event:g,status:a}),w=_?.status?.drawDetails?.[m.drawId],L=!!_?.status?.published,F=w?.structureDetails,x=!1,k=!1,V=C.map(B=>{let z={},H=B.map(K=>{let{structure:Y}=tt({drawDefinition:m,structureId:K}),{seedAssignments:J}=Ur({drawDefinition:m,structure:Y});return Y?.stage===W&&Y.stageSequence===1&&(N=J),Y?.stage===Z&&(A[Y.stageSequence??0]=J),Y}).sort((K,Y)=>Hi(K,Y,l)).map(K=>{if(!K)return;let Y=K?.structureId,J=[];K.stage&&[W,me,Vt].includes(K.stage)&&(J=N),K?.stage===Z&&(J=A[K.stageSequence??0]);let{matchUps:ct,roundMatchUps:Et,roundProfile:Ht}=ht({seedAssignments:K?.seedAssignments?.length?void 0:J,context:{drawId:E.drawId,...f},hydrateParticipants:t.hydrateParticipants,participantsProfile:t.participantsProfile,tournamentParticipants:e,policyDefinitions:n,tournamentRecord:o,usePublishState:s,publishStatus:v,contextProfile:p,drawDefinition:m,inContext:i,structure:K,event:g}),{positionAssignments:Ut}=Pt({structure:K}),pe=Ut?.filter(Vr(sr)).map(Kn=>{let zr=ot({element:Kn,name:Bo})?.extension?.value,{drawPosition:so,participantId:Zo}=Kn;return k=!0,{participantResult:zr,participantId:Zo,drawPosition:so}});if(ct.length&&(!pe?.length&&t.allParticipantResults||u&&!K.structures)){let{subOrderMap:Kn}=Zl({positionAssignments:Ut}),so=ct.some(ti=>ti.matchUpType===Ir)?ct.filter(ti=>ti.matchUpType===Ir):ct,Zo=ea({matchUpFormat:K.matchUpFormat,matchUps:so,policyDefinitions:n,pressureRating:c,subOrderMap:Kn});D=Zo?.report,pe=Ut?.filter(Vr(sr)).map(ti=>{let{drawPosition:la,participantId:fa}=ti;return k=!0,{participantResult:fa&&Zo?.participantResults?.[fa],participantId:fa,drawPosition:la}})}let ye=K?{stageSequence:K.stageSequence,structureName:K.structureName,structureType:K.structureType,finishingPosition:K.finishingPosition,matchUpFormat:K.matchUpFormat,stage:K.stage}:{},Jt=ot({element:K,name:Nl}).extension?.value;ye.display=Jt?.[$C]??Jt,ye.sourceStructureIds=U[Y],ye.hasDrawFeedProfile=b[Y],ye.positionAssignments=Ut,ye.structureActive=ct.reduce((Kn,zr)=>{let so=[Qt,ge,Cn,ie,to,Mt,De,vt].includes(zr.matchUpStatus);return Kn||so||!!zr.winningSide||!!zr.score?.scoreStringSide1},!1);let pr=ct.every(Kn=>[...Ot,"BYE"].includes(Kn.matchUpStatus));return ye.structureCompleted=pr,z[Y]=pr,ye.structureActive&&(x=!0),{...ye,participantResults:pe,seedAssignments:J,roundMatchUps:Et,roundProfile:Ht,structureId:Y,report:D}});return H.forEach(K=>{r||delete K.positionAssignments,K.sourceStructuresComplete=K.sourceStructureIds?.every(Y=>z[Y])}),H}).flat().filter(B=>!s||ro(F?.[B?.structureId])||!0);return E.drawActive=x,E.participantPlacements=k,E.drawGenerated=V?.reduce((B,z)=>B||!!z?.roundMatchUps,!1),E.drawCompleted=V?.reduce((B,z)=>B&&z.structureCompleted,!0),E.drawPublished=s?L&&uA({publishStatus:v,drawId:E.drawId}):void 0,{structures:!s||E.drawPublished?d&&V||q(V,!1,!0):void 0,drawInfo:d?E:q(E,!1,!0),...P}}function tm(t){let{includePositionAssignments:e,participantsProfile:r,policyDefinitions:n,usePublishState:o,status:i=br,contextProfile:s,sortConfig:a}=t,c=X(t,[{tournamentRecord:!0},{[yp]:{event:!1,eventId:!1}}]);if(c.error)return c;let u=q(t.tournamentRecord,!1,!0),p=t.event==null?_e({tournamentRecord:u,eventId:t.eventId}).event:void 0,m=t.event?q(t.event,!1,!0):p&&q(p,!1,!0)||void 0;if(!m)return{error:Wr};let{eventId:d}=m,{tournamentId:l,endDate:f}=u,g=Cr({event:m,status:i}),I=ra({event:m}).publishState??{},S=!!I?.status?.published,{participants:h}=bt({participantFilters:t.participantFilters,withGroupings:!0,withEvents:!1,withDraws:!1,policyDefinitions:n,...r,tournamentRecord:u}),T=({stage:v,drawId:w})=>{if(!o)return!0;let L=g?.drawDetails?.[w]?.stageDetails;return!L||!Object.keys(L).length?!0:ro(L[v])},y=({structureId:v,drawId:w})=>{if(!o)return!0;let L=g?.drawDetails?.[w]?.structureDetails;return!L||!Object.keys(L).length?!0:ro(L[v])},E=({drawId:v})=>o?uA({publishStatus:g,drawId:v}):!0,A=({drawId:v,drawType:w,structure:L})=>{if(!o||!yn(w))return L;let F=g?.drawDetails?.[v]?.structureDetails?.[L.structureId]?.roundLimit;if(yt(F)){let x=Q(1,F+1),k={},G={};for(let V of x)L.roundMatchUps[V]&&(k[V]=L.roundMatchUps[V],G[V]=L.roundProfile[V]);L.roundMatchUps=k,L.roundProfile=G}return L},N=m.drawDefinitions??[],D=!o||S?N.filter(E).map(v=>(({drawInfo:w,structures:L})=>({...w,structures:L}))(yf({allParticipantResults:t.allParticipantResults,hydrateParticipants:t.hydrateParticipants,context:{eventId:d,tournamentId:l,endDate:f},pressureRating:t.pressureRating,refreshResults:t.refreshResults,includePositionAssignments:e,tournamentParticipants:h,eventPublishState:I,noDeepCopy:!0,policyDefinitions:n,tournamentRecord:u,usePublishState:o,contextProfile:s,drawDefinition:v,publishStatus:g,sortConfig:a,event:m}))).map(({structures:v,...w})=>{let L=v?.filter(({stage:F,structureId:x})=>y({structureId:x,drawId:w.drawId})&&T({stage:F,drawId:w.drawId})).map(F=>A({drawId:w.drawId,drawType:w.drawType,structure:F}));return{...w,structures:L}}).filter(v=>v.structures?.length):void 0,U=(Array.isArray(u.venues)?u.venues:[]).map(v=>{let{venueData:w}=Eu({venueId:v.venueId,tournamentRecord:u});return{...w}}),b=(({eventId:v,eventName:w,eventType:L,eventLevel:F,surfaceCategory:x,matchUpFormat:k,category:G,gender:V,startDate:B,endDate:z,ballType:H,discipline:K})=>({eventId:v,eventName:w,eventType:L,eventLevel:F,surfaceCategory:x,matchUpFormat:k,category:G,gender:V,startDate:B,endDate:z,ballType:H,discipline:K}))(m);b.display=ot({element:m,name:Nl}).extension?.value;let{tournamentInfo:C}=ia({tournamentRecord:u}),_={tournamentInfo:C,venuesData:U,eventInfo:b,drawsData:D};return _.eventInfo.publishState=I,_.eventInfo.published=I?.status?.published,{...P,eventData:_,participants:h}}function Ef({byeAdvancements:t=!1,tournamentRecord:e,drawDefinition:r,event:n}){if(!r)return{error:$};let{participantIds:o,participantIdMatchUps:i}=qF({tournamentParticipants:e?.participants,drawDefinition:r}),s=Object.values(i).some(f=>f.some(g=>g.containerStructureId)),c=(s&&tm({tournamentRecord:e,event:n}))?.eventData?.drawsData?.find(f=>f.drawId===r.drawId)?.structures,u=r?.structures?.find(f=>f.stage===W&&f.stageSequence===1),p=u?.structureType===de&&u.structures,d=(s?xu({tournamentRecord:e,drawDefinition:r,structureId:u?.structureId})?.positionAssignments:void 0)?.length||0,l=o?.map(f=>{let I=i[f].filter(y=>[ie,"BYE"].includes(y.matchUpStatus)||y.winningSide),S=I.map(y=>{let E=y.sides.find(R=>R.bye),A=y.sides.find(R=>R.participantId===f).sideNumber;if(y.containerStructureId){let R=t6({containedStructures:p,drawPositionsCount:d,drawDataStructures:c,drawDefinition:r,participantId:f,matchUp:y});if(R)return R}return(y.winningSide||t&&E&&A)===A?y.finishingPositionRange.winner:y.finishingPositionRange.loser}),h=y=>Math.abs(y[0]-y[1]),T=S.reduce((y,E)=>y&&h(y)<h(E)?y:E,void 0);return{[f]:{finishingPositionRanges:S,finishingPositionRange:T,relevantMatchUps:I}}})??[];return Object.assign({},...l)}function t6({containedStructures:t,drawPositionsCount:e,drawDataStructures:r,drawDefinition:n,participantId:o,matchUp:i}){let a=t?.find(f=>f.structureId===i.structureId)?.positionAssignments?.length,c=r.find(f=>f.structureId===i.containerStructureId)?.participantResults?.find(f=>f.participantId===o)?.participantResult,{ties:u,groupOrder:p,provisionalOrder:m}=c??{},d=t?.length,l=n.structure?.find(f=>f.stage===Vt);if(je()&&console.log({drawPositionsCount:e,provisionalOrder:m,bracketsCount:d,bracketSize:a,groupOrder:p,ties:u}),e===a&&p)return[p,p];if(d>1&&p&&!l)return[1,d];if(d>1&&p&&l){let f=n.links?.find(I=>I.source.structureId===i.containerStructureId)?.source?.finishingPositions,g=f.length*d;if(p in f)return[1,g];{let I=(a-p)*d;return[g+1,e-I]}}}function zo({tournamentRecords:t,tournamentRecord:e,tournamentId:r,drawId:n}){if(!e&&!t)return{error:j};if(!n)return{error:Nn};if(!e&&t){if(typeof r!="string"&&(r=rA({tournamentRecords:t,drawId:n}),!r))return{error:ac};if(e=t[r],!e)return{error:j}}let o=e&&_e({tournamentRecord:e,drawId:n});return o?.drawDefinition?{drawDefinition:o.drawDefinition,event:o.event,tournamentRecord:e,...P}:M({result:{error:Mr},stack:"findDrawDefinition"})}function pA(t){let{drawDefinition:e,error:r}=zo(t);return r?{error:r}:{drawDefinition:q(e)}}function QF({tournamentParticipants:t,returnParticipants:e,drawPosition:r,participant:n,drawId:o,event:i}){let s=i?.entries?.filter(({entryStatus:a})=>[Gr,qi].includes(a)).map(({participantId:a})=>a)??[];if(s.length){let a=n.individualParticipantIds,c=e?t.filter(({participantId:m})=>s.includes(m)):void 0,u=e?t.filter(({participantId:m})=>a.includes(m)):void 0;return{validModifyAssignedPairAction:et({payload:{participantId:n.participantId,replacementIndividualParticipantId:void 0,existingIndividualParticipantId:void 0,drawPosition:r,drawId:o},method:DF,availableIndividualParticipantIds:s,availableIndividualParticipants:c,existingIndividualParticipantIds:a,existingIndividualParticipants:u,type:_S},!1,!1,!0)}}return{}}function es(t){let{inContextDrawMatchUps:e,targetData:r,drawDefinition:n,relevantLink:o}=t;if(o?.linkCondition===Wn&&r?.matchUp?.matchUpStatus==="BYE")return!1;let{targetMatchUps:{loserMatchUp:s,winnerMatchUp:a},targetLinks:c}=r,u=s&&er({matchUpId:s.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),p=u?.targetMatchUps?.loserMatchUp,m=u?.targetMatchUps?.loserMatchUpDrawPositionIndex,d=p?.sides[m]?.participant,l=Ye(s?.matchUpStatus),f=l&&!d,g=s?.sides?.filter(E=>E?.participant).length??0,I=s?.winningSide&&l&&g===1,S=a?.drawPositions?.filter(Boolean).length||0;if(!I&&(s?.winningSide&&!f||a?.winningSide&&S===2&&(!a.feedRound||!Ye(a?.matchUpStatus))))return!0;let h=a&&er({matchUpId:a.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),T=u&&es({relevantLink:c?.loserTargetLink,targetData:u,inContextDrawMatchUps:e,drawDefinition:n});return!!(h&&es({targetData:h,inContextDrawMatchUps:e,drawDefinition:n})||T)}var mA={[Zn]:{policyName:"positionActionsDefault",enabledStructures:[{stages:[Z,W],stageSequences:[1],enabledActions:[],disabledActions:[]},{stages:[],stageSequences:[],enabledActions:[zp,ja,ld,Ya],disabledActions:[]}],disbledStructures:[],otherFlightEntries:!1,activePositionOverrides:[]}};var BS="positionAction",dA="matchUpAction";function lA({actionType:t=BS,appliedPolicies:e,drawDefinition:r,structure:n}){let o=t===BS&&Zn||t===dA&&He,i=t===BS&&mA||t===dA&&qb,s=o&&(e?.[o]||i?.[o]),c=r.links?.filter(d=>d?.target?.structureId===n?.structureId)?.map(({target:d})=>d.feedProfile)??[],{enabledStructures:u,disabledStructures:p}=s??{},m=p?.find(d=>{let{stages:l,stageSequences:f,structureTypes:g,feedProfiles:I}=d;return(!I?.length||Array.isArray(I)&&I.some(S=>c.includes(S)))&&(!l?.length||Array.isArray(l)&&l?.includes(n?.stage))&&(!g?.length||Array.isArray(g)&&g?.includes(n?.structureType))&&(!f?.length||Array.isArray(f)&&f.includes(n?.stageSequence))});return{enabledStructures:u,actionsDisabled:m,actionsPolicy:s}}function XF({activePositionOverrides:t,activeDrawPositions:e,action:r}){return r&&t.includes(r)?!0:!e.length}function fA({enabledStructures:t,drawDefinition:e,structure:r}){if(t===!1)return{};if(!t?.length)return{policyActions:{enabledActions:[],disabledActions:[]}};let{stage:n,stageSequence:o,structureType:i}=r??{},a=e.links?.filter(u=>u?.target?.structureId===r?.structureId)?.map(({target:u})=>u.feedProfile)??[];return{policyActions:t.find(u=>{let{stages:p,stageSequences:m,structureTypes:d,feedProfiles:l}=u??{},f=!p?.length||Array.isArray(p)&&p.includes(n),g=!m?.length||Array.isArray(m)&&m.includes(o),I=!d?.length||Array.isArray(d)&&d.includes(i),S=!l?.length||Array.isArray(l)&&l.some(h=>a.includes(h));return g&&I&&S&&u&&f})}}function 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 KC="replaceTieMatchUpParticipantId",zC="assignTieMatchUpParticipantId",gA="removeTieMatchUpParticipantId",QC="assignMatchUpSideParticipant",JF="removeMatchUpSideParticipant",XC="substituteParticipant",IA="REMOVE_SUBSTITUTION",JC="REPLACE_PARTICIPANT",WS="REMOVE_PARTICIPANT",SA="setMatchUpStatus",hA="SUBSTITUTION",ZC="SCHEDULE",e6="PENALTY",TA="REFEREE",tM="STATUS",yA="START",eM="SCORE";var ZF={REPLACE_TEAM_POSITION_METHOD:KC,ASSIGN_TEAM_POSITION_METHOD:zC,REMOVE_TEAM_POSITION_METHOD:gA,REPLACE_PARTICIPANT:JC,SUBSTITUTION_METHOD:XC,REMOVE_SUBSTITUTION:IA,REMOVE_PARTICIPANT:WS,SCHEDULE_METHOD:SA,SUBSTITUTION:hA,SCHEDULE:ZC,PENALTY:e6,REFEREE:TA,STATUS:tM,SCORE:eM,START:yA,END:"END"};function t1({specifiedPolicyDefinitions:t,inContextDrawMatchUps:e,matchUpParticipantIds:r,matchUpActionsPolicy:n,inContextMatchUp:o,policyActions:i,enforceGender:s,participantId:a,sideNumber:c,matchUpId:u,matchUp:p,drawId:m,side:d}){let l=[],f=o.sides?.find(F=>F.participant),g=nn(o.gender)&&o.sideNumber&&o.sides?.filter(F=>F.particiapntId).length===1&&f?.participant?.person?.sex,I=o.matchUpType,h=(s??n?.participants?.enforceGender)!==!1?o.gender:void 0,y=o.sides?.flatMap(F=>F.participant?.individualParticipants||F.participant).filter(Boolean)?.map(gt),E=o.sides?.filter(F=>!c||F.sideNumber===c).flatMap(F=>F.participant?.individualParticipants||F.participant).filter(Boolean),A=E?.map(gt),D=e?.find(F=>F.matchUpId===o.matchUpTieId)?.sides?.map(F=>F?.participant?.individualParticipants?.filter(({participantId:x,person:k})=>!A?.includes(x)&&(!h||Oo(h)||k.sex===h||nn(h)&&!g||g&&k.sex!==g))),R=c?D?.[c-1]:D?.map((F,x)=>({participants:F,sideNumber:x+1})),U=c?D?.[c-1]?.map(gt):D?.map((F,x)=>({participants:F?.map(gt),sideNumber:x+1})),b=c&&(re(Os)(I)&&!A?.length||re(ei)(I)&&(A?.length??0)<2)||!c&&(re(Os)(I)&&(A?.length??0)<2||re(ei)(I)&&(A?.length??0)<4),C=U?.filter(F=>!y?.includes(F)),_=R?.filter(({participantId:F})=>C.includes(F));if(b&&C?.length&&l.push({availableParticipantIds:C,method:zC,availableParticipants:_,type:na,payload:{participantId:void 0,tieMatchUpId:u,sideNumber:c,drawId:m}}),A?.length&&(!ue(p)||d?.substitutions?.length)&&l.push({method:gA,type:WS,existingParticipantIds:A,payload:{participantId:void 0,tieMatchUpId:u,drawId:m}}),_?.length&&(!c&&A?.length||c&&d?.participant)&&l.push({availableParticipantIds:C,method:KC,availableParticipants:_,type:JC,existingParticipantIds:A,payload:{existingParticipantId:void 0,participantId:void 0,tieMatchUpId:u,drawId:m}}),qn({policyActions:i,action:IA})&&d?.substitutions?.length){let F=d.participant?.participantType===St&&[d.participantId]||d.participant?.participantType===lt&&d.participant.individualParticipantIds||[],x=d.substitutions.map(k=>k.participantId).filter(k=>F.includes(k));(!a||x.includes(a))&&l.push({method:gA,type:IA,substitutedParticipantIds:x,payload:{participantId:void 0,tieMatchUpId:u,drawId:m}})}let v=t?.[He],w=v?.substituteWithoutScore,L=v?.substituteAfterCompleted;if(qn({policyActions:i,action:hA})&&r.length===2&&(!c&&A?.length||c&&d?.participant)&&(w||ue(p))&&(L||p.matchUpStatus&&!Ot.includes(p.matchUpStatus))&&E?.length&&R.length){let F=E.map(gt);l.push({info:"list of team players available for substitution",method:XC,availableParticipantIds:U,existingParticipantIds:F,availableParticipants:R,existingParticipants:E,type:hA,payload:{substituteParticipantId:void 0,existingParticipantId:void 0,sideNumber:c,matchUpId:u,drawId:m}})}return l}function e1({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(D=>D.type===na)?.availableParticipantIds,f=i?.[Zn]?.otherFlightEntries,g=i?.[Zn]?.restrictQualifyingAlternates,I=(s.entries??[]).filter(({entryStage:D})=>!g||(p.stage===Z?D===Z:D!==Z)).sort((D,R)=>(D.entryPosition??1/0)-(R.entryPosition??1/0)).map(({participantId:D})=>D).filter(Boolean),{allPositionedParticipantIds:S}=qy({drawDefinition:s}),h=n.map(D=>D.participantId).filter(Boolean),T=I.filter(D=>p.stage&&[Z,W,Vt].includes(p.stage)?!S?.includes(D):!h.includes(D)),E=(d?.entries??[]).filter(D=>D.entryStatus===Zr&&rM({restrictQualifyingAlternates:g,structure:p,entry:D})&&(p.stage&&[Z,W,Vt].includes(p.stage)?!S?.includes(D.participantId):!h.includes(D.participantId))).sort((D,R)=>(D.entryPosition??1/0)-(R.entryPosition??1/0)).map(D=>D.participantId),A=pt(T.concat(E));if(f){let R=(d?Bt({event:d}).flightProfile:void 0)?.flights?.filter(U=>U.drawId!==m).map(U=>U.drawEntries.filter(b=>b.participantId&&![Mn,Gr,qi].includes(b.entryStatus)&&!I.includes(b.participantId)).map(({participantId:b})=>b)).flat().filter(Boolean);R?.length&&A.push(...R)}l?.length&&(A=A.filter(D=>!l.includes(D)));let N=o?t?.filter(D=>A.includes(D.participantId)):void 0;return N?.forEach(D=>{let R=(s.entries??[]).find(U=>U.participantId===D.participantId);D.entryPosition=R?.entryPosition}),N?.sort((D,R)=>(D.entryPosition||1/0)-(R.entryPosition||1/0)),A.length?{validAlternatesAction:et({payload:{drawId:m,structureId:u,drawPosition:a},willDisableLinks:e,method:PF,availableAlternatesParticipantIds:A,type:xS,availableAlternates:N})}:{}}function rM({restrictQualifyingAlternates:t,structure:e,entry:r}){let{stage:n}=e;if(!r.entryStage||r.entryStage===n||n===Z&&!t||r.entryStage===W&&n===me)return!0}function r1({eventEntries:t,structure:e}){let r=o=>o.entryStatus===Zr&&rM({structure:e,entry:o}),n=(o,i)=>(o.entryPosition||1/0)-(i.entryPosition||1/0);return t.filter(r).sort(n).map(gt)}function n1({restrictAdHocRoundParticipants:t,tournamentParticipants:e,matchUpParticipantIds:r,otherFlightEntries:n,drawDefinition:o,structureId:i,sideNumber:s,matchUpId:a,structure:c,matchUp:u,drawId:p,event:m}){let d=[],l=c?.matchUps??[],g=u.sides?.find(R=>R.sideNumber===s)?.participantId,I=l.filter(({roundNumber:R})=>R===u.roundNumber),S=o?.entries?.filter(({entryStatus:R})=>R&&$i.includes(R)).map(gt)??[],h=I.map(R=>(R.sides??[]).flatMap(gt)).flat().filter(Boolean),T=S.filter(R=>!r.includes(R)&&(!t||!h.includes(R))),y=e?.filter(R=>T?.includes(R.participantId)).map(R=>q(R,void 0,!0));y?.forEach(R=>{let U=(o.entries??[]).find(b=>b.participantId===R.participantId);R.entryPosition=U?.entryPosition}),T.length&&d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},method:QC,type:na,availableParticipantIds:T,participantsAvailable:y});let E=m?.entries??[],A=r1({eventEntries:E,structure:c}),N=pt(S.concat(A));if(n){let U=(m?Bt({event:m}):void 0)?.flights?.filter(b=>b.drawId!==p).flatMap(b=>b.drawEntries.filter(C=>C.participantId&&![Mn,Gr,qi].includes(C.entryStatus)).map(({participantId:C})=>C)).filter(Boolean);U?.length&&N.push(...U)}N=N.filter(R=>!r.includes(R)&&!T.includes(R)&&(!t||!h.includes(R)));let D=e?.filter(R=>N.includes(R.participantId)).map(R=>q(R,void 0,!0));if(D?.forEach(R=>{let U=(o.entries??[]).find(b=>b.participantId===R.participantId);R.entryPosition=U?.entryPosition}),D?.sort((R,U)=>(R.entryPosition||1/0)-(U.entryPosition||1/0)),N.length&&d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},availableParticipantIds:N,participantsAvailable:D,method:QC,type:Zr}),!ue(u)&&s&&g){d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},method:JF,type:WS});let R=x=>x.sides.map(gt),U=({matchUpId:x})=>x!==u.matchUpId,b=x=>!ue(x),C=u.sides?.find(x=>x.sideNumber!==s)?.participantId,v=l.filter(({roundNumber:x})=>x!==u.roundNumber).filter(U).map(R),w=[C,...v.filter(x=>x.includes(g)).flat()].filter(Boolean),L=x=>!w.flat().includes(x),F=I.filter(b).filter(U).map(R).flat().filter(L);if(F.length){let x=e?.filter(k=>F.includes(k.participantId)).map(k=>q(k,void 0,!0));d.push({payload:{participantIds:[g],roundNumber:u.roundNumber,structureId:i,sideNumber:s,matchUpId:a,drawId:p},swappableParticipantIds:F,method:UF,type:gd,swappableParticipants:x})}}return d}function Af(t){if(!t)return{error:O};let{drawDefinition:e,event:r}=t,{restrictAdHocRoundParticipants:n=!0,policyDefinitions:o,enforceGender:i,participantId:s,sideNumber:a,matchUpId:c}=t,u=t.tournamentRecord??(t.tournamentId&&wt(t.tournamentId)&&t.tournamentRecords?.[t.tournamentId]);if(!u)return{error:j};if(!c||!wt(c))return{error:mr};if(a&&![1,2].includes(a))return M({result:{error:O},context:{sideNumber:a}});if(!e){let w=r6({tournamentRecord:u,matchUpId:c});w.drawDefinition&&(e=w.drawDefinition),w.event&&(r=w.event)}if(!e)return{error:$};let p=bt({withIndividualParticipants:!0,tournamentRecord:u}).participants,{drawId:m}=e,{matchUp:d,structure:l}=Wt({drawDefinition:e,matchUpId:c,event:r});if(!d)return{error:Be};let{appliedPolicies:f,policyActions:g,matchUpActionsPolicy:I,otherFlightEntries:S}=n6({specifiedPolicyDefinitions:o,tournamentRecord:u,drawDefinition:e,structure:l,event:r}),h=t.matchUpsMap??Ie({drawDefinition:e}),T=t.inContextDrawMatchUps??te({tournamentParticipants:p,inContext:!0,drawDefinition:e,matchUpsMap:h,event:r}).matchUps,y=T?.find(w=>w.matchUpId===c),E=a&&y?.sides?.find(w=>w.sideNumber===a),A=y?.sides?.map(w=>w.participantId||w.participant?.participantid).filter(Boolean)??[],{assignedPositions:N,allPositionsAssigned:D}=se({structure:l}),{structureId:R}=l??{},U=[];if(!R)return{validActions:U};let b=!!d.collectionId;Ae({structure:l})&&!b&&U.push(...n1({restrictAdHocRoundParticipants:n,tournamentParticipants:p,matchUpParticipantIds:A,otherFlightEntries:S,drawDefinition:e,structureId:R,sideNumber:a,matchUpId:c,structure:l,matchUp:d,drawId:m,event:r}));let C=Ro({drawDefinition:e,structure:l}),_=o6({matchUp:d,isCollectionMatchUp:b,assignedPositions:N});if(_)return{validActions:U,isByeMatchUp:_};let v=d.matchUpStatus&&[Qt,ge].includes(d.matchUpStatus);return i6({validActions:U,policyActions:g,matchUpActionsPolicy:I,specifiedPolicyDefinitions:o,inContextDrawMatchUps:T,matchUpParticipantIds:A,allPositionsAssigned:D,inContextMatchUp:y,assignedPositions:N,appliedPolicies:f,isCollectionMatchUp:b,enforceGender:i,participantId:s,isDoubleExit:v,sideNumber:a,matchUpId:c,structure:l,matchUp:d,drawId:m,drawDefinition:e,side:E}),{structureIsComplete:C,validActions:U,isDoubleExit:v,...P}}function r6({tournamentRecord:t,matchUpId:e}){let n=(qt({tournamentRecord:t}).matchUps??[]).find(s=>s.matchUpId===e),o=(t?.events??[]).find(s=>s.eventId===n?.eventId);return{drawDefinition:(o?.drawDefinitions??[]).find(s=>s.drawId===n?.drawId),event:o}}function n6({specifiedPolicyDefinitions:t,tournamentRecord:e,drawDefinition:r,structure:n,event:o}){let i=ft({tournamentRecord:e,drawDefinition:r,structure:n,event:o}).appliedPolicies??{};Object.assign(i,t??{});let s=i?.[Zn]?.otherFlightEntries,a=i?.[He]??Ns[He],{enabledStructures:c}=lA({actionType:dA,appliedPolicies:i,drawDefinition:r,structure:n}),{policyActions:u}=fA({enabledStructures:c,drawDefinition:r,structure:n});return{appliedPolicies:i,policyActions:u,matchUpActionsPolicy:a,otherFlightEntries:s}}function o6({matchUp:t,isCollectionMatchUp:e,assignedPositions:r}){let n=r?.filter(o=>o.bye).map(o=>o.drawPosition);return t.matchUpStatus==="BYE"||!e&&t.drawPositions?.reduce((o,i)=>n?.includes(i)||o,!1)}function i6({validActions:t,policyActions:e,matchUpActionsPolicy:r,specifiedPolicyDefinitions:n,inContextDrawMatchUps:o,matchUpParticipantIds:i,allPositionsAssigned:s,inContextMatchUp:a,assignedPositions:c,appliedPolicies:u,isCollectionMatchUp:p,enforceGender:m,participantId:d,isDoubleExit:l,sideNumber:f,matchUpId:g,structure:I,matchUp:S,drawId:h,drawDefinition:T,side:y}){qn({policyActions:e,action:TA})&&t.push({type:TA,payload:{matchUpId:g}});let E=!Va({matchUpStatus:S.matchUpStatus}),A=s6({appliedPolicies:u,allPositionsAssigned:s,structure:I}),N=S.sides?.filter(_=>_?.participantId).length===2,D=er({inContextDrawMatchUps:o,drawDefinition:T,matchUpId:g}),R=es({inContextDrawMatchUps:o,drawDefinition:T,targetData:D}),U=c?.filter(_=>_.participantId).map(_=>_.drawPosition),C=(a?.drawPositions?.length===2&&a.drawPositions.every(_=>U?.includes(_))&&a?.sides?.length===2&&a.sides.every(({participantId:_})=>_)||N)&&!(l&&R);E&&t.push({payload:{drawId:h,matchUpId:g,schedule:{}},method:SA,type:ZC}),qn({policyActions:e,action:ja})&&(y?.participant||!f&&i?.length)&&t.push({method:JE,type:ja,payload:{drawId:h,matchUpId:g,penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0}}),E&&C&&t.push({type:tM}),A&&C&&(t.push({info:"set outcome and winningSide",method:SA,type:eM,payload:{drawId:h,matchUpId:g,matchUpFormat:S.matchUpFormat,outcome:{scoreStringSide1:void 0,scoreStringSide2:void 0,sets:[]},winningSide:void 0}}),qn({policyActions:e,action:yA})&&t.push({type:yA}),qn({policyActions:e,action:"END"})&&t.push({type:"END"})),p&&a&&t.push(...t1({specifiedPolicyDefinitions:n,inContextDrawMatchUps:o,matchUpParticipantIds:i,matchUpActionsPolicy:r,inContextMatchUp:a,policyActions:e,enforceGender:m,participantId:d,sideNumber:f,matchUpId:g,matchUp:S,drawId:h,side:y}))}function s6({appliedPolicies:t,allPositionsAssigned:e,structure:r}){let n=t?.scoring?.structures,o=r?.stage&&n?.stage?.[r.stage],i=r?.stageSequence&&o?.stageSequence?.[r.stageSequence];return!(t?.scoring?.requireAllPositionsAssigned||o?.requireAllPositionsAssigned||i?.requireAllPositionsAssigned)||e}function i1({positionAssignments:t,activeDrawPositions:e,drawDefinition:r,isByePosition:n,structure:o,drawPosition:i,structureId:s,drawId:a}){if(o.stage!==W||o.stageSequence!==1)return{};if(o.structureType===de)return{};if(n)return{};if(e.length)return{};let c=t.find(f=>f.drawPosition===i);if(!c?.participantId)return{};let{seedAssignments:u}=Ur({drawDefinition:r,structure:o});if(!u?.length)return{};let p=u.find(f=>f.participantId===c.participantId);if(!p)return{};let{validSeedBlocks:m}=hi({drawDefinition:r,structure:o});if(!m?.length)return{};let d=m.findIndex(f=>f.seedNumbers.includes(p.seedNumber));return d<0||d>=m.length-1?{}:m.slice(d+1).some(f=>u.some(g=>f.seedNumbers.includes(g.seedNumber)&&g.participantId))?{validSeedCascadeAction:{type:RC,method:vF,payload:{drawId:a,structureId:s,drawPosition:i}}}:{}}function s1({tournamentParticipants:t=[],sourceStructuresComplete:e,possiblyDisablingAction:r,isWinRatioFedStructure:n,activeDrawPositions:o,positionAssignments:i,drawDefinition:s,drawPosition:a,structureId:c,structure:u,drawId:p,event:m}){if(o.includes(a)||n&&!e)return{};let{sourceStructureIds:d,targetStructureIds:l}=s.links?.reduce((S,h)=>{let T=h.source?.structureId,y=h.target?.structureId;return S.sourceStructureIds.includes(T)||S.sourceStructureIds.push(T),S.targetStructureIds.includes(y)||S.targetStructureIds.push(y),S},{sourceStructureIds:[],targetStructureIds:[]})??{},f=[],g=s.links?.filter(S=>S.target?.structureId===u.structureId)??[];for(let S of g){let h=S?.source?.structureId,{structure:T}=tt({structureId:h,drawDefinition:s}),y=T?.finishingPosition===Ss&&(d?.length!==1||l?.length!==1),E={};if(y){let{matchUps:R}=ht({drawDefinition:s,structure:u,event:m}),{initialRoundNumber:U}=Zs({drawPosition:a,matchUps:R}),C=s.links?.find(_=>_.target?.structureId===u?.structureId&&_.target.roundNumber===U)?.source?.roundNumber;E.roundNumbers=[C]}let{completedMatchUps:A}=Gp({structureId:h,inContext:!0,matchUpFilters:E,drawDefinition:s}),N=i.map(R=>R.participantId).filter(Boolean);A?.filter(({matchUpType:R,winningSide:U})=>U&&(m?.eventType!==Oe||R===Oe)).map(({winningSide:R,sides:U})=>R&&U?.[1-(R-1)]).map(gt).filter(R=>R&&!N.includes(R))?.forEach(R=>{f.includes(R)||f.push(R)})}let I=t?.filter(S=>f?.includes(S.participantId));return I?.forEach(S=>{let h=(s.entries??[]).find(T=>T.participantId===S.participantId);S.entryPosition=h?.entryPosition}),f?.length?{validLuckyLosersAction:{type:LS,method:NF,availableLuckyLosers:I,availableLuckyLoserParticipantIds:f,willDisableLinks:r,payload:{drawId:p,structureId:c,drawPosition:a}}}:{}}function a1({positionSourceStructureIds:t,unassignedParticipantIds:e,possiblyDisablingAction:r,provisionalPositioning:n,tournamentParticipants:o,isWinRatioFedStructure:i,positionAssignments:s,returnParticipants:a,appliedPolicies:c,drawDefinition:u,seedingProfile:p,isByePosition:m,drawPosition:d,structureId:l,event:f}){let{drawId:g}=u,I=[],S,h,T=[],y=c?.[Hn]?.validSeedPositions?.ignore;if(y||({unplacedSeedParticipantIds:S,unplacedSeedAssignments:h,unfilledPositions:T}=CE({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:CF,type:"BYE"}),i&&y){let E=s.map(U=>U.participantId).filter(Boolean),A={structureIds:t},{completedMatchUps:N}=Ga({inContext:!0,matchUpFilters:A,drawDefinition:u}),D=pt((N??[]).filter(({matchUpType:U})=>f?.eventType!==Oe||U===Oe)?.map(({sides:U})=>U?.map(gt)).flat().filter(U=>U&&!E.includes(U))),R=a?o?.filter(U=>D?.includes(U.participantId)).map(U=>q(U,void 0,!0)):void 0;return R?.forEach(U=>{let b=(u.entries??[]).find(C=>C.participantId===U.participantId);U.entryPosition=b?.entryPosition}),R?.length&&I.push(et({payload:{drawId:g,structureId:l,drawPosition:d},willDisableLinks:r,method:UC,type:na,availableParticipantIds:D,participantsAvailable:R})),{validAssignmentActions:I}}if(T.includes(d)||m){let E;if(h?.length){let N=h.filter(D=>S?.includes(D.participantId));N.sort(a6),E=N.map(D=>D.participantId)}else E=e;let A=a?o?.filter(N=>E.includes(N.participantId)).map(N=>q(N,void 0,!0)):void 0;A?.length&&I.push(et({payload:{drawId:g,structureId:l,drawPosition:d},willDisableLinks:r,method:UC,type:na,availableParticipantIds:E,participantsAvailable:A}))}return{validAssignmentActions:I}}function a6(t,e){return t.bye||Uu(t.seedValue)<Uu(e.seedValue)||t.seedValue&&!e.seedValue?-1:(t.seedNumber||0)-(e.seedNumber||0)}function c1({drawPositionInitialRounds:t,tournamentParticipants:e,positionAssignments:r,returnParticipants:n,appliedPolicies:o,drawDefinition:i,drawPosition:s,structureId:a,drawId:c}){let u=[],p=[],m=[],d=[],l=new Set(r.map(E=>E.participantId).filter(Boolean)),f=o?.[Zn],g=!f?.disableRoundRestrictions&&t[s],I=f?.requireCompletedStructures,{sourceStructureIds:S,relevantLinks:h}=$p({targetRoundNumber:g,linkType:Pr,drawDefinition:i,structureId:a})??{};S?.length&&d.push(...S);let{sourceStructureIds:T,relevantLinks:y}=$p({targetRoundNumber:g,linkType:fn,drawDefinition:i,structureId:a})??{};return T?.length&&d.push(...T),c6({requireCompletedStructures:I,tournamentParticipants:e,assignedParticipantIds:l,eliminationSourceLinks:h,qualifyingParticipantIds:p,qualifyingParticipants:u,returnParticipants:n,drawDefinition:i}),u6({requireCompletedStructures:I,tournamentParticipants:e,assignedParticipantIds:l,qualifyingParticipantIds:p,qualifyingParticipants:u,roundRobinSourceLinks:y,returnParticipants:n,drawDefinition:i}),p.length&&m.push(et({qualifyingParticipants:n?u:void 0,method:EF,type:ld,qualifyingParticipantIds:p,payload:{qualifyingParticipantId:void 0,drawPosition:s,structureId:a,drawId:c}})),{validAssignmentActions:m,sourceStructureIds:d}}function c6({requireCompletedStructures:t,tournamentParticipants:e,assignedParticipantIds:r,eliminationSourceLinks:n,qualifyingParticipantIds:o,qualifyingParticipants:i,returnParticipants:s,drawDefinition:a}){for(let c of n){let u=a.structures?.find(l=>l.structureId===c.source.structureId);if(u?.stage!==Z)continue;let p=Ro({structureId:c.source.structureId,drawDefinition:a});if(t&&!p)continue;let m=u.qualifyingRoundNumber,{matchUps:d}=ht({matchUpFilters:{roundNumbers:[m],isCollectionMatchUp:!1,hasWinningSide:!0},afterRecoveryTimes:!1,tournamentParticipants:e,inContext:!0,structure:u});for(let l of d){let f=l.sides.find(I=>I?.sideNumber===l.winningSide),g=l.matchUpStatus==="BYE"&&l.sides?.find(({participantId:I})=>I);if(f||g){let{participantId:I,participant:S}=f||(g??{});I&&!r.has(I)&&(S&&s&&i.push(S),o.push(I))}}}}function u6({requireCompletedStructures:t,tournamentParticipants:e,assignedParticipantIds:r,qualifyingParticipantIds:n,qualifyingParticipants:o,roundRobinSourceLinks:i,returnParticipants:s,drawDefinition:a}){for(let c of i){let u=a.structures?.find(l=>l.structureId===c.source.structureId);if(u?.stage!==Z)continue;let p=Ro({structureId:c.source.structureId,drawDefinition:a});if(t&&!p)continue;let{positionAssignments:m}=Pt({structure:u}),d=m?.map(l=>{let f=l.participantId,g=ot({element:l,name:Bo}).extension?.value;return g?{participantId:f,groupOrder:g?.groupOrder}:{}}).filter(({groupOrder:l,participantId:f})=>l===1&&!r.has(f)).map(({participantId:l})=>l)??[];if(d&&n.push(...d),s){let l=new Set(d),f=e.filter(({participantId:g})=>l.has(g));o.push(...f)}}}function u1({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=U=>!t||U.participantId||U.qualifier||U.bye,I=n?.filter(U=>U!==p&&!(u&&a.includes(U))),S=i?.filter(U=>g(U)&&I?.includes(U.drawPosition))??[],h=S.map(({drawPosition:U})=>U),{matchUps:T}=ht({afterRecoveryTimes:!1,inContext:!0,drawDefinition:c,structure:d,event:f}),y=T.filter(({drawPositions:U})=>Re(U,h)),E=Object.assign({},...y.map(U=>U.sides?.filter(({sourceDrawPositionRange:b})=>b).map(({drawPosition:b,sourceDrawPositionRange:C})=>({[b]:C}))).flat()),A=S.map(U=>U.participantId).filter(Boolean),N=(r??[]).filter(U=>A.includes(U.participantId)),D=Object.assign({},...N.map(U=>({[U.participantId]:U}))),R=S.map(U=>{let b=D?.[U.participantId],C=E[U.drawPosition];return et({...U,participant:s?q(b,!1,!0):void 0,sourceDrawPositionRange:C})});return R.length?{validSwapAction:{payload:{drawId:l,structureId:m,drawPositions:[p]},willDisableLinks:e,method:XE,type:gd,availableAssignments:R}}:{}}function p6(t,e){return t.filter(r=>!e.includes(r.participantId)).map(r=>r.participantId)}function m6({validActions:t,policyActions:e,isActiveDrawPosition:r,positionAssignments:n,disablePlacementActions:o,positionAssignment:i,isByePosition:s,getValidAssignmentActions:a,positionSourceStructureIds:c,unassignedParticipantIds:u,possiblyDisablingAction:p,isWinRatioFedStructure:m,tournamentParticipants:d,returnParticipants:l,appliedPolicies:f,drawDefinition:g,drawPosition:I,structureId:S,event:h}){if(qn({policyActions:e,action:na})&&!r&&n&&!o&&(!i||s)){let{validAssignmentActions:T}=a({positionSourceStructureIds:c,unassignedParticipantIds:u,possiblyDisablingAction:p,isWinRatioFedStructure:m,tournamentParticipants:d,positionAssignments:n,returnParticipants:l,appliedPolicies:f,drawDefinition:g,isByePosition:s,drawPosition:I,structureId:S,event:h});T?.forEach(y=>t.push(y))}}function d6({validActions:t,policyActions:e,isActiveDrawPosition:r,getValidQualifiersAction:n,drawPositionInitialRounds:o,tournamentParticipants:i,positionAssignments:s,returnParticipants:a,appliedPolicies:c,drawDefinition:u,drawPosition:p,structureId:m,drawId:d}){if(qn({policyActions:e,action:ld})&&!r){let{validAssignmentActions:l}=n({drawPositionInitialRounds:o,tournamentParticipants:i,positionAssignments:s,returnParticipants:a,appliedPolicies:c,drawDefinition:u,drawPosition:p,structureId:m,drawId:d});l?.forEach(f=>t.push(f))}}function l6({isLuckyDrawAdvancedPosition:t,validActions:e,policyActions:r,isActiveDrawPosition:n,drawId:o,structureId:i,drawPosition:s,possiblyDisablingAction:a,isByePosition:c}){qn({policyActions:r,action:ZE})&&!n&&(e.push({type:ZE,method:DC,payload:{drawId:o,structureId:i,drawPosition:s},willDisableLinks:a}),!c&&!t&&e.push({type:wS,method:AF,payload:{drawId:o,structureId:i,drawPosition:s},willDisableLinks:a}),qn({policyActions:r,action:"BYE"})&&!c&&!t&&e.push({type:"BYE",method:DC,payload:{drawId:o,structureId:i,drawPosition:s,replaceWithBye:!0},willDisableLinks:a}))}function f6({validActions:t,policyActions:e,activePositionsCheck:r,activePositionOverrides:n,activeDrawPositions:o,drawDefinition:i,structureId:s,drawPosition:a,structure:c,isByePosition:u,participantId:p,participant:m,drawId:d}){let l=c.stage===Z||c.stage===W&&c.stageSequence===1;if(!u&&r({activePositionOverrides:n,activeDrawPositions:o,action:Ya})&&qn({policyActions:e,action:Ya})&&pd({drawDefinition:i,structureId:s,drawPosition:a})&&l){let{seedAssignments:f}=Ur({returnAllProxies:!0,drawDefinition:i,structure:c}),{seedNumber:g,seedValue:I}=f?.find(S=>S.participantId===p)??{};t.push({type:Ya,method:MF,participant:m,seedNumber:g,payload:{drawId:d,structureId:s,participantId:p,seedValue:I}})}if(!u&&r({activePositionOverrides:n,activeDrawPositions:o,action:fd})&&qn({policyActions:e,action:fd})&&pd({drawDefinition:i,structureId:s,drawPosition:a})&&l){let{seedAssignments:f}=Ur({returnAllProxies:!0,drawDefinition:i,structure:c}),{seedNumber:g}=f?.find(I=>I.participantId===p)??{};t.push({method:bF,type:fd,participant:m,seedNumber:g,payload:{participantId:p,structureId:s,drawId:d}})}}function g6({validActions:t,policyActions:e,isByePosition:r,participantId:n,participant:o,drawId:i}){if(!r&&n){if(qn({policyActions:e,action:ja})){let s={type:ja,method:JE,participant:o,payload:{penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0,drawId:i}};t.push(s)}if(qn({policyActions:e,action:zp})){let s={type:zp,method:RF,participant:o,payload:{participantId:n,otherName:void 0}};t.push(s)}}}function I6({validActions:t,policyActions:e,getValidSwapAction:r,possiblyDisablingAction:n,tournamentParticipants:o,inactiveDrawPositions:i,activeDrawPositions:s,positionAssignments:a,returnParticipants:c,byeDrawPositions:u,drawDefinition:p,isByePosition:m,drawPosition:d,structureId:l,structure:f,drawId:g}){if(qn({policyActions:e,action:gd})){let{validSwapAction:I}=r({possiblyDisablingAction:n,tournamentParticipants:o,inactiveDrawPositions:i,activeDrawPositions:s,positionAssignments:a,returnParticipants:c,byeDrawPositions:u,drawDefinition:p,isByePosition:m,drawPosition:d,structureId:l,structure:f,drawId:g});I&&t.push(I)}}function S6({validActions:t,policyActions:e,getValidAlternatesAction:r,possiblyDisablingAction:n,tournamentParticipants:o,positionAssignments:i,activeDrawPositions:s,returnParticipants:a,appliedPolicies:c,drawDefinition:u,drawPosition:p,structureId:m,structure:d,drawId:l,event:f,disablePlacementActions:g}){if(qn({policyActions:e,action:xS})&&!g){let{validAlternatesAction:I}=r({possiblyDisablingAction:n,tournamentParticipants:o,positionAssignments:i,activeDrawPositions:s,returnParticipants:a,appliedPolicies:c,drawDefinition:u,drawPosition:p,validActions:t,structureId:m,structure:d,drawId:l,event:f});I&&t.push(I)}}function h6({validActions:t,policyActions:e,getValidLuckyLosersAction:r,sourceStructuresComplete:n,possiblyDisablingAction:o,isWinRatioFedStructure:i,tournamentParticipants:s,activeDrawPositions:a,positionAssignments:c,drawDefinition:u,drawPosition:p,structureId:m,structure:d,drawId:l,disablePlacementActions:f,isActiveDrawPosition:g}){if(qn({policyActions:e,action:LS})&&!f&&!g&&c){let{validLuckyLosersAction:I}=r({sourceStructuresComplete:n,possiblyDisablingAction:o,isWinRatioFedStructure:i,tournamentParticipants:s,activeDrawPositions:a,positionAssignments:c,drawDefinition:u,drawPosition:p,structureId:m,structure:d,drawId:l});I&&t.push(I)}}function T6({validActions:t,policyActions:e,getValidModifyAssignedPairAction:r,participant:n,tournamentParticipants:o,returnParticipants:i,drawPosition:s,drawId:a,event:c}){if(n?.participantType===lt&&qn({policyActions:e,action:_S})){let{validModifyAssignedPairAction:u}=r({tournamentParticipants:o,returnParticipants:i,drawPosition:s,participant:n,drawId:a,event:c});u&&t.push(u)}}function AA(t){return E6(t)}function y6(t){let e=X(t,[{event:!0,drawDefinition:!0,structureId:!0}]);if(e.error)return{earlyReturn:e};let{policyDefinitions:r,returnParticipants:n=!0,provisionalPositioning:o,tournamentRecord:i,drawDefinition:s,drawPosition:a,event:c}=t,u=t.tournamentParticipants??(i&&bt({withIndividualParticipants:!0,tournamentRecord:i}).participants)??[],p=tt({structureId:t.structureId,drawDefinition:s});if(p.error)return{earlyReturn:p};let m=p.containingStructure||p.structure;if(!m)return{earlyReturn:{error:Nt}};let d=m.structureId;if(p=Xi({drawDefinition:s,structureId:d}),a===void 0&&!p.isAdHoc)return{earlyReturn:{error:Ta}};if(p.isAdHoc)return{earlyReturn:Af(t)};if(p.error)return{earlyReturn:p};let{drawPositionInitialRounds:l,inactiveDrawPositions:f,activeDrawPositions:g,byeDrawPositions:I}=p,S=ft({tournamentRecord:i,drawDefinition:s,structure:m,event:c}).appliedPolicies??{};Object.assign(S,r??{});let{actionsPolicy:h,enabledStructures:T,actionsDisabled:y}=lA({actionType:BS,appliedPolicies:S,drawDefinition:s,structure:m}),E=h?.activePositionOverrides??[],{sourceStructureIds:A}=$p({finishingPosition:po,targetRoundNumber:1,linkType:fn,drawDefinition:s,structureId:d})??{},N;A?.length&&(N=A.every(J=>Ro({structureId:J,drawDefinition:s})));let D=A.length,R=A.length&&!N,{policyActions:U}=fA({enabledStructures:T,drawDefinition:s,structure:m}),b=![Z,W].includes(m.stage)||m.stageSequence!==1,{drawId:C}=s,{assignedPositions:_,positionAssignments:v}=se({structure:m}),w=_?.find(J=>J.drawPosition===a),L=!!w;if(!v?.map(J=>J.drawPosition)?.includes(a)&&!(m.matchUps?.flatMap(ct=>ct.drawPositions??[])??[]).includes(a))return{earlyReturn:{error:ps}};let{stage:x,stageSequence:k}=m,G=[x];x===me&&G.push(W),x===W&&G.push(me);let V=Ki({entryStatuses:$i,provisionalPositioning:o,drawDefinition:s,stageSequence:k,structureId:d,stages:G}),B=Ji({drawDefinition:s,stages:G}).assignedParticipantIds??[],z=p6(V,B),H=I.includes(a),K=g.includes(a),Y=an(s.drawType)&&l?.[a]>1;return y?{earlyReturn:{info:"Actions Disabled for structure",isActiveDrawPosition:K,isDrawPosition:!0,hasPositionAssigned:L,validActions:[],isByePosition:H}}:{positionSourceStructureIds:A,isLuckyDrawAdvancedPosition:Y,drawPositionInitialRounds:l,unassignedParticipantIds:z,sourceStructuresComplete:N,activePositionOverrides:E,tournamentParticipants:u,disablePlacementActions:R,possiblyDisablingAction:b,isWinRatioFedStructure:D,inactiveDrawPositions:f,isActiveDrawPosition:K,positionAssignments:v,hasPositionAssigned:L,positionAssignment:w,activeDrawPositions:g,returnParticipants:n,byeDrawPositions:I,appliedPolicies:S,drawDefinition:s,policyActions:U,isByePosition:H,drawPosition:a,structureId:d,structure:m,drawId:C,event:c}}function E6(t){let e=y6(t);if("earlyReturn"in e)return e.earlyReturn;let{positionSourceStructureIds:r,isLuckyDrawAdvancedPosition:n,drawPositionInitialRounds:o,unassignedParticipantIds:i,sourceStructuresComplete:s,activePositionOverrides:a,tournamentParticipants:c,disablePlacementActions:u,possiblyDisablingAction:p,isWinRatioFedStructure:m,inactiveDrawPositions:d,isActiveDrawPosition:l,positionAssignments:f,hasPositionAssigned:g,positionAssignment:I,activeDrawPositions:S,returnParticipants:h,byeDrawPositions:T,appliedPolicies:y,drawDefinition:E,policyActions:A,isByePosition:N,drawPosition:D,structureId:R,structure:U,drawId:b,event:C}=e,_=[];m6({validActions:_,policyActions:A,isActiveDrawPosition:l,positionAssignments:f,disablePlacementActions:u,positionAssignment:I,isByePosition:N,getValidAssignmentActions:a1,positionSourceStructureIds:r,unassignedParticipantIds:i,possiblyDisablingAction:p,isWinRatioFedStructure:m,tournamentParticipants:c,returnParticipants:h,appliedPolicies:y,drawDefinition:E,drawPosition:D,structureId:R,event:C}),d6({validActions:_,policyActions:A,isActiveDrawPosition:l,getValidQualifiersAction:c1,drawPositionInitialRounds:o,tournamentParticipants:c,positionAssignments:f,returnParticipants:h,appliedPolicies:y,drawDefinition:E,drawPosition:D,structureId:R,drawId:b});let{participantId:v}=I??{},w=v&&c.find(L=>L.participantId===v);if(I){if(l6({isLuckyDrawAdvancedPosition:n,validActions:_,policyActions:A,isActiveDrawPosition:l,drawId:b,structureId:R,drawPosition:D,possiblyDisablingAction:p,isByePosition:N}),n||f6({validActions:_,policyActions:A,activePositionsCheck:XF,activePositionOverrides:a,activeDrawPositions:S,drawDefinition:E,structureId:R,drawPosition:D,structure:U,isByePosition:N,participantId:v,participant:w,drawId:b}),!n&&!N){let{validSeedCascadeAction:L}=i1({positionAssignments:f,activeDrawPositions:S,drawDefinition:E,isByePosition:N,structure:U,drawPosition:D,structureId:R,drawId:b});L&&_.push(L)}g6({validActions:_,policyActions:A,isByePosition:N,participantId:v,participant:w,drawId:b}),I6({validActions:_,policyActions:A,getValidSwapAction:u1,possiblyDisablingAction:p,tournamentParticipants:c,inactiveDrawPositions:d,activeDrawPositions:S,positionAssignments:f,returnParticipants:h,byeDrawPositions:T,drawDefinition:E,isByePosition:N,drawPosition:D,structureId:R,structure:U,drawId:b})}return S6({validActions:_,policyActions:A,getValidAlternatesAction:e1,possiblyDisablingAction:p,tournamentParticipants:c,positionAssignments:f,activeDrawPositions:S,returnParticipants:h,appliedPolicies:y,drawDefinition:E,drawPosition:D,structureId:R,structure:U,drawId:b,event:C,disablePlacementActions:u}),h6({validActions:_,policyActions:A,getValidLuckyLosersAction:s1,sourceStructuresComplete:s,possiblyDisablingAction:p,isWinRatioFedStructure:m,tournamentParticipants:c,activeDrawPositions:S,positionAssignments:f,drawDefinition:E,drawPosition:D,structureId:R,structure:U,drawId:b,disablePlacementActions:u,isActiveDrawPosition:l}),T6({validActions:_,policyActions:A,getValidModifyAssignedPairAction:QF,participant:w,tournamentParticipants:c,returnParticipants:h,drawPosition:D,drawId:b,event:C}),{isActiveDrawPosition:l,isDrawPosition:!0,hasPositionAssigned:g,isByePosition:N,validActions:_,...P}}function em({policyDefinitions:t,appliedPolicies:e,drawType:r}){let n=t?.[El]?.drawTypeCoercion,o=e?.[El]?.drawTypeCoercion;return(typeof n=="boolean"?n:void 0)??(r&&n?.[r])??(typeof o=="boolean"?o:void 0)??(r&&o?.[r])??!0}var PA=({drawDefinition:t,random:e})=>{let r=X({drawDefinition:t},[{[Kt]:!0}]);if(r.error)return r;let n=t.structures?.find(s=>s.stage===W&&s.stageSequence===1);if(!n)return M({result:{error:Vg}});let{qualifierPositions:o}=se({structure:n}),i=e??Math.random;return Q(0,o.length).sort(()=>i()-.5)};function Pf({participantIds:t,matchUps:e,allowDraws:r=!1}){let n=new Map;for(let s of t)n.set(s,{participantId:s,wins:0,losses:0,draws:0,points:0,opponentIds:[],opponentOutcomes:new Map,roundPoints:[]});for(let s of e){if(s.matchUpStatus!==ie||!s.sides||s.sides.length<2)continue;let a=gt(s.sides[0]),c=gt(s.sides[1]);if(!a||!c)continue;let u=n.get(a),p=n.get(c);!u||!p||(u.opponentIds.includes(c)||u.opponentIds.push(c),p.opponentIds.includes(a)||p.opponentIds.push(a),s.winningSide===1?(u.wins+=1,u.points+=1,p.losses+=1,u.opponentOutcomes.set(c,"WIN"),p.opponentOutcomes.set(a,"LOSS"),u.roundPoints.push(1),p.roundPoints.push(0)):s.winningSide===2?(p.wins+=1,p.points+=1,u.losses+=1,p.opponentOutcomes.set(a,"WIN"),u.opponentOutcomes.set(c,"LOSS"),u.roundPoints.push(0),p.roundPoints.push(1)):r&&(u.draws+=1,p.draws+=1,u.points+=.5,p.points+=.5,u.opponentOutcomes.set(c,"DRAW"),p.opponentOutcomes.set(a,"DRAW"),u.roundPoints.push(.5),p.roundPoints.push(.5)))}let o=new Map;for(let[s,a]of n){let c=`${a.wins}-${a.losses}-${a.draws}`,u=o.get(c)??[];u.push(s),o.set(c,u)}let i=[];for(let[s,a]of o){let[c,u,p]=s.split("-").map(Number);i.push({wins:c,losses:u,draws:p,participantIds:a})}return i.sort((s,a)=>{let c=s.wins+s.draws*.5,u=a.wins+a.draws*.5;return u!==c?u-c:s.losses-a.losses}),{scoreGroups:i,records:n}}function m1({records:t,tiebreakMethods:e=["BUCHHOLZ","SONNEBORN_BERGER"]}){let r=[];for(let[n,o]of t){let i={participantId:n,wins:o.wins,losses:o.losses,draws:o.draws,points:o.points,opponentIds:o.opponentIds,rank:0};e.includes("BUCHHOLZ")&&(i.buchholz=d1(n,t)),e.includes("MEDIAN_BUCHHOLZ")&&(i.medianBuchholz=A6(n,t)),e.includes("SONNEBORN_BERGER")&&(i.sonnebornBerger=P6(n,t)),e.includes("PROGRESSIVE_SCORE")&&(i.progressiveScore=N6(o)),r.push(i)}D6(r,e);for(let n=0;n<r.length;n++)r[n].rank=n+1;return r}function d1(t,e){let r=e.get(t);return r?r.opponentIds.reduce((n,o)=>{let i=e.get(o);return n+(i?.points??0)},0):0}function A6(t,e){let r=e.get(t);return!r||r.opponentIds.length<3?d1(t,e):r.opponentIds.map(i=>e.get(i)?.points??0).sort((i,s)=>i-s).slice(1,-1).reduce((i,s)=>i+s,0)}function P6(t,e){let r=e.get(t);if(!r)return 0;let n=0;for(let o of r.opponentIds){let i=e.get(o);if(!i)continue;let s=r.opponentOutcomes.get(o);s==="WIN"?n+=i.points:s==="DRAW"&&(n+=i.points*.5)}return n}function N6(t){let e=0,r=0;for(let n of t.roundPoints)e+=n,r+=e;return r}function D6(t,e){t.sort((r,n)=>{if(n.points!==r.points)return n.points-r.points;for(let o of e){let i=p1(r,o),s=p1(n,o);if(s!==i)return s-i}return 0})}function p1(t,e){switch(e){case"BUCHHOLZ":return t.buchholz??0;case"MEDIAN_BUCHHOLZ":return t.medianBuchholz??0;case"SONNEBORN_BERGER":return t.sonnebornBerger??0;case"PROGRESSIVE_SCORE":return t.progressiveScore??0;default:return 0}}function NA({tiebreakMethods:t=["BUCHHOLZ","SONNEBORN_BERGER"],drawDefinition:e,structureId:r}){if(!e)return{error:$};let n=r?tt({drawDefinition:e,structureId:r}).structure:e.structures?.find(d=>Ae({structure:d}));if(!n)return{error:Nt};let o=n.matchUps??[],i=(e.entries??[]).filter(d=>yr.includes(d.entryStatus??"")).map(gt).filter(Boolean);if(!i.length)return{standings:[],scoreGroups:[],roundsPlayed:0,...P};let{scoreGroups:s,records:a}=Pf({participantIds:i,matchUps:o}),c=m1({records:a,tiebreakMethods:t}),u=o.filter(d=>d.winningSide),m=[...new Set(u.map(d=>d.roundNumber).filter(Boolean))].length;return{standings:c,scoreGroups:s,roundsPlayed:m,...P}}function DA({structureId:t,drawDefinition:e}){if(!e)return{error:$};if(!wt(t))return{error:O};let r=ka({drawDefinition:e,structureId:t});if(r.error)return r;let n=r.links.target.flatMap(i=>i.target.feedProfile).filter(Boolean),o=!Yt([Fi,qe,Ym,Li],n).length;return{...P,valid:o}}function UA({drawDefinition:t,structureId:e}){if(!t)return{error:$};let r=e?tt({drawDefinition:t,structureId:e}).structure:t.structures?.find(a=>Ae({structure:a}));if(!r)return{error:Nt};let n=r.matchUps??[],o=(t.entries??[]).filter(a=>yr.includes(a.entryStatus??"")).map(gt).filter(Boolean);if(!o.length)return{rounds:[],totalRounds:0,...P};let i=[...new Set(n.map(a=>a.roundNumber).filter(Boolean))].sort((a,c)=>(a??0)-(c??0)),s=[];s.push({roundNumber:0,nodes:[{wins:0,losses:0,draws:0,participantIds:[...o]}]});for(let a of i){let c=n.filter(p=>p.matchUpStatus===ie&&(p.roundNumber??0)<=(a??0)),{scoreGroups:u}=Pf({matchUps:c,participantIds:o});s.push({roundNumber:a??0,nodes:u.map(p=>({wins:p.wins,losses:p.losses,draws:p.draws,participantIds:[...p.participantIds]}))})}return{rounds:s,totalRounds:i.length,...P}}function RA({drawDefinition:t}){if(!t)return{error:$};let{extension:e}=ot({element:t,name:Vi});if(!e?.value)return{error:fe,info:"No draft found"};let r=e.value,n=r.tiers?.reduce((s,a)=>s+(a.participantIds?.length??0),0),o=Object.keys(r.preferences??{}).length,i=r.tiers?.filter(s=>s.resolved).length??0;return{draftState:r,summary:{status:r.status,totalParticipants:n,preferencesSubmitted:o,preferencesOutstanding:n-o,tiersTotal:r.tiers?.length??0,tiersResolved:i,unassignedDrawPositions:r.unassignedDrawPositions,preferencesCount:r.preferencesCount}}}function bA({participantsCount:t,participantCount:e}){if(t=t??e,!t)return{error:O};let r=Pi(t);return r?{drawSize:r}:M({result:{error:O},stack:"getEliminationDrawSize",context:{participantsCount:t}})}function rm(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=fo({tournamentRecord:i,drawDefinition:s,event:a});if(I.error)return M({result:I,stack:c});r=I.policyDefinitions}let p=yt(u);if(u&&!p)return M({result:{error:O},context:{participantsCount:u},stack:c});if(o&&!p)return M({result:{error:gU},stack:c});if(Number.isNaN(Number(n)))if(u)({drawSize:n}=bA({participantsCount:u}));else return M({result:{error:$c},stack:c});let m=o&&u||n;if(m&&m>n)return{error:zg};let d=r?.[Hn];if(!d)return{error:eU};let l=d.seedsCountThresholds;return l?(d.drawSizeProgression!==void 0&&(e=d.drawSizeProgression),{seedsCount:l.filter(I=>e?I.drawSize<=n:n===I.drawSize).reduce((I,S)=>u&&u>=S.minimumParticipantCount?S.seedsCount:I,0)}):{error:FD}}function Nf({consideredEntries:t,policyDefinitions:e,tournamentRecord:r,appliedPolicies:n,participantMap:o,enforceGender:i,participants:s,event:a}){if((!s||!o)&&r&&({participants:s,participantMap:o}=bt({tournamentRecord:r})),!s)return{error:zc};if(!Array.isArray(s))return{error:O};if(!a)return{error:le};let c=e?.[He]??n?.[He]??Ns[He],u=(i??c?.participants?.enforceGender)!==!1,{eventType:p,gender:m}=a,d=p===si,l=p===Ze&&_t||d&<||St,f=Object.assign({},...(t??a.entries??[]).map(h=>({[h.participantId]:h.entryStatus}))),g=Object.keys(f),S=s.filter(h=>g.includes(h.participantId)).filter(h=>{let T=U6({participant:h,participantType:l,eventType:p,entryStatusMap:f}),y=R6({genderEnforced:u,participantMap:o,eventGender:m,participant:h,isDoubles:d,mismatch:T});return T||!y});if(S.length){let h=S.map(T=>T.participantId);return{error:qD,invalidParticipantIds:h}}return{...P,valid:!0}}function U6({participant:t,participantType:e,eventType:r,entryStatusMap:n}){if(r===EI&&[St,lt].includes(t.participantType))return!1;let o=n[t.participantId],i=r&&[si,Ze].includes(r)&&t.participantType===St&&(ta(o)||o===Mn);return t.participantType!==e&&!i}function R6(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||Oo(n)||Un(n)&&Ar(a[0])===Ar(n)||nn(n)&&(a.length===1&&e.individualParticipantIds?.length===1||a.length===2),u=e?.person?.sex,p=!e?.person||!n||nn(n)||Oo(n)||Un(n)&&Ar(u)===Ar(n);return!s||c&&p}function CA({hasExistingDrawDefinition:t,qualifyingProfiles:e,appliedPolicies:r,qualifyingOnly:n,tieFormat:o,idPrefix:i,isMock:s,uuids:a}){let c="generateQualifyingSTructures",u=[],p=[],m=[],d=(h,T)=>h.stageSequence-T.stageSequence,l=(h,T)=>h.roundTarget-T.roundTarget,f=0,g=0,I,S=1;for(let h of e.sort(l)){let T=h.structureProfiles??[];S=h.roundTarget||S;let y=1,E=0,A,N,D;for(let R of(T??[]).sort(d)){let U=b6({structureProfile:R,qualifyingProfiles:e,structureProfiles:T,hasExistingDrawDefinition:t,appliedPolicies:r,qualifyingOnly:n,stageSequence:y,roundTarget:S,tieFormat:o,idPrefix:i,isMock:s,uuids:a,stack:c,finalQualifyingStructureId:N,finalQualifyingRoundNumber:A,qualifyingDrawPositionsCount:f,targetRoundQualifiersCount:E,finishingPositions:I,linkType:D,links:m,structures:p});if(U.error)return U;({qualifyingDrawPositionsCount:f,targetRoundQualifiersCount:E,finalQualifyingStructureId:N,finalQualifyingRoundNumber:A,finishingPositions:I,linkType:D,stageSequence:y}=U)}g+=E,u.push({qualifiersCount:E,finalQualifyingRoundNumber:A,finalQualifyingStructureId:N,finishingPositions:I,roundTarget:S,linkType:D}),S+=1}return{qualifiersCount:g,qualifyingDrawPositionsCount:f,qualifyingDetails:u,structures:p,...P,links:m}}function b6({structureProfile:t,qualifyingProfiles:e,structureProfiles:r,hasExistingDrawDefinition:n,appliedPolicies:o,qualifyingOnly:i,stageSequence:s,roundTarget:a,tieFormat:c,idPrefix:u,isMock:p,uuids:m,stack:d,finalQualifyingStructureId:l,finalQualifyingRoundNumber:f,qualifyingDrawPositionsCount:g,targetRoundQualifiersCount:I,finishingPositions:S,linkType:h,links:T,structures:y}){let E=el(t.drawSize||t.participantsCount),{qualifyingRoundNumber:A,structureOptions:N,matchUpFormat:D,structureName:R,structureId:U,drawType:b}=t,C=t.matchUpType,_=t.qualifyingPositions||C6({drawSize:E,qualifyingRoundNumber:A});if(!yt(E))return M({result:{error:$c},stack:d});let v=e.length>1?`${a}-`:"",w=r.length>1||v?s:"",L=R||(v||w?`${xe(Z)} ${v}${w}`:xe(Z)),F,x,k;if(b===hr){let G=Rc({structureName:t.structureName||L,structureId:U||m?.pop(),hasExistingDrawDefinition:n,stage:Z,structureOptions:N,appliedPolicies:o,qualifyingOnly:i,stageSequence:s,matchUpType:C,roundTarget:a,tieFormat:c,drawSize:E,idPrefix:u,isMock:p,uuids:m});I=G.groupCount,F=G.maxRoundNumber,x=G.structures[0],S=[1]}else({drawSize:E,matchUps:k,roundLimit:F}=Er({qualifyingRoundNumber:A,qualifyingPositions:_,matchUpType:C,drawSize:E,idPrefix:u,isMock:p,uuids:m})),x=lr({structureName:t.structureName||L,structureId:U||m?.pop(),qualifyingRoundNumber:F,hasExistingDrawDefinition:n,stage:Z,qualifyingOnly:i,matchUpFormat:D,stageSequence:s,matchUpType:C,roundLimit:F,tieFormat:c,matchUps:k}),a&&ut({extension:{name:bn,value:a},element:x}),I=k?.filter(G=>G.roundNumber===F)?.length||0;if(s>1){let{link:G}=oa({sourceStructureId:l,sourceRoundNumber:f,targetStructureId:x.structureId,finishingPositions:h===fn?[1]:void 0,linkType:h});T.push(G),g+=(E||0)-I}else g+=E||0;return h=b===hr?fn:Pr,l=x.structureId,f=F,c&&(k=ht({structure:x})?.matchUps??[],k?.forEach(G=>{let{tieMatchUps:V}=ts({tieFormat:c,matchUp:G,isMock:p});Object.assign(G,{tieMatchUps:V,matchUpType:C})})),y.push(x),s+=1,{qualifyingDrawPositionsCount:g,targetRoundQualifiersCount:I,finalQualifyingStructureId:l,finalQualifyingRoundNumber:f,finishingPositions:S,stageSequence:s,linkType:h}}function C6({drawSize:t,qualifyingRoundNumber:e}){let r=t,n=0;for(;n<e;)r=Math.floor(r/2),n+=1;return r}function MA(t){let{drawTypeCoercion:e,enforceMinimumDrawSize:r}=t,n=st(t.drawSize),o=e&&!yn(t.drawType)&&(typeof e=="boolean"||e<=2)&&n===2&&Nr||t.drawType||Nr,i=RR.includes(o);if(n&&i){if(e&&(typeof e=="boolean"&&n<4||n<=e))o=Nr;else if(n<4&&r)return{...M({context:{enforceMinimumDrawSize:r,drawSize:n,drawType:o},result:{error:vm},stack:"getCoercedDrawType"}),drawType:o}}return{drawType:o}}function Df(t){let{enforceMinimumDrawSize:e=!0,overwriteExisting:r,appliedPolicies:n,qualifyingOnly:o,staggeredEntry:i,drawDefinition:s,tieFormat:a,isMock:c,uuids:u}=t??{},p=st(t.drawSize),m=t.drawTypeCoercion??em({appliedPolicies:n,drawType:t.drawType}),d="generateDrawStructuresAndLinks",l=MA({drawType:t.drawType,enforceMinimumDrawSize:e,drawTypeCoercion:m,drawSize:p});if(l.error)return l;let f=l.drawType,g=[],I=[],S=t?.matchUpType??Ct,{existingQualifyingDrawPositionsCount:h,mainStructureIsPlaceholder:T,existingQualifyingLinks:y,existingMainStructure:E,existingQualifiersCount:A}=M6({drawDefinition:s,structures:g});if(s?.structures?.filter(({stage:V})=>V===Z)?.length&&!T)return{error:$T};let N=!s?.structures?.filter(({stage:V})=>V===Z)?.length&&t.qualifyingProfiles,D=N?.length&&CA({idPrefix:t.idPrefix,qualifyingProfiles:N,appliedPolicies:n,qualifyingOnly:o,tieFormat:a,isMock:c,uuids:u});if(D?.error)return D;let{qualifyingDrawPositionsCount:R,qualifyingDetails:U,qualifiersCount:b}=D||{qualifyingDrawPositionsCount:h,qualifiersCount:A},C=b||t.qualifiersCount||0;R&&(D?.structures&&g.push(...D.structures),D?.links&&I.push(...D.links)),Object.assign(t,et({drawSize:p,matchUpType:S,tieFormat:a}));let _=v6({drawType:f,drawSize:p,staggeredEntry:i});if(_&&!R)return M({context:{drawSize:p,invalidDrawSize:_},result:{error:vm},stack:d});let{generators:v,error:w}=df(t);if(w)return{error:w};let L=v[f];if(!L)return{error:rp};let F=L?.();if(F.error)return F;let{structures:x,links:k}=F;if(x?.length){let V=O6({mainStructureIsPlaceholder:T,existingMainStructure:E,generatedStructures:x,overwriteExisting:r,generatedLinks:k,structures:g});if(V?.error)return V}g.sort(Hi),k?.length&&I.push(...k);let G=F.structures.find(({stage:V,stageSequence:B})=>V===W&&B===1);for(let V of U??[]){let{finalQualifyingRoundNumber:B,finalQualifyingStructureId:z,roundTarget:H,finishingPositions:K,linkType:Y}=V,J=G&&oa({targetStructureId:G.structureId,sourceStructureId:z,sourceRoundNumber:B,finishingPositions:K,targetEntryRound:H,linkType:Y})?.link;if(J?.error)return J;J&&I.push(J)}return y&&I.push(...y),{...P,qualifyingResult:{qualifyingDrawPositionsCount:R,qualifiersCount:C},structures:g,links:I}}function l1(t,e){if(t.linkType===fn&&e?.structures){let r=t.source.finishingPositions??[];return e.structures.length*r.length}else if(t.linkType===Pr&&e?.matchUps?.length){let r=t.source.roundNumber;return e.matchUps.filter(({roundNumber:o})=>o===r).length}}function M6({drawDefinition:t,structures:e}){let r=t?.structures?.filter(({stage:u})=>u===Z);r&&e.push(...r);let n=r?.map(({structureId:u})=>u),o=t?.structures?.find(({stage:u,stageSequence:p})=>u===W&&p===1),i=t?.links?.filter(u=>u.target.structureId===o?.structureId&&n?.includes(u.source.structureId)),s=r?.map(u=>{let p=i?.find(g=>g.target.structureId===u.structureId),m=Pt({structure:u})?.positionAssignments?.length??0;if(!p)return m;let d=p?.source.structureId,l=t.structures?.find(g=>g.structureId===d),f=l1(p,l)||0;return m-f}).filter(Boolean).reduce((u,p)=>u+p,0),a=i?.map(u=>{let p=u.source.structureId,m=r?.find(d=>d.structureId===p);return l1(u,m)}).filter(Boolean).reduce((u,p)=>u+p,0),c=!!(o&&!o?.matchUps?.length);return{existingQualifyingDrawPositionsCount:s,mainStructureIsPlaceholder:c,existingQualifyingLinks:i,existingMainStructure:o,existingQualifiersCount:a}}function v6({drawType:t,drawSize:e,staggeredEntry:r}){return!!(!yn(t)&&(!e||e<2||[ai,ki].includes(t)&&!en(e)&&e<5||!r&&![pc,ai,ki].includes(t)&&([Tr,hr].includes(t)&&e<3||![hr,Tr].includes(t)&&!en(e))))}function O6({mainStructureIsPlaceholder:t,existingMainStructure:e,generatedStructures:r,overwriteExisting:n,generatedLinks:o,structures:i}){let s=r.find(({stage:a,stageSequence:c})=>a===W&&c===1);if(e&&s){if(t)_6(s,e.structureId,o);else if(!n)return{error:$T}}i.push(...r)}function _6(t,e,r){let n=t.structureId;t.structureId=e;for(let o of r??[])o.source.structureId===n&&(o.source.structureId=e),o.target.structureId===n&&(o.target.structureId=e)}function Uf(t){let{modifyOriginal:e=!0,isMock:r}=t??{},n="generateDrawTypeAndModifyDrawDefinition";if(!t.drawDefinition)return M({result:{error:$},stack:n});let o=e?t.drawDefinition:q(t.drawDefinition,!1,!0),{tieFormat:i,matchUpType:s}=t;if(i){let I=or({tieFormat:i});if(I.error)return I}i=nr(i??ze({drawDefinition:o})?.tieFormat),s=s??(o.matchUpType||Ct),t.tieFormat=i,t.matchUpType=s;let a=Hb({drawDefinition:o,stage:W});t.drawSize=t.drawSize??a;let c=new Set(Ie({drawDefinition:o}).drawMatchUps.map(Te)),u=Df(t);if(u.error)return M({result:u,stack:n});let{structures:p,links:m}=u;o.structures=p,o.links=m;let d=t.drawSize??a;Object.assign(t,et({drawSize:d,matchUpType:s,tieFormat:i}));let{matchUps:l,matchUpsMap:f}=te({drawDefinition:o});i&&l?.forEach(I=>{if(!c.has(I.matchUpId)){let{tieMatchUps:S}=ts({tieFormat:i,matchUp:I,isMock:r});Object.assign(I,{tieMatchUps:S,matchUpType:s})}});let{inContextDrawMatchUps:g}=Ps({drawDefinition:o,matchUpsMap:f});return Ft({tournamentId:t.tournamentRecord?.tournamentId,drawDefinition:o}),{inContextDrawMatchUps:g,drawDefinition:o,matchUpsMap:f,...P,structures:p,matchUps:l,links:m}}function $a(t){let{removePriorValues:e,tournamentRecord:r,participantId:n,scaleItem:o}=t,i,s;if(!f1({scaleItem:o}))return{error:Qc};if(n&&Array.isArray(r.participants)&&(s=r.participants.find(a=>a.participantId===n),s)){if(s.participantType===ur&&o?.eventType!==Ze)return{error:Qc};let a=g1({removePriorValues:e,participant:s,scaleItem:o});if(a.error)return a;i=!a.valueChanged;let{topics:c}=vr();c.includes(tr)&&at({topic:tr,payload:{tournamentId:r.tournamentId,participants:[s]}})}return i&&{...P,info:oI,existingValue:o?.scaleValue}||s&&{...P,newValue:o?.scaleValue}||{error:ee}}function oM(t){let{scaleItemsWithParticipantIds:e=[],removePriorValues:r,tournamentRecord:n,auditData:o,context:i}=t,s=dt({tournamentRecord:n},[rt]);if(s.error)return s;if(!n.participants)return{error:zc};let a=x6(e);if(a.error)return a;let{modificationsApplied:c,modifiedParticipants:u,error:p}=w6({participants:n.participants,participantScaleItemsMap:a,removePriorValues:r});if(p)return p;let m=c?void 0:Na,{topics:d}=vr();return d.includes(tr)&&c&&at({topic:tr,payload:{tournamentId:n.tournamentId,participants:u}}),L6({context:i,tournamentRecord:n}),o&&d.includes(Yi)&&at({topic:Yi,payload:o}),et({...P,modificationsApplied:c,info:m})}function f1({scaleItem:t}){let e=t&&Object.keys(t),r=["scaleType","eventType","scaleName"];return!!(r.filter(o=>e?.includes(o)).length===r.length)}function g1({removePriorValues:t,participant:e,scaleItem:r}){if(!e)return{error:Aa};let n=r&&Object.keys(r),o=["scaleType","eventType","scaleName"];if(!(o.filter(p=>n.includes(p)&&r[p]).length===o.length))return{error:Qc};let s=new Date().toISOString();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){if(r.scaleDate&&typeof r.scaleDate=="string"&&!Me(r.scaleDate))return{error:ae};let{scaleType:p,eventType:m,scaleName:d}=r,l=[ci,p,m,d].join("."),f=et({itemValue:r.scaleValue,itemDate:r.scaleDate,createdAt:s,itemType:l});r.scaleId&&(f.itemSubTypes=[r.scaleId]),t&&(e.timeItems=e.timeItems.filter(g=>g.itemType!==l)),e.timeItems.push(f)}return{...P,valueChanged:u,newValue:r.scaleValue}}function x6(t){let e={};for(let r of t){let n=r?.participantId;if(Array.isArray(r?.scaleItems))for(let o of r.scaleItems)if(f1({scaleItem:o}))Array.isArray(e[n])||(e[n]=[]),e[n].push(o);else return{error:Qc}}return e}function w6({participants:t,participantScaleItemsMap:e,removePriorValues:r}){let n=0,o=[];for(let i of t){let{participantId:s}=i??{};if(Array.isArray(e[s]))for(let a of e[s]){if(i.participantType===ur&&a?.eventType!==Ze)return{error:M({context:{participantId:s,scaleItem:a,participantType:i.participantType},info:"Invalid participantType for eventType",result:{error:Qc}}),modificationsApplied:n,modifiedParticipants:o};g1({participant:i,scaleItem:a,removePriorValues:r}),o.push(i),n++}}return{modificationsApplied:n,modifiedParticipants:o,error:void 0}}function L6({context:t,tournamentRecord:e}){if(!t)return;let{eventId:r,drawId:n,...o}=t,i=o.scaleAttributes?.scaleType&&[o.scaleAttributes.scaleType];if(!Object.keys(o).length)return;let s={itemType:GI,itemValue:o};if(i&&(s.itemSubTypes=i),n||r){let{drawDefinition:a,event:c}=_e({tournamentRecord:e,eventId:r,drawId:n});n&&OS({drawDefinition:a,timeItem:s}),r&&Rs({event:c,timeItem:s})}else vu({tournamentRecord:e,timeItem:s})}function HS(t){let{tournamentRecord:e,modifiedScaleValues:r,removePriorValues:n}=t,o=X(t,[{[rt]:!0},{modifiedScaleValues:!0,[Ge]:qr}]);if(o.error)return o;for(let i in r){let s=$a({scaleItem:r[i],removePriorValues:n,tournamentRecord:e,participantId:i});if(s.error)return s}return{...P}}var F6=(t=0)=>250/Math.pow(t+5,.4),k6=()=>1;function G6(t=3,e=2){let r=t/e;return Number.isNaN(r)?Rf.kDefault():r}var Rf={nSpread:400,diffThreshold:.125,kCalc:F6,kMultiplier:G6,kDefault:k6};function vA(t){let{winnerRating:e,loserRating:r}=t,{ratings:n=Ke,winnerCountables:o=1,loserCountables:i=0,ratingType:s="ELO",maxCountables:a,countables:c}=t??{},u=n?.[s];if(!u)return{error:nt};let p=u.range||t.ratingRange;e=e||u.defaultInitialization,r=r||u.defaultInitialization;let m=p[0]>p[1],d=u.decimalsCount||0,l=m?p.slice().reverse():p,f=(L,F)=>Number.parseFloat(F)>=Math.min(...L)&&Number.parseFloat(F)<=Math.max(...L);(!f(p,e)||!f(p,r))&&(f(p,e)||(e=u.defaultInitialization),f(p,r)||(r=u.defaultInitialization));let g=Dp({targetRange:Ke["ELO"].range,sourceRange:l,value:m?p[0]-e:e}),I=Dp({targetRange:Ke["ELO"].range,sourceRange:l,value:m?p[0]-r:r}),S=(L,F)=>1/(1+Math.pow(10,(F-L)/Rf.nSpread)),h=S(g,I),T=S(I,g),y=Rf.kCalc(o),E=Rf.kCalc(i),A=Rf.kMultiplier(a,c),N=g+A*y*(1-h),D=I+A*E*(0-T),R=Dp({sourceRange:Ke["ELO"].range,value:N,targetRange:l}),U=Dp({sourceRange:Ke["ELO"].range,value:D,targetRange:l}),b=m?p[0]-R:R,C=Number.parseFloat(b.toFixed(d)),_=m?p[0]-U:U,v=Number.parseFloat(_.toFixed(d)),w=Math.max(...p)?Math.abs(e-r)/Math.max(...p):0;return(R>U&&w>Rf.diffThreshold||C<0||v<0)&&(C=e,v=r),{newWinnerRating:C,newLoserRating:v}}var I1=t=>t?.reduce((e,r)=>(r.winningSide&&(e[r.winningSide-1]+=1),e),[0,0])||[0,0];function OA(t){let e=X(t,[{[rt]:!0},{matchUpIds:!0,[Ge]:ke,[jr]:xs},{ratingType:!1,[$e]:N=>Ke[N]}]);if(e.error)return e;let{updateParticipantRatings:r,removePriorValues:n=!0,tournamentRecord:o,ratingType:i="ELO",convertToELO:s,refreshDynamic:a,considerGames:c,drawDefinition:u,matchUpIds:p,asDynamic:m}=t,d=Ke[i],l=s&&i!=="ELO",f=l?"ELO":i,g=Ke[f],I=d.accessor,S=g.accessor,h={},T=(t.matchUps||a&&rr({drawDefinition:u,tournamentRecord:o,inContext:!0,matchUpFilters:{matchUpStatuses:Ot}}).matchUps||qt({matchUpFilters:{matchUpIds:p,matchUpStatuses:Ot},tournamentRecord:o,inContext:!0}).matchUps)??[],y=`${f}.${Ep}`,E=m?y:f;T.sort(Qi);for(let N of T){let{endDate:D,matchUpFormat:R,score:U,sides:b,winningSide:C}=N,_=N.matchUpType,v={eventType:_,scaleName:i,scaleType:Lo},w={scaleName:y,eventType:_,scaleType:Lo},L=l?{scaleName:`${i}.${Ep}`,eventType:_,scaleType:Lo}:void 0,F=Object.assign({},...(b??[]).map(H=>{let{sideNumber:K,participant:Y}=H;return K&&{[K]:[Y?.participantId,...Y?.individualParticipantIds??[]].filter(Boolean).flat()}})),x=Object.assign({},...Object.values(F).flat().map(H=>V6({participantId:H,modifiedScaleValues:h,refreshDynamic:a,dynamicScaleAttributes:w,sourceDynamicScaleAttributes:L,scaleAttributes:v,tournamentRecord:o,sourceAccessor:I,outputScaleName:E,ratingType:i,isEloNative:l,accessor:S,matchUpType:_,endDate:D}))),k=R?oe(R):{},G=k?.bestOf||1,V=k?.setsTo||1,B=c?G&V:G,z=U?.sets&&I1(U.sets)||C===1&&[1,0]||[0,1];W6({sideParticipantIds:F,computeRatingType:f,outputScaleName:E,scaleItemMap:x,winningSide:C,countables:z,maxCountables:B,accessor:S}),Object.assign(h,x),r&&HS({tournamentRecord:o,modifiedScaleValues:h,removePriorValues:n})}let A=T.map(({matchUpId:N})=>N);return{...P,modifiedScaleValues:h,outputScaleName:E,processedMatchUpIds:A,...l&&{sourceRatingType:i}}}function V6({participantId:t,modifiedScaleValues:e,refreshDynamic:r,dynamicScaleAttributes:n,sourceDynamicScaleAttributes:o,scaleAttributes:i,tournamentRecord:s,sourceAccessor:a,outputScaleName:c,ratingType:u,isEloNative:p,accessor:m,matchUpType:d,endDate:l}){let f=e[t],g=!r||f,I=g?Zi({scaleAttributes:n,tournamentRecord:s,participantId:t}).scaleItem:void 0;!I&&o&&g&&(I=B6({sourceDynamicScaleAttributes:o,tournamentRecord:s,participantId:t,sourceAccessor:a,outputScaleName:c,ratingType:u}));let S=Zi({tournamentRecord:s,scaleAttributes:i,participantId:t}).scaleItem,h=I??S;if(!I&&S&&p){let y=S.scaleValue,E=a&&typeof y=="object"?y[a]:y;E!=null&&(h={...S,scaleName:c,scaleValue:Up({sourceRatingType:u,sourceRating:E})})}let T=m?{[m]:void 0}:void 0;return t&&{[t]:h??{scaleName:c,eventType:d,scaleDate:l,scaleType:Lo,scaleValue:T}}}function B6({sourceDynamicScaleAttributes:t,tournamentRecord:e,participantId:r,sourceAccessor:n,outputScaleName:o,ratingType:i}){let s=Zi({scaleAttributes:t,tournamentRecord:e,participantId:r}).scaleItem;if(!s)return;let a=s.scaleValue,c=n&&typeof a=="object"?a[n]:a;if(c!=null)return{...s,scaleName:o,scaleValue:Up({sourceRatingType:i,sourceRating:c})}}function W6({sideParticipantIds:t,computeRatingType:e,outputScaleName:r,scaleItemMap:n,winningSide:o,countables:i,maxCountables:s,accessor:a}){let c=o?t[o]:[],u=o?t[3-o]:[];for(let p of c){let m=n[p]?.scaleValue,d=typeof m=="object"?m[a]:m;for(let l of u){let f=n[l]?.scaleValue,g=typeof f=="object"?f[a]:f,I=o?i[o]:[0,0],S=o?i[3-o]:[0,0],{newWinnerRating:h,newLoserRating:T}=vA({ratingType:e,winnerCountables:I,loserCountables:S,maxCountables:s,winnerRating:d,loserRating:g}),y=a?{...m,[a]:h}:h,E=a?{...f,[a]:T}:T;n[p].scaleValue=y,n[l].scaleValue=E,n[p].scaleName=r,n[l].scaleName=r}}}function Mc(t){let{matchUpIds:e=[],drawDefinition:r,roundNumber:n,newRound:o,isMock:i,event:s}=t;if(typeof r!="object")return{error:$};let{participantIdPairings:a,matchUpsCount:c}=t,u=hf(t);if(u.error)return M({result:u});let{lastRoundNumber:p,availableMatchUpsCount:m=0,roundMatchUpsCount:d=0}=u;if(!c)o?c=d:m>0&&(c=m);else if(c>d&&t.restrictMatchUpsCount!==!1)return M({result:{error:O,info:"matchUpsCount error",context:{roundMatchUpsCount:d}}});if(a&&!Array.isArray(a)||c&&!yt(c)||e&&!Array.isArray(e)||!a&&!c)return{error:O,info:"matchUpsCount or pairings error"};if(c&&t.restrictMatchUpsCount!==!1&&c>32)return{error:O,info:"matchUpsCount must be less than 33"};if(n&&!t.ignoreLastRoundNumber&&n-1>(p||0))return{error:O,info:"roundNumber error"};let l=n??(o&&(p??0)+1||p||1);a=a??Q(0,c).map(()=>({participantIds:[void 0,void 0]}));let f=I=>{if(!t.idPrefix)return;let S=r.drawId,h=t.idPrefix??"ah";return`${S}-${h}-${l}-${I}`},g=a?.map((I,S)=>{let h=I?.participantIds??[void 0,void 0];h.push(void 0,void 0);let y=h.slice(0,2).map((A,N)=>et({sideNumber:N+1,participantId:A})),E=e[S]??f(S)??it();return{roundNumber:l,matchUpStatus:zt,matchUpId:E,sides:y}});if(g?.length){let I=ze({drawDefinition:r,event:s})?.tieFormat;I&&g.forEach(S=>{let{tieMatchUps:h}=ts({tieFormat:I,matchUp:S,isMock:i});Object.assign(S,{tieMatchUps:h,matchUpType:xt})})}return{roundNumber:l,matchUpsCount:g?.length??0,matchUps:g,...P}}function h1({maxIterations:t=4e3,valueSortedPairings:e,pairingValues:r,valueObjects:n,deltaObjects:o,random:i}){let s=i??Math.random,a=Object.assign({},...e.map(y=>({[y.pairing]:y.value}))),c=Object.keys(r),u=[],p=S1({actorsCount:c.length,valueSortedPairings:e,pairingValueMap:a,deltaObjects:o,valueObjects:n,random:i}),m=[iM(p)];u.push(p);let d=p.value,l=p,f=1,g=0,I=c.length,S;do I-=1,S=c.length*r[c[0]].length;while(S>t&&I>5);let h=[];c.forEach(y=>{r[y].slice(0,I).forEach(A=>{g+=1;let N=sa(y,A.opponent);if(!h.includes(N)){let D=S1({stipulated:[[y,A.opponent]],actorsCount:c.length,valueSortedPairings:e,pairingValueMap:a,deltaObjects:o,valueObjects:n,random:i});if(!m.includes(iM(D))){m.push(iM(D)),u.push(D);let{maxDelta:R,value:U}=D;R<l.maxDelta&&(l=D),(U<d||U===d&&Math.round(s()))&&(d=U),h.push(N),f+=1}}}),u=u.filter(A=>Math.abs(A.value-d)<5)}),u.sort((y,E)=>y.maxDiff-E.maxDiff);let T=Sr(u,i);return{candidatesCount:f,deltaCandidate:l,maxIterations:t,iterations:g,candidate:T}}function iM(t){return t.participantIdPairings.map(({participantIds:e})=>e.sort().join("|")).sort().join("/")}function S1({valueSortedPairings:t,stipulated:e=[],pairingValueMap:r,deltaObjects:n,valueObjects:o,actorsCount:i,random:s}){let a=s??Math.random,c=e.flat(),u=[],p=0;e.filter(Boolean).forEach(f=>{let[g,I]=f,S=sa(g,I),h=r[S];u.push({participantIds:f,value:h}),p+=r[S]}),he(t,i).flatMap(f=>ar(f,s).map(g=>({...g,value:g.value+a()*Math.round(a())}))).forEach(f=>{let g=f.pairing.split("|");if(!g.reduce((S,h)=>c.includes(h)||S,!1)){c.push(...g);let S=f.value;p+=S,u.push({participantIds:g,value:S})}}),u.sort((f,g)=>f.value-g.value);let d=u.reduce((f,g)=>{let[I,S]=g.participantIds,h=sa(I,S),T=n[h];return Math.max(T,f)},0),l=u.reduce((f,g)=>{let[I,S]=g.participantIds,h=sa(I,S),T=o[h];return Math.max(T,f)},0);return{value:p,participantIdPairings:u,maxDelta:d,maxDiff:l}}function sa(t,e){return[t,e].sort(Wp).join("|")}function sM({participantIds:t}){let e={},r=[];t.forEach(o=>{e[o]=t.filter(i=>i!==o),e[o].forEach(i=>{let s=sa(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 _A({matchUps:t}){let e=[];for(let r of t){let n=r.sides.map(gt);if(n.length===2){let[o,i]=n,s=sa(o,i);e.includes(s)||e.push(s)}}return{encounters:e}}function T1({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=sa(o,i);return{opponent:i,value:e[s]}}return{pairingValues:r}}var H6=0;function y1({tournamentParticipants:t,adHocRatings:e,eventType:r,scaleName:n,pairing:o}){let i=Ke[n]?.defaultInitialization??H6;return o.split("|").map(s=>{if(r===Lt){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 E1(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=y1({tournamentParticipants:e,adHocRatings:r,scaleName:p,eventType:u,pairing:T}),E=typeof m=="number"&&m||.5,A=t.random??Math.random,N=m&&(Math.round(A())?E:E*-1)||0,D=Math.abs(y[0]-y[1])+N,R=Math.abs(y[0]-y[1]);a[T]=R,c[T]||(c[T]=0),c[T]+=D?Math.pow(D,2):0});let d=o.map(T=>({pairing:T,value:c[T]})).sort((T,y)=>T.value-y.value),{pairingValues:l}=T1({possiblePairings:n,valueObjects:c}),{candidate:f,candidatesCount:g,deltaCandidate:I,iterations:S}=h1({random:t.random,valueSortedPairings:d,maxIterations:i,pairingValues:l,deltaObjects:a,valueObjects:c}),{participantIdPairings:h}=s?I:f;return{participantIdPairings:h,candidatesCount:g,deltaCandidate:I,iterations:S,candidate:f}}var Y6=100,j6=100,q6=4e3;function bf(t){let{encounterValue:e=Y6,sameTeamValue:r=j6,maxIterations:n=q6,updateParticipantRatings:o,generateMatchUps:i=!0,ignoreLastRoundNumber:s,iterationMatchUps:a,tournamentRecord:c,dynamicRatings:u,convertToELO:p,refreshDynamic:m,participantIds:d,drawDefinition:l,roundNumber:f,structureId:g,matchUpIds:I,eventType:S,scaleName:h,idPrefix:T,isMock:y,salted:E,event:A}=t;if(!l)return{error:$};if(!t.structure&&!g)return{error:Nt};let N=t.structure||tt({drawDefinition:l,structureId:g}).structure;if(!Tt(N))return{error:_i};if(!d?.length)return{error:Mo};let D=[...a??[],...N?.matchUps??[]],{encounters:R}=_A({matchUps:D}),U=c?.participants??[],b={},C,{competitionPolicy:_}=Ao({tournamentRecord:c,drawDefinition:l,event:A}),{competitionState:v}=_?Wo({drawDefinition:l}):{competitionState:void 0};if(_&&v&&_.pairingPolicy.ratingSource==="DYNAMIC_FORM")for(let[Ut,pe]of Object.entries(v.participantStates))b[Ut]=pe.dynamicFormRating;else if(u){let Ut=pt(N?.matchUps?N.matchUps.map(({roundNumber:ye})=>ye):[]),pe=Math.max(...Ut,0);if(pe){let ye=N?.matchUps?.filter(({roundNumber:pr})=>pr===pe).map(({matchUpId:pr})=>pr),Jt=OA({ratingType:h??A?.category?.ratingType,updateParticipantRatings:o,tournamentRecord:c,asDynamic:!0,convertToELO:p,refreshDynamic:m,drawDefinition:l,matchUpIds:ye});if(Jt.error)return Jt;Jt.modifiedScaleValues&&(b=Jt.modifiedScaleValues),Jt.sourceRatingType&&(C=Jt.sourceRatingType)}}let{valueObjects:L}=$6({tournamentParticipants:U,encounterValue:e,sameTeamValue:r,encounters:R}),{uniquePairings:F,possiblePairings:x,deltaObjects:k}=sM({participantIds:d}),G=Object.values(b).length?b:t.adHocRatings,V={tournamentParticipants:U,possiblePairings:x,participantIds:d,uniquePairings:F,drawDefinition:l,maxIterations:n,adHocRatings:G,deltaObjects:k,valueObjects:L,random:t.random,eventType:S,scaleName:h,structure:N,salted:E},{candidatesCount:B,participantIdPairings:z,deltaCandidate:H,iterations:K,candidate:Y}=E1(V);if(!B)return{error:xm};let J,ct;if(i){let Ut=Mc({structureId:N?.structureId,ignoreLastRoundNumber:s,participantIdPairings:z,newRound:!0,drawDefinition:l,roundNumber:f,matchUpIds:I,idPrefix:T,isMock:y,event:A});if(Ut.error)return Ut;J=Ut.roundNumber,ct=Ut.matchUps}let{maxDelta:Et,maxDiff:Ht}=Y;return{roundNumber:J,participantIdPairings:z,modifiedScaleValues:b,sourceRatingType:C,candidatesCount:B,deltaCandidate:H,...P,iterations:K,matchUps:ct,maxDelta:Et,maxDiff:Ht}}function $6({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===_t);if(i)for(let s of i){let a=s.individualParticipantIds??[],{uniquePairings:c}=sM({participantIds:a});for(let u of c)o[u]||(o[u]=0),o[u]+=n}return{valueObjects:o}}function xA(t){let{drawType:e=Nr,applyPositioning:r=!0,tournamentRecord:n,staggeredEntry:o,automated:i,placeByes:s,isMock:a,event:c}=t,u=t?.drawDefinition;if(!u)return{error:$};let p=Fe,m=Ki({entryStatuses:td,stageSequence:1,drawDefinition:u,stage:p}),l=[hr,Gs,Tr,ai].includes(e)?m.length:Pi(m.length);if(!o&&e===pc&&m.length<2||e===hr&&m.length<3)return{error:vm};let{tieFormat:f,matchUpType:g}=t;if(f){let v=or({tieFormat:f});if(v.error)return v}f=nr(f??ze({drawDefinition:u})?.tieFormat),g=g??u.matchUpType;let{structures:I}=Sn({stageSequence:1,drawDefinition:u,stage:p});if(I.length>1)return{error:$D};if(I?.[0]?.matchUps?.length)return{error:aI};let h=I?.[0]?.structureId;Object.assign(t,et({structureName:t.structureName??xe(Fe),structureId:h,matchUpType:g,tieFormat:f,drawSize:l,stage:p}));let T=df(t);if(T.error)return T;let y=T.generators[e];if(!y)return{error:rp};let E=y?.();if(E.error)return E;let{structures:A,links:N}=E,D=A.flatMap(v=>ht({structure:v}).matchUps);f&&D.forEach(v=>{let{tieMatchUps:w}=ts({matchUp:v,tieFormat:f,isMock:a});Object.assign(v,{tieMatchUps:w,matchUpType:g})});let R=q(u,!1,!0);R.links??=[],N.length&&R.links.push(...N);let U=new Set(A.map(({structureId:v})=>v));R.structures??=[];let b=new Set(R.structures.map(({structureId:v})=>v));R.structures=R.structures.map(v=>U.has(v.structureId)?A.find(({structureId:w})=>w===v.structureId):v);let C=A.filter(({structureId:v})=>!b.has(v));if(C.length&&R.structures.push(...C),i&&r){let v=A[0],w=(v?.structures?.length||0)>1;Ou({structureId:h||v?.structureId,seedingProfile:t.seedingProfile,drawDefinition:R,random:t.random,multipleStructures:w,applyPositioning:r,tournamentRecord:n,placeByes:s,event:c})}let _=R.structures.filter(({structureId:v})=>U.has(v));return{links:N,structures:_,...P}}var nh={};Gt(nh,{ScoringEngine:()=>JS,addPoint:()=>Cs,analyzeScore:()=>th,analyzeSequence:()=>VM,analyzeSet:()=>om,calculateMatchStatistics:()=>Cf,calculatePointsTo:()=>yd,checkScoreHasValue:()=>ue,checkSetIsComplete:()=>Pd,createMatchUp:()=>ns,deduceMatchUpFormat:()=>bd,enrichPointHistory:()=>uM,exportMatchUpJSON:()=>nk,generate:()=>gM,generateScoreString:()=>Ci,generateTieMatchUpScore:()=>_u,getEpisodes:()=>jS,getQuickStats:()=>pM,getScore:()=>os,getScoreboard:()=>YS,getSetComplement:()=>rh,getSetScoreString:()=>z1,getTiebreakComplement:()=>Ud,getWinner:()=>$S,groupByMatch:()=>JA,helpers:()=>_M,inferServeSide:()=>KS,isComplete:()=>qS,isValidMatchUpFormat:()=>xr,keyValueScore:()=>OM,mcpValidator:()=>rk,mutate:()=>IM,parseCSV:()=>XA,parseMCPPoint:()=>QA,parseMatchUpFormat:()=>oe,parseScoreString:()=>Rd,pbpValidator:()=>J1,pointParser:()=>BM,query:()=>LM,resolvePointValue:()=>zS,reverseScore:()=>aM,shotParser:()=>zA,shotSplitter:()=>GM,stringifyMatchUpFormat:()=>mp,toStatObjects:()=>Mf,validateMCPMatch:()=>WM,validateMatchUp:()=>FM,validateMatchUpScore:()=>xM,validateScore:()=>eh,validateSet:()=>Q1,validateSetScore:()=>$A,validateTieFormat:()=>or});var gM={};Gt(gM,{ScoringEngine:()=>JS,generateScoreString:()=>Ci,generateTieMatchUpScore:()=>_u,reverseScore:()=>aM});function Ci(t){let{winnerFirst:e=!0,setTBlast:r=!0,addOutcomeString:n,reversed:o=!1,matchUpStatus:i,matchUpFormat:s,autoComplete:a,winningSide:c,sets:u}=t;if(!u)return{error:nt,info:"missing sets"};let p=s&&oe(s),{bestOf:m,finalSetFormat:d,setFormat:l}=p??{},g=o||!(!e||!c||c===1),I=n?K6({matchUpStatus:i}):"",S=u?.sort(z6).map(h).filter(Boolean).join(" ")||"";if(!I)return S;if(c===2)return`${I} ${S}`;return`${S} ${I}`;function h(T){let E=m&&T.setNumber===m&&d?d:l,A=Y=>Le(Y?.side1Score)||Le(Y?.side2Score),D=(Y=>Le(Y?.side1TiebreakScore)||Le(Y?.side2TiebreakScore))(T),R=E?.tiebreakSet||!A(T)&&D,{side1Score:U,side2Score:b,side1TiebreakScore:C,side2TiebreakScore:_}=T,v=C||(Le(C)||D&&a?0:""),w=_||(Le(_)||D&&a?0:"");if(R){let Y=A(T)&&!D,J=Y?U:v,ct=Y?b:w;return`[${(g?[ct,J]:[J,ct]).join("-")}]`}let L=D?Math.min(v,w):"",F=L===v?1:2,x=Le(L)?`(${L})`:"",k=U||(Le(U)||a?0:""),G=b||(Le(b)||a?0:""),V=Y=>!r&&F===Y?x:"",B=`${k}${V(1)}`,z=`${G}${V(2)}`,H=r&&D?`(${L})`:"",K=g?`${[z,B].join("-")}${H}`:`${[B,z].join("-")}${H}`;return["-"," "].includes(K)&&(K=""),K}}function K6({matchUpStatus:t}){let e={[De]:"RET",[vt]:"WO",[ge]:"DF/DF",[Qt]:"WO/WO",[Wi]:"SUS",[Fr]:"ABN",[Mt]:"DEF",[Rp]:"DR"};return t&&e[t]||""}function z6(t,e){return t.setNumber-e.setNumber}function aM(t){if(!t?.score)return{error:nt};let{sets:e}=t.score,r=e.map(s=>{let{side1TiebreakScore:a,side2TiebreakScore:c,side1PointScore:u,side2PointScore:p,winningSide:m,side1Score:d,side2Score:l,setNumber:f}=s;return et({winningSide:m?3-m:void 0,side1TiebreakScore:c,side2TiebreakScore:a,side1PointScore:p,side2PointScore:u,side1Score:l,side2Score:d,setNumber:f})}),n=t?.setTBlast,o=Ci({setTBlast:n,sets:r}),i=Ci({sets:r,reversed:!0,setTBlast:n});return{reversedScore:{sets:r,scoreStringSide1:o,scoreStringSide2:i},...P}}var Q6={A:"Ace",D:"Double Fault",S:"Serve Winner",R:"Return Winner",W:"Winner",E:"Unforced Error",F:"Forced Error"},X6=new Set(["A","S"]),J6=new Set(["D","R","E","F"]);function A1(t,e){let r={...t};return r.server=e.server,r.index=e.index,r.set=e.set,r.game=e.game,r.code&&!r.winner&&(r.winner=Z6(r.code,e.server)),r.code&&!r.result&&(r.result=Q6[r.code]),r.first_serve?r.serve=2:r.serve||(r.serve=1),r}function Z6(t,e){return X6.has(t)?e:J6.has(t)?1-e:e}function P1(t){let e=[],r=[],n=t.result?.toLowerCase()||"";return n.includes("ace")&&e.push("aces"),(n.includes("winner")||n.includes("ace"))&&e.push("winners"),n.includes("double fault")&&r.push("doubleFaults"),n.includes("unforced error")&&r.push("unforcedErrors"),n.includes("forced error")&&r.push("forcedErrors"),t.winner===t.server?(e.push("servesWon"),t.serve===1?e.push("serves1stWon"):t.serve===2&&e.push("serves2ndWon")):(e.push("returns"),t.serve===1?e.push("received1stWon"):t.serve===2&&e.push("received2ndWon")),e.push("pointsWon"),{winner:e,loser:r}}function cM(t,e){let r={players:{},teams:{}};for(let i=0;i<2;i++)r.players[i]={},r.teams[i]={};let n=t;e?.setFilter!==void 0&&(n=t.filter(i=>i.set===e.setFilter));let o;return n.forEach((i,s)=>{if(i.winner===void 0){je()&&console.warn("Point missing winner:",i);return}let{winner:a,loser:c}=P1(i),u=i.winner,p=1-u;N1(r,u,a,i),N1(r,p,c,i),tK(r,i),eK(r,i,u,s),rK(r,i,o),nK(r,i,u),o=i}),r}function vc(t,e,r,n){t[e][r]||(t[e][r]=[]),t[e][r].push(n)}function N1(t,e,r,n){r.forEach(o=>{vc(t.teams,e,o,n),vc(t.players,e,o,n)})}function tK(t,e){if(e.server===void 0)return;let r=e.server;vc(t.teams,r,"pointsServed",e),e.serve===1?vc(t.teams,r,"serves1stIn",e):e.serve===2&&vc(t.teams,r,"serves2ndIn",e)}function eK(t,e,r,n){e.hand&&vc(t.teams,r,e.hand,{point:e,index:n})}function rK(t,e,r){if(!oK(e,r)||r?.winner===void 0)return;let n=r.winner;vc(t.teams,n,"gamesWon",r),vc(t.players,n,"gamesWon",r)}function nK(t,e,r){if(!e.breakpoint)return;let n=e.server;vc(t.teams,n,"breakpointsFaced",e),r===n&&vc(t.teams,n,"breakpointsSaved",e)}function oK(t,e){return e&&t.game!==void 0&&e.game!==void 0?t.game!==e.game:!1}function D1(t){let e={totalPoints:0,byTeam:[0,0],byCategory:{}};for(let n=0;n<2;n++)if(t.teams[n].pointsWon){let o=t.teams[n].pointsWon.length;e.byTeam[n]=o,e.totalPoints+=o}let r=new Set;for(let n=0;n<2;n++)Object.keys(t.teams[n]).forEach(o=>r.add(o));return r.forEach(n=>{e.byCategory[n]=0;for(let o=0;o<2;o++)t.teams[o][n]&&(e.byCategory[n]+=t.teams[o][n].length)}),e}function R1(t){if(!t?.teams)return[];let e=[];return Object.values({Aces:{category:"Aces",numerators:["aces"],calc:"number"},"Double Faults":{category:"Double Faults",numerators:["doubleFaults"],calc:"number"},Winners:{category:"Winners",numerators:["winners"],calc:"number"},"Unforced Errors":{category:"Unforced Errors",numerators:["unforcedErrors"],calc:"number"},"Forced Errors":{category:"Forced Errors",numerators:["forcedErrors"],calc:"number"},"Total Points Won":{category:"Total Points Won",numerators:["pointsWon"],calc:"number"},"Max Pts/Row":{category:"Max Pts/Row",numerators:["pointsWon"],calc:"maxConsecutive",attribute:"index"},"Max Games/Row":{category:"Max Games/Row",numerators:["gamesWon"],calc:"maxConsecutive",attribute:"game"},"First Serve %":{category:"First Serve %",numerators:["serves1stIn"],denominators:["pointsServed"],calc:"percentage"},"Points Won 1st":{category:"Points Won 1st",numerators:["serves1stWon"],denominators:["serves1stIn"],calc:"percentage"},"Points Won 2nd":{category:"Points Won 2nd",numerators:["serves2ndWon"],denominators:["serves2ndIn"],calc:"percentage"},"Points Won Receiving":{category:"Points Won Receiving",numerators:["received1stWon","received2ndWon"],denominators:["-pointsServed"],calc:"percentage"},"Breakpoints Saved":{category:"Breakpoints Saved",numerators:["breakpointsSaved"],denominators:["breakpointsFaced"],calc:"percentage"},"Breakpoints Converted":{category:"Breakpoints Converted",numerators:["-breakpointsSaved"],denominators:["-breakpointsFaced"],calc:"difference"},"Games Won":{category:"Games Won",numerators:["gamesWon"],calc:"number"},"Service Points Won":{category:"Service Points Won",numerators:["servesWon"],denominators:["pointsServed"],calc:"percentage"},"Aggressive Margin":{category:"Aggressive Margin",numerators:["*doubleFaults","*unforcedErrors"],denominators:["*aces","*winners","-*forcedErrors"],calc:"aggressiveMargin"}}).forEach(n=>{let o=[U1(n,t.teams,0),U1(n,t.teams,1)];(o[0].value!==0||o[1].value!==0)&&e.push({category:n.category,teams:o})}),e}function U1(t,e,r){switch(t.calc){case"number":return iK(t,e,r);case"percentage":return sK(t,e,r);case"maxConsecutive":return aK(t,e,r);case"difference":return cK(t,e,r);case"aggressiveMargin":return uK(t,e,r)}}function iK(t,e,r){let n=Td(t.numerators,e,r);return{value:n,display:String(n),numerators:t.numerators}}function sK(t,e,r){let n=Td(t.numerators,e,r),o=Td(t.denominators??[],e,r);if(!o)return{value:0,display:"0",numerators:t.numerators};let i=Math.round(n/o*100);return{value:i,display:`${i}% (${n}/${o})`,numerators:t.numerators}}function aK(t,e,r){let n=t.numerators[0],o=t.attribute||"index";if(!e[r][n])return{value:0,display:"0"};let i=e[r][n],s=0,a=i.length?1:0,c;return i.forEach(u=>{let p=u[o];c!==void 0&&p===c+1?a++:(a>s&&(s=a),a=1),c=p}),a>s&&(s=a),{value:s,display:String(s)}}function cK(t,e,r){let n=Td(t.numerators,e,r),o=Td(t.denominators??[],e,r);if(!o)return{value:0,display:"0",numerators:t.numerators};let i=Math.abs(o-n),s=Math.round(i/o*100);return{value:s,display:`${s}% (${i}/${o})`,numerators:t.numerators}}function uK(t,e,r){let n=Td(t.denominators??[],e,r),o=Td(t.numerators,e,r),i=n-o;return{value:i,display:String(i)}}function Td(t,e,r){return t?t.reduce((n,o)=>{let i=o.startsWith("-"),s=o.includes("*"),a=o.replace("-","").replace("*",""),c=i?1-r:r,u=e[c]?.[a];return u?n+u.length:n},0):0}function Cf(t,e,r){let n=cM(e??[],r),o=R1(n),i=D1(n);return{counters:n,calculated:o,summary:i}}function uM(t){if(!t)return[];let e=[],r=0,n=0,o=0;return t.forEach((i,s)=>{let a=A1(i,{server:r,index:s,set:n,game:o});e.push(a)}),e}function pM(t,e){let r=cM(t??[],e);return{aces:[r.teams[0].aces?.length||0,r.teams[1].aces?.length||0],doubleFaults:[r.teams[0].doubleFaults?.length||0,r.teams[1].doubleFaults?.length||0],winners:[r.teams[0].winners?.length||0,r.teams[1].winners?.length||0],unforcedErrors:[r.teams[0].unforcedErrors?.length||0,r.teams[1].unforcedErrors?.length||0],totalPoints:[r.teams[0].pointsWon?.length||0,r.teams[1].pointsWon?.length||0]}}function Ne(t,e,r){return t.teams[e]?.[r]?.length??0}function rs(t,e){return!e||!t?0:Number.parseFloat((t/e*100).toFixed(2))}function wA(t,e,r){return t.find(o=>o.category===e)?.teams[r]?.value??0}function Mf(t){if(!t?.counters?.teams)return[];let{counters:e,calculated:r}=t,n=[];n.push({name:"Aces",numerator:[Ne(e,0,"aces"),Ne(e,1,"aces")],default:"numerator"},{name:"Double Faults",numerator:[Ne(e,0,"doubleFaults"),Ne(e,1,"doubleFaults")],default:"numerator"});let o=[Ne(e,0,"serves1stWon"),Ne(e,1,"serves1stWon")],i=[Ne(e,0,"servesWon"),Ne(e,1,"servesWon")];if(o[0]+o[1]>0&&(i[0]!==o[0]||i[1]!==o[1])){let E=[Ne(e,0,"pointsServed"),Ne(e,1,"pointsServed")],A=[Ne(e,0,"serves1stIn"),Ne(e,1,"serves1stIn")],N=[Ne(e,0,"serves2ndWon"),Ne(e,1,"serves2ndWon")],D=[Ne(e,0,"serves2ndIn"),Ne(e,1,"serves2ndIn")];n.push({name:"1st Serve In",numerator:A,denominator:E,pct:[rs(A[0],E[0]),rs(A[1],E[1])]},{name:"1st Serve Points Won",numerator:o,denominator:A,pct:[rs(o[0],A[0]),rs(o[1],A[1])]},{name:"2nd Serve Points Won",numerator:N,denominator:D,pct:[rs(N[0],D[0]),rs(N[1],D[1])]})}n.push({name:"Total Points Won",numerator:[Ne(e,0,"pointsWon"),Ne(e,1,"pointsWon")],default:"numerator"});let a=Ne(e,0,"received1stWon")+Ne(e,0,"received2ndWon"),c=Ne(e,1,"received1stWon")+Ne(e,1,"received2ndWon"),u=Ne(e,1,"pointsServed"),p=Ne(e,0,"pointsServed");n.push({name:"Receiving Points Won",numerator:[a,c],denominator:[u,p],pct:[rs(a,u),rs(c,p)]});let m=Ne(e,1,"breakpointsFaced")-Ne(e,1,"breakpointsSaved"),d=Ne(e,0,"breakpointsFaced")-Ne(e,0,"breakpointsSaved"),l=Ne(e,1,"breakpointsFaced"),f=Ne(e,0,"breakpointsFaced");n.push({name:"Break Points Won",numerator:[m,d],denominator:[l,f],pct:[rs(m,l),rs(d,f)]});let g=Ne(e,0,"breakpointsSaved"),I=Ne(e,1,"breakpointsSaved"),S=Ne(e,0,"breakpointsFaced"),h=Ne(e,1,"breakpointsFaced");n.push({name:"Break Points Saved",numerator:[g,I],denominator:[S,h],pct:[rs(g,S),rs(I,h)]},{name:"Winners",numerator:[Ne(e,0,"winners"),Ne(e,1,"winners")],default:"numerator"},{name:"Unforced Errors",numerator:[Ne(e,0,"unforcedErrors"),Ne(e,1,"unforcedErrors")],default:"numerator"},{name:"Forced Errors",numerator:[Ne(e,0,"forcedErrors"),Ne(e,1,"forcedErrors")],default:"numerator"});let T=i,y=[Ne(e,0,"pointsServed"),Ne(e,1,"pointsServed")];return n.push({name:"Service Points Won",numerator:T,denominator:y,pct:[rs(T[0],y[0]),rs(T[1],y[1])]},{name:"Games Won",numerator:[Ne(e,0,"gamesWon"),Ne(e,1,"gamesWon")]},{name:"Most Consecutive Points Won",numerator:[wA(r,"Max Pts/Row",0),wA(r,"Max Pts/Row",1)]},{name:"Most Consecutive Games Won",numerator:[wA(r,"Max Games/Row",0),wA(r,"Max Games/Row",1)]}),n}function LA(t){return t?!!t.aggregate:!1}function wu(t,e){let r=t.bestOf||t.exactly||3,n=Math.ceil(r/2);if(e[0]===n-1&&e[1]===n-1&&t.finalSetFormat){let s=t.finalSetFormat;return s.tiebreakSet?"matchTiebreak":s.timed?"timed":"standard"}let i=t.setFormat;return i?i.tiebreakSet?"tiebreakOnly":i.timed?"timed":"standard":"standard"}function ns(t){let{matchUpId:e=it(),matchUpFormat:r,participants:n=[],isDoubles:o=!1,matchUpType:i}=t,s=i||(o?"DOUBLES":"SINGLES"),a=n.map((p,m)=>({sideNumber:m+1,participantId:p.participantId,participant:p}));return a.length===0&&a.push({sideNumber:1},{sideNumber:2}),{matchUpId:e,matchUpFormat:r,matchUpStatus:"TO_BE_PLAYED",matchUpType:s,sides:a,score:{sets:[]},createdAt:new Date().toISOString()}}function YS(t,e){let r=t.score.sets;if(r.length===0)return"0-0";let n=e?.perspective,o=r.map(s=>{let a=s.side1Score||0,c=s.side2Score||0;if(n===1&&([a,c]=[c,a]),s.side1TiebreakScore!==void 0||s.side2TiebreakScore!==void 0){let u=s.side1TiebreakScore||0,p=s.side2TiebreakScore||0;return n===1&&([u,p]=[p,u]),a>c?`${a}-${c}(${p})`:`${a}(${u})-${c}`}return`${a}-${c}`}),i=r.at(-1);if(t.matchUpStatus==="IN_PROGRESS"&&i&&!i.winningSide){let s=i.side1GameScores??[],a=s.length-1;if(a>=0&&s.length>0){let c=s[a]||0,u=(i.side2GameScores??[])[a]||0;if(c===0&&u===0)return o.join(", ");n===1&&([c,u]=[u,c]);let p=i.side1Score||0,m=i.side2Score||0,d=t.matchUpFormat?oe(t.matchUpFormat):void 0,l=d?.setFormat?.setTo||6,f=(typeof d?.setFormat?.tiebreakAt=="number"?d.setFormat.tiebreakAt:void 0)??l,g=p===f&&m===f,I=d?.gameFormat?.type==="CONSECUTIVE",S=o.at(-1),h=`${o.slice(0,-1).join(", ")}${o.length>1?", ":""}${S}`;if(g||I)return`${h} (${c}-${u})`;{let T=pK(c,u);return`${h} (${T})`}}}return o.join(", ")}function pK(t,e){let r=["0","15","30","40"];if(t<=3&&e<=3)return`${r[t]}-${r[e]}`;if(t>=3&&e>=3){let n=t-e;return n===0?"40-40":n===1?"A-40":n===-1?"40-A":n>=2?"G-40":"40-G"}return t>=3?"G-40":e>=3?"40-G":`${r[t]}-${r[e]}`}function jS(t){if(!t)return[];let e=t.history?.points;if(!e||e.length===0)return[];let r=[];for(let n=0;n<e.length;n++){let o=e[n],i=n<e.length-1?e[n+1]:void 0,s=n===e.length-1,a=t.matchUpStatus==="COMPLETED",c=o.set??0,u=o.game??0,p=o.number??0,{gameComplete:m,setComplete:d}=mK({nextPoint:i,isLastPoint:s,isCompleted:a,pointSet:c,pointGame:u}),l=m?o.winner:void 0,f=dK(d,t,c),g=lK(o),I=i?.server??o.server??0,S=fK(t,c,u);r.push({action:"addPoint",point:{index:n,number:p,winner:o.winner,server:o.server,score:o.score,result:o.result},game:{index:u,isTiebreak:S,complete:m,winner:l},set:{index:c,complete:d,winner:f},needed:g,nextService:I,result:o.result,complete:s&&a})}return r}function mK({nextPoint:t,isLastPoint:e,isCompleted:r,pointSet:n,pointGame:o}){let i=t?t.set??0:void 0,s=t?t.game??0:void 0;return{gameComplete:e?r||i===void 0&&s===void 0:i!==n||s!==o,setComplete:e?r||!1:t!==void 0&&i!==n}}function dK(t,e,r){if(!t)return;let n=e.score.sets[r];if(n?.winningSide!==void 0)return n.winningSide-1}function lK(t){let e={};return t.pointsToGame&&(e.pointsToGame=t.pointsToGame),t.pointsToSet&&(e.pointsToSet=t.pointsToSet),t.pointsToMatch&&(e.pointsToMatch=t.pointsToMatch),t.gamesToSet&&(e.gamesToSet=t.gamesToSet),t.isBreakpoint!==void 0&&(e.isBreakpoint=t.isBreakpoint),e}function fK(t,e,r){let n=t.score.sets[e];return!!(n?.isTiebreakOnly||r>0&&n?.side1Score!==void 0&&n?.side2Score!==void 0&&!n?.isTiebreakOnly)}function qS(t){return t.matchUpStatus==="COMPLETED"}function $S(t){if(t.matchUpStatus==="COMPLETED")return t.winningSide}function yd(t,e,r,n,o){if(r==="timed"||!n)return;let i=gK(t),s=IK(t),a=e.exactly||e.bestOf||3,c=Math.ceil(a/2),{side1Points:u,side2Points:p}=SK(i),m=hK(u,p,n,r,e,i),d=yK(i,n,r),l=EK(m,d,n,r),f=AK(l,s,c,e),g=NK(m,o);return{pointsToGame:m,pointsToSet:l,pointsToMatch:f,gamesToSet:d,isBreakpoint:g}}function gK(t){let e=t.score.sets;if(e.length===0)return;let r=e.at(-1);return r?.winningSide===void 0?r:void 0}function IK(t){let e=[0,0];return t.score.sets.forEach(r=>{r.winningSide===1&&e[0]++,r.winningSide===2&&e[1]++}),e}function SK(t){if(!t)return{side1Points:0,side2Points:0};let e=t.side1GameScores??[],r=t.side2GameScores??[];if(e.length===0&&r.length===0)return{side1Points:0,side2Points:0};let n=Math.max(e.length,r.length)-1;return{side1Points:e[n]??0,side2Points:r[n]??0}}function hK(t,e,r,n,o,i){if(n==="tiebreakOnly"){let s=r.tiebreakSet?.tiebreakTo||11,a=r.tiebreakSet?.NoAD||!1;return mM(t,e,s,a)}if(n==="matchTiebreak"){let s=o.finalSetFormat?.tiebreakSet?.tiebreakTo||10,a=o.finalSetFormat?.tiebreakSet?.NoAD||!1;return mM(t,e,s,a)}if(i){let s=i.side1Score||0,a=i.side2Score||0,c=r.setTo||6,u=(typeof r.tiebreakAt=="number"?r.tiebreakAt:void 0)??c;if(!(r.noTiebreak||!1)&&s===u&&a===u){let m=r.tiebreakFormat?.tiebreakTo||7,d=r.tiebreakFormat?.NoAD||!1;return mM(t,e,m,d)}}if(o.gameFormat?.type==="CONSECUTIVE"){let s=o.gameFormat.count||3;return[s,s]}return TK(t,e,r,o)}function TK(t,e,r,n){let o=r.gameFormat?.NoAD||r.NoAD||!1,i=n?.gameFormat?.deuceAfter,s=4;return[b1(t,e,s,o,i),b1(e,t,s,o,i)]}function b1(t,e,r,n,o){if(t>=r-1&&e>=r-1){if(n||o&&t>=2+o&&e>=2+o)return t>e?0:t===e?1:2;let i=t-e;return i>=2?0:i===1?1:2}return t>=r?0:r-t}function mM(t,e,r,n){return[C1(t,e,r,n),C1(e,t,r,n)]}function C1(t,e,r,n){if(t>=r&&(t-e>=2||n&&t>e))return 0;if(t>=r-1&&e>=r-1){if(n)return t>e?0:t===e?1:2;let o=t-e;return o>=2?0:o===1?1:2}return t>=r?0:r-t}function yK(t,e,r){if(r==="tiebreakOnly"||r==="matchTiebreak")return!t||t.winningSide!==void 0?[1,1]:[1,1];let n=t?.side1Score||0,o=t?.side2Score||0,i=e.setTo||6,s=(typeof e.tiebreakAt=="number"?e.tiebreakAt:void 0)??i,a=e.noTiebreak||!1,c=e.winBy||2;return[M1(n,o,i,s,a,c),M1(o,n,i,s,a,c)]}function M1(t,e,r,n,o,i){if(!o&&t===n&&e===n)return 1;if(t>=r){let a=t-e;return a>=i?0:i-a}let s=r-t;if(e>=r-1&&t>=r-1){if(!o)return Math.max(1,r-t);let a=t-e;return a>=i?0:i-a}return s}function EK(t,e,r,n){if(n==="tiebreakOnly"||n==="matchTiebreak")return[...t];let o=4;return[v1(t[0],e[0],o),v1(t[1],e[1],o)]}function v1(t,e,r){if(e<=0)return 0;let n=Math.max(0,e-1);return t+n*r}function AK(t,e,r,n){let o=n.setFormat,i=PK(o,n);return[O1(t[0],e[0],r,i),O1(t[1],e[1],r,i)]}function PK(t,e){if(!t)return 24;if(t.tiebreakSet)return t.tiebreakSet.tiebreakTo||11;if(t.timed)return 0;let r=t.setTo||6,o=e.gameFormat?.type==="CONSECUTIVE"?e.gameFormat?.count||3:4;return r*o}function O1(t,e,r,n){if(e>=r)return 0;let o=Math.max(0,r-e-1);return t+o*n}function NK(t,e){if(e===void 0)return!1;let r=1-e;return t[r]===1}function KS(t,e,r){if(r==="timed")return;let n=DK(t);return LA(e)?UK(t,n):r==="tiebreakOnly"||r==="matchTiebreak"?RK(n):bK(t,e,n)}function DK(t){let e=t.score.sets;if(e.length===0)return;let r=e[e.length-1];return r.winningSide===void 0?r:void 0}function UK(t,e){let r=0;for(let n of t.score.sets)n.winningSide!==void 0&&(n.side1TiebreakScore!==void 0?r+=(n.side1TiebreakScore??0)+(n.side2TiebreakScore??0):r+=(n.side1Score??0)+(n.side2Score??0));if(e&&e.winningSide===void 0){let n=e.side1GameScores??[],o=e.side2GameScores??[];if(n.length>0||o.length>0){let i=Math.max(n.length,o.length)-1;r+=(n[i]??0)+(o[i]??0)}else r+=(e.side1Score??0)+(e.side2Score??0)}return r%2===0?"deuce":"ad"}function RK(t){if(!t)return"deuce";let e=t.side1GameScores??[],r=t.side2GameScores??[];return e.length===0&&r.length===0||((e[0]??0)+(r[0]??0))%2===0?"deuce":"ad"}function bK(t,e,r){if(!r)return"deuce";let n=r.side1GameScores??[],o=r.side2GameScores??[];if(n.length===0&&o.length===0)return"deuce";let i=Math.max(n.length,o.length)-1;return((n[i]??0)+(o[i]??0))%2===0?"deuce":"ad"}function zS(t,e){if(!e.length)return 1;for(let{condition:r,value:n}of e)if(r.results&&t.result&&r.results.includes(t.result)||r.strokes&&t.stroke&&r.strokes.includes(t.stroke))return n;return 1}function Cs(t,e,r){if(!Tt(e))return t;let n=e.winner,o=e.server,{timestamp:i}=e;if(n===void 0&&e.winningSide!==void 0&&(n=e.winningSide-1),o===void 0&&e.serverSideNumber!==void 0&&(o=e.serverSideNumber-1),n==null)return t;let s=t;s.history??={points:[]};let a=oe(t.matchUpFormat);if(!a)throw new Error(`Invalid matchUpFormat: ${t.matchUpFormat}`);let c=a.exactly||a.bestOf||3,u=Math.ceil(c/2),p=s.history.points.length+1,m=s.history.points.length,d=[0,0];s.score.sets.forEach(N=>{N.winningSide===1&&d[0]++,N.winningSide===2&&d[1]++});let l=wu(a,d),f=d[0]===u-1&&d[1]===u-1,g=f&&a.finalSetFormat?a.finalSetFormat:a.setFormat,I=g?.tiebreakSet?.modifier==="RALLY"||g?.modifier==="RALLY";o===void 0&&!I&&(o=XS(s,a,l));let S=e.code;!S&&n!==void 0&&o!==void 0&&(S=n===o?"S":"R");let h={...e,pointNumber:p,winner:n,winningSide:n+1,server:o,serverSideNumber:o===void 0?void 0:o+1,serverParticipantId:e.serverParticipantId,timestamp:i||new Date().toISOString()};S&&(h.code=S),h.index=m;let T=yd(s,a,l,g,o);T&&(h.pointsToGame=T.pointsToGame,h.pointsToSet=T.pointsToSet,h.pointsToMatch=T.pointsToMatch,h.gamesToSet=T.gamesToSet,h.isBreakpoint=T.isBreakpoint);let y=KS(s,a,l);y!==void 0&&(h.serveSide=y);let E=r?.pointMultipliers??[],A=e.scoreValue??zS(h,E);switch(A!==1&&(h.scoreValue=A),s.history.points.push(h),s.matchUpStatus==="TO_BE_PLAYED"&&(s.matchUpStatus="IN_PROGRESS"),l){case"tiebreakOnly":vK(s,h,n,a,g,u,A);break;case"matchTiebreak":OK(s,h,n,a,u,A);break;case"timed":_K(s,h,n,g,A);break;default:CK(s,h,n,a,g,u,f);break}return s}function CK(t,e,r,n,o,i,s){let a=FA(t,!1,!1),c=t.score.sets.indexOf(a),u=a.side1Score||0,p=a.side2Score||0,m=a.side1GameScores??[],d=a.side2GameScores??[];m.length===0&&d.length===0&&(m.push(0),d.push(0));let l=Math.max(m.length,d.length)-1,f=l>=0?m[l]??0:0,g=l>=0?d[l]??0:0,I=Math.max(m.length,d.length)-1,S=u+p-I;e.set=c,e.game=S+l,e.number=f+g;let h=o.setTo||6,T=(typeof o.tiebreakAt=="number"?o.tiebreakAt:void 0)??h,y=s&&n.finalSetFormat?.noTiebreak;r===0?(f++,m[m.length-1]=f):(g++,d[d.length-1]=g),a.side1GameScores=m,a.side2GameScores=d;let E=n.gameFormat?.type==="CONSECUTIVE",A=n.gameFormat?.count||3;if(E){let U=a.currentStreak;U?.side===r?a.currentStreak={side:r,count:U.count+1}:a.currentStreak={side:r,count:1}}let N=!y&&u===T&&p===T,D;E&&!N?D=a.currentStreak.count>=A?a.currentStreak.side:void 0:D=xK(f,g,o,N,n);let R=D===void 0?fM(f,g,N,E&&!N):"0-0";e.score=R,D!==void 0&&MK(a,D,u,p,f,g,N,E,t,n,o,s,i)}function MK(t,e,r,n,o,i,s,a,c,u,p,m,d){a&&(t.currentStreak=void 0),e===0?t.side1Score=r+1:t.side2Score=n+1,s&&(t.side1TiebreakScore=o,t.side2TiebreakScore=i);let l=lM(t.side1Score||0,t.side2Score||0,p,m,u.finalSetFormat);typeof l=="number"?(t.winningSide=l+1,QS(c,u,d)):(t.side1GameScores.push(0),t.side2GameScores.push(0))}function vK(t,e,r,n,o,i,s=1){let a=FA(t,!0,!1),c=t.score.sets.indexOf(a),u=o.tiebreakSet.tiebreakTo||11,p=o.tiebreakSet.NoAD||!1,m=a.side1GameScores??[],d=a.side2GameScores??[];m.length===0&&d.length===0&&(m.push(0),d.push(0),a.side1GameScores=m,a.side2GameScores=d);let l=m[0]||0,f=d[0]||0;e.set=c,e.game=0,e.number=l+f,r===0?(l+=s,m[0]=l):(f+=s,d[0]=f),a.side1GameScores=m,a.side2GameScores=d;let g=dM(l,f,u,p);e.score=g===void 0?`${l}-${f}`:"0-0",g!==void 0&&(a.winningSide=g+1,a.side1TiebreakScore=l,a.side2TiebreakScore=f,a.side1Score=g===0?1:0,a.side2Score=g===0?0:1,QS(t,n,i))}function OK(t,e,r,n,o,i=1){let s=n.finalSetFormat?.tiebreakSet?.tiebreakTo||10,a=n.finalSetFormat?.tiebreakSet?.NoAD||!1,c=FA(t,!1,!1),u=t.score.sets.indexOf(c),p=c.side1GameScores??[],m=c.side2GameScores??[];p.length===0&&m.length===0&&(p.push(0),m.push(0),c.side1GameScores=p,c.side2GameScores=m);let d=p[0]||0,l=m[0]||0;e.set=u,e.game=0,e.number=d+l,r===0?(d+=i,p[0]=d):(l+=i,m[0]=l),c.side1GameScores=p,c.side2GameScores=m;let f=dM(d,l,s,a);e.score=f===void 0?`${d}-${l}`:"0-0",f!==void 0&&(c.side1TiebreakScore=d,c.side2TiebreakScore=l,c.side1Score=f===0?1:0,c.side2Score=f===0?0:1,c.winningSide=f+1,QS(t,n,o))}function _K(t,e,r,n,o=1){let i=FA(t,!1,!0),s=t.score.sets.indexOf(i);e.set=s,e.game=0,e.number=(i.side1Score||0)+(i.side2Score||0),r===0?i.side1Score=(i.side1Score||0)+o:i.side2Score=(i.side2Score||0)+o;let a=i.side1Score||0,c=i.side2Score||0;e.score=`${a}-${c}`}function FA(t,e,r){let n=t.score.sets.length-1,o=n>=0?t.score.sets[n]:void 0;if(o&&o.winningSide===void 0&&!o.segmentComplete)return o;let i={setNumber:t.score.sets.length+1,side1Score:0,side2Score:0,side1GameScores:[],side2GameScores:[]};return e&&(i.isTiebreakOnly=!0),r&&(i.isTimed=!0),t.score.sets.push(i),i}function QS(t,e,r){let n=[0,0];t.score.sets.forEach(c=>{c.winningSide===1&&n[0]++,c.winningSide===2&&n[1]++});let o=LA(e),i=e.exactly;if(o){let c=i||e.bestOf||3;if(t.score.sets.length<c)return;let p=t.score.sets.reduce((m,d)=>(d.side1TiebreakScore!==void 0&&d.side2TiebreakScore!==void 0?(m[0]+=d.side1TiebreakScore,m[1]+=d.side2TiebreakScore):(m[0]+=d.side1Score??0,m[1]+=d.side2Score??0),m),[0,0]);p[0]!==p[1]&&(t.matchUpStatus="COMPLETED",t.winningSide=p[0]>p[1]?1:2,t.endTime=new Date().toISOString());return}if(!(n[0]>=r||n[1]>=r)||i&&t.score.sets.filter(u=>u.winningSide!==void 0).length<i)return;let a=n[0]>=r?0:1;t.matchUpStatus="COMPLETED",t.winningSide=a+1,t.endTime=new Date().toISOString()}function dM(t,e,r,n=!1){let o=Math.abs(t-e),i=n?1:2;if((t>=r||e>=r)&&o>=i)return t>e?0:1}function xK(t,e,r,n,o){let i=r.gameFormat?.NoAD||r.NoAD||!1;if(n){let u=r.tiebreakFormat?.tiebreakTo||7,p=r.tiebreakFormat?.NoAD||!1;return dM(t,e,u,p)}let s=4,a=Math.abs(t-e);if(i)return t>=s||e>=s?t>e?0:1:void 0;let c=o?.gameFormat?.deuceAfter;if(c&&t>=2+c&&e>=2+c)return t!==e?t>e?0:1:void 0;if((t>=s||e>=s)&&a>=2)return t>e?0:1}function lM(t,e,r,n,o){let i=r.setTo||6,s=(typeof r.tiebreakAt=="number"?r.tiebreakAt:void 0)??i,a=n&&o?.noTiebreak;if(i===1)return t>=1||e>=1?t>e?0:1:void 0;let u=(n&&o?o:r).winBy||2;if(!a&&(t===s+1||e===s+1)||(t>=i||e>=i)&&Math.abs(t-e)>=u)return t>e?0:1}function XS(t,e,r){let n=kA(t,e,r);if(t.serverFlip!==void 0)return t.serverFlip?1-n:n;let o=t.history?.points?.[0];if(o?.server!==void 0){let i=o.set??0,s=o.game??0,a=0;for(let u=0;u<i;u++){let p=t.score.sets[u];a+=(p.side1Score||0)+(p.side2Score||0)}a+=s;let c=a%2;if(o.server!==c)return 1-n}return n}function kA(t,e,r){let n=t.score.sets.length-1,o=n>=0?t.score.sets[n]:void 0;if(r==="tiebreakOnly"||r==="matchTiebreak")return wK(t,o);if(r==="timed")return LK(o);let i=o?.side1Score||0,s=o?.side2Score||0,a=0;for(let l=0;l<t.score.sets.length-1;l++){let f=t.score.sets[l];a+=(f.side1Score||0)+(f.side2Score||0)}let c=e.setFormat?.setTo||6,u=(typeof e.setFormat?.tiebreakAt=="number"?e.setFormat.tiebreakAt:void 0)??c;if(!e.finalSetFormat?.noTiebreak&&i===u&&s===u){let l=o?.side1GameScores??[],f=o?.side2GameScores??[],g=(l.at(-1)||0)+(f.at(-1)||0),S=(a+i+s)%2,h=Math.floor(g/2)%2;return(S+h)%2}return(a+i+s)%2}function wK(t,e){let r=e?.side1GameScores??[],n=e?.side2GameScores??[],o=(r[0]||0)+(n[0]||0),i=0;for(let c=0;c<t.score.sets.length-1;c++){let u=t.score.sets[c];i+=(u.side1Score||0)+(u.side2Score||0)}let s=i%2,a=Math.floor(o/2)%2;return(s+a)%2}function LK(t){return((t?.side1Score||0)+(t?.side2Score||0))%2}function fM(t,e,r,n){if(r||n)return`${t}-${e}`;let o=["0","15","30","40"];if(t<4&&e<4)return`${o[t]}-${o[e]}`;if(t>=3&&e>=3&&t===e)return"40-40";if(t>=3&&e>=3){let i=t-e;if(i===1)return"A-40";if(i===-1)return"40-A";if(i>=2)return"G-40";if(i<=-2)return"40-G"}return t>=3?`40-${e<4?o[e]:"40"}`:e>=3?`${t<4?o[t]:"40"}-40`:`${t<4?o[t]:"0"}-${e<4?o[e]:"0"}`}function os(t,e){let r=t.score.sets,n=GK(t,e?.useBracketNotation),o=r.length>0?r.at(-1):null,i=o&&o.winningSide===void 0?[o.side1Score||0,o.side2Score||0]:[0,0],s=[0,0];if(o?.side1GameScores&&o.side2GameScores){let u=Math.max(o.side1GameScores.length,o.side2GameScores.length)-1;u>=0&&(s=[o.side1GameScores[u]||0,o.side2GameScores[u]||0])}let a=FK(t,s),c=kK(t);return{sets:r,scoreString:n,games:i,points:s,pointDisplay:a,situation:c}}function FK(t,e){if(t.matchUpStatus==="COMPLETED"||t.matchUpStatus==="TO_BE_PLAYED")return;let r=oe(t.matchUpFormat);if(!r)return;let n=t.score.sets.at(-1);if(!n||n.winningSide!==void 0)return;let o=[0,0];t.score.sets.forEach(m=>{m.winningSide===1&&o[0]++,m.winningSide===2&&o[1]++});let i=wu(r,o),s=i==="tiebreakOnly"||i==="matchTiebreak",a=r.gameFormat?.type==="CONSECUTIVE",c=s;if(!c&&i==="standard"){let m=r.exactly||r.bestOf||3,d=Math.ceil(m/2),l=o[0]===d-1&&o[1]===d-1,f=l&&r.finalSetFormat?r.finalSetFormat:r.setFormat;if(f){let g=n.side1Score||0,I=n.side2Score||0,S=f.setTo||6,h=(typeof f.tiebreakAt=="number"?f.tiebreakAt:void 0)??S,T=f.noTiebreak||!1,y=l&&r.finalSetFormat?.noTiebreak;c=!T&&!y&&g===h&&I===h}}let p=fM(e[0],e[1],c,a&&!c).split("-");return p.length===2?[p[0],p[1]]:[String(e[0]),String(e[1])]}function kK(t){if(t.matchUpStatus==="COMPLETED"||t.matchUpStatus==="TO_BE_PLAYED")return;let e=oe(t.matchUpFormat);if(!e)return;let r=e.exactly||e.bestOf||3,n=Math.ceil(r/2),o=[0,0];t.score.sets.forEach(A=>{A.winningSide===1&&o[0]++,A.winningSide===2&&o[1]++});let i=wu(e,o),s=o[0]===n-1&&o[1]===n-1,a=s&&e.finalSetFormat?e.finalSetFormat:e.setFormat,c=a?.tiebreakSet?.modifier==="RALLY"||a?.modifier==="RALLY",u;c||(u=XS(t,e,i));let p=yd(t,e,i,a,u);if(!p)return{isBreakPoint:!1,isGamePoint:!1,isSetPoint:!1,isMatchPoint:!1,isGoldenPoint:!1,isTiebreak:!1,server:u};let{pointsToGame:m,pointsToSet:d,pointsToMatch:l,isBreakpoint:f}=p,g=i==="tiebreakOnly"||i==="matchTiebreak";if(!g&&i==="standard"&&a){let A=t.score.sets.at(-1);if(A){let N=A.side1Score||0,D=A.side2Score||0,R=a.setTo||6,U=(typeof a.tiebreakAt=="number"?a.tiebreakAt:void 0)??R,b=a.noTiebreak||!1,C=s&&e.finalSetFormat?.noTiebreak;g=!b&&!C&&N===U&&D===U}}let I=!!(a?.NoAD||a?.gameFormat?.NoAD||g&&(a?.tiebreakFormat?.NoAD||a?.tiebreakSet?.NoAD||e.finalSetFormat?.tiebreakSet?.NoAD)),S=e.gameFormat?.deuceAfter,h=m[0]===1&&m[1]===1&&(I||!!S&&!g),T=u===void 0?!1:m[u]===1,y=Math.min(d[0],d[1])===1,E=Math.min(l[0],l[1])===1;return{isBreakPoint:f,isGamePoint:T,isSetPoint:y,isMatchPoint:E,isGoldenPoint:h,isTiebreak:g,server:u}}function GK(t,e=!1){let r=t.score.sets;return r.length===0?"0-0":r.map(o=>{let i=o.side1Score||0,s=o.side2Score||0;if(o.side1TiebreakScore!==void 0||o.side2TiebreakScore!==void 0){let a=o.side1TiebreakScore||0,c=o.side2TiebreakScore||0;return e&&(i===0&&s===1||i===1&&s===0)?`[${a}-${c}]`:i>s?`${i}-${s}(${c})`:`${i}(${a})-${s}`}return`${i}-${s}`}).join(", ")}var JS=class{constructor(e={}){this.pointMultipliers=[];this.redoStack=[];e.competitionFormat?(this.competitionFormat=e.competitionFormat,this.matchUpFormat=e.matchUpFormat||e.competitionFormat.matchUpFormat||"SET3-S:6/TB7",this.pointMultipliers=e.pointMultipliers||(e.competitionFormat.pointMultipliers??[])):(this.matchUpFormat=e.matchUpFormat||"SET3-S:6/TB7",this.pointMultipliers=e.pointMultipliers??[]),this.matchUpId=e.matchUpId,this.isDoubles=e.isDoubles||!1,this.eventHandlers=e.eventHandlers,this.state=ns({matchUpFormat:this.matchUpFormat,matchUpId:this.matchUpId,isDoubles:this.isDoubles}),this.cacheFormatStructure()}setState(e){this.state=e,this.matchUpFormat=e.matchUpFormat,this.matchUpId=e.matchUpId,this.isDoubles=e.matchUpType==="DOUBLES",this.redoStack=[],this.initialScore=void 0,this.cacheFormatStructure()}getState(){return JSON.parse(JSON.stringify(this.state))}addPoint(e){let r=this.state.history?.points.length||0,n=this.state.score.sets.reduce((a,c)=>a+(c.side1Score||0)+(c.side2Score||0),0),o=this.state.score.sets.filter(a=>a.winningSide!==void 0).length,i=this.state.matchUpStatus==="COMPLETED",s=this.hasLineUp()?this.getActivePlayers():void 0;if(this.state=Cs(this.state,e,{pointMultipliers:this.pointMultipliers}),s){let a=this.state.history.points[this.state.history.points.length-1];this.isDoubles?a.activePlayers=[s.side1,s.side2]:a.activePlayers=[s.side1[0]||"",s.side2[0]||""]}if(e.penaltyType){let a=this.state.history.points[this.state.history.points.length-1];a.penaltyType=e.penaltyType}if(this.ensureHistory(),this.state.history.entries.push({type:"point",data:{winner:e.winner,winningSide:e.winningSide,server:e.server,serverSideNumber:e.serverSideNumber,serverParticipantId:e.serverParticipantId,timestamp:e.timestamp,rallyLength:e.rallyLength,result:e.result,penaltyType:e.penaltyType},timestamp:e.timestamp||new Date().toISOString(),pointIndex:r}),this.redoStack=[],this.eventHandlers){let a=this.buildEventContext();if(this.eventHandlers.onPoint?.(a),this.state.score.sets.reduce((p,m)=>p+(m.side1Score||0)+(m.side2Score||0),0)>n&&this.eventHandlers.onGameComplete?.({...a,gameWinner:e.winner}),this.state.score.sets.filter(p=>p.winningSide!==void 0).length>o){let m=this.state.score.sets.findLast(d=>d.winningSide!==void 0)?.winningSide===1?0:1;this.eventHandlers.onSetComplete?.({...a,setWinner:m})}if(!i&&this.state.matchUpStatus==="COMPLETED"){let p=this.state.winningSide===1?0:1;this.eventHandlers.onMatchComplete?.({...a,matchWinner:p})}}}addSet(e){this.applyAddSet(e),this.ensureHistory();let r=this.state.score.sets.at(-1)?.winningSide;this.state.history.entries.push({type:"set",data:{...e,winningSide:r},timestamp:e.timestamp||new Date().toISOString()}),this.redoStack=[]}addGame(e){this.applyAddGame(e),this.ensureHistory(),this.state.history.entries.push({type:"game",data:e,timestamp:e.timestamp||new Date().toISOString()}),this.redoStack=[]}endSegment(e){this.applyEndSegment(e),this.ensureHistory();let r=(e?.setNumber??this.state.score.sets.length)-1;this.state.history.entries.push({type:"endSegment",data:{setNumber:r+1,...e},timestamp:e?.timestamp||new Date().toISOString()})}setInitialScore(e){this.initialScore=e,this.redoStack=[],this.applyInitialScore(this.state,e),this.ensureHistory(),this.state.history.entries.push({type:"setInitialScore",data:e,timestamp:new Date().toISOString()}),this.state.matchUpStatus==="TO_BE_PLAYED"&&(this.state.matchUpStatus="IN_PROGRESS")}undo(e=1){let r=this.state.history?.entries;if(r&&r.length>0){let i=Math.min(e,r.length);for(let s=0;s<i;s++){let a=r.pop();this.redoStack.push(a),a.type==="point"&&this.state.history.points.pop()}return this.rebuildFromEntries(),this.eventHandlers?.onUndo?.(this.buildEventContext()),!0}let n=this.state.history?.points??[];if(n.length===0)return!1;let o=Math.min(e,n.length);for(let i=0;i<o;i++){let s=n.pop();this.redoStack.push({type:"point",data:{winner:s.winner,server:s.server,timestamp:s.timestamp,rallyLength:s.rallyLength},timestamp:s.timestamp||""})}return this.rebuildState(),this.eventHandlers?.onUndo?.(this.buildEventContext()),!0}redo(e=1){if(this.redoStack.length===0)return!1;let r=Math.min(e,this.redoStack.length);for(let n=0;n<r;n++){let o=this.redoStack.pop();this.ensureHistory(),this.state.history.entries.push(o),o.type}return this.rebuildFromEntries(),this.eventHandlers?.onRedo?.(this.buildEventContext()),!0}canUndo(){let e=this.state.history?.entries;return e&&e.length>0?!0:(this.state.history?.points.length||0)>0}canRedo(){return this.redoStack.length>0}getUndoDepth(){let e=this.state.history?.entries;return e&&e.length>0?e.length:this.state.history?.points.length||0}getRedoDepth(){return this.redoStack.length}getScore(){return os(this.state)}getScoreboard(e){return YS(this.state,e)}getWinner(){return $S(this.state)}isComplete(){return qS(this.state)}getPointCount(){return this.state.history?.points.length||0}getFormat(){return this.state.matchUpFormat}getStatistics(e){let r=this.state.history?.points??[];return Cf(this.state,r,e)}getStatObjects(e){return Mf(this.getStatistics(e))}getNextServer(){if(this.competitionFormat?.serverRule==="WINNER_SERVES"){let o=this.state.history?.points.at(-1);return o?o.winner:0}if(!this.cachedFormatStructure)return 0;let r=[0,0];this.state.score.sets.forEach(o=>{o.winningSide===1&&r[0]++,o.winningSide===2&&r[1]++});let n=wu(this.cachedFormatStructure,r);return XS(this.state,this.cachedFormatStructure,n)}setServer(e,r){if(!this.cachedFormatStructure)return;let n=[0,0];this.state.score.sets.forEach(s=>{s.winningSide===1&&n[0]++,s.winningSide===2&&n[1]++});let o=wu(this.cachedFormatStructure,n),i=kA(this.state,this.cachedFormatStructure,o);this.state.serverFlip=e!==i,r?.recordEntry!==!1&&(this.ensureHistory(),this.state.history.entries.push({type:"setServer",data:{side:e},timestamp:new Date().toISOString()}),this.redoStack=[])}getEpisodes(){return jS(this.state)}isNoAd(){return!!(this.cachedFormatStructure?.setFormat?.NoAD||this.cachedFormatStructure?.setFormat?.gameFormat?.NoAD)}getSetsToWin(){if(!this.cachedFormatStructure)return 2;let e=this.cachedFormatStructure.exactly||this.cachedFormatStructure.bestOf||3;return Math.ceil(e/2)}getTiebreakAt(){let e=this.cachedFormatStructure?.setFormat;if(!e||e.tiebreakSet||e.timed||e.noTiebreak)return null;let r=e.setTo||6;return(typeof e.tiebreakAt=="number"?e.tiebreakAt:void 0)??r}hasFinalSetTiebreak(){let e=this.cachedFormatStructure?.finalSetFormat;return e?e.tiebreakSet?!0:e.noTiebreak?!1:!!(e.tiebreakFormat||e.tiebreakAt!==void 0):this.getTiebreakAt()!==null}getFormatStructure(){return this.cachedFormatStructure}getInputMode(){let e=this.state.history?.entries??[];if(e.length===0)return(this.state.history?.points.length||0)>0?"points":"none";let r=new Set(e.filter(n=>n.type!=="setInitialScore"&&n.type!=="endSegment").map(n=>n.type));if(r.size===0)return"none";if(r.size===1){let n=r.values().next().value;if(n==="point")return"points";if(n==="game")return"games";if(n==="set")return"sets"}return"mixed"}setLineUp(e,r){let n=this.state.sides.find(o=>o.sideNumber===e);n&&(n.lineUp=r),this.initialLineUps??={},this.initialLineUps[e]=r.map(o=>({...o}))}substitute(e){let r=this.state.sides.find(i=>i.sideNumber===e.sideNumber);if(!r?.lineUp)return;let n=r.lineUp.findIndex(i=>i.participantId===e.outParticipantId);if(n===-1)return;this.ensureHistory(),this.state.history.substitutions??=[];let o={sideNumber:e.sideNumber,outParticipantId:e.outParticipantId,inParticipantId:e.inParticipantId,beforePointIndex:this.state.history.points.length,timestamp:e.timestamp};this.state.history.substitutions.push(o),r.lineUp[n]={...r.lineUp[n],participantId:e.inParticipantId},this.state.history.entries.push({type:"substitution",data:o,timestamp:e.timestamp||new Date().toISOString()}),this.redoStack=[]}getActivePlayers(){let e=this.state.sides.find(n=>n.sideNumber===1),r=this.state.sides.find(n=>n.sideNumber===2);return{side1:e?.lineUp?.map(n=>n.participantId)??[],side2:r?.lineUp?.map(n=>n.participantId)??[]}}hasLineUp(){return this.state.sides.some(e=>e.lineUp&&e.lineUp.length>0)}setPointMultipliers(e){this.pointMultipliers=e}getPointMultipliers(){return this.pointMultipliers}getSupplementaryState(){return{redoStack:[...this.redoStack],initialLineUps:this.initialLineUps?Object.fromEntries(Object.entries(this.initialLineUps).map(([e,r])=>[e,r.map(n=>({...n}))])):void 0}}loadSupplementaryState(e){e.redoStack&&(this.redoStack=[...e.redoStack]),e.initialLineUps&&(this.initialLineUps=Object.fromEntries(Object.entries(e.initialLineUps).map(([r,n])=>[r,n.map(o=>({...o}))])))}getPenaltyProfile(){return this.competitionFormat?.penaltyProfile}getPointProfile(){return this.competitionFormat?.pointProfile}getTimerProfile(){return this.competitionFormat?.timerProfile}getTimeoutRules(){return this.competitionFormat?.timeoutRules}getPenaltyBoxProfile(){return this.competitionFormat?.penaltyBoxProfile}getSubstitutionRules(){return this.competitionFormat?.substitutionRules}getPlayerRules(){return this.competitionFormat?.playerRules}setEventHandlers(e){this.eventHandlers=e}getEventHandlers(){return this.eventHandlers}decoratePoint(e,r){let n=this.state.history?.points[e];n&&Object.assign(n,r)}markHardBoundary(e){let r=this.state.score.sets[e.setIndex];r&&(r.hardBoundaries??=[],r.hardBoundaries.includes(e.gameIndex)||(r.hardBoundaries.push(e.gameIndex),r.hardBoundaries.sort((n,o)=>n-o)))}editPoint(e,r,n){let o=this.state.history?.points;if(!o||e<0||e>=o.length)return;let i=n?.recalculate!==!1,s=o[e];if(r.winner!==void 0&&(s.winner=r.winner),r.server!==void 0&&(s.server=r.server),r.timestamp!==void 0&&(s.timestamp=r.timestamp),r.rallyLength!==void 0&&(s.rallyLength=r.rallyLength),r.wrongSide!==void 0&&(s.wrongSide=r.wrongSide),r.wrongServer!==void 0&&(s.wrongServer=r.wrongServer),r.penaltyPoint!==void 0&&(s.penaltyPoint=r.penaltyPoint),!i)return;let a=this.state.history?.entries;if(a){let c=a.find(u=>u.type==="point"&&u.pointIndex===e);c&&(r.winner!==void 0&&(c.data.winner=r.winner),r.server!==void 0&&(c.data.server=r.server))}a&&a.length>0?this.rebuildFromEntries():this.rebuildState(),this.redoStack=[]}removePoint(e,r){let n=this.state.history?.points;if(!n||e<0||e>=n.length)return;let o=r?.recalculate!==!1;n.splice(e,1);let i=this.state.history?.entries;if(i){let s=i.findIndex(a=>a.type==="point"&&a.pointIndex===e);s!==-1&&i.splice(s,1);for(let a of i)a.type==="point"&&a.pointIndex>e&&(a.pointIndex-=1)}o&&(i&&i.length>0?this.rebuildFromEntries():this.rebuildState(),this.redoStack=[])}reset(){this.state=ns({matchUpFormat:this.matchUpFormat,matchUpId:this.matchUpId,isDoubles:this.isDoubles}),this.redoStack=[],this.initialScore=void 0,this.initialLineUps=void 0,this.eventHandlers?.onReset?.(this.buildEventContext())}ensureHistory(){this.state.history??={points:[]},this.state.history.entries??=[]}buildEventContext(){return{state:this.state,score:os(this.state)}}cacheFormatStructure(){this.cachedFormatStructure=oe(this.matchUpFormat)}getInitialLineUps(){return this.initialLineUps}applyAddSet(e){let{side1Score:r,side2Score:n,side1TiebreakScore:o,side2TiebreakScore:i}=e,s=e.winningSide;s===void 0&&(r>n?s=1:n>r&&(s=2));let a={setNumber:this.state.score.sets.length+1,side1Score:r,side2Score:n,winningSide:s};o!==void 0&&(a.side1TiebreakScore=o),i!==void 0&&(a.side2TiebreakScore=i),this.state.score.sets.push(a),this.state.matchUpStatus==="TO_BE_PLAYED"&&(this.state.matchUpStatus="IN_PROGRESS"),s!==void 0&&this.checkMatchCompletion()}applyAddGame(e){let{winner:r,tiebreakScore:n}=e,o=this.state.score.sets.length>0?this.state.score.sets.at(-1):void 0;(!o||o.winningSide!==void 0)&&(o={setNumber:this.state.score.sets.length+1,side1Score:0,side2Score:0},this.state.score.sets.push(o)),r===0?o.side1Score=(o.side1Score||0)+1:o.side2Score=(o.side2Score||0)+1,(o.side1GameScores?.length||o.side2GameScores?.length)&&(o.side1GameScores=o.side1GameScores??[],o.side2GameScores=o.side2GameScores??[],o.side1GameScores.push(0),o.side2GameScores.push(0)),n&&(o.side1TiebreakScore=n[0],o.side2TiebreakScore=n[1]),this.state.matchUpStatus==="TO_BE_PLAYED"&&(this.state.matchUpStatus="IN_PROGRESS"),this.checkSetCompletion(o),o.winningSide!==void 0&&this.checkMatchCompletion()}applySubstitution(e){let r=this.state.sides.find(o=>o.sideNumber===e.sideNumber);if(!r?.lineUp)return;let n=r.lineUp.findIndex(o=>o.participantId===e.outParticipantId);n!==-1&&(r.lineUp[n]={...r.lineUp[n],participantId:e.inParticipantId},this.state.history??={points:[]},this.state.history.substitutions??=[],this.state.history.substitutions.push(e))}applyEndSegment(e){let r=(e?.setNumber??this.state.score.sets.length)-1,n=this.state.score.sets[r];if(!n||n.winningSide!==void 0)return;let o=n.side1Score||0,i=n.side2Score||0;o>i?n.winningSide=1:i>o&&(n.winningSide=2),n.segmentComplete=!0,this.checkMatchCompletion()}checkSetCompletion(e){let r=oe(this.state.matchUpFormat);if(!r)return;let n=r.exactly||r.bestOf||3,o=Math.ceil(n/2),i=[0,0];this.state.score.sets.forEach(p=>{p.winningSide===1&&i[0]++,p.winningSide===2&&i[1]++});let s=i[0]===o-1&&i[1]===o-1,a=s&&r.finalSetFormat?r.finalSetFormat:r.setFormat;if(!a)return;let c=e.side1Score||0,u=e.side2Score||0;if(a.tiebreakSet){let p=a.tiebreakSet.tiebreakTo||11,d=a.tiebreakSet.NoAD||!1?1:2;(c>=p||u>=p)&&Math.abs(c-u)>=d&&(e.winningSide=c>u?1:2)}else if(!a.timed){let p=lM(c,u,a,s,r.finalSetFormat);typeof p=="number"&&(e.winningSide=p+1)}}checkMatchCompletion(){let e=oe(this.state.matchUpFormat);if(!e)return;let r=e.exactly||e.bestOf||3,n=Math.ceil(r/2);QS(this.state,e,n)}rebuildFromEntries(){let e=this.state.history?.entries??[],r=this.prepareRebuildState(e);this.state=r;for(let n of e)switch(n.type){case"point":this.state=Cs(this.state,n.data,{pointMultipliers:this.pointMultipliers}),this.state.history.entries=r.history.entries;break;case"set":this.applyAddSet(n.data);break;case"game":this.applyAddGame(n.data);break;case"endSegment":this.applyEndSegment(n.data);break;case"substitution":this.applySubstitution(n.data);break;case"setInitialScore":break;case"setServer":this.replaySetServerEntry(n.data);break}}prepareRebuildState(e){let r=this.getInitialLineUps(),n=ns({matchUpFormat:this.matchUpFormat,matchUpId:this.matchUpId,isDoubles:this.isDoubles});if(r)for(let o of n.sides)r[o.sideNumber]&&(o.lineUp=r[o.sideNumber].map(i=>({...i})));return this.initialScore&&(this.applyInitialScore(n,this.initialScore),n.matchUpStatus==="TO_BE_PLAYED"&&(n.matchUpStatus="IN_PROGRESS")),n.history={points:[],entries:[...e]},n}replaySetServerEntry(e){let r=[0,0];this.state.score.sets.forEach(i=>{i.winningSide===1&&r[0]++,i.winningSide===2&&r[1]++});let n=wu(this.cachedFormatStructure,r),o=kA(this.state,this.cachedFormatStructure,n);this.state.serverFlip=e.side!==o}rebuildState(){let e=this.state.history?.points??[],r=ns({matchUpFormat:this.matchUpFormat,matchUpId:this.matchUpId,isDoubles:this.isDoubles});this.initialScore&&(this.applyInitialScore(r,this.initialScore),r.matchUpStatus==="TO_BE_PLAYED"&&(r.matchUpStatus="IN_PROGRESS"));for(let n of e)r=Cs(r,{winner:n.winner,server:n.server,timestamp:n.timestamp,rallyLength:n.rallyLength,result:n.result},{pointMultipliers:this.pointMultipliers});this.state=r}applyInitialScore(e,r){e.score.sets=[];for(let n=0;n<r.sets.length;n++){let o=r.sets[n],i={setNumber:n+1,side1Score:o.side1Score,side2Score:o.side2Score};if(o.side1TiebreakScore!==void 0&&(i.side1TiebreakScore=o.side1TiebreakScore),o.side2TiebreakScore!==void 0&&(i.side2TiebreakScore=o.side2TiebreakScore),o.winningSide===void 0){let s=this.cachedFormatStructure,c=(s?.finalSetFormat&&n===(s.bestOf??s.exactly??3)-1?s.finalSetFormat:s?.setFormat)?.setTo;c&&(o.side1Score>=c||o.side2Score>=c)&&(o.side1Score>o.side2Score?i.winningSide=1:o.side2Score>o.side1Score&&(i.winningSide=2))}else i.winningSide=o.winningSide;e.score.sets.push(i)}if(r.currentSetScore){let n={setNumber:e.score.sets.length+1,side1Score:r.currentSetScore.side1Score,side2Score:r.currentSetScore.side2Score,side1GameScores:[],side2GameScores:[]};r.currentGameScore?(n.side1GameScores=[r.currentGameScore.side1Points],n.side2GameScores=[r.currentGameScore.side2Points]):(n.side1GameScores=[0],n.side2GameScores=[0]),e.score.sets.push(n)}}};var IM={};Gt(IM,{addPoint:()=>Cs,calculatePointsTo:()=>yd,createMatchUp:()=>ns,inferServeSide:()=>KS,resolvePointValue:()=>zS});var _M={};Gt(_M,{keyValueScore:()=>OM,parseMatchUpFormat:()=>oe,stringifyMatchUpFormat:()=>mp});var _1="COMPLETED";var VK="WO/WO";var GA=["RET","DEF","WO",VK,"ABN","SUS","INT"];var VA="DEFAULTED";var SM="WALKOVER";var BA="ABANDONED",WA="SUSPENDED",hM="RETIRED",HA="INTERRUPTED";var x1=[hM,VA,SM],BK="Enter Score",aa="()",ca="[]",TM=["up","left","shift+tab"],yM=["enter","down","tab","right"],vf="backspace",EM="r",AM="s",PM="a",NM="d",DM="w",UM="i",Of=[EM,NM,DM,PM,AM,UM],Ed="space",YA=["[","("],_f=[...TM,...yM,Ed,"]"],w1="-",WK="/",za=w1,Mi=w1,RM=[WK],L1=0,HK=["=","+","num_1","num_2","shift+=","shift+-"],Ka=["0","1","2","3","4","5","6","7","8","9"].concat(Of),F1=Ka.map(t=>`shift+${t}`),bM=[za,vf].concat(_f,RM),CM=[Ka,F1,bM].join(","),YK=[CM,TM,yM,HK].join(","),SJt=[].concat(...Ka,...Ka,...bM,...Ka,...Ka,...Ka,...Ka,...Ka,...Ka),k1={OUTCOMEKEYS:Of,SIDE1KEYS:Ka,SIDE2KEYS:F1,MODIFIERS:bM,PROMPT:BK,MOVEUP:TM,MOVEDOWN:yM,HOTKEYS:YK};function Ad({scoreString:t,lowSide:e,outcome:r}){if({scoreString:t}=G1({scoreString:t}),e===2){let o=t?.[t.length-1]===" "?"":" ";return t+o+r}else return r+" "+t}function G1({scoreString:t}){if(!t)return{scoreString:""};let e=!1;for(let r of GA){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 jK({newScore:t,scoreString:e,lastMatchTiebreakOpenBracketIndex:r,lastSet:n,lowSide:o,NoAD:i,tiebreakTo:s}){let c=t.slice(r+1).split(Mi),u=c?.length>0&&c[0]!==void 0&&!Number.isNaN(Number.parseInt(c[0]))&&Number.parseInt(c[0])||void 0,p=c?.length>1&&c[1]!==void 0&&!Number.isNaN(Number.parseInt(c[1]))&&Number.parseInt(c[1])||void 0,m=[u,p],d=!1;if(p){let l=o===1?1:0;m[l]=(m?.[1-l]||0)+(i?1:2),(m[l]||0)<s&&(m[l]=s),t=e.slice(0,r+1),t+=m.join(Mi)}else u===void 0?(t=e.slice(0,r),d=!0):(t=e.slice(0,r+1),t+=u);return n.side1TiebreakScore=m[0]||0,n.side2TiebreakScore=m[1]||0,{newScore:t,isIncompleteScore:d}}function qK({lastSet:t,sets:e,analysis:r}){let n=t.side1Score?.toString();if(n){let i=n?.slice(0,-1);t.side1Score=Number.parseInt(i)&&!Number.isNaN(Number.parseInt(i))||void 0,t.side1Score===void 0&&(t.side2Score=void 0)}let o;return r.isTimedSet?(o=t.side1Score?e:e?.slice(0,-1)??[],o[e.length-1]=t):o=e?.slice(0,-1)??[],o}function $K({lastSet:t,sets:e,analysis:r}){let n=t.side2Score?.toString(),o=t.side1Score?.toString();if(!r.isTiebreakEntry&&!r.isMatchTiebreak)if(t.side2Score){let s=n?.slice(0,-1);t.side2Score=!isNaN(s)&&parseInt(s)||void 0}else{let s=o?.slice(0,-1);t.side1Score=!isNaN(s)&&parseInt(s)||void 0}let i;return r.isTimedSet?t.side1Score?(i=e??[],i[e.length-1]=t):i=e?.slice(0,e.length-1)??[]:(i=e??[],i[e.length-1]=t),i[i.length-1]&&Object.assign(i[i.length-1],{winningSide:void 0}),i}function ZS({analysis:t,scoreString:e,sets:r,lowSide:n}){let o,i;if(!e)return{scoreString:e,sets:r};let{scoreString:s,removed:a}=G1({scoreString:e});if(e=s,a)return{scoreString:e,sets:r,outcomeRemoved:!0};let c=r.at(-1)??{},u=Object.values(c).filter(g=>g!==void 0).length;c.setNumber&&u===1&&(r=r.slice(0,-1),c=r.at(-1)??{});let{tiebreakSet:p}=t.setFormat,{tiebreakTo:m,NoAD:d}=p??{},{isTiebreakEntry:l}=nm({brackets:ca,scoreString:e}),f=KK(e);if(f>=0){o=e.slice(0,f);let{isTiebreakEntry:g}=nm({brackets:aa,scoreString:o}),{lastOpenBracketIndex:I,isTiebreakEntry:S}=nm({brackets:ca,scoreString:o}),h=o?.length?o[o.length-1].trim():void 0,T=o&&!isNaN(h),y=t.isIncompleteSetScore;return l&&S&&({newScore:o,isIncompleteScore:y}=jK({newScore:o,scoreString:e,lastMatchTiebreakOpenBracketIndex:I,lastSet:c,lowSide:n,NoAD:d,tiebreakTo:m})),o.length||(o=void 0),y?i=qK({lastSet:c,sets:r,analysis:t}):T?i=$K({lastSet:c,sets:r,analysis:t}):g?(i=r??[],Object.assign(i[i.length-1]??{},{winningSide:void 0,side1TiebreakScore:void 0,side2TiebreakScore:void 0})):(l&&!S?i=r?.slice(0,-1)??[]:(i=r,i[r.length-1]=c),l||(i[i.length-1].side2Score=0,i[i.length-1].winningSide=void 0)),{scoreString:o,sets:i}}return{scoreString:e,sets:r}}function nm({brackets:t=aa,scoreString:e}){if(!e)return{};let[r,n]=t.split(""),o=e.split(""),i=Math.max(...us(r,o)),s=Math.max(...us(n,o));return{isTiebreakEntry:i>s,lastOpenBracketIndex:i}}function V1({scoreString:t}){if(!t)return!1;let e=t?.[t.length-1].trim(),r=t&&!isNaN(e),[n,o]=ca.split(""),i=t.split(""),s=Math.max(...us(n,i)),a=Math.max(...us(o,i)),c=Math.max(...us(Mi,i));return r&&s>a&&c>s}function KK(t){return t.split("").reduce((n,o,i)=>(o.match(/\d+/g)&&n.push(i),n),[]).pop()}function jA(t){let{lowValue:e=0,NoAD:r=!1,tiebreakTo:n}=t??{},o=r?1:2;return e+1>=n?e+o:parseInt(n)}function MM({matchUpFormat:t,matchUpStatus:e,winningSide:r,sets:n}){let o=oe(t),{bestOf:i}=o,s=Math.ceil(i/2),c=n?.reduce((u,p)=>{let{winningSide:m}=p;return m&&u[m-1]++,u},[0,0])?.indexOf(s)+1||void 0;return x1.includes(e)&&r&&(c=r),{matchUpWinningSide:c}}function Pd({ignoreTiebreak:t=!1,matchUpScoringFormat:e,matchUpFormat:r,isTiebreakSet:n,isDecidingSet:o,isTimedSet:i,set:s}){if(!s)return{error:nt,info:"missing set"};e=e||r&&oe(r);let a=o&&e.finalSetFormat||(e?.setFormat??{}),{side1Score:c,side2Score:u}=s,{setTo:p,tiebreakAt:m}=a,d=c||u,l=Nd({set:s}),f=Math.abs(c-u),g=c>=p||u>=p,I=n||c>=p&&u>=p||m&&m<p&&(c===m||u===m),S=t||I&&(l===1&&s.side1TiebreakScore>s.side2TiebreakScore||l===2&&s.side2TiebreakScore>s.side1TiebreakScore),h=!I&&a.NoAD||I||n&&a.tiebreakFormat?.NoAD?1:2,T=f>=h;return!!((i&&d||g&&(T||I)||n)&&(!I||S))}function Nd({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 xf({analysis:t,set:e}){let r=Nd({set:e}),{isDecidingSet:n,isTiebreakSet:o,matchUpScoringFormat:i}=t;return Pd({matchUpScoringFormat:i,isDecidingSet:n,isTiebreakSet:o,set:e})&&r}function B1({analysis:t,scoreString:e,sets:r,value:n}){let o;if(!r?.length)return{sets:[]};let i=r[r.length-1];n=st(n);let{validSide2Score:s,requiresTiebreak:a}=zK({analysis:t,set:i,value:n});if(s){o=!0,e=(e||"")+n,i.side2Score=n;let c=xf({analysis:t,set:r[r.length-1]});if(i.winningSide=c||void 0,a){let u=aa.split("")[0];e+=u}else t.isDecidingSet||(e+=" ")}return{sets:r,scoreString:e,updated:o}}function zK({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 qA({lowSide:t,value:e,sets:r,scoreString:n,winningSide:o,matchUpStatus:i}){let s;return e===EM?n?(s=!0,n=Ad({scoreString:n,lowSide:t,outcome:"RET"}),o=t===2?1:2,i=hM):(s=!0,n=Ad({scoreString:n,lowSide:t,outcome:"DEF"}),o=t===2?1:2,i=VA):e===NM?(s=!0,n=Ad({scoreString:n,lowSide:t,outcome:"DEF"}),o=t===2?1:2,i=VA):e===DM?(s=!0,r=[],n="WO",o=t===2?1:2,i=SM):e===AM&&n?(s=!0,n=Ad({scoreString:n,lowSide:t,outcome:"SUS"}),i=WA,o=void 0):e===PM?(s=!0,n=Ad({scoreString:n,lowSide:t,outcome:"ABN"}),i=BA,o=void 0):e===UM&&n&&(s=!0,n=Ad({scoreString:n,lowSide:t,outcome:"INT"}),i=HA,o=void 0),{updated:s,sets:r,scoreString:n,matchUpStatus:i,winningSide:o}}function H1(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!==vf&&(e=[{setNumber:1}]);let m=e.length-1;if(Of.includes(c))({sets:e,info:r,scoreString:n,winningSide:o,matchUpStatus:i,updated:u}=tz({sets:e,info:r,scoreString:n,winningSide:o,matchUpStatus:i,analysis:s,lowSide:a,value:c}));else if(c===vf)({scoreString:n,sets:e,outcomeRemoved:p}=ZS({analysis:s,scoreString:n,sets:e})),{sets:e,scoreString:n,winningSide:o,matchUpStatus:i,updated:u}=ez({sets:e,scoreString:n,outcomeRemoved:p});else if(s.hasOutcome)r="has outcome";else{if(o)return{sets:e,scoreString:n,winningSide:o,matchUpStatus:i,updated:!1,info:"matchUp is complete"};c===Ed?{sets:e,scoreString:n,updated:u}=rz({sets:e,scoreString:n,winningSide:o,analysis:s}):c===za&&e[m].side1Score!==void 0&&e[m].side2Score===void 0&&n&&s.isNumericEnding?(n+="-",e[m].side2Score=0,i=void 0,o=void 0,u=!0):Number.isNaN(Number(c))||({sets:e,scoreString:n,updated:u}=nz({sets:e,setIndex:m,value:c,scoreString:n}))}return{sets:e,scoreString:n,winningSide:o,matchUpStatus:i,info:r,updated:u}}function tz({sets:t,info:e,scoreString:r,winningSide:n,matchUpStatus:o,analysis:i,lowSide:s,value:a}){let c,u=t.at(-1)??{},{side1Score:p,side2Score:m}=u;return p&&!m?e="missing side2Score":i.finalSetIsComplete||n?e="final set is already complete":i.isIncompleteSetScore?e="incomplete set scoreString":{sets:t,scoreString:r,winningSide:n,matchUpStatus:o,updated:c}=qA({lowSide:s,value:a,sets:t,scoreString:r,matchUpStatus:o,winningSide:n}),{sets:t,info:e,scoreString:r,winningSide:n,matchUpStatus:o,updated:c}}function ez({sets:t,scoreString:e,outcomeRemoved:r}){let n=e,o=t;if(n?.trim()===""&&(n=n.trim()),n||(o=[]),r){let i=o.at(-1)??{},{side1Score:s,side2Score:a}=i;if(s&&a){let c=s>a&&1||a>s&&2||void 0;c&&(i.winningSide=c,o.push({setNumber:o.length+1}))}}return{sets:o,scoreString:n,winningSide:void 0,matchUpStatus:void 0,updated:!0}}function rz({sets:t,scoreString:e,winningSide:r,analysis:n}){let o,i=e,s=t.at(-1)??{},{side1Score:a,side2Score:c}=s,u=a>c&&1||c>a&&2||void 0;return u&&!r&&!n.isIncompleteSetScore&&(t.at(-1).winningSide=u,t.push({setNumber:t.length+1}),i+=" ",o=!0),{sets:t,scoreString:i,updated:o}}function nz({sets:t,setIndex:e,value:r,scoreString:n}){let o,i,s=n;if(t[e].side2Score===void 0){let a=st((t[e].side1Score||0).toString()+r).toString().slice(0,2);t[e].side1Score=st(a),o=t[e].side1Score.toString(),i=!0}else{let a=st((t[e].side2Score||0).toString()+r).toString().slice(0,2);t[e].side2Score=st(a),o=[t[e].side1Score,t[e].side2Score].join("-"),i=!0}if(i){let a=(t.slice(0,e)??[]).filter(c=>c).map(c=>[c.side1Score,c.side2Score].join("-")).join(" ");s=a?a+" "+o:o}return{sets:t,scoreString:s,updated:i}}function Y1({analysis:t,auto:e,lowSide:r,scoreString:n="",sets:o,value:i}){let s,a,{tiebreakSet:{tiebreakTo:c,NoAD:u}}=t.setFormat,[p]=ca.split("");if(t.isMatchTiebreakEntry||(n+=p),o[t.setNumber-1]){let{lastOpenBracketIndex:d}=nm({brackets:ca,scoreString:n}),f=(n.slice((d??0)+1)+(e?"":i)).split(Mi);if((f[r-1]?.length||0)>=2)a="tiebreak digit limit";else if(e){r===1&&(f[0]=(f[0]||"")+i),r===2&&(f[1]=(f[1]||"")+i);let I=[f[0]||0,f[1]||0].map(T=>st(T)),S=r===1?1:0;I[S]=I[1-S]+(u?1:2),I[S]<c&&(I[S]=c);let h=o[o.length-1];h.side1TiebreakScore=I[0],h.side2TiebreakScore=I[1],n=n.slice(0,(d??0)+1),n+=I.join(Mi),s=!0}else{let I=[f[0]||0,f[1]||0].map(h=>st(h)),S=o[o.length-1];S.side1TiebreakScore=I[0],S.side2TiebreakScore=I[1],n+=i,s=!0}}else{let d=jA({lowValue:st(i||0),tiebreakTo:c,NoAD:u}),l=[st(i),d];r===2&&l.reverse();let f={side1TiebreakScore:l[0],side2TiebreakScore:l[1],setNumber:o?.length+1||1};o.push(f),n+=l.join(Mi),s=!0}return{info:a,scoreString:n,sets:o,updated:s}}function j1({analysis:t,lowSide:e,scoreString:r,value:n}){let{setTo:o,tiebreakAt:i,NoAD:s}=t?.setFormat??{},a=n===parseInt(i||o);if(i&&i<o&&n>i)return{scoreString:r};if(s&&n===o&&!a||n>o)return{scoreString:r};let c=g(),u=[n,c];e===2&&u.reverse();let m=aa.split("")[0],d=u.join(za)+(a?m:" ");r=(r||"")+d;let l={side1Score:u[0],side2Score:u[1]},f=xf({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 q1({matchUpFormat:t,scoreString:e,winningSide:r,value:n,sets:o}){let s=(o?.filter(z=>z?.winningSide)?.length||0)+(r?0:1),a=oe(t),c=s===a?.bestOf,u=c&&a?.finalSetFormat||(a?.setFormat??{}),p=u?.timed,m=c&&o[a?.bestOf-1],d=m?.winningSide,{isTiebreakEntry:l}=nm({brackets:aa,scoreString:e}),{isTiebreakEntry:f}=nm({brackets:ca,scoreString:e}),g=l||f,I=!!u.tiebreakSet,S=e?.[e.length-1]?.trim(),h=e&&!isNaN(S),T=!g&&S===za,y=l&&YA.includes(S),E=f&&YA.includes(S),A=f&&S===Mi,N=e?.split(""),[D]=ca.split(""),R=N&&Math.max(...us(D,N)),U=N&&Math.max(...us(Mi,N)),b=N&&U>R,C=o[o.length-1]?.winningSide,_=o?.length&&!C,v=GA.find(z=>e?.indexOf(z)>=0),w=!isNaN(n),L=n===Ed,F=_f.includes(n),x=e?.split("").find(z=>YA.includes(z)),k=F&&f&&!E&&(A||!V1({scoreString:e}));return{isTiebreakSetValue:I&&w,matchUpScoringFormat:a,setNumber:s,setFormat:u,matchTiebreakHasJoiner:b,isGameScoreEntry:_,isSpace:L,isCloser:F,isTiebreakCloser:F&&x&&g&&h,isDecidingSet:c,isTiebreakSet:I,isTimedSet:p,isNumericEnding:h,isNumericValue:w,hasOpener:x,hasOutcome:v,finalSet:m,finalSetIsComplete:d,lastSetIsComplete:C,isInvalidSetTiebreakValue:L&&g&&y,isInvalidMatchTiebreakValue:k,isTiebreakEntry:g,isSetTiebreakEntry:l,isMatchTiebreakEntry:f,isIncompleteSetScore:T,isIncompleteSetTiebreak:y,isIncompleteMatchTiebreak:E,isPartialMatchTiebreakValue:A}}function oz({analysis:t,lowSide:e,sets:r,scoreString:n,matchUpStatus:o,winningSide:i,value:s}){let a,c;return t.finalSetIsComplete||i?a="final set is already complete":!t.isTiebreakEntry&&!t.isIncompleteSetScore?{sets:r,scoreString:n,matchUpStatus:o,winningSide:i,updated:c}=qA({lowSide:e,sets:r,scoreString:n,matchUpStatus:o,winningSide:i,value:s}):t.isTiebreakEntry||t.isIncompleteSetScore?a="incomplete set scoreString or tiebreak entry":console.log("handle case",{value:s}),{info:a,sets:r,scoreString:n,matchUpStatus:o,winningSide:i,updated:c}}function iz({analysis:t,scoreString:e,sets:r,lowSide:n}){return{scoreString:e,sets:r}=ZS({analysis:t,scoreString:e,sets:r,lowSide:n}),e||(r=[]),{scoreString:e,sets:r,updated:!0,matchUpStatus:void 0,winningSide:void 0}}function sz({analysis:t,scoreString:e,sets:r,lowSide:n}){let o,i;return(!t.isSetTiebreakEntry||t.isSetTiebreakEntry&&!t.isNumericEnding)&&(o=!0,{scoreString:e,sets:r}=ZS({analysis:t,scoreString:e,sets:r,lowSide:n}),i=void 0),{scoreString:e,sets:r,updated:o,matchUpStatus:i}}function az({analysis:t,scoreString:e}){let r,n;return t.matchTiebreakHasJoiner?r="existing joiner":t.isNumericEnding&&(n=!0,e+=Mi),{info:r,scoreString:e,updated:n}}function cz({analysis:t,scoreString:e,sets:r}){let n=t.isSetTiebreakEntry?aa:ca,o=n.split("").reverse()[0],i=n.split("")[0],s=r[r.length-1],{tiebreakFormat:a}=t.setFormat,{tiebreakTo:c,NoAD:u}=a??{},p=Nd({set:s});if(!t.isTiebreakSet){let d=Number.parseInt(e.split(i).reverse()[0]),l=jA({lowValue:d,tiebreakTo:c,NoAD:u});p===1?(s.side1TiebreakScore=l,s.side2TiebreakScore=d):(s.side1TiebreakScore=d,s.side2TiebreakScore=l)}e=(e||"")+o,t.isDecidingSet||(e+=" ");let m=xf({analysis:t,set:s});return s.winningSide=m||void 0,{scoreString:e,sets:r,updated:!0}}function uz({analysis:t,scoreString:e,value:r}){let n,o,[i]=aa.split(""),s=Math.max(...us(i,e.split(""))),a=e.slice(s+1),c=a&&st(a)===L1,u=st(a?a+r:r),{tiebreakFormat:p}=t.setFormat,{tiebreakTo:m,NoAD:d}=p??{};return!c&&a.length<2?d&&u>m-1?n="invalid low value for NoAD tiebreak":(o=!0,e=(e||"")+r):n=c?"tiebreak begins with zero":"tiebreak digit limit",{info:n,scoreString:e,updated:o}}function pz({analysis:t,lowSide:e,scoreString:r,sets:n,value:o}){let{scoreString:i,set:s}=j1({analysis:t,lowSide:e,scoreString:r,value:st(o)});return s&&(s.setNumber=n?.length+1||1),n=n?.concat(s).filter(Boolean)||[s],r=i||void 0,{scoreString:r,sets:n,updated:!0}}function mz({sets:t,winningSide:e,matchUpStatus:r,matchUpFormat:n,scoreString:o,info:i}){t=t?.filter(Boolean);let{matchUpWinningSide:s}=MM({sets:t,winningSide:e,matchUpStatus:r,matchUpFormat:n});return e=s,s&&(!r||[zt,Xr].includes(r))?(r=_1,t=t.filter(a=>{let{side1Score:c,side2Score:u,side1TiebreakScore:p,side2TiebreakScore:m}=a;return c||u||p||m})):o&&!e&&![WA,BA,HA].includes(r)&&(r=void 0),{updated:!0,scoreString:o,sets:t,winningSide:e,matchUpStatus:r,info:i}}function OM(t){let{lowSide:e=1,value:r}=t,{scoreString:n,sets:o,winningSide:i,matchUpStatus:s}=t,{matchUpFormat:a,shiftFirst:c,auto:u=!0}=t;if(!CM.includes(r))return{updated:!1,info:"invalid key"};c&&(e=3-e);let p=c&&e===2||!c&&e===1,{matchUpWinningSide:m}=MM({sets:o,winningSide:i,matchUpStatus:s,matchUpFormat:a});i=m;let d=q1({value:r,winningSide:i,scoreString:n,sets:o,matchUpFormat:a});({value:r,scoreString:n}=dz({analysis:d,value:r,scoreString:n,isShifted:p}));let l=lz({analysis:d,lowSide:e,sets:o,scoreString:n,matchUpStatus:s,winningSide:i,value:r,auto:u});if(l.earlyReturn)return{updated:l.updated,info:l.info};({sets:o,scoreString:n,matchUpStatus:s,winningSide:i}=l);let{updated:f,info:g}=l;return f?mz({sets:o,winningSide:i,matchUpStatus:s,matchUpFormat:a,scoreString:n,info:g}):{updated:f,scoreString:n,sets:o,winningSide:i,matchUpStatus:s,info:g}}function dz({analysis:t,value:e,scoreString:r,isShifted:n}){let o=e,i=r;if(RM.includes(o)&&(o=za),t.hasOpener&&t.isTiebreakEntry&&!t.isTiebreakSet&&n&&st(o)===0&&(t.isTiebreakCloser=!0),_f.includes(o)&&t.hasOpener&&(o=""),_f.includes(o)&&(o=Ed),t.lastSetIsComplete){let s=i?.length&&i.at(-1);i&&s!==" "&&(i+=" ")}return{value:o,scoreString:i}}function lz({analysis:t,lowSide:e,sets:r,scoreString:n,matchUpStatus:o,winningSide:i,value:s,auto:a}){let c,u,p=r,m=n,d=o,l=i;if(t.isTimedSet)({info:c,sets:p,scoreString:m,updated:u,matchUpStatus:d,winningSide:l}=H1({analysis:t,lowSide:e,scoreString:n,sets:r,matchUpStatus:o,winningSide:i,value:s}));else if(Of.includes(s))({info:c,sets:p,scoreString:m,matchUpStatus:d,winningSide:l,updated:u}=oz({analysis:t,lowSide:e,sets:r,scoreString:n,matchUpStatus:o,winningSide:i,value:s}));else if(s===vf)({scoreString:m,sets:p,updated:u,matchUpStatus:d,winningSide:l}=iz({analysis:t,scoreString:n,sets:r,lowSide:e}));else if(t.hasOutcome)c="has outcome";else if(s===za&&!t.isMatchTiebreakEntry)({scoreString:m,sets:p,updated:u,matchUpStatus:d}=sz({analysis:t,scoreString:n,sets:r,lowSide:e}));else if(s===Mi&&t.isMatchTiebreakEntry&&!t.isSetTiebreakEntry)({info:c,scoreString:m,updated:u}=az({analysis:t,scoreString:n}));else if([za,Mi].includes(s))c="invalid location for joiner";else{if(i)return{earlyReturn:!0,updated:!1,info:"matchUp is complete"};({info:c,updated:u,sets:p,scoreString:m}=fz({analysis:t,auto:a,lowSide:e,scoreString:n,sets:r,value:s}))}return{info:c,updated:u,sets:p,scoreString:m,matchUpStatus:d,winningSide:l}}function fz({analysis:t,auto:e,lowSide:r,scoreString:n,sets:o,value:i}){let s,a,c=o,u=n;return t.isIncompleteSetScore?t.isNumericValue&&({sets:c,scoreString:u,updated:a}=B1({analysis:t,scoreString:n,sets:o,value:i})):t.isInvalidMatchTiebreakValue?s="invalid matchUp tiebreak character":t.isInvalidSetTiebreakValue?s="invalid set tiebreak character":t.isTiebreakCloser?{scoreString:u,sets:c,updated:a}=cz({analysis:t,scoreString:n,sets:o}):t.isTiebreakSetValue?{info:s,scoreString:u,sets:c,updated:a}=Y1({analysis:t,auto:e,lowSide:r,scoreString:n,sets:o,value:i}):t.isSetTiebreakEntry?{info:s,scoreString:u,updated:a}=uz({analysis:t,scoreString:n,value:i}):t.isCloser?s=`invalid key: ${i}`:t.isGameScoreEntry?s="game scoreString entry":t.lastSetIsComplete||!o.length?{scoreString:u,sets:c,updated:a}=pz({analysis:t,lowSide:r,scoreString:n,sets:o,value:i}):console.log("error: unknown outcome"),{info:s,updated:a,sets:c,scoreString:u}}var LM={};Gt(LM,{analyzeScore:()=>th,analyzeSet:()=>om,calculateMatchStatistics:()=>Cf,checkScoreHasValue:()=>ue,checkSetIsComplete:()=>Pd,deduceMatchUpFormat:()=>bd,enrichPointHistory:()=>uM,getEpisodes:()=>jS,getQuickStats:()=>pM,getScore:()=>os,getScoreboard:()=>YS,getSetComplement:()=>rh,getTiebreakComplement:()=>Ud,getWinner:()=>$S,isComplete:()=>qS,isValidMatchUpFormat:()=>xr,parseScoreString:()=>Rd,toStatObjects:()=>Mf,validateMatchUpScore:()=>xM,validateScore:()=>eh,validateSetScore:()=>$A,validateTieFormat:()=>or});function gz(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 Iz(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 Sz(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 hz(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 Tz(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 yz(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 Ez(t,e,r,n,o,i,s){if(r&&n){let c=Iz(t,e,r,n);if(!c.isValid)return c}return(o!==void 0||i!==void 0)&&s?Sz(o,i,s):{isValid:!0}}function Az(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 Pz(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=hz(n,o,c,u);if(!p.isValid)return p}return r?Az(i,s,c):c?Tz(i,s,a,c,u):{isValid:!0}}function $A(t,e,r,n){if(!e)return{isValid:!0};let o=oe(e);if(!o)return{isValid:!0};let i=r&&o.finalSetFormat?o.finalSetFormat:o.setFormat;if(!i)return{isValid:!0};if(i.timed){if(!n){let N=t.side1Score??0,D=t.side2Score??0;if(N===0&&D===0)return{isValid:!1,error:"Timed set requires at least one side to have scored"};if(i.based==="P"&&N===D&&N>0&&i.tiebreakFormat&&!(t.side1TiebreakScore!==void 0||t.side2TiebreakScore!==void 0))return{isValid:!1,error:"Tied timed set requires tiebreak"}}return{isValid:!0}}let{setTo:s,tiebreakAt:a,tiebreakFormat:c,tiebreakSet:u}=i,p=u?.tiebreakTo,m=!!p&&!s,d=t.side1TiebreakScore!==void 0&&t.side2TiebreakScore!==void 0,{side1Score:l,side2Score:f,side1TiebreakScore:g,side2TiebreakScore:I}=yz(t,m,d),S=Math.max(l,f),h=Math.min(l,f),T=S-h;if(m){let N=t.NoAD??i.tiebreakSet?.NoAD??!1;return gz(S,h,T,p,n??!1,N)}let y=g!==void 0||I!==void 0,E=s&&S===s+1&&h===s;return y||E?Ez(S,h,s,a,g,I,c):Pz({side1:l,side2:f,winner:S,loser:h,diff:T},{setTo:s,tiebreakAt:a},n)}function xM(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=[De,vt,Mt].includes(r||"");for(let s=0;s<t.length;s++){let a=t[s],c=s+1===o,u=a.winningSide!==void 0,d=$A(a,e,c,i||r===void 0&&!u);if(!d.isValid)return{isValid:!1,error:`Set ${s+1}: ${d.error}`}}return{isValid:!0}}function Dd(t){return!!t?.aggregate}function Nz(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 Dz(t,e,r,n,o,i){let a=e+1===n,{side1Score:c,side2Score:u,side1TiebreakScore:p,side2TiebreakScore:m,winningSide:d}=t,l=Math.max(c??0,u??0),f=p??m,{finalSetFormat:g,setFormat:I}=r,S=a&&g||I;return f&&!Nz(S?.tiebreakFormat,p,m,d,o,i)?!1:S.setTo?!(!S.noTiebreak&&l>S.setTo+1):!0}function Uz(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 Rz(t,e,r,n,o){return(!o||t===e)&&r===1&&n.indexOf(t)+1||void 0}function th({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}){let i=o?.sets??[],a=(i?.filter(U=>U?.winningSide)??[]).reduce((U,b)=>{let{winningSide:C}=b;if(!C)return U;let _=C-1;return U[_]++,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?oe(e):void 0,l=Math.max(...a),f=mn(a)[l],g=d?.setFormat?.timed||d?.finalSetFormat?.timed,I=d?.bestOf||d?.exactly,S=I&&Math.ceil(I/2)||1,h=r??t,T=!!(h&&[Mt,De,vt].includes(h)),y=!d||!i.length||i.every((U,b)=>Dz(U,b,d,I??0,b===i.length-1,T)),E=d?.exactly,A=!E||!h||h!==ie||T||i.length>=E,N=Dd(d),D=N&&i.length>0?Uz(i):Rz(l,S,f,a,e);return{valid:!!(y&&A&&(n&&N&&n===D||n&&!N&&p>m&&n===D||n&&T||!n&&!D&&(![ie,Mt,De,vt].includes(h)||g&&h===ie)))}}function eh({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}){if(typeof o!="object")return{error:O};let{sets:i,scoreStringSide1:s,scoreStringSide2:a}=o,c="scoreString must be a string!";if(s!==void 0&&typeof s!="string")return{error:O,info:c};if(a!==void 0&&typeof a!="string")return{error:O,info:c};if(i!==void 0&&!Array.isArray(i))return{error:O,info:Ri("sets")};if(i?.length){let u=i.map(m=>m?.setNumber).filter(Boolean);if(u.length!==pt(u).length)return{error:O,info:"setNumbers not unique"};for(let m of i){let{side1Score:d,side2Score:l,side1TiebreakScore:f,side2TiebreakScore:g,side1PointScore:I,side2PointScore:S,winningSide:h,setNumber:T}=m;if(![[d,l],[f,g]].filter(D=>D.some(R=>![void 0,null].includes(R))).every(D=>D.every(R=>yt(R))))return{error:O,info:"non-numeric values"};let E=[I,S];if(E.some(D=>D!=null)&&!E.every(D=>D!=null))return{error:O,info:"both sides must have point scores if one does"};if(![T,h].filter(D=>![void 0,null].includes(D)).every(D=>yt(D)))return{error:O,info:"non-numeric values"};if(h&&![1,2].includes(h))return{error:O,info:"winningSide must be 1 or 2"}}let{valid:p}=th({existingMatchUpStatus:t,matchUpStatus:r,matchUpFormat:e,winningSide:n,score:o});if(!p)return{error:aU,info:"score is invalid for matchUpFormat or winningSide does not match calculated winningSide"}}return{valid:!0}}var rh=t=>{let{isSide1:e,lowValue:r,setTo:n,tiebreakAt:o,NoAD:i}=t;if(r===void 0)return!1;let s=st(r);s?.toString().length>2&&(s=Number.parseInt(s.toString().slice(0,2))),o&&o<n&&s>o&&(s=o);let a;return i&&!o?s>n?a=n:a=s<n?n:n-1:a=s+1<n&&n||o&&o<n&&s===o&&n||!o&&s+2||n+1,[e?s:a,e?a:s]},Ud=t=>{let{isSide1:e,lowValue:r,tiebreakTo:n,tiebreakNoAd:o}=t;if(r===void 0)return!1;let i=typeof r=="string"?Number.parseInt(r):r;i?.toString().length>2&&(i=Number.parseInt(i.toString().slice(0,2))),o&&i>n-1&&(i=n-1);let s=bz({lowValue:i,NoAD:o,tiebreakTo:n});return[e?i:s,e?s:i]};function bz(t){let{lowValue:e,NoAD:r,tiebreakTo:n}=t,o=r?1:2;return e+1>=n?e+o:n}function wM(t,e){return t>e&&1||t<e&&2||void 0}function Cz(t,e){return e?{side1Score:t[0],side2Score:t[1],winningSide:wM(t[0],t[1])}:{side1TiebreakScore:t[0],side2TiebreakScore:t[1],winningSide:wM(t[0],t[1])}}function Rd({tiebreakTo:t=7,scoreString:e="",matchUpFormat:r}){let n,o=3;if(r)try{n=oe(r);let p=/SET(\d+)/.exec(r)?.[1];o=p?Number.parseInt(p):3}catch{}return e?.split(" ").filter(Boolean).map((p,m)=>u({set:p,setNumber:m+1}));function i(p,m){if(!n||!m)return!1;let l=p===o&&n.finalSetFormat?n.finalSetFormat:n.setFormat;if(!l)return!1;let f=l.tiebreakSet?.tiebreakTo,g=l.setTo;return!!f&&!g}function s(p){if(!n)return t;let d=p===o&&n.finalSetFormat?n.finalSetFormat:n.setFormat;return d?.tiebreakSet?.tiebreakTo??d?.tiebreakFormat?.tiebreakTo??t}function a(p,m,d){let l=p[1],f=s(d),g=Ud({lowValue:l,isSide1:m===2,tiebreakTo:f});return Array.isArray(g)?[g[0],g[1]]:[void 0,void 0]}function c(p,m,d,l){let g=(m&&p.replace(m[0],"")||d&&p.replace(d[0],"")||p).split("-").map(E=>Number.parseInt(E)),I=g[0],S=g[1],h=wM(I,S),T,y;if(m&&([T,y]=a(m,h,l)),d){let E=d[1].split("-").map(A=>Number.parseInt(A));T=E[0],y=E[1]}return{side1Score:I,side2Score:S,side1TiebreakScore:T,side2TiebreakScore:y,winningSide:h}}function u({set:p,setNumber:m}){let d=/\(([^)]+)\)/,l=/\[([^\]]+)\]/,f=d.exec(p),g=l.exec(p),I=p?.startsWith("[")&&g,S=i(m,!!I),h=s(m),T=S&&h===1,y;if(I){let E=g[1].split("-").map(A=>Number.parseInt(A));y=Cz(E,S)}else y=c(p,f,g,m);return{side1Score:y.side1Score,side2Score:y.side2Score,side1TiebreakScore:y.side1TiebreakScore,side2TiebreakScore:y.side2TiebreakScore,winningSide:y.winningSide,setNumber:m,...T&&{NoAD:!0},...S&&{tiebreakSet:!0}}}}function $1({matchUpScoringFormat:t,isDecidingSet:e,isTiebreakSet:r,isTimedSet:n,setObject:o}){if(!o)return;let i=Nd({set:o});return Pd({matchUpScoringFormat:t,set:o,isDecidingSet:e,isTiebreakSet:r,isTimedSet:n})&&i||void 0}function om(t){let{setObject:e,matchUpScoringFormat:r}=t;if(!e)return{error:Yg};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=Mz(e),{sideGameScores:f,sidePointScores:g,sideTiebreakScores:I}=l,S=f.filter(k=>k!==void 0).length,h=g.filter(k=>k!==void 0).length,T=I.filter(k=>k!==void 0).length,y=f?.filter(k=>typeof k=="number"&&!Number.isNaN(k)).length,E=I?.filter(k=>typeof k=="number"&&!Number.isNaN(k)).length,{tiebreakAt:A}=c??{},N=A&&f.filter(k=>k>=A).length===2,D=vz(N,f),R=!!(E&&!y),U=!!e?.winningSide,{error:b,result:C}=xz({sideTiebreakScores:I,sideGameScores:f,setFormat:c,setObject:e}),{error:_,result:v}=Lz({sideTiebreakScores:I,setObject:e,setFormat:c}),w=Oz({isValidStandardSetOutcome:C,isValidTiebreakSetOutcome:v,expectStandardSet:m,expectTiebreakSet:u,expectTimedSet:p,isTiebreakSet:R}),L=d&&!(u&&!R)&&!(m&&R)&&(!U||w),F=$1({isTimedSet:p,matchUpScoringFormat:r,isDecidingSet:a,isTiebreakSet:R,setObject:e}),x={expectTiebreakSet:u,expectTimedSet:p,hasTiebreakCondition:N,isCompletedSet:U,isDecidingSet:a,isTiebreakSet:R,isValidSet:L,isValidSetNumber:d,isValidSetOutcome:w,leadingSide:D,setFormat:c,sideGameScores:f,sideGameScoresCount:S,sidePointScores:g,sidePointScoresCount:h,sideTiebreakScores:I,sideTiebreakScoresCount:T,winningSide:F};return e?.winningSide!==void 0&&_z({isValidStandardSetOutcome:C,isValidTiebreakSetOutcome:v,standardSetError:b,tiebreakSetError:_,isTiebreakSet:R,analysis:x}),x}function Mz(t){return{sideGameScores:[t?.side1Score,t?.side2Score],sidePointScores:[t?.side1PointScore,t?.side2PointScore],sideTiebreakScores:[t?.side1TiebreakScore,t?.side2TiebreakScore]}}function vz(t,e){if(t){if(e[0]>e[1])return 1;if(e[1]>e[0])return 2}}function Oz({isValidStandardSetOutcome:t,isValidTiebreakSetOutcome:e,expectStandardSet:r,expectTiebreakSet:n,expectTimedSet:o,isTiebreakSet:i}){return r&&!i&&t||n&&i&&e||o}function _z({isValidStandardSetOutcome:t,isValidTiebreakSetOutcome:e,standardSetError:r,tiebreakSetError:n,isTiebreakSet:o,analysis:i}){o?(i.isValidTiebreakSetOutcome=e,e||(i.tiebreakSetError=n)):(i.isValidStandardSetOutcome=t,t||(i.standardSetError=r))}function xz({setObject:t,setFormat:e,sideGameScores:r,sideTiebreakScores:n}){if(!t)return{result:!1,error:Yg};let o=!!e?.tiebreakSet,i=!!e?.timed;if(!e||o||i)return{result:!1,error:O};if(!(r?.filter(R=>typeof R=="number"&&!Number.isNaN(R)).length===2))return{result:!1,error:YT};let{setTo:a,tiebreakAt:c,tiebreakFormat:u,NoAD:p}=e??{};if(!!!(a&&r?.find(R=>R>=a)))return{result:!1,error:YT};let l=new Set([1,2]).has(t?.winningSide);if(!t||!l)return{result:!1,error:sl};let f=t?.winningSide-1,g=1-f,I=r[f],S=r[g],h=I-S;if(!(I>S))return{result:!1,error:{message:"winningSide game scoreString is not high"}};let y=wz({winningSideGameScore:I,sideTiebreakScores:n,winningSideIndex:f,losingSideIndex:g,sideGameScores:r,gamesDifference:h,tiebreakFormat:u,tiebreakAt:c,setTo:a});if(y)return y;let E=c&&r.filter(R=>R>=c).length===2,A=p?1:2,N=S>=a-1;return h&&N&&!E&&h<A?{result:!1,error:{message:"invalid winning game scoreString (3)"}}:h>A&&I>a?{result:!1,error:{message:"invalid winning game scoreString (4)"}}:{result:!0}}function wz({winningSideGameScore:t,sideTiebreakScores:e,winningSideIndex:r,losingSideIndex:n,sideGameScores:o,gamesDifference:i,tiebreakFormat:s,tiebreakAt:a,setTo:c}){if(!(a&&s))return;let p=e?.filter(S=>typeof S=="number"&&!Number.isNaN(S)).length===2,m=e?.[r],d=e?.[n],l=a&&o.filter(S=>S>=a).length===2,{NoAD:f,tiebreakTo:g}=s;if(l){if(i>1)return{result:!1,error:{message:"invalid winning game scoreString (5)"}};if(!p)return{result:!1,error:{message:"invalid tiebreak scores (1)"}};if(typeof g!="number"||Number.isNaN(g))return{result:!1,error:{message:"tiebreakTo error"}};if(!!!(g&&e?.find(N=>N>=g)))return{result:!1,error:{message:"invalid tiebreak scores (2)"}};let h=a<c?c:c+1;if(t>h)return{result:!1,error:{message:"invalid winning game scoreString (1)"}};if(!m||!d||m<d)return{result:!1,error:{message:"winningSide tiebreak value is not high"}};let T=f?1:2,y=m-d,E=d>=g-1;if(y&&E&&y<T)return{result:!1,error:{message:"invalid tiebreak scores (3)"}}}if(t>c&&!l)return{result:!1,error:{message:"invalid winning game scoreString (2)"}}}function Lz({setObject:t,setFormat:e,sideTiebreakScores:r}){if(!t)return{result:!1,error:Yg};let n=!!e?.tiebreakSet,o=!!e?.timed;if(!e||!n||o)return{result:!1,error:{message:"not tiebreak set"}};let s=new Set([1,2]).has(t?.winningSide);if(!t||!s)return{result:!1,error:sl};let{tiebreakSet:a}=e??{},{NoAD:c,tiebreakTo:u}=a??{};if(!(r?.filter(y=>typeof y=="number"&&!Number.isNaN(y)).length===2))return{result:!1,error:{message:"invalid tiebreak scores (1)"}};if(Number.isNaN(u))return{result:!1,error:{message:"tiebreakTo error"}};if(!!!r?.find(y=>y>=u))return{result:!1,error:{message:"invalid tiebreak scores (2)"}};let d=t?.winningSide-1,l=1-d,f=r[d],g=r[l];if(!f||!g||f<g)return{result:!1,error:{message:"winningSide tiebreak value is not high"}};let I=c?1:2,S=f-g,h=g>=u-1;return S&&h&&S<I?{result:!1,error:{message:"invalid tiebreak scores (3)"}}:{result:!0}}var K1="SET3-S:6/TB7";function bd(t){let e=t.split(/[\s,]+/).filter(s=>s.length>0);if(e.length===0)return K1;let r=Fz(e.length),n=kz(e,r);if(n)return n;let o=Gz(e);if(o===void 0)return K1;let i=Wz(e,o);return Hz(r,o,i)}function Fz(t){return t===1?1:t===2?3:5}function KA(t){return t.replaceAll(/\([^)]*\)/g,"").match(/(\d+)/g)?.map(r=>Number.parseInt(r,10))??[]}function kz(t,e){for(let r of t){let n=KA(r);if(n.length===2){let o=Math.max(...n),i=Math.min(...n),s=o-i;if(o===10||o>10&&s<=2)return`SET${e}-S:TB10`}}}function Gz(t){let e=t.find(r=>/\(/.test(r));return e?Vz(e):Bz(t)}function Vz(t){let e=KA(t);if(e.length===0)return;let r=Math.max(...e),n=Math.min(...e);return r===n+1?n:r-1}function Bz(t){let e=[];for(let n of t){let o=KA(n);o.length>0&&e.push(Math.max(...o))}if(e.length===0)return;let r=Math.max(...e);return r>=6?6:r}function Wz(t,e){if(t.length<3)return!1;let r=t.at(-1),n=KA(r);if(n.length!==2)return!1;let o=Math.max(...n),i=Math.min(...n);return o>e+1&&o-i===2}function Hz(t,e,r){let n;return e===6?n=`SET${t}-S:6/TB7`:e===4?n=`SET${t}-S:4/TB7`:n=`SET${t}-S:${e}/TB7`,r&&(n+=`-F:${e}`),n}function FM(t){let{matchUp:e,expectedScore:r}=t;if(!e)return{isValid:!1,errors:["No matchUp provided"],warnings:[],actual:{sets:[],scoreString:""},expected:{sets:r?.sets,scoreString:r?.scoreString},pointsProcessed:0,pointsRejected:0};let n=[],o=[],i=ns({matchUpFormat:e?.matchUpFormat,matchUpId:e?.matchUpId,participants:e?.sides?.map(p=>p.participant).filter(p=>p!==void 0)}),s=e?.history?.points??[];s.length===0&&o.push("No points found to validate");let a=0,c=0;for(let p of s)try{i=Cs(i,{winner:p.winner,server:p.server}),a++}catch(m){c++;let d=m instanceof Error?m.message:String(m);n.push(`Point ${p.pointNumber||a+1}: ${d}`)}let u=os(i);return r&&(r.sets&&(u.sets.length!==r.sets.length&&n.push(`Set count mismatch: expected ${r.sets.length}, got ${u.sets.length}`),r.sets.forEach((p,m)=>{let d=u.sets[m];if(!d){n.push(`Missing set ${m+1}`);return}p.side1Score!==void 0&&d.side1Score!==p.side1Score&&n.push(`Set ${m+1} side1Score: expected ${p.side1Score}, got ${d.side1Score}`),p.side2Score!==void 0&&d.side2Score!==p.side2Score&&n.push(`Set ${m+1} side2Score: expected ${p.side2Score}, got ${d.side2Score}`),p.side1TiebreakScore!==void 0&&d.side1TiebreakScore!==p.side1TiebreakScore&&n.push(`Set ${m+1} side1TiebreakScore: expected ${p.side1TiebreakScore}, got ${d.side1TiebreakScore}`),p.side2TiebreakScore!==void 0&&d.side2TiebreakScore!==p.side2TiebreakScore&&n.push(`Set ${m+1} side2TiebreakScore: expected ${p.side2TiebreakScore}, got ${d.side2TiebreakScore}`)})),r.scoreString&&u.scoreString!==r.scoreString&&n.push(`Score string mismatch: expected "${r.scoreString}", got "${u.scoreString}"`)),{isValid:n.length===0,errors:n,warnings:o,actual:{sets:u.sets,scoreString:u.scoreString},expected:{sets:r?.sets,scoreString:r?.scoreString},pointsProcessed:a,pointsRejected:c}}function z1(t){let e=t?.side1Score||0,r=t?.side2Score||0;if(t?.side1TiebreakScore!==void 0||t?.side2TiebreakScore!==void 0){let n=t?.side1TiebreakScore||0,o=t?.side2TiebreakScore||0;return e>r?`${e}-${r}(${o})`:`${e}(${n})-${r}`}return`${e}-${r}`}function Q1(t){let{points:e,matchUpFormat:r,expectedGames:n,expectedTiebreak:o}=t,i={matchUpId:"validation",matchUpFormat:r,matchUpStatus:"TO_BE_PLAYED",matchUpType:"SINGLES",sides:[{sideNumber:1},{sideNumber:2}],score:{sets:[]},history:{points:e?.map((s,a)=>({...s,pointNumber:a+1,timestamp:"",winner:s.winner,server:s.server}))}};return FM({matchUp:i,expectedScore:{sets:[{side1Score:n?.[0],side2Score:n?.[1],side1TiebreakScore:o?.[0],side2TiebreakScore:o?.[1]}]}})}function J1(t){let{points:e,expectedScore:r,matchUpFormat:n,allowExtraPoints:o=!1,debug:i=!1}=t,s=[],a=[],c=[],u,p=!1;n?u=n:r?(u=bd(r),p=!0,i&&console.log(`Deduced format: ${u} from score: ${r}`)):(u="SET3-S:6/TB7",p=!0,a.push("No format provided, using default SET3-S:6/TB7"));let m=ns({matchUpFormat:u}),d=e?.split("").map(h=>{let T=Number.parseInt(h,10);return Number.isNaN(T)||T!==0&&T!==1?null:T}).filter(h=>h!==null);if(d?.length===0)return s.push("No valid points found in point string"),{valid:!1,errors:s,warnings:a,pointsProcessed:0,pointsRejected:[],actualScore:"0-0",matchUpFormat:u,formatDeduced:p,sets:[]};let l=0;for(let h=0;h<d?.length;h++){let T=d[h];if(m.matchUpStatus==="COMPLETED"&&!o){c.push(T),i&&console.log(`Point ${h+1}: Rejected (match complete)`);continue}try{if(m=Cs(m,{winner:T}),l++,i){let y=os(m);console.log(`Point ${h+1}: ${T} \u2192 ${y.scoreString}`)}}catch(y){c.push(T);let E=y instanceof Error?y.message:String(y);s.push(`Point ${h+1}: ${E}`),i&&console.log(`Point ${h+1}: Error - ${E}`)}}let f=os(m),g=f.scoreString,I=f.sets.map(h=>{let T=[h.side1Score||0,h.side2Score||0],y=h.side1TiebreakScore===void 0?void 0:[h.side1TiebreakScore,h.side2TiebreakScore||0],E=`${T[0]}-${T[1]}`;return y&&(E=T[0]>T[1]?`${T[0]}-${T[1]}(${y[1]})`:`${T[0]}(${y[0]})-${T[1]}`),{games:T,tiebreak:y,scoreString:E}}),S=!0;if(r){let h=X1(r),T=X1(g);h!==T&&(S=!1,s.push(`Score mismatch: expected "${r}", got "${g}"`))}return c.length>0&&a.push(`${c.length} excess points after match complete`),s.length>0&&(S=!1),{valid:S,errors:s,warnings:a,pointsProcessed:l,pointsRejected:c,expectedScore:r,actualScore:g,matchUpFormat:u,formatDeduced:p,sets:I}}function X1(t){return t.replace(/\s+/g,"").replace(/,/g,", ").toLowerCase()}var Yz={4:"Wide",5:"Body",6:"T"},Z1={f:"Forehand",r:"Forehand Slice",v:"Forehand Volley",o:"Overhead Smash",u:"Forehand Drop Shot",l:"Forehand Lob",h:"Forehand Half-volley",j:"Forehand Drive Volley"},tk={b:"Backhand",s:"Backhand Slice",z:"Backhand Volley",p:"Backhand Overhead Smash",y:"Backhand Drop Shot",m:"Backhand Lob",i:"Backhand Half-volley",k:"Backhand Drive Volley"},jz={t:"Trick Shot",q:"Unknown Shot"},qz={...Z1,...tk,...jz},$z={7:"shallow",8:"deep",9:"very deep"},Kz={1:1,2:2,3:3},zz={"+":"approach","-":"net","=":"baseline"},Cd={n:"Net",w:"Out Wide",d:"Out Long",x:"Out Wide and Long",g:"Foot Fault",e:"Unknown","!":"Shank"};function Qz(t,e){return t.PtWinner===t.Svr?e:1-e}function GM(t){let e=[],r="",n="fbrsvzouymlhijkpqt";for(let i=0;i<t.length;i++){let s=t[i];s&&(n.includes(s)||"456".includes(s)?(r&&e.push(r),r=s):r+=s)}return r&&e.push(r),e}function Xz(t){if(t.includes("*"))return"*";if(t.includes("#"))return"#";if(t.includes("@"))return"@"}function Qa(t){if(t){for(let e of Object.keys(Cd))if(t.includes(e))return e}}function Jz(t){let e=[];for(let r of t){if(!r)continue;let n=r[0];if(n&&/[456]/.test(n))e.push(r);else break}return e}function VM(t){if(!wt(t))return{serves:[],rally:[]};let e,r,n,o=t.split("c").length-1;t=t.split("c").join("");let i=GM(t),s=i;for(let p=i.length-1;p>=0;p--){let m=i[p];if(m&&(r=Xz(m),r)){s=i.slice(0,p+1),n=i.slice(p+1),e=m;break}}let a=Jz(s),c=a.length?s.slice(a.length):s;if(!r&&!a.length&&c.length===1){let p=c[0];p&&["S","P","Q","R"].includes(p)&&(e=p,c.length=0)}let u={serves:a,rally:c};return o&&(u.lets=o),r&&(u.terminator=r),e&&(u.result=e),n?.length,u}function BM(t){let e=t.join("|"),r=zA(t[0],1);if(r.winner==="S"||!t[1])return r.serve=1,r.code=e,r;let n=zA(t[1],2);return n.serve=2,n.first_serve={serves:r.serves},r.lets&&(n.first_serve.lets=r.lets),r.error&&(n.first_serve.error=r.error),r.parse_notes&&(n.first_serve.parse_notes=r.parse_notes),n.code=e,n}function zA(t,e){let r=VM(t);if(["Q","S"].includes(r.result||""))return r.winner="S",r;if(["P","R"].includes(r.result||"")||!r.terminator&&!Qa(r.serves[0])&&r.serves.length>2)return r.winner="R",r;let n=(r.serves.length+r.rally.length)%2===0?"R":"S",o;return r.rally.length>0?o=r.rally[r.rally.length-1]:r.serves.length>0&&(o=r.serves[r.serves.length-1]),o?r.rally.length?t8(r,n,o):Zz(r,e):{...r,winner:void 0}}function Zz(t,e){if(t.terminator==="*")t.result="Ace",t.winner="S";else if(t.terminator==="#")t.result="Serve Winner",t.winner="S";else{let r=Qa(t.serves[0]);r?(t.error=Cd[r],e===2&&(t.result="Double Fault",t.winner="R")):(t.parse_notes="treated as a fault",e===2&&(t.result="Double Fault",t.winner="R"))}return t}function t8(t,e,r){if(t.rally.length===1&&r.includes("#")){t.result="Serve Winner",t.winner="S";let n=Qa(r);return n&&(t.error=Cd[n]),t}return r.includes("#")?(t.result="Forced Error",t.error=Cd[Qa(r)],t.winner=e==="R"?"S":"R"):r.includes("*")?(t.result="Winner",t.winner=e):r.includes("@")?(t.result="Unforced Error",t.error=Cd[Qa(r)],t.winner=e==="R"?"S":"R"):Qa(t.serves[0])?t.rally.length===1&&Qa(r)&&(t.error=Cd[Qa(r)],t.winner=e==="R"?"S":"R"):t.serves.length&&t.rally.length?(t.parse_notes="no terminator: receiver wins point",t.result="Unknown",t.winner="R"):t.rally.length===1&&Qa(r)&&(t.error=Cd[Qa(r)],t.winner=e==="R"?"S":"R"),t}function kM(t){if(t)for(let e of t){let r=qz[e];if(r)return r}}function e8(t){if(t)for(let e of t){let r=Yz[e];if(r)return r}}function r8(t,e,r){let n=[],o=1,i=r;if(t.length>0&&!Qa(t[t.length-1])){let s=t[t.length-1],a=kM(s)||"Forehand";n.push({shotNumber:o++,player:i,stroke:a,code:s}),i=1-i}for(let s of e){let a=kM(s);if(!a)continue;let c={shotNumber:o++,player:i,stroke:a,code:s};for(let u of s){let p=Kz[u];p!==void 0&&(c.direction=p)}for(let u of s){let p=$z[u];p&&(c.depth=p)}for(let u of s){let p=zz[u];p&&(c.position=p)}n.push(c),i=1-i}return n}function QA(t,e){let r=Qz(t,e),n=t["1st"]||"",o=t["2nd"]||"";if(!n&&!o)return{winner:r,server:e,result:"Unknown"};let i=BM([n,o]),s={winner:r,server:e};i.result&&(s.result=i.result),i.serve&&(s.serve=i.serve);let a=i.serve===1?n:o,c=e8(a);c&&(s.serveLocation=c);let u=i.rally[i.rally.length-1];if(u){let m=kM(u);m&&(s.stroke=m,Object.values(Z1).includes(m)?s.hand="Forehand":Object.values(tk).includes(m)&&(s.hand="Backhand"))}let p=r8(i.serves,i.rally,e);return p.length>0&&(s.rally=p,s.rallyLength=p.length),i.code&&(s.code=i.code),s}function XA(t){if(!t||!wt(t))return[];let e=t.trim().split(`
|
|
@@ -21,7 +21,7 @@ var _W=Object.defineProperty;var Gt=(t,e)=>{for(var r in e)_W(t,r,{get:e[r],enum
|
|
|
21
21
|
|
|
22
22
|
And a special thanks to my family for putting up with the long days and weeks and months of coding
|
|
23
23
|
and conversations at all hours.
|
|
24
|
-
`}var KM={};Gt(KM,{filterParticipants:()=>Hp,getCompetitionParticipants:()=>eP,getPairedParticipant:()=>Tn,getParticipantEventDetails:()=>rP,getParticipantMembership:()=>nP,getParticipantScaleItem:()=>Zi,getParticipantSchedules:()=>oP,getParticipantSignInStatus:()=>iP,getParticipantTimeItem:()=>tE,getParticipants:()=>bt,getScaleValues:()=>lc,participantScaleItem:()=>Po,validateLineUp:()=>sf});function eP(t){let{tournamentRecords:e}=t??{};if(typeof e!="object"||!Object.keys(e).length)return{error:kt};let r=[],n={},o={},i={},s=[],a={},c=[];for(let u of Object.values(e)){let{participantIdsWithConflicts:p,mappedMatchUps:m,participantMap:d,participants:l,matchUps:f,derivedEventInfo:g,derivedDrawInfo:I}=bt({...t,tournamentRecord:u});Object.assign(a,m),Object.assign(n,d),Object.assign(o,g),Object.assign(i,I),r.push(...l??[]),s.push(...f??[]),p?.forEach(S=>{c.includes(S)||c.push(S)})}return{participantIdsWithConflicts:c,derivedEventInfo:o,derivedDrawInfo:i,participantMap:n,mappedMatchUps:a,participants:r,...P,matchUps:s}}function rP({tournamentRecord:t,participantId:e}){let r=dt({tournamentRecord:t,participantId:e},[rt,sr]);if(r.error)return r;let n=[e].concat((t.participants??[]).filter(i=>i?.participantType&&[_t,lt].includes(i.participantType)&&i.individualParticipantIds?.includes(e)).map(i=>i.participantId));return{eventDetails:(t.events??[]).filter(i=>{let s=(i?.entries??[]).map(a=>a.participantId);return Re(s,n)}).map(i=>({eventName:i.eventName,eventId:i.eventId}))}}function nP({tournamentRecord:t,participantId:e}){let r=dt({tournamentRecord:t,participantId:e},[rt,sr]);if(r.error)return r;let{participants:n}=bt({participantFilters:{participantTypes:[_t,lt,$r]},tournamentRecord:t});return(n??[]).filter(i=>i.individualParticipantIds?.includes(e)).reduce((i,s)=>{let a=s.participantType;return a&&(i[a]||(i[a]=[]),i[a].push(s)),i},{})}function oP({participantFilters:t={},tournamentRecord:e}){if(!e)return{error:j};if(typeof t!="object")return{error:yo,context:{participantFilters:t}};let r={eventIds:t.eventIds},n=qt({tournamentRecord:e,contextFilters:r}).matchUps??[],o=Object.assign({},...n.map(p=>({[p.matchUpId]:p}))),i=n.filter(({schedule:p})=>p&&Object.keys(p).length),s=tn({tournamentRecord:e,matchUps:n}).sourceMatchUpIds??[],a={};for(let p of i){let{sides:m}=p,d,l=m?.map(g=>{if(g.participant)return[g.participant].concat(...g.participant.individualParticipants??[]);s[p.matchUpId]&&!d&&(d=(s[p.matchUpId]??[]).map(I=>o[I]).filter(({winningSide:I,bye:S})=>!I&&!S))}).filter(Boolean).flat()??[];for(let g of l){let{participantId:I}=g;a[I]||(a[I]={potentialMatchUps:[],participant:g,matchUps:[]}),a[I].matchUps.push(p)}let f=d?.map(({sides:g})=>g).flat().map(({participant:g})=>g&&[g].concat(...g.individualParticipants??[])).filter(Boolean).flat()??[];for(let g of f){let{participantId:I}=g;a[I]||(a[I]={potentialMatchUps:[],participant:g,matchUps:[]}),a[I].potentialMatchUps.push(p)}}return{participantSchedules:Object.values(a).filter(({participant:p})=>!(t.participantIds&&!t.participantIds.includes(p.participantId)||t.participantTypes&&!t.participantTypes.includes(p.participantType))),...P}}function iP({tournamentRecord:t,participantId:e}){let r=dt({tournamentRecord:t,participantId:e},[rt,sr]);if(r.error)return r;let{participant:n}=Do({tournamentRecord:t,participantId:e});if(!n)return{error:ee};let{timeItem:o}=Jr({itemType:fu,element:n});return o&&o.itemValue===vp&&vp}var tv={};Gt(tv,{analyzeDraws:()=>Xp,analyzeTournament:()=>IP,cleanExpiredMutationLocks:()=>aP,getAggregateTeamResults:()=>pP,getAllowedDrawTypes:()=>kf,getAllowedMatchUpFormats:()=>sP,getApplicableAwardProfileLevels:()=>vd,getAppliedPolicies:()=>ft,getCompetitionDateRange:()=>Vf,getCompetitionPenalties:()=>cP,getEventRankingPoints:()=>Od,getMutationLocks:()=>SP,getPolicyDefinitions:()=>fo,getRegistrationProfile:()=>uP,getTournamentInfo:()=>ia,getTournamentPenalties:()=>Gf,getTournamentPersons:()=>mP,getTournamentPoints:()=>Ja,getTournamentStructures:()=>jE,getTournamentTimeItem:()=>_l,suggestFormatPlans:()=>gP});function sP({tournamentRecord:t,categoryName:e,categoryType:r}){if(!t)return{error:j};let{appliedPolicies:n}=ft({tournamentRecord:t});return(n?.[Qr]?.matchUpFormats??[]).filter(({categoryNames:s,categoryTypes:a})=>!e&&!a||e&&s?.includes(e)||r&&a?.includes(r))}function kf({tournamentRecord:t,categoryName:e,categoryType:r}){if(!t)return{error:j};let{appliedPolicies:n}=ft({tournamentRecord:t});return(n?.[El]?.allowedDrawTypes??[]).filter(({categoryNames:s,categoryTypes:a})=>!e&&!a||e&&s?.includes(e)||r&&a?.includes(r))}var b8="RANKING_POINTS",C8="QUALITY_WIN",M8="fullToEach",zM="splitEven",v8="teamOnly",QM=["ageCategoryCodes","genders","categoryNames","categoryTypes","ratingTypes","ballTypes","wheelchairClasses","subTypes"],XM=["eventTypes","drawTypes","drawSizes","maxDrawSize","stages","stageSequences","levels","maxLevel","flights","maxFlightNumber","participationOrder","dateRanges"],Tk={RANKING_POINTS:b8,QUALITY_WIN:C8,FULL_TO_EACH:M8,SPLIT_EVEN:zM,TEAM_ONLY:v8,CATEGORY_SCOPE_FIELDS:QM,PROFILE_SCOPE_FIELDS:XM};function Md(t){let{participation:e={},awardProfiles:r,wheelchairClass:n,startDate:o,eventType:i,drawSize:s,drawType:a,category:c,endDate:u,gender:p,level:m}=t,{participationOrder:d,flightNumber:l,rankingStage:f}=e,g=E=>!o&&!u||!E.dateRanges?!0:E.dateRanges.some(A=>{let N=!o||!A.startDate||new Date(o)>new Date(A.startDate),D=!u||!A.endDate||new Date(u)<=new Date(A.endDate);return N&&D}),I=E=>{if(!E)return!0;let A=c??{};return!(E.ageCategoryCodes?.length&&!E.ageCategoryCodes.includes(A.ageCategoryCode)||E.genders?.length&&!E.genders.includes(p)||E.categoryNames?.length&&!E.categoryNames.includes(A.categoryName)||E.categoryTypes?.length&&!E.categoryTypes.includes(A.type)||E.ratingTypes?.length&&!E.ratingTypes.includes(A.ratingType)||E.ballTypes?.length&&!E.ballTypes.includes(A.ballType)||E.wheelchairClasses?.length&&!E.wheelchairClasses.includes(n)||E.subTypes?.length&&!E.subTypes.includes(A.subType))},S=E=>g(E)&&(!E.maxFlightNumber||l<=E.maxFlightNumber)&&(!E.drawTypes?.length||E.drawTypes?.includes(a))&&(!E.drawSizes?.length||E.drawSizes.includes(s))&&(!E.stages?.length||E.stages.includes(f))&&(!E.levels?.length||E.levels.includes(m))&&(!E.maxDrawSize||s<=E.maxDrawSize)&&(!E.drawSize||E.drawSize===s)&&(!E.maxLevel||m<=E.maxLevel)&&(!l||!E.flights?.flightNumbers?.length||E.flights.flightNumbers.includes(l))&&(!E.participationOrder||E.participationOrder===d)&&I(E.category)&&(!E.eventTypes?.length||E.eventTypes?.includes(i)),h=r.filter(S);if(h.length===0)return{awardProfile:void 0};if(h.length===1)return{awardProfile:h[0]};let T=h.filter(E=>E.priority!==void 0);if(T.length){let E=Math.max(...T.map(N=>N.priority));return{awardProfile:T.find(N=>N.priority===E)}}let y=h.map((E,A)=>({profile:E,score:O8(E),index:A}));return y.sort((E,A)=>A.score-E.score||E.index-A.index),{awardProfile:y[0].profile}}function O8(t){let e=0;for(let r of XM){let n=t[r];if(n!=null){if(Array.isArray(n)&&n.length===0)continue;e+=1}}if(t.category)for(let r of QM){let n=t.category[r];Array.isArray(n)&&n.length>0&&(e+=1)}return e}var _8=[{rankingStage:W,participationOrder:1,flightNumber:1},{rankingStage:W,participationOrder:2,flightNumber:1},{rankingStage:Z,participationOrder:1,flightNumber:1},{rankingStage:Z,participationOrder:2,flightNumber:1}];function vd({policyDefinitions:t,tournamentRecord:e,eventId:r,drawId:n}){if(!e)return{error:j};let{policyDefinitions:o}=fo({policyTypes:[gr],tournamentRecord:e}),i=t?.[gr]??o?.[gr];if(!i)return{error:Ea};let s=i.awardProfiles;if(!s?.length)return{levels:[],...P};let a=x8(s);if(!r&&!n)return{levels:a,...P};let c=w8({tournamentRecord:e,eventId:r,drawId:n});return{levels:L8(a,s,c),...P}}function x8(t){let e=new Set;for(let n of t)if(n.levels?.length)for(let o of n.levels)e.add(o);let r=t.filter(n=>n.maxLevel!==void 0).map(n=>n.maxLevel);if(r.length){let n=Math.max(...r);for(let o=1;o<=n;o++)e.add(o)}return[...e].sort((n,o)=>n-o)}function w8({tournamentRecord:t,eventId:e,drawId:r}){let n=_e({tournamentRecord:t,eventId:e,drawId:r}),o=n.event,i=n.drawDefinition;return{eventType:o?.eventType,category:o?.category,gender:o?.gender,drawType:i?.drawType}}function L8(t,e,r){let{eventType:n,drawType:o,category:i,gender:s}=r;return t.filter(a=>_8.some(c=>Md({awardProfiles:e,participation:c,eventType:n,drawType:o,category:i,gender:s,level:a}).awardProfile))}function aP(t){let{tournamentRecord:e}=t;if(!e)return{error:j};let r=new Date().toISOString(),n=0,o=a=>{let{extension:c}=ot({element:a,name:sn});if(!c?.value?.locks?.length)return;let u=c.value,p=u.locks.length;u.locks=u.locks.filter(d=>d.expiresAt===null||d.expiresAt>r);let m=p-u.locks.length;m>0&&(n+=m,ut({element:a,extension:{name:sn,value:u},creationTime:!1}))};o(e);let i=e.events??[];for(let a of i){o(a);let c=a.drawDefinitions??[];for(let u of c)o(u)}let s=e.venues??[];for(let a of s)o(a);return{...P,removedCount:n}}function Gf({tournamentRecord:t}){if(!t)return{error:j};let r=(t?.participants??[]).reduce((n,o)=>{let{participantId:i}=o;return(o.penalties??[]).forEach(s=>{let{penaltyId:a}=s??{};n[a]?n[a].participants.push(i):n[a]={...s,participantIds:[i]}}),n},{});return{penalties:Object.values(r)}}function cP({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:kt};let e=[];for(let r of Object.values(t)){let{penalties:n}=Gf({tournamentRecord:r});e.push(...n??[])}return{penalties:e}}function Vf({tournamentRecords:t}){if(!Tt(t))return{error:kt};let r=Object.keys(t??{}).reduce((i,s)=>{let a=t[s],{tournamentInfo:{startDate:c,endDate:u}}=ia({tournamentRecord:a}),p=c&&mt(c),m=p&&new Date(p);(!i.startDate||m&&m<i.startDate)&&(i.startDate=m);let d=u&&mt(u),l=d&&new Date(d);return(!i.endDate||l&&l>i.endDate)&&(i.endDate=l),i},{startDate:void 0,endDate:void 0}),n=r.startDate&&mt(r.startDate.toISOString()),o=r.endDate&&mt(r.endDate.toISOString());return!n||!o?{error:oU}:{startDate:n,endDate:o}}function uP(t){if(!t?.tournamentRecord)return{error:j};let{tournamentRecord:e}=t;return{registrationProfile:e.registrationProfile?q(e.registrationProfile):void 0}}function pP(t){let e=X(t,[{[rt]:!0}]);if(e.error)return e;let r=t.finishingPositionRangeBounsPoints??{},n={},o=m=>{let d=m?.individualParticipants?.map(l=>l.teams?.length===1&&l.teams[0]);return m?.teams?.length===1&&m?.teams?.[0]||d?.[0].participantId===d?.[1].participantId&&d?.[0]},{matchUps:i,participants:s}=bt({participantFilters:{participantTypes:[St]},withRankingProfile:!0,withStatistics:!0,...t});for(let m of s??[]){if(m.participantType===ur)continue;m.draws?.[0]?.drawId==="draw-0-3"&&console.log(m.participantType,m.draws[0].finishingPositionRange);let d=o(m);if(d)for(let l of m?.draws??[]){let f=l?.finishingPositionRange?.join("-");if(f&&r?.[f]){let g=d?.participantId,I=l?.drawId,S=`${g}|${I}|${f}`;n[S]=r[f]}}}let a=m=>({teamName:m,standingPoints:0,pointsPlayed:0,pointsPct:0,points:0,bonus:0,diff:0,loss:0,win:0}),c=(m,d,l)=>{m[d]===void 0&&(m[d]=0),m[d]+=l},{individualResults:u,teamResults:p}=F8({getTeamParticipant:o,initializeResults:a,increment:c,matchUps:i});return G8({teamBonusPointHashes:n,teamResults:p}),V8(u),{...P,individualResults:u,teamResults:p}}function F8({getTeamParticipant:t,initializeResults:e,increment:r,matchUps:n}){let o={},i={};for(let s of n??[]){let{sides:a,matchUpFormat:c}=s,u=c&&oe(c);if(a?.length===2&&u.setFormat?.timed&&(!u.finalSetFormat||u.finalSetFormat?.timed))for(let p of a)k8({side:p,matchUp:s,getTeamParticipant:t,initializeResults:e,increment:r,individualResults:o,teamResults:i})}return{individualResults:o,teamResults:i}}function k8({side:t,matchUp:e,getTeamParticipant:r,initializeResults:n,increment:o,individualResults:i,teamResults:s}){let a=r(t.participant),c=a?.participantId,u=t.participant?.participantId,p=a?.participantName,m=t.sideNumber,d=t.participant?.individualParticipantIds||((u&&[u])??[]);if(d.forEach(l=>{l&&!i[l]&&(i[l]=n(p))}),c&&m){s[c]||(s[c]=n(p));let l=[...d.map(g=>i[g]),s[c]];e.winningSide&&(m===e.winningSide?l.forEach(g=>o(g,"win",1)):l.forEach(g=>o(g,"loss",1)));let f=e.score?.sets??[];for(let g of f){let I=g?.[`side${3-m}Score`]||0,S=g?.[`side${m}Score`]||0,h=S-I;l.forEach(T=>o(T,"pointsPlayed",S+I)),l.forEach(T=>o(T,"points",S)),l.forEach(T=>o(T,"diff",h))}}}function G8({teamBonusPointHashes:t,teamResults:e}){for(let r of Object.keys(t)){let[n]=r.split("|");e[n]&&(e[n].bonus+=t[r],e[n].pointsPct=parseFloat((e[n].points/e[n].pointsPlayed).toFixed(2)),e[n].standingPoints=e[n].win+e[n].bonus)}}function V8(t){for(let e of Object.keys(t))t[e].pointsPct=parseFloat((t[e].points/t[e].pointsPlayed).toFixed(2))}function mP({tournamentRecord:t,participantFilters:e}){if(!t)return{error:j};let r=t.participants??[];e&&(r=Hp({participants:r,participantFilters:e,tournamentRecord:t}));let n={},o=i=>{if(i.person){let{personId:s}=i.person;n[s]?n[s].participantIds.push(i.participantId):n[s]={...i.person,participantIds:[i.participantId]}}};return r.forEach(i=>{i.person&&o(i)}),{tournamentPersons:Object.values(n)}}function Lu(t,e){return t&&e&&Array.isArray(e)&&e[t-1]||typeof e=="object"&&e[t]}function ih({qualityWinProfiles:t,wonMatchUpIds:e,mappedMatchUps:r,participantSideMap:n,tournamentParticipants:o,tournamentStartDate:i,level:s}){let a=0,c=[],u={};for(let p of o)u[p.participantId]=p;for(let p of t){let{rankingScaleName:m,rankingSnapshot:d="latestAvailable",includeWalkovers:l=!1,rankingRanges:f=[],maxBonusPerTournament:g}=p,I=0;for(let S of e){let h=W8({matchUpId:S,mappedMatchUps:r,participantSideMap:n,participantById:u,includeWalkovers:l,rankingScaleName:m,rankingSnapshot:d,tournamentStartDate:i,rankingRanges:f,level:s});h&&(I+=h.points,c.push(h))}g!==void 0&&I>g&&(I=g),a+=I}return{qualityWinPoints:a,qualityWins:c}}function B8({participant:t,rankingScaleName:e,rankingSnapshot:r,tournamentStartDate:n}){let i=(t.timeItems??[]).filter(u=>{if(!u?.itemType)return!1;let p=u.itemType.split(".");return p[0]===ci&&p[1]===Jn&&p[3]===e});if(!i.length)return;let s=i;if(r==="tournamentStart"&&n){let u=new Date(n).getTime();s=i.filter(p=>(p.itemDate?new Date(p.itemDate).getTime():0)<=u)}if(!s.length)return;s.sort((u,p)=>(u.createdAt?new Date(u.createdAt).getTime():0)-(p.createdAt?new Date(p.createdAt).getTime():0));let c=s.at(-1)?.itemValue;return typeof c=="number"?c:void 0}function W8({matchUpId:t,mappedMatchUps:e,participantSideMap:r,participantById:n,includeWalkovers:o,rankingScaleName:i,rankingSnapshot:s,tournamentStartDate:a,rankingRanges:c,level:u}){let p=e[t];if(!p)return;let{matchUpStatus:m,sides:d=[],winningSide:l}=p;if(!o&&(m===vt||m===Mt))return;let f=r[t];if(!f||l!==f)return;let I=d.find(E=>E.sideNumber!==f)?.participantId;if(!I)return;let S=n[I];if(!S)return;let h=B8({participant:S,rankingScaleName:i,rankingSnapshot:s,tournamentStartDate:a});if(!h)return;let T=c.find(E=>h>=E.rankRange[0]&&h<=E.rankRange[1]);if(!T)return;let y;if(typeof T.value=="number")y=T.value;else if(typeof T.value=="object"){let E=Lu(u,T.value.level??T.value);typeof E=="number"&&(y=E)}if(y)return{opponentParticipantId:I,opponentRank:h,points:y,matchUpId:t}}function Bf({participantWon:t,flightNumber:e,valueObj:r,drawSize:n,flights:o,level:i}){let s=(f,g)=>{if(f){if(Array.isArray(g)){let I=g.find(S=>S.flight===f||S.f===f);return I.value||I.v}if(typeof g=="object"){let I=g.flights||g.f;if(Array.isArray(I))return I[f-1]}}},a=(f,g)=>{let I=f?.value||f?.v||(yt(f)?f:0),S=Lu(i,f?.level);return{value:s(g,S)||yt(S)&&S||I}},c=0,u,p,m,d,l=t&&"won"||t===!1&&"lost"||void 0;if(Array.isArray(r)){let f=r.find(S=>S.drawSize===n||S.drawSizes?.includes(n)),g=r.find(S=>S.drawSize&&S.threshold&&n>S.drawSize),I=r.find(S=>!S.drawSize&&!S.drawSizes?.length);l!==void 0&&(f=f?.[l],g=g?.[l],I=I?.[l]),p=a(f,e).value,m=a(g,e).value,d=a(I,e).value,c=p||m||d,u=p&&f.requireWin||m&&g.requireWin||I?.requireWin}else if(typeof r=="object"){let f=r?.drawSizes?.[n],g=r;l!==void 0&&(f=f?.[l],g=g?.[l]),p=a(f,e).value,d=a(g,e).value,c=p||d,u=p?f.requireWin:g?.requireWin}else yt(r)&&l===void 0&&(c=r);return e&&o?.pct?.[e]&&(c=Math.round(c*o.pct[e])),{awardPoints:c,requireWin:u}}function H8(t,e,r){let n=0;if(t?.bonusPoints&&e!==void 0){for(let o of t.bonusPoints)if(o.finishingPositions?.includes(e)){let i=o.value;if(typeof i=="number")n=i;else if(typeof i=="object"){let s=Lu(r,i.level??i);typeof s=="number"&&(n=s)}break}}return n}function Y8(t,e){if(typeof t=="object"&&t.line)return t.limit&&e>t.limit?void 0:t.line[e-1];if(typeof t=="number")return t}function j8({tieMatchUp:t,lineValue:e,participantIndividualIdsMap:r,participantPersonMap:n,personPoints:o,eventType:i,drawId:s}){let{collectionPosition:a}=t;for(let c of t.sides??[]){if(c.sideNumber!==t.winningSide)continue;let u=c.participantId;if(!u)continue;let m=r[u]||[u];for(let d of m){let l=n[d];l&&(o[l]||(o[l]=[]),o[l].push({linePoints:e,collectionPosition:a,eventType:i,drawId:s}))}}}function q8({participantType:t,participantId:e,awardProfile:r,participant:n,participation:o,mappedMatchUps:i,levelValue:s,participantIndividualIdsMap:a,participantPersonMap:c,personPoints:u,eventType:p,drawId:m}){if(t!==ur||!r||!s)return;let d=(n.matchUps??[]).filter(({structureId:l})=>l===o.structureId);for(let{matchUpId:l}of d){let f=i[l],g=f?.sides?.find(I=>I.participantId===e)?.sideNumber;if(!(!g||f.winningSide!==g))for(let I of f.tieMatchUps??[]){if(!I.winningSide)continue;let S=Y8(s,I.collectionPosition);S&&j8({tieMatchUp:I,lineValue:S,participantIndividualIdsMap:a,participantPersonMap:c,personPoints:u,eventType:p,drawId:m})}}}function $8({qualityWinProfiles:t,participant:e,drawId:r,mappedMatchUps:n,participantId:o,person:i,tournamentRecord:s,level:a,personPoints:c,eventType:u}){if(!t?.length||!e.matchUps)return;let p=Object.values(e.matchUps).filter(g=>g.drawId===r&&g.participantWon);if(!p.length)return;let m=p.map(g=>g.matchUpId),d={};for(let g of p)d[g.matchUpId]=g.sideNumber;let{qualityWinPoints:l,qualityWins:f}=ih({qualityWinProfiles:t,wonMatchUpIds:m,mappedMatchUps:n,participantId:o,participantSideMap:d,tournamentParticipants:s.participants??[],tournamentStartDate:s.startDate,level:a});if(l>0){let g=i?.personId;g&&(c[g]||(c[g]=[]),c[g].push({qualityWinPoints:l,qualityWins:f,eventType:u,drawId:r}))}}function K8(t,e,r){if(r!==void 0||t.maxCountableMatches===void 0)return r;let n=t.maxCountableMatches;if(typeof n=="number")return n;if(typeof n=="object"){let o=Lu(e,n.level??n);if(typeof o=="number")return o}return r}function z8({awardProfile:t,participation:e,level:r,drawSize:n}){let{finishingPositionRange:o,participationOrder:i,participantWon:s,flightNumber:a,rankingStage:c}=e,u=Array.isArray(o)&&Math.max(...o);c===Z&&u&&e.finishingRound&&(u=s?1:Math.pow(2,e.finishingRound));let{finishingPositionPoints:p={},finishingPositionRanges:m,finishingRound:d,flights:l}=t,f=p.participationOrders,g=!f||f.includes(i),I=0,S;if(g&&m&&u){let h=m[u];h&&({awardPoints:I,requireWin:S}=Bf({flightNumber:a,valueObj:h,drawSize:n,flights:l,level:r}))}if(!I&&d&&i===1&&u){let h=d[u];h&&({awardPoints:I,requireWin:S}=Bf({participantWon:s,flightNumber:a,valueObj:h,drawSize:n,flights:l,level:r}))}return{awardPoints:I,winRequired:S,accessor:u}}function Q8({awardProfile:t,participation:e,level:r,maxCountable:n,countedWins:o}){let{participationOrder:i,winCount:s}=e,{pointsPerWin:a}=t,c=n!==void 0&&n>0?Math.min(s||0,Math.max(0,n-o)):s,u=pt(e.finishingPositionRange??[]).join("-"),p=0,m=0,d;a&&c&&(p+=c*a,m+=c,d=u);let l=Array.isArray(t.perWinPoints)?t.perWinPoints?.find(f=>f.participationOrders?.includes(i)):t.perWinPoints;if(s&&l){let f=Lu(r,l?.level);typeof f=="number"?(p+=(c||0)*f,m+=c||0):!f&&l.value&&(p+=(c||0)*l.value,m+=c||0)}return{perWin:p,counted:m,rangeAccessor:d}}function X8({award:t,participantType:e,participantId:r,person:n,personPoints:o,pairPoints:i,teamPoints:s,doublesAttribution:a,participantIndividualIdsMap:c,participantPersonMap:u}){let p=n?.personId;if(p)o[p]||(o[p]=[]),o[p].push(t);else if(e===lt){if(i[r]||(i[r]=[]),i[r].push(t),a){let m=a===zM?.5:1,d=c[r]??[];for(let l of d){let f=u[l];if(!f)continue;let g={...t,points:Math.round(t.points*m),positionPoints:Math.round(t.positionPoints*m),perWinPoints:Math.round(t.perWinPoints*m),bonusPoints:Math.round(t.bonusPoints*m),doublesParticipantId:r};o[f]||(o[f]=[]),o[f].push(g)}}}else e===ur&&(s[r]||(s[r]=[]),s[r].push(t))}function J8({participation:t,awardProfiles:e,wheelchairClass:r,eventType:n,startDate:o,category:i,drawInfo:s,drawType:a,endDate:c,gender:u,level:p,accum:m}){let{finishingPositionRange:d,rankingStage:l,winCount:f}=t;if(m.totalWinsCount+=f||0,Array.isArray(d)&&d.length){let S=Math.min(...d);(m.bestFinishingPosition===void 0||S<m.bestFinishingPosition)&&(m.bestFinishingPosition=S)}let g=s?.drawSize,{awardProfile:I}=Md({wheelchairClass:r,awardProfiles:e,participation:t,eventType:n,startDate:o,category:i,drawSize:g,drawType:a,endDate:c,gender:u,level:p});if(I){if(!g)return{awardProfile:I,skip:!0};I.profileName&&(m.profileName=I.profileName),m.primaryAwardProfile??=I,m.maxCountable=K8(I,p,m.maxCountable);let{awardPoints:S,winRequired:h,accessor:T}=z8({awardProfile:I,participation:t,drawSize:g,level:p}),y=T&&l!==Z&&d?.includes(g);if(I.requireWinForPoints!==void 0&&(m.requireWin=I.requireWinForPoints),I.requireWinFirstRound!==void 0&&(m.requireWinFirstRound=I.requireWinFirstRound),y&&m.requireWinFirstRound!==void 0&&(m.requireWin=m.requireWinFirstRound),h!==void 0&&(m.requireWin=h),S>m.positionPoints&&(!m.requireWin||f)&&(m.positionPoints=S,m.rangeAccessor=T,m.primaryAwardProfile=I),!S){let E=Q8({awardProfile:I,participation:t,maxCountable:m.maxCountable,countedWins:m.countedWins,level:p});m.perWinPoints+=E.perWin,m.countedWins+=E.counted,E.rangeAccessor&&(m.rangeAccessor=E.rangeAccessor)}}return{awardProfile:I,skip:!1}}function Z8({participant:t,draw:e,eventInfo:r,drawInfo:n,mappedMatchUps:o,awardProfiles:i,requireWinForPoints:s,requireWinFirstRound:a,doublesAttribution:c,qualityWinProfiles:u,personPoints:p,pairPoints:m,teamPoints:d,participantPersonMap:l,participantIndividualIdsMap:f,level:g,devContext:I,tournamentRecord:S}){let{participantType:h,participantId:T,person:y}=t,{drawId:E,structureParticipation:A}=e,N=n?.drawType,{category:D,eventType:R,gender:U,wheelchairClass:b}=r??{},C=e.startDate||r.startDate||S.startDate,_=e.endDate||r.endDate||S.endDate;if(R===Ze&&h!==ur)return;let v;if(i&&A){let w=t7({initialRequireWinFirstRound:a,requireWinForPoints:s});e7({structureParticipation:A,awardProfiles:i,wheelchairClass:b,participantType:h,participantId:T,participant:t,eventType:R,startDate:C,category:D,drawInfo:n,drawType:N,endDate:_,gender:U,level:g,accum:w,mappedMatchUps:o,participantIndividualIdsMap:f,participantPersonMap:l,personPoints:p,drawId:E});let L=H8(w.primaryAwardProfile,w.bestFinishingPosition,g);v=w.positionPoints+w.perWinPoints+L,(w.perWinPoints||w.positionPoints||L)&&r7({accum:w,bonusPoints:L,points:v,eventType:R,drawId:E,category:D,drawType:N,startDate:C,endDate:_,level:g,devContext:I,participantType:h,participantId:T,person:y,personPoints:p,pairPoints:m,teamPoints:d,doublesAttribution:c,participantIndividualIdsMap:f,participantPersonMap:l}),$8({qualityWinProfiles:u,participant:t,drawId:E,mappedMatchUps:o,participantId:T,person:y,tournamentRecord:S,level:g,personPoints:p,eventType:R})}}function t7({initialRequireWinFirstRound:t,requireWinForPoints:e}){return{requireWinFirstRound:t,requireWin:e,bestFinishingPosition:void 0,primaryAwardProfile:void 0,maxCountable:void 0,rangeAccessor:void 0,profileName:void 0,totalWinsCount:0,positionPoints:0,perWinPoints:0,countedWins:0}}function e7({structureParticipation:t,awardProfiles:e,wheelchairClass:r,participantType:n,participantId:o,participant:i,eventType:s,startDate:a,category:c,drawInfo:u,drawType:p,endDate:m,gender:d,level:l,accum:f,mappedMatchUps:g,participantIndividualIdsMap:I,participantPersonMap:S,personPoints:h,drawId:T}){for(let y of t){let{awardProfile:E,skip:A}=J8({participation:y,awardProfiles:e,wheelchairClass:r,eventType:s,startDate:a,category:c,drawInfo:u,drawType:p,endDate:m,gender:d,level:l,accum:f});if(!A&&n===ur&&E){let N=Array.isArray(E.perWinPoints)?E.perWinPoints?.find(R=>R.participationOrders?.includes(y.participationOrder)):E.perWinPoints,D=N&&Lu(l,N.level);q8({participantType:n,participantId:o,awardProfile:E,participant:i,participation:y,mappedMatchUps:g,levelValue:D,participantIndividualIdsMap:I,participantPersonMap:S,personPoints:h,eventType:s,drawId:T})}}}function r7({accum:t,bonusPoints:e,points:r,eventType:n,drawId:o,category:i,drawType:s,startDate:a,endDate:c,level:u,devContext:p,participantType:m,participantId:d,person:l,personPoints:f,pairPoints:g,teamPoints:I,doublesAttribution:S,participantIndividualIdsMap:h,participantPersonMap:T}){let y={winCount:t.totalWinsCount,positionPoints:t.positionPoints,rangeAccessor:t.rangeAccessor,perWinPoints:t.perWinPoints,bonusPoints:e,eventType:n,drawId:o,points:r,category:i,drawType:s,startDate:a,endDate:c,level:u};p&&t.profileName&&(y.profileName=t.profileName),X8({award:y,participantType:m,participantId:d,person:l,personPoints:f,pairPoints:g,teamPoints:I,doublesAttribution:S,participantIndividualIdsMap:h,participantPersonMap:T})}function Ja({participantFilters:t,policyDefinitions:e,tournamentRecord:r,level:n}){if(!r)return{error:j};let o=je(),{policyDefinitions:i}=fo({policyTypes:[gr],tournamentRecord:r}),s=e?.[gr]??i?.[gr];if(!s)return{error:Ea};let a=s.awardProfiles,c=s.requireWinFirstRound,u=s.requireWinForPoints,p=s.doublesAttribution,m=s.qualityWinProfiles,{participants:d,derivedEventInfo:l,derivedDrawInfo:f,mappedMatchUps:g}=bt({withRankingProfile:!0,participantFilters:t,tournamentRecord:r}),I=d?.filter(A=>A.draws?.length),S={},h={};for(let A of r.participants??[])A.person?.personId&&(S[A.participantId]=A.person.personId),A.individualParticipantIds?.length&&(h[A.participantId]=A.individualParticipantIds);let T={},y={},E={};for(let A of I??[])for(let N of A.draws){let D=l[N.eventId],R=f[N.drawId];Z8({participant:A,draw:N,eventInfo:D,drawInfo:R,mappedMatchUps:g,awardProfiles:a,requireWinForPoints:u,requireWinFirstRound:c,doublesAttribution:p,qualityWinProfiles:m,personPoints:T,pairPoints:E,teamPoints:y,participantPersonMap:S,participantIndividualIdsMap:h,level:n,devContext:o,tournamentRecord:r})}return{participantsWithOutcomes:I,personPoints:T,pairPoints:E,teamPoints:y,...P}}function Od({policyDefinitions:t,tournamentRecord:e,eventId:r,level:n}){if(!e)return{error:j};if(!r)return{error:le};let o=e.events?.find(I=>I.eventId===r);if(!o)return{error:le};if(!t?.[gr])return{error:Ea};let i=n??o7(o.eventTier??e.tournamentTier,t?.[gr]),s=Ja({participantFilters:{eventIds:[r]},level:i,policyDefinitions:t,tournamentRecord:e});if(s.error)return s;let{personPoints:a={},pairPoints:c={},teamPoints:u={}}=s,{participants:p}=bt({tournamentRecord:e}),m={},d={};for(let I of p??[])d[I.participantId]={participantName:I.participantName??"",personId:I.person?.personId},I.person?.personId&&(m[I.person.personId]={participantId:I.participantId,participantName:I.participantName??""});let l=new Set((o.drawDefinitions??[]).map(I=>I.drawId)),f=[];n7({personPoints:a,personToParticipant:m,eventDrawIds:l,eventAwards:f}),yk({points:c,participantLookup:d,eventDrawIds:l,eventAwards:f}),yk({points:u,participantLookup:d,eventDrawIds:l,eventAwards:f}),f.sort((I,S)=>(S.points||0)-(I.points||0)||(I.participantName??"").localeCompare(S.participantName??""));let g=o.eventType===Lt;return{eventAwards:f,eventName:o.eventName,eventType:o.eventType,isDoubles:g,...P}}function n7({personPoints:t,personToParticipant:e,eventDrawIds:r,eventAwards:n}){for(let[o,i]of Object.entries(t)){let s=e[o];if(s)for(let a of i)r.has(a.drawId)&&n.push({...a,participantId:s.participantId,participantName:s.participantName,personId:o})}}function o7(t,e){if(!(!t?.system||!t?.value||!e?.tierToLevel))return e.tierToLevel[t.system]?.[t.value]}function yk({points:t,participantLookup:e,eventDrawIds:r,eventAwards:n}){for(let[o,i]of Object.entries(t)){let s=e[o];if(s)for(let a of i)r.has(a.drawId)&&n.push({...a,participantId:o,participantName:s.participantName})}}var i7=.5,s7=.5,a7={histogram:[],count:0,stddev:0,median:0,mean:0,iqr:0,min:0,max:0,gaps:[]};function JM(t,e){if(t.length===0)return 0;if(t.length===1)return t[0];let r=(t.length-1)*e,n=Math.floor(r),o=Math.ceil(r);if(n===o)return t[n];let i=r-n;return t[n]+(t[o]-t[n])*i}function c7(t,e,r,n){if(t.length===0||n<=0)return[];let o=Math.floor(e/n)*n,i=Math.ceil(r/n)*n,s=[];for(let a=o;(a<i||a===o)&&(s.push({binStart:a,binEnd:a+n,count:0}),!(a>=i));a+=n);for(let a of t){let c=Math.min(s.length-1,Math.floor((a-o)/n));s[c].count++}return s}function u7(t,e){let r=[];for(let n=1;n<t.length;n++){let o=t[n]-t[n-1];o>=e&&r.push({start:t[n-1],end:t[n],size:o})}return r.sort((n,o)=>o.size-n.size)}function dP({binWidth:t=i7,gapThreshold:e=s7,ratings:r}){if(!Array.isArray(r)||r.length===0)return a7;let n=[...r].sort((f,g)=>f-g),o=n.length,i=n[0],s=n[o-1],a=n.reduce((f,g)=>f+g,0)/o,c=JM(n,.5),u=n.reduce((f,g)=>f+(g-a)**2,0)/o,p=Math.sqrt(u),m=JM(n,.25),l=JM(n,.75)-m;return{histogram:c7(n,i,s,t),gaps:u7(n,e),count:o,stddev:p,median:c,mean:a,iqr:l,min:i,max:s}}var p7=[2,3,4,6],m7=[.5,1],Ek=4,lP=4;function d7(t){return t<=8?1:t<=16?2:t<=32?4:t<=64?6:8}function l7(t){return[...t].sort((e,r)=>r.rating-e.rating)}function fP(t,e){return{participantIds:e.map(r=>r.participantId),ratings:e.map(r=>r.rating),label:t}}function Ak(t,e,r){return`${t} ${e+1} of ${r}`}function f7(t,e){if(e<=0)return[];let r=[],n=Math.floor(t.length/e),o=t.length%e,i=0;for(let s=0;s<e;s++){let a=n+(s<o?1:0);r.push(t.slice(i,i+a)),i+=a}return r}function g7(t,e){if(e>t.length)return;let r=f7(t,e);if(r.some(o=>o.length<lP))return;let n=r.map((o,i)=>fP(Ak("Tier",i,e),o));return{type:"EQUAL_COUNT",variant:`k=${e}`,flights:n}}function I7(t,e){if(t.length===0||e<=0)return;let r=t[0].rating,n=t.at(-1)?.rating??0,o=new Map;for(let a of t){let c=Math.floor((r-a.rating)/e);o.has(c)||o.set(c,[]),o.get(c).push(a)}let i=[...o.keys()].sort((a,c)=>a-c),s=[];for(let a of i){let c=o.get(a);if(c.length<lP)continue;let u=r-a*e,m=`${Math.max(n,u-e).toFixed(2)} \u2013 ${u.toFixed(2)}`;s.push(fP(m,c))}if(!(s.length<2))return{type:"EQUAL_BAND",variant:`width=${e}`,flights:s}}function S7(t){if(t.length<lP*2)return;let e=t.map(u=>u.rating),n=dP({ratings:e}).gaps.map(u=>u.start),o=new Set;for(let u of n)o.add(u);let i=[],s=[];for(let u of t)o.has(u.rating)&&s.length>=Ek&&(i.push(s),s=[]),s.push(u);s.length>0&&i.push(s);let a=h7(i);return a.length<2?void 0:{type:"NATURAL_CLUSTER",flights:a.map((u,p)=>fP(Ak("Cluster",p,a.length),u))}}function h7(t){let e=[];for(let r of t)if(r.length>=Ek||e.length===0)e.push(r);else{let n=e.at(-1);n&&n.push(...r)}return e}function T7(t){return{type:"STAGGERED_SINGLE",flights:[fP("All Levels",t)]}}function Pk(t){if(!Array.isArray(t)||t.length<lP)return[];let e=l7(t),r=d7(t.length),n=[];for(let i of p7){if(i>r)continue;let s=g7(e,i);s&&n.push(s)}for(let i of m7){let s=I7(e,i);s&&s.flights.length<=r&&n.push(s)}let o=S7(e);return o&&o.flights.length<=r&&n.push(o),n.push(T7(e)),n}var sh=2,y7=[4,6,8],E7=[3,5,7],A7=[3,5],P7=.5,N7={NONE:["SINGLE_ELIMINATION","ROUND_ROBIN","SWISS","DRAW_MATIC","LUCKY_DRAW","FEED_IN"],LIGHT:["SINGLE_ELIMINATION","ROUND_ROBIN","SWISS","DRAW_MATIC","LUCKY_DRAW","FEED_IN","FIRST_MATCH_LOSER_CONSOLATION","ROUND_ROBIN_WITH_PLAYOFF","DOUBLE_ELIMINATION"],FULL:["SINGLE_ELIMINATION","ROUND_ROBIN","SWISS","DRAW_MATIC","LUCKY_DRAW","FEED_IN","FIRST_MATCH_LOSER_CONSOLATION","ROUND_ROBIN_WITH_PLAYOFF","DOUBLE_ELIMINATION","FIRST_ROUND_LOSER_CONSOLATION","COMPASS","ADAPTIVE"]},D7={ROUND_ROBIN:0,ROUND_ROBIN_WITH_PLAYOFF:0,SWISS:0,SINGLE_ELIMINATION:0,FEED_IN:.05,DOUBLE_ELIMINATION:.1,DRAW_MATIC:.1,LUCKY_DRAW:.1,FIRST_MATCH_LOSER_CONSOLATION:.2,FIRST_ROUND_LOSER_CONSOLATION:.25,COMPASS:.3,ADAPTIVE:.3};function ZM(t){return t<=1?1:2**Math.ceil(Math.log2(t))}function U7(t){return t>0&&(t&t-1)===0}function To(t,e,r,n={}){return{withdrawalRiskFactor:D7[t],minMatchesPerPlayer:e,totalMatches:r,kind:t,...n}}function R7(t){if(t<sh)return[];let e=ZM(t),r=t-1,n=Math.max(1,Math.ceil(Math.log2(e)));return[To("SINGLE_ELIMINATION",1,r),To("FIRST_MATCH_LOSER_CONSOLATION",2,Math.round(r*1.5),{variantId:"FMLC"}),To("FIRST_ROUND_LOSER_CONSOLATION",n,Math.round(r*1.7),{variantId:"FRLC",rounds:n}),To("DOUBLE_ELIMINATION",2,r*2-1)]}function b7(t){return t>=7&&t<=8?[To("COMPASS",3,12,{variantId:"COMPASS_8"})]:t>=13&&t<=16?[To("COMPASS",4,28,{variantId:"COMPASS_16"})]:[]}function C7(t){if(t<sh||t>8)return[];let e=t*(t-1)/2;return[To("ROUND_ROBIN",t-1,e,{groupSize:t})]}function M7(t,e){if(t<e*2||t%e!==0)return[];let r=t/e,o=e*(e-1)/2*r,i=ZM(r),s=i-1;return[To("ROUND_ROBIN",e-1,o,{variantId:`RR_${e}x${r}`,groupSize:e}),To("ROUND_ROBIN_WITH_PLAYOFF",e-1+Math.max(0,Math.ceil(Math.log2(i))),o+s,{variantId:`RR_${e}x${r}_PLAYOFF`,groupSize:e})]}function v7(t){let e=y7.flatMap(r=>M7(t,r));return[...C7(t),...e]}function O7(t){if(t<sh)return[];let e=Math.max(3,Math.ceil(Math.log2(t)));return E7.filter(r=>r<=t-1).map(r=>{let n=Math.floor(t*r/2);return To("SWISS",r,n,{variantId:`SWISS_R${r}${r===e?"_REC":""}`,rounds:r})})}function _7(t){return t<sh?[]:A7.filter(e=>e<=t-1).map(e=>To("DRAW_MATIC",e,Math.floor(t*e/2),{variantId:`DRAW_MATIC_R${e}`,rounds:e}))}function x7(t){if(t<sh)return[];if(U7(t))return[];let e=t-1;return[To("LUCKY_DRAW",1,e)]}function w7(t){if(t<4)return[];let e=Math.max(2,Math.ceil(Math.log2(t))),r=Math.round(t*1.6);return[To("ADAPTIVE",e,r)]}function L7(t){if(t<8)return[];let e=Math.max(2,Math.ceil(Math.log2(t))),r=t-1,n=[To("FEED_IN",1,r,{rounds:e,variantId:`FEED_IN_${e}_TIERS`})];return t>=8&&n.push(To("FEED_IN",2,Math.round(r*1.4),{rounds:e,variantId:"FIC_SF"})),t>=12&&n.push(To("FEED_IN",2,Math.round(r*1.6),{rounds:e,variantId:"FIC_QF"})),t>=16&&(n.push(To("FEED_IN",3,Math.round(r*1.8),{rounds:e,variantId:"FIC_R16"})),n.push(To("FEED_IN",3,Math.round(r*2),{rounds:e,variantId:"FIC"})),n.push(To("FEED_IN",2,Math.round(r*1.7),{rounds:e,variantId:"MFIC"}))),n}function F7(t,e){if(t.length===0||e<4)return[];let r=Math.max(2,Math.floor(e*P7)),n=ZM(r),o=Math.max(0,n-1);return t.map(i=>({...i,voluntaryConsolation:!0,totalMatches:i.totalMatches+o,variantId:i.variantId?`${i.variantId}_VC`:"VC"}))}function k7(t,e){let r=[...R7(t),...b7(t),...v7(t),...O7(t),..._7(t),...x7(t),...w7(t)];return e&&r.push(...L7(t)),r}function Nk({consolationAppetite:t="LIGHT",voluntaryConsolation:e=!1,allowedDrawTypes:r,singleFlight:n=!0,flightSize:o}){let i=new Set(N7[t]),s=r&&r.length>0?new Set(r):void 0,a=k7(o,n).filter(c=>!(!i.has(c.kind)||s&&!s.has(c.kind)));return e?[...a,...F7(a,o)]:a}var G7=90,V7=8,B7=.2,W7={SINGLE_ELIMINATION:Nr,FIRST_MATCH_LOSER_CONSOLATION:wo,FIRST_ROUND_LOSER_CONSOLATION:Ma,DOUBLE_ELIMINATION:Gs,COMPASS:xo,LUCKY_DRAW:ai,ADAPTIVE:ki,ROUND_ROBIN:hr,ROUND_ROBIN_WITH_PLAYOFF:Tr,SWISS:Bs},ah={competitive:60,floor:20,utilization:15,withdrawal:5};function H7({predictionModel:t,structure:e,flight:r}){let{kind:n}=e,o=r.ratings;if(n==="DRAW_MATIC")return Zp({ratings:o,projectionMode:"MIN_DELTA",predictionModel:t});if(n==="FEED_IN")return Zp({ratings:o,projectionMode:"BALANCED_BRACKET",predictionModel:t});let i=W7[n];return i?Zp({ratings:o,drawType:i,groupSize:e.groupSize,predictionModel:t}):Tf(0,t??{competitiveAnchors:[],decisiveAnchors:[]})}function Y7(t){let e=t.reduce((r,n)=>{let o=n.structure.totalMatches;return r.competitive+=n.predictedBands.competitive*o,r.decisive+=n.predictedBands.decisive*o,r.routine+=n.predictedBands.routine*o,r.totalMatches+=o,r},{competitive:0,decisive:0,routine:0,totalMatches:0});return e.totalMatches===0?{competitive:0,decisive:0,routine:0,totalMatches:0}:{competitive:e.competitive/e.totalMatches,decisive:e.decisive/e.totalMatches,routine:e.routine/e.totalMatches,totalMatches:e.totalMatches}}function j7(t){if(t.length===0)return{minMatchesPerPlayer:0};let e=1/0;for(let r of t)r.structure.minMatchesPerPlayer<e&&(e=r.structure.minMatchesPerPlayer);return{minMatchesPerPlayer:e}}function q7(t,e){let r=e.avgMinutes??G7,n=e.hoursPerDay??V7,o=t*r/60,i=e.courts*e.days*n,s=i>0?o/i:1/0;return{courtHoursRequired:o,courtHoursAvailable:i,courtUtilization:s}}function $7({minMatchesPerPlayer:t,flightStructures:e,courtUtilization:r,constraints:n}){let o=[];return typeof n.targetMatchesPerPlayer=="number"&&t<n.targetMatchesPerPlayer&&o.push("BELOW_FLOOR"),r>1&&o.push("OVER_CAPACITY"),e.some(i=>i.structure.withdrawalRiskFactor>=B7)&&o.push("WITHDRAWAL_RISK"),o}function K7(t,e){if(typeof t!="number")return e;let r=Math.abs(e-t);return Math.max(0,1-r)}function z7(t,e){return typeof e!="number"||t>=e?1:Math.max(0,t/e)}function Q7(t){return Number.isFinite(t)?t>1?Math.max(0,2-t):t:0}function X7(t){return t.length===0?1:1-Math.max(...t.map(r=>r.structure.withdrawalRiskFactor))}function J7({minMatchesPerPlayer:t,flightStructures:e,courtUtilization:r,constraints:n,competitive:o}){let i=K7(n.targetCompetitivePct,o),s=z7(t,n.targetMatchesPerPlayer),a=Q7(r),c=X7(e),u=i*ah.competitive+s*ah.floor+a*ah.utilization+c*ah.withdrawal,p=Object.values(ah).reduce((m,d)=>m+d,0);return u/p}function Dk({recommendationsByFlightSize:t,predictionModel:e,constraints:r,strategy:n}){if(n.flights.length===0)return[];let o=n.flights.length===1,i=new Set(n.flights.map(u=>u.participantIds.length)),s=new Map;for(let u of i)s.set(u,t(u,o));let a=Z7(n.flights,s),c=[];for(let u of a){let p=n.flights.map(d=>{let l=s.get(d.participantIds.length).find(f=>Uk(f,u));return{predictedBands:H7({flight:d,structure:l,predictionModel:e}),structure:l,flight:d}}),m=tQ({strategy:n,flightStructures:p,constraints:r});c.push(m)}return c}function Uk(t,e){return t.kind===e.kind&&(t.variantId??"")===(e.variantId??"")&&(t.groupSize??0)===(e.groupSize??0)}function Z7(t,e){if(t.length===0)return[];let r=t[0].participantIds.length;return(e.get(r)??[]).filter(o=>t.every(i=>(e.get(i.participantIds.length)??[]).some(a=>Uk(a,o))))}function tQ({flightStructures:t,constraints:e,strategy:r}){let n=Y7(t),o=j7(t),i=q7(n.totalMatches,e),s={minMatchesPerPlayer:o.minMatchesPerPlayer,courtHoursRequired:i.courtHoursRequired,courtHoursAvailable:i.courtHoursAvailable,courtUtilization:i.courtUtilization,totalMatches:n.totalMatches,competitive:n.competitive,decisive:n.decisive,routine:n.routine},a=$7({minMatchesPerPlayer:o.minMatchesPerPlayer,courtUtilization:i.courtUtilization,flightStructures:t,constraints:e}),c=J7({minMatchesPerPlayer:o.minMatchesPerPlayer,courtUtilization:i.courtUtilization,competitive:n.competitive,flightStructures:t,constraints:e});return{strategy:r.type,variant:r.variant,flightStructures:t,aggregate:s,warnings:a,score:c}}var eQ=Hs[gn].predictionModel,Rk={histogram:[],count:0,stddev:0,median:0,mean:0,iqr:0,min:0,max:0,gaps:[]};function rQ(t,e){if(t)return t;if(e){let{policy:r}=go({policyType:gn,tournamentRecord:e});if(r?.predictionModel)return r.predictionModel}return eQ}function nQ(t){return[...t].sort((r,n)=>n.score-r.score).map((r,n)=>({...r,rank:n+1}))}function gP({predictionModel:t,tournamentRecord:e,participants:r,governance:n,constraints:o}){if(!Array.isArray(r)||r.length<2)return{plans:[],distribution:Rk,error:O};if(!o||typeof o.courts!="number"||typeof o.days!="number")return{plans:[],distribution:Rk,error:O};let i=r.map(d=>d.rating),s=dP({ratings:i}),a=Pk(r),c=rQ(t,e),u=(d,l)=>Nk({consolationAppetite:o.consolationAppetite,voluntaryConsolation:o.voluntaryConsolation,allowedDrawTypes:n?.allowedDrawTypes,singleFlight:l,flightSize:d}),p=[],m=[];for(let d of a){let l=Dk({recommendationsByFlightSize:u,predictionModel:c,constraints:o,strategy:d});if(l.length===0){p.push({strategy:d.type,reason:"NO_ELIGIBLE_STRUCTURE"});continue}m.push(...l)}return{rejected:p.length>0?p:void 0,plans:nQ(m),distribution:s}}function bk(t){let r=t.participants?.filter(({participantType:a})=>a===_t)?.length===2,n=t.events?.length===1&&t.events[0],o=n?.drawDefinitions?.length===1&&n.drawDefinitions[0],s=(o?.structures?.length===1&&o.structures[0])?.positionAssignments?.length===2;return!!(n.tieFormat&&r&&s)}function IP({tournamentRecord:t}){if(!t)return{error:j};let{drawsAnalysis:e}=Xp({tournamentRecord:t}),r={isDual:bk(t),drawsAnalysis:e},n=bt({tournamentRecord:t});return n.missingParticipantIds?.length&&(r.missingParticipantIds=n.missingParticipantIds),{...P,analysis:r}}function SP(t){let{tournamentRecord:e,scope:r}=t;if(!e)return{error:j};let n=new Date().toISOString(),o=[],i=(c,u)=>{let{extension:p}=ot({element:c,name:sn}),m=p?.value??{locks:[]};for(let d of m.locks)d.expiresAt!==null&&d.expiresAt<=n||r&&d.scope!==r||o.push({...d,...u})};i(e);let s=e.events??[];for(let c of s){i(c,{eventId:c.eventId});let u=c.drawDefinitions??[];for(let p of u)i(p,{eventId:c.eventId,drawId:p.drawId})}let a=e.venues??[];for(let c of a)i(c,{venueId:c.venueId});return{...P,mutationLocks:o}}var rv={};Gt(rv,{compareTieFormats:()=>Ti,getTieFormat:()=>Hf,tieFormatGenderValidityCheck:()=>ml,validateCollectionDefinition:()=>gp});function Wf(t){if(!t)return{};let e=[],r=t.tieFormatName,n=t.collectionDefinitions?.map(o=>{let{matchUpType:i,matchUpFormat:s,matchUpCount:a,category:c,gender:u}=o;e.includes(s)||e.push(s);let p=c?.ageCategoryCode;return[a,i===ei?"D":"S",p,s,u].join(";")}).join("|");return{tieFormatName:t&&r||"UNNAMED",matchUpFormats:e,tieFormatDesc:n}}function Ti({considerations:t={},descendant:e,ancestor:r}){let n={},o={},{matchUpFormats:i,tieFormatDesc:s}=Wf(e),{matchUpFormats:a,tieFormatDesc:c}=Wf(r),u=pt((i??[]).filter(E=>!(a??[]).includes(E)).concat((a??[]).filter(E=>!(i??[]).includes(E)))),p=!!(t?.collectionName&&e.collectionDefinitions.map(({collectionName:E})=>E).join("|")!==r.collectionDefinitions.map(({collectionName:E})=>E).join("|")),m=!!(t?.collectionOrder&&e.collectionDefinitions.map(({collectionOrder:E})=>E).join("|")!==r.collectionDefinitions.map(({collectionOrder:E})=>E).join("|")),d=Object.assign({},...(e?.collectionDefinitions??[]).map(E=>({[E.collectionId]:E}))),l=Object.assign({},...(r?.collectionDefinitions??[]).map(E=>({[E.collectionId]:E})));n.collectionIds=DD(Object.keys(d),Object.keys(l)),o.collectionIds=DD(Object.keys(l),Object.keys(d)),n.collectionsValue=Ck(d),o.collectionsValue=Ck(l),n.groupsCount=r?.collectionGroups?.length??(0-(e?.collectionGroups?.length??0)||0),o.groupsCount=n.groupsCount?-1*n.groupsCount:0;let f=n.collectionsValue.totalValue-o.collectionsValue.totalValue,g=n.collectionsValue.totalMatchUps-o.collectionsValue.totalMatchUps,I=o.collectionsValue.assignmentValues.length!==n.collectionsValue.assignmentValues.length,S=o.collectionsValue.assignmentValues.some((E,A)=>{let N=n.collectionsValue.assignmentValues[A];return!N||E.valueKey!==N.valueKey||E.value!==N.value?!0:Array.isArray(E.value)?E.value.every((D,R)=>N.value[R]===D):!1}),h=p||m||c!==s||I||S||f!==0,T=[...o.collectionsValue.invalidValues,...n.collectionsValue.invalidValues],y=T.length&&T;return{matchUpFormatDifferences:u,matchUpCountDifference:g,descendantDifferences:n,ancestorDifferences:o,orderDifference:m,valueDifference:f,nameDifference:p,descendantDesc:s,ancestorDesc:c,...P,different:h,invalid:y}}function Ck(t){let e=[],r=[],n=0;return{totalValue:Object.keys(t).sort(Wp).reduce((s,a)=>{let c=t[a],{collectionValueProfiles:u,collectionValue:p,matchUpCount:m,matchUpValue:d,scoreValue:l,setValue:f}=c,g={collectionValueProfiles:u,collectionValue:p,matchUpValue:d,scoreValue:l,setValue:f},I=Object.keys(g).filter(h=>![void 0,null].includes(g[h])&&(!Array.isArray(g[h])||g[h].length>0));I.length!==1&&e.push({collectionId:a});let S=I[0];if(S){let h=S==="collectionValueProfiles"?Object.values(u):g[S];r.push({valueKey:S,value:h})}return n+=m,u?.length?s+u.reduce((h,T)=>h+T.value,0):m?yt(d)?s+d*m:yt(l)?s+l*m:yt(f)?s+f*m:s+p:s},0),totalMatchUps:n,invalidValues:e,assignmentValues:r}}function ch(t){Object.assign(t,{inContext:!0});let{matchUp:e,error:r}=ev(t);return{matchUp:q(e,!0,!0),error:r}}function ev({participantsProfile:t,afterRecoveryTimes:e,tournamentRecord:r,contextContent:n,contextProfile:o,drawDefinition:i,nextMatchUps:s,matchUpId:a,inContext:c,eventId:u,drawId:p,event:m}){if(!r)return{error:j};if(typeof a!="string")return{error:mr};if(!i||!m){let g=(qt({tournamentRecord:r,nextMatchUps:s}).matchUps??[]).find(I=>I.matchUpId===a);if(!g)return{error:Be};({eventId:u,drawId:p}=g),{event:m,drawDefinition:i}=_e({tournamentRecord:r,eventId:u,drawId:p})}if(!i)return{error:Mr};o&&!n&&(n=eo({tournamentRecord:r,contextProfile:o}));let d={surfaceCategory:m?.surfaceCategory??r.surfaceCategory,indoorOutDoor:m?.indoorOutdoor??r.indoorOutdoor,endDate:m?.endDate??r.endDate,tournamentId:r.tournamentId,eventId:u??m?.eventId,drawId:p},{participants:l=[]}=di({participantsProfile:t,tournamentRecord:r,contextProfile:o,inContext:c});if(s){let g=(rr({context:c?d:void 0,participants:l,afterRecoveryTimes:e,contextContent:n,contextProfile:o,drawDefinition:i,nextMatchUps:s,inContext:c,event:m}).matchUps??[]).find(S=>S.matchUpId===a);if(!g)return{error:Be};let I=i?.structures?.find(S=>S.structureId===g.structureId);return{drawDefinition:i,structure:I,matchUp:g}}else{let{matchUp:f,structure:g}=Wt({context:c?d:void 0,tournamentParticipants:l,participantsProfile:t,afterRecoveryTimes:e,contextContent:n,drawDefinition:i,contextProfile:o,matchUpId:a,inContext:c,event:m});return{matchUp:f,structure:g,drawDefinition:i}}}function Hf({tournamentRecord:t,drawDefinition:e,structureId:r,matchUpId:n,structure:o,eventId:i,drawId:s,event:a}){if(!t)return{error:j};if(!s&&!a&&!r&&!n)return M({result:{error:nt},stack:"getTieFormat"});i&&!a&&(a=t.events?.find(l=>l.eventId===i));let c=ch({tournamentRecord:t,drawDefinition:e,matchUpId:n,drawId:s,event:a});if(n&&c?.error)return c;if(!e&&c?.drawDefinition&&(e=c?.drawDefinition),o=o??c?.structure,!o&&r&&!n){if(!e)return{error:Nn};let l=tt({drawDefinition:e,structureId:r});if(l.error)return l;o=l.structure}let u=(o?.tieFormat||o?.tieFormatId)&&ze({structure:o,drawDefinition:e,event:a})?.tieFormat,p=(e?.tieFormat||e?.tieFormatId)&&ze({drawDefinition:e,event:a})?.tieFormat,m=ze({event:a})?.tieFormat,d=ze({matchUp:c?.matchUp,drawDefinition:e,structure:o,event:a})?.tieFormat;return{...P,matchUp:c?.matchUp,structureDefaultTieFormat:nr(u),eventDefaultTieFormat:nr(m),drawDefaultTieFormat:nr(p),tieFormat:nr(d),structure:o}}var nv={};Gt(nv,{bulkUpdatePublishedEventIds:()=>hP,getAllEventData:()=>yP,getCourtInfo:()=>$l,getDrawData:()=>yf,getEventData:()=>tm,getEventPublishStatus:()=>Cr,getPublishState:()=>ra,getRoundVisibilityState:()=>TP,getTournamentPublishStatus:()=>Uc,getVenueData:()=>Eu,isEmbargoed:()=>Uo,isVisiblyPublished:()=>ro});function hP({tournamentRecord:t,outcomes:e}){if(!t)return{error:j};if(!e?.length)return{error:nt,info:"Missing outcomes"};let r=e.reduce((s,a)=>{let{drawId:c,eventId:u}=a;return u&&c&&(s[u]?s[u].includes(c)||s[u].push(c):s[u]=[c]),s},{}),n=Object.keys(r);return{publishedEventIds:(t.events?.filter(s=>n.includes(s.eventId))).filter(s=>{let a=Cr({event:s}),{drawDetails:c,drawIds:u}=a??{},{eventId:p}=s;return r[p].filter(d=>{let l=c?Object.keys(a.drawDetails).filter(f=>Bp({drawId:f,drawDetails:c})):[];return u?.includes(d)||l.includes(d)}).length}).map(s=>s.eventId),eventIdPublishedDrawIdsMap:r}}function TP(t,e){if(!t||!e?.length)return;let r=t.roundLimit,n=t.scheduledRounds??{},o=e.reduce((a,c)=>Math.max(a,c.roundNumber||0),0);if(o===0)return;let i={},s=!1;for(let a=1;a<=o;a++){let c={};r!=null&&a>r&&(c.hidden=!0,s=!0);let u=n[a];u&&Uo(u)&&(c.embargoed=!0,s=!0),(c.hidden||c.embargoed)&&(i[a]=c)}return s?i:void 0}function yP({tournamentRecord:t,policyDefinitions:e}){if(!t)return{error:j};let r=t.events??[],n=t?.participants??[],{tournamentInfo:o}=ia({tournamentRecord:t}),{venues:i}=kn({tournamentRecord:t}),s=r.map(c=>{let{eventId:u}=c,p=aA({event:c}).eventInfo,m=Ac({tournamentRecord:t,event:c}).scheduleTiming,d=(c.drawDefinitions??[]).map(f=>{let{drawId:g,drawName:I,matchUpFormat:S,updatedAt:h}=f,T={drawId:g,drawName:I,matchUpFormat:S,updatedAt:h},{abandonedMatchUps:y,completedMatchUps:E,upcomingMatchUps:A,pendingMatchUps:N}=Ga({requireParticipants:!0,tournamentParticipants:n,context:{eventId:u},policyDefinitions:e,tournamentRecord:t,inContext:!0,scheduleTiming:m,drawDefinition:f,event:c});return{drawInfo:T,matchUps:{abandonedMatchUps:y,completedMatchUps:E,upcomingMatchUps:A,pendingMatchUps:N}}}),l=Cr({event:c});return Object.assign(p,{drawsData:d,publish:l}),p});return{allEventData:{tournamentInfo:o,venuesData:i,eventsData:s}}}var av={};Gt(av,{courtGridRows:()=>qf,findVenue:()=>Ln,getMatchUpsToSchedule:()=>Yf,getPersonRequests:()=>is,getProfileRounds:()=>jf,getScheduledRoundsDetails:()=>sm,getSchedulingProfile:()=>bo,getSchedulingProfileIssues:()=>EP,publicFindCourt:()=>SE});function Za({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:e,timeAfterRecovery:r,matchUp:n}){let{individualParticipantIds:o}=Mp(n);r=r??n.schedule?.timeAfterRecovery;let i=u=>{t[u]||(t[u]=[]),t[u]=pt(t[u].concat(...o))},s=u=>{r&&(!e[u]||r>e[u])&&(e[u]=r)},a=n.winnerTo?.matchUpId||n.winnerMatchUpId;a&&(r&&s(a),i(a));let c=n.loserTo?.matchUpId||n.loserMatchUpId;c&&(r&&s(c),i(c)),n.sidesTo?.length&&n.sidesTo.forEach(({matchUpId:u})=>{u&&(r&&s(u),i(u))})}function Yf(t){let e=X(t,[{[CI]:!0}]);if(e.error)return e;let{matchUpPotentialParticipantIds:r,dateScheduledMatchUpIds:n=[],scheduleCompletedMatchUps:o,matchUpNotBeforeTimes:i,matchUpScheduleTimes:s,orderedMatchUpIds:a,clearDate:c,matchUps:u}=t,p=s?Object.keys(s):[],m=(a??[]).map(l=>u.find(f=>f.matchUpId===l)).filter(Boolean).filter(l=>{let f=!c&&(n.includes(l.matchUpId)||p.includes(l.matchUpId)),g=["BYE",Mt,ie,Fr,De,vt,Qt,ge].includes(l?.matchUpStatus);return o||!f&&!l.winningSide&&!g}),d=r&&i?m.reduce((l,f)=>{let{drawId:g,tournamentId:I}=f;return l.matchUpMap[I]||(l.matchUpMap[I]={}),l.matchUpMap[I][g]?l.matchUpMap[I][g].push(f):l.matchUpMap[I][g]=[f],Za({matchUpPotentialParticipantIds:r,matchUpNotBeforeTimes:i,matchUp:f}),l},{matchUpMap:{}}).matchUpMap:{};return{matchUpsToSchedule:m,matchUpMap:d}}function _d({defaultRecoveryMinutes:t=0,defaultAverageMinutes:e,tournamentRecords:r,matchUpFormat:n,categoryName:o,categoryType:i,tournamentId:s,eventType:a,eventId:c}){if(!xr({matchUpFormat:n}))return{error:Kc};let u=Object.keys(r).filter(m=>!s||m===s),p;return u.forEach(m=>{if(p)return;let d=r[m],l=c?_e({tournamentRecord:d,eventId:c})?.event:void 0;return p=Fp({tournamentRecord:d,matchUpFormat:n,categoryName:o,categoryType:i,eventType:a,event:l}),p?.averageMinutes||p?.recoveryMinutes}),{recoveryMinutes:p?.recoveryMinutes||t,averageMinutes:p?.averageMinutes||e,typeChangeRecoveryMinutes:p?.typeChangeRecoveryMinutes||p?.recoveryMinutes||t}}function sm(t){let e=X(t,[{[yp]:{tournamentRecords:!1,tournamentRecord:!1}},{rounds:!0,[Ge]:ke}]);if(e.error)return e;let{scheduleCompletedMatchUps:r,periodLength:n=30}=t,o=t.tournamentRecords||t.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord}||{};if(typeof o!="object")return{error:kt};let i={},s=[],a=[],c=t.rounds.toSorted((I,S)=>(I.sortOrder??0)-(S.sortOrder??0)),u=t.containedStructureIds??Object.assign({},...Object.values(o).map(I=>ji({tournamentRecord:I}).containedStructures)),p=t.matchUps??cn({nextMatchUps:!0,tournamentRecords:o}).matchUps,m=0,d={},l={},f={};return{scheduledRoundsDetails:c.flatMap(I=>{let S=I.periodLength||n,h=[];u?.[I.structureId]?h.push(...u[I.structureId]):h.push(I.structureId);let T=p?zi({tournamentIds:[I.tournamentId],roundNumbers:[I.roundNumber],matchUpIds:I.matchUpIds,eventIds:[I.eventId],drawIds:[I.drawId],processContext:!0,structureIds:h,matchUps:p}).sort(Qi):[],{segmentNumber:y,segmentsCount:E}=I.roundSegment??{};if(yt(y)&&en(T?.length)&&en(E)&&y>0&&y<=E&&E<T?.length&&!I.matchUpIds?.length){let R=T.length/E,U=R*(y-1);T=T.slice(U,U+R)}let A=o[I.tournamentId],N=_e({drawId:I.drawId,tournamentRecord:A}).event,D=[];for(let R of T){let U=R.matchUpFormat;U&&(i[U]||(i[U]=[],i[U].push(R)),D.push(U))}for(let R of D){let{eventType:U,category:b}=N??{},{categoryName:C,ageCategoryCode:_}=b??{},{typeChangeRecoveryMinutes:v,recoveryMinutes:w,averageMinutes:L,error:F}=_d({categoryName:C??_,categoryType:b?.categoryType,tournamentId:I.tournamentId,eventId:I.eventId,tournamentRecords:o,matchUpFormat:R,eventType:U});if(F)return{error:F,round:I};let x=T.filter(G=>(r||!Ot.includes(G.matchUpStatus))&&G.matchUpStatus!=="BYE").map(Te);x.forEach(G=>{f[G]={typeChangeRecoveryMinutes:v,recoveryMinutes:w,averageMinutes:L},d[G]=w,l[G]=L}),a.push(...x),m=Math.max(L||0,m);let k=`${L}|${S}`;return s.includes(k)||s.push(k),{roundPeriodLength:S,recoveryMinutes:w,averageMinutes:L,matchUpIds:x,hash:k}}}),greatestAverageMinutes:m,matchUpFormatCohorts:i,recoveryMinutesMap:d,averageMinutesMap:l,orderedMatchUpIds:a,minutesMap:f,...P}}function ov({schedulingProfile:t,venueIds:e,eventIds:r,drawIds:n}){let o=[],i=t?.map(a=>{let c=mt(a?.scheduleDate);if(!c){o.push(`Invalid date: ${a?.scheduledDate}`);return}let u=(a?.venues??[]).map(p=>{let{rounds:m,venueId:d}=p;if(!e?.includes(d)){o.push(`Missing venueId: ${d}`);return}let f=m.filter(g=>{let I=r.includes(g.eventId)&&n.includes(g.drawId);return I||o.push(`Invalid eventId: ${g.eventId} or drawId: ${g.drawId}`),I});if(f.length)return{venueId:d,rounds:f}}).filter(Boolean);return u.length&&c&&{...a,venues:u}}).filter(Boolean),s=o.length;return{updatedSchedulingProfile:i,modifications:s,issues:o}}function xd({tournamentRecords:t,schedulingProfile:e}){if(!e)return{valid:!0};if(!Array.isArray(e))return{valid:!1,error:O};let{venueIds:r,tournamentsMap:n}=iQ({tournamentRecords:t}),o,i,s=e.every(a=>{let{scheduleDate:c,venues:u}=a;return Me(c)?u.every(p=>{let{venueId:m,rounds:d}=p;return typeof m!="string"?(i="venueId should be a string",!1):Array.isArray(d)?r.includes(m)?!!d.every(f=>{if(!f)return i="empty round",!1;let{roundSegment:g,tournamentId:I,structureId:S,roundNumber:h,eventId:T,drawId:y}=f,A=n?.[I]?.[T]?.[y]?.[S]?.includes(h);A||(i="Invalid rounds");let{segmentNumber:N,segmentsCount:D}=g??{},R=!g||yt(N)&&en(D)&&N<=D;return R||(i="Invalid segment"),A&&R}):(o=wi,!1):(i="rounds should be an array",!1)}):!1});return!s&&!o&&(o=O),{valid:!!s,error:o,info:i}}function oQ(t){let{tournamentRecord:e={},tournamentMap:r={},requireCourts:n}=t,o=[],i=[],s=[],a=[],c=(e?.venues??[]).map(({venueId:p,courts:m})=>(!n||m?.length)&&p),u=e?.tournamentId;if(u){o.push(u),r[u]={};let p=e?.events??[];for(let m of p){let d=m.eventId;s.push(d),r[u][d]={};let l=f=>parseInt(f);for(let f of m.drawDefinitions??[]){let g=f.drawId;a.push(g),r[u][d][g]={};let{structures:I}=Sn({drawDefinition:f});for(let S of I??[]){let h=S.structureId,{matchUps:T}=ht({structure:S}),{roundMatchUps:y}=Ue({matchUps:T}),E=y&&Object.keys(y).map(l);if(r[u][d][g][h]=E,i.push(h),S.structures?.length)for(let A of S.structures)i.push(A.structureId),r[u][d][g][A.structureId]=E}}}}return{tournamentMap:r,tournamentIds:o,structureIds:i,venueIds:c,eventIds:s,drawIds:a}}function iQ(t){let e=(t?.tournamentRecords&&Object.values(t?.tournamentRecords))??[],r={},{venueIds:n,eventIds:o,drawIds:i,structureIds:s,tournamentIds:a}=e.reduce((c,u)=>{let{tournamentIds:p,tournamentMap:m,structureIds:d,venueIds:l,eventIds:f,drawIds:g}=oQ({tournamentRecord:u});return l.forEach(I=>{c.venueIds.includes(I)||c.venueIds.push(I)}),c.tournamentIds.push(...p),c.structureIds.push(...d),c.eventIds.push(...f),c.drawIds.push(...g),Object.assign(r,m),c},{tournamentIds:[],structureIds:[],venueIds:[],eventIds:[],drawIds:[]});return{tournamentsMap:r,tournamentIds:a,structureIds:s,venueIds:n,eventIds:o,drawIds:i}}function bo({tournamentRecords:t,tournamentRecord:e}){if(typeof t!="object"||!Object.keys(t).length)return{error:kt};let{extension:r}=ot({element:e,name:hc,tournamentRecords:t,discover:!0}),n=r?.value??[];if(n.length){let{venueIds:o}=hd({requireCourts:!0,tournamentRecords:t}),{eventIds:i,drawIds:s}=kS({tournamentRecords:t}),{updatedSchedulingProfile:a,modifications:c,issues:u}=ov({schedulingProfile:n,venueIds:o,eventIds:i,drawIds:s});if(c){n=a;let p=Fu({tournamentRecords:t,tournamentRecord:e,schedulingProfile:n});return p.error?p:{schedulingProfile:n,modifications:c,issues:u}}}return{schedulingProfile:n,modifications:0}}function Fu({tournamentRecords:t,tournamentRecord:e,schedulingProfile:r}){let n=xd({tournamentRecords:t,schedulingProfile:r});return n.error?n:r?ut({tournamentRecords:t,discover:!0,extension:{name:hc,value:r}}):dr({element:e,name:hc,tournamentRecords:t,discover:!0})}function ku(t){let{tournamentRecord:e}=t,r=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!t.schedulingProfile){let{modifications:u,issues:p}=bo({tournamentRecords:r,tournamentRecord:e});return{success:!u,modifications:u,issues:p}}let{venueIds:n}=hd({tournamentRecords:r}),{eventIds:o,drawIds:i}=kS({tournamentRecords:r}),{updatedSchedulingProfile:s,modifications:a,issues:c}=ov({schedulingProfile:t.schedulingProfile,venueIds:n,eventIds:o,drawIds:i});return a?{...Fu({schedulingProfile:s,tournamentRecords:r}),modifications:a,issues:c}:{...P,modifications:a,issues:c}}function EP(t){let{scheduleDates:e=[],tournamentRecords:r,periodLength:n=30}=t??{};if(typeof r!="object")return{error:Hc};if(!Array.isArray(e))return{error:O};if(!e.every(Me))return{error:ae};let i=[],s=0,a={},{schedulingProfile:c}=bo({tournamentRecords:r});if(!c)return{issues:i,...P};let{matchUps:u}=cn({nextMatchUps:!0,tournamentRecords:r});for(let m of c){let{scheduleDate:d,venues:l=[]}=m;if(!e?.length||e.includes(d)){for(let f of l??[])if(f){let{rounds:g}=f,I=[],{orderedMatchUpIds:S,scheduledRoundsDetails:h}=sm({tournamentRecords:r,periodLength:n,matchUps:u,rounds:g}),{matchUpDependencies:T}=tn({tournamentRecords:r,matchUps:u}),y=E=>{let A;return h?.find((N,D)=>{let R=N.matchUpIds.includes(E);return R&&(A=D),R}),A};if(S?.forEach((E,A)=>{let N=S.slice(A+1),D=Yt(N,T?.[E]?.matchUpIds??[]);D.length&&I.push({matchUpId:E,shouldBeAfter:D})}),I.length){s+=I.length;let E=I.map(({matchUpId:A,shouldBeAfter:N})=>{let D=y(A),R=pt(N.map(y));return a[d]||(a[d]={}),a[d][D]||(a[d][D]=[]),R.forEach(U=>{a[d][D].includes(U)||a[d][D].push(U)}),{matchUpId:A,matchUpRoundIndex:D,earlierRoundIndices:R,shouldBeAfter:N}});i.push(...E)}}}}let p={matchUpIdShouldBeAfter:Object.assign({},...i.map(m=>{let{matchUpId:d,shouldBeAfter:l,earlierRoundIndices:f}=m;return{[d]:{earlierRoundIndices:f,shouldBeAfter:l}}}))};return{issuesCount:s,profileIssues:p,roundIndexShouldBeAfter:a,...P}}function is(t){let{tournamentRecords:e,requestType:r}=t,n=X(t,[{[Ee]:!0}]);if(n.error)return n;let o={};for(let i of Object.values(e)){let{extension:s}=ot({element:i,name:Sc}),a=s?.value??[];for(let c of a){let{personId:u,requests:p}=c??{};o[u]||(o[u]=[]);for(let m of p)r&&m.requestType!==r||o[u].push(m)}}return{personRequests:o,...P}}function uh(t){let{containerStructureId:e,roundSegment:r,isRoundRobin:n,tournamentId:o,roundNumber:i,structureId:s,eventId:a,drawId:c}=t,u=n?e:s,p=[o,a,c,u,i].join("|");return et({structureId:u,roundSegment:r,tournamentId:o,roundNumber:i,eventId:a,drawId:c,id:p})}function iv({round:t,matchUps:e,events:r,tournamentRecords:n}){let o=r.find(d=>d.eventId===t.eventId),{eventType:i,category:s,categoryType:a}=o??{},{categoryName:c,ageCategoryCode:u}=s??{},p=mn(e.map(({matchUpFormat:d})=>d)),m=0;return Object.keys(p).forEach(d=>{let l=p[d],f=_d({categoryName:c||u,tournamentId:t.tournamentId,eventId:t.eventId,tournamentRecords:n,matchUpFormat:d,categoryType:a,eventType:i});if(f.error)return f;let g=f.averageMinutes*l;isNaN(m)||(m+=g)}),{roundMinutes:m}}function Mk(t){return(t??[]).reduce((e,r)=>{let n=(r.finishingPositionRange?.winner??[]).reduce((i,s)=>i+s,0),o=(r.finishingPositionRange?.winner??[]).join("-")||"";return!e.minFinishingSum||n<e.minFinishingSum?{minFinishingSum:n,winnerFinishingPositionRange:o}:e},{minFinishingSum:0,winnerFinishingPositionRange:""})}function sv(t){let e=t.length,r=t.filter(({sides:p})=>p?.some(({bye:m})=>m)).length||0,n=t.filter(({winningSide:p,matchUpStatus:m})=>p||Ot.includes(m)).length||0,o=t.filter(({schedule:p,matchUpStatus:m})=>p?.scheduledDate&&p?.scheduledTime&&m!=="BYE").length||0,i=e-r,s=i===n,a=i-o,c=i-o;return{unscheduledCount:a,incompleteCount:c,scheduledCount:o,completedCount:n,matchUpsCount:e,isScheduled:i===o,isComplete:s,byeCount:r}}function jf({tournamentRecords:t,schedulingProfile:e,tournamentRecord:r,withRoundId:n}){if(r&&!t){if(typeof r!="object")return{error:Hc};t={[r.tournamentId]:r}}if(e){let s=xd({tournamentRecords:t,schedulingProfile:e});if(s.error)return s}if(!e&&t){let s=bo({tournamentRecords:t});if(s.error)return s;e=s.schedulingProfile}if(!e)return{error:fe};let o={};return{profileRounds:e.map(({venues:s,scheduleDate:a})=>s.map(({rounds:c})=>c.map(u=>{let p=uh(u);return p.roundSegment?.segmentsCount&&(o[p.id]=p.roundSegment.segmentsCount),et({id:n?p.id:void 0,scheduleDate:a,...p})}))).flat(1/0),segmentedRounds:o}}function Qo({court:t,date:e}){let r=e&&t.dateAvailability?.find(o=>Xn(o.date,e)),n=t.dateAvailability?.find(o=>!o.date);return r||n}function vk({court:t,date:e}){let r=Qo({court:t,date:e}),n=new Map,o=[];return(r?.bookings??[]).forEach(i=>{if(typeof i.courtOrder=="number"){let s=i.rowCount||1;for(let a=0;a<s;a++)n.set(i.courtOrder+a,i)}else o.push(i)}),{gridBookings:n,timeBookings:o}}function qf({courtPrefix:t="C|",minRowsCount:e,courtsData:r,scheduledDate:n}){if(!Array.isArray(r))return{error:O};let o=r?.reduce((a,c)=>{let u=c.matchUps??[],p=Math.max(0,...u.map(m=>m.schedule.courtOrder||0));return Math.max(p,a)},1),i=Math.max(e||0,o),s=Q(0,i).map(a=>({matchUps:Q(0,r.length).map(c=>{let u=r[c],{courtId:p,venueId:m}=u;if(n){let{gridBookings:d}=vk({court:u,date:n});if(d.has(a+1)){let l=d.get(a+1);return{schedule:{courtOrder:a+1,venueId:m,courtId:p},isBlocked:!0,booking:l}}}return{schedule:{courtOrder:a+1,venueId:m,courtId:p}}})}));return r.forEach((a,c)=>{for(let u of a.matchUps){let p=u.schedule?.courtOrder;p&&(s[p-1].matchUps[c]=u)}}),{courtPrefix:t,rows:s.map((a,c)=>Object.assign({rowId:`rowId-${c+1}`},...a.matchUps.map((u,p)=>({[`${t}${p}`]:u}))))}}var cv={};Gt(cv,{getEntriesAndSeedsCount:()=>$f,getMaxEntryPosition:()=>AP});function $f({policyDefinitions:t,drawDefinition:e,drawSize:r,drawId:n,event:o,stage:i}){if(!o)return{error:le};let{entries:s,stageEntries:a}=UE({drawDefinition:e,drawId:n,stage:i,event:o}),c=a.length,{drawSize:u}=bA({participantsCount:c}),p=rm({drawSize:r??u,participantsCount:c,policyDefinitions:t});if(p.error)return M({result:p,stack:"getEntriesAndSeedsCount"});let{seedsCount:m}=p;return{entries:s,seedsCount:m,stageEntries:a}}function AP(t){let{entries:e=[],entryStatus:r,stage:n}=t;return Math.max(...e.filter(o=>(!n||n===o.entryStage)&&(!r||o.entryStatus===r)&&!isNaN(o.entryPosition)).map(({entryPosition:o})=>st(o||0)),0)}var dv={};Gt(dv,{allCompetitionMatchUps:()=>cn,allDrawMatchUps:()=>rr,allEventMatchUps:()=>vn,allTournamentMatchUps:()=>qt,analyzeMatchUp:()=>Ld,calculateMatchUpMargin:()=>Id,calculateWinCriteria:()=>ua,checkMatchUpIsComplete:()=>Js,competitionScheduleMatchUps:()=>am,drawMatchUps:()=>FP,eventMatchUps:()=>Qf,filterMatchUps:()=>zi,getAllDrawMatchUps:()=>te,getAllStructureMatchUps:()=>ht,getCheckedInParticipantIds:()=>$s,getCompetitionFormat:()=>MP,getCompetitionMatchUps:()=>wd,getEventMatchUpFormatTiming:()=>UP,getHomeParticipantId:()=>_P,getMatchUpCompetitiveProfile:()=>js,getMatchUpContextIds:()=>OP,getMatchUpDailyLimits:()=>Jf,getMatchUpDailyLimitsUpdate:()=>CP,getMatchUpDependencies:()=>tn,getMatchUpFormat:()=>xP,getMatchUpFormatTiming:()=>Fp,getMatchUpFormatTimingUpdate:()=>NP,getMatchUpScheduleDetails:()=>Kl,getMatchUpType:()=>zl,getMatchUpsStats:()=>wP,getModifiedMatchUpFormatTiming:()=>Kf,getParticipantResults:()=>Vp,getPredictiveAccuracy:()=>vP,getRoundMatchUps:()=>Ue,getRounds:()=>LP,isValidMatchUpFormat:()=>xr,matchUpActions:()=>Af,participantScheduledMatchUps:()=>bP,predictMatchUpCompetitiveBands:()=>RP,tallyParticipantResults:()=>ea,tournamentMatchUps:()=>Xf,validMatchUp:()=>rS,validMatchUps:()=>Rr});function PP({tournamentRecords:t,extensionName:e}){if(typeof t!="object"||!Object.keys(t).length)return{error:kt};let r=[],n;for(let o of Object.values(t)){let{extension:i}=ot({element:o,name:e});i&&!n&&(r.push({params:{extension:i,discover:!0},method:"addExtension"}),n=!0);let s=o.events??[];for(let a of s){let{eventId:c}=a,{extension:u}=ot({name:e,element:a});u&&r.push({params:{eventId:c,extension:u},method:"addEventExtension"})}}return{methods:r}}function NP({tournamentRecords:t}){return PP({extensionName:pi,tournamentRecords:t})}var uv="ADULT",pv="JUNIOR",DP="WHEELCHAIR",mv={[ko]:{allowModificationWhenMatchUpsScheduled:{courts:!1,venues:!1},defaultTimes:{averageTimes:[{categoryNames:[],minutes:{default:90}}],recoveryTimes:[{minutes:{[Rt]:30,default:60}}]},defaultDailyLimits:{[Ct]:2,[Rt]:2,total:3},matchUpAverageTimes:[{matchUpFormatCodes:[xn],averageTimes:[{categoryNames:[],minutes:{default:90}},{categoryTypes:[DP],minutes:{default:120}}]},{matchUpFormatCodes:["SET3-S:6/TB7-F:TB10"],averageTimes:[{categoryNames:[],minutes:{default:85}}]},{matchUpFormatCodes:["SET3-S:6/TB7-F:TB7"],averageTimes:[{categoryNames:[],minutes:{default:70}}]},{matchUpFormatCodes:["SET3-S:4NOAD-F:TB7"],averageTimes:[{categoryNames:[],minutes:{default:55}}]},{matchUpFormatCodes:["SET3-S:4/TB7"],averageTimes:[{categoryNames:[],minutes:{default:60}}]},{matchUpFormatCodes:["SET3-S:4/TB7-F:TB7"],averageTimes:[{categoryNames:[],minutes:{default:50}}]},{matchUpFormatCodes:["SET3-S:4/TB7-F:TB10"],averageTimes:[{categoryNames:[],minutes:{default:55}}]},{matchUpFormatCodes:["SET3-S:4/TB5@3"],averageTimes:[{categoryNames:[],minutes:{default:45}}]},{matchUpFormatCodes:["SET1-S:8/TB7","SET1-S:8/TB7@7"],averageTimes:[{categoryNames:[],minutes:{default:40}}]},{matchUpFormatCodes:["SET1-S:5/TB9@4"],averageTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:6/TB7"],averageTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:6NOAD"],averageTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:4/TB7","SET1-S:4/TB5@3","SET3-S:TB10","SET1-S:T20"],averageTimes:[{categoryNames:[],minutes:{default:20}}]},{matchUpFormatCodes:["SET1-S:4NOAD"],averageTimes:[{categoryNames:[],minutes:{default:20}}]},{matchUpFormatCodes:["SET1-S:TB10"],averageTimes:[{categoryNames:[],minutes:{default:10}}]}],matchUpRecoveryTimes:[{matchUpFormatCodes:["SET3-S:6/TB7","SET3-S:6/TB7-F:TB10","SET3-S:6/TB7-F:TB7"],recoveryTimes:[{categoryTypes:[uv,DP],minutes:{default:60,[Rt]:30}},{categoryTypes:[pv],minutes:{default:60,[Rt]:60}}]},{matchUpFormatCodes:["SET3-S:4/TB7-F:TB7","SET3-S:4/TB7-F:TB10","SET3-S:4NOAD-F:TB7","SET3-S:4/TB7","SET3-S:4/TB5@3"],recoveryTimes:[{categoryTypes:[uv,DP],minutes:{default:30}},{categoryTypes:[pv],minutes:{default:60}}]},{matchUpFormatCodes:["SET1-S:8/TB7","SET1-S:8/TB7@7","SET1-S:5/TB9@4","SET1-S:6/TB7","SET1-S:6NOAD","SET1-S:4/TB7","SET1-S:4NOAD","SET3-S:TB10","SET1-S:T20"],recoveryTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:4/TB5@3"],recoveryTimes:[{categoryTypes:[uv,pv],minutes:{default:30}},{categoryTypes:[DP],minutes:{default:15}}]},{matchUpFormatCodes:["SET1-S:TB10"],recoveryTimes:[{categoryNames:[],minutes:{default:15}}]}],matchUpDailyLimits:[]}},Ok=mv;function UP({tournamentRecord:t,matchUpFormats:e,categoryType:r,event:n}){if(!n)return{error:le};let o,i;if(e?.length){let m=[];o=e.map(d=>{let l=typeof d=="string"?{matchUpFormat:d}:d;if(!m.includes(l?.matchUpFormat)&&xr({matchUpFormat:l?.matchUpFormat}))return m.push(l.matchUpFormat),l}).filter(Boolean)}else{let{policy:m}=go({policyType:Qr,tournamentRecord:t,event:n});if(m?.matchUpFormats)o=m?.matchUpFormats;else{let{extension:d}=ot({name:pi,element:n}),l,f;d?.value?{matchUpAverageTimes:l,matchUpRecoveryTimes:f}=d.value:{matchUpAverageTimes:l,matchUpRecoveryTimes:f}=Ok[ko],o=pt([...(l??[]).map(g=>g.matchUpFormatCodes),...(f??[]).map(g=>g.matchUpFormatCodes)].flat()).map(g=>({matchUpFormat:g})),i="default scheduling policy in use"}}let{eventType:s,eventId:a,category:c}=n,u=c?.categoryName??c?.ageCategoryCode??a;if(!a)return{error:le};let p=o.map(({matchUpFormat:m,description:d})=>{let l=Fp({tournamentRecord:t,matchUpFormat:m,categoryName:u,categoryType:r,eventType:s,event:n});return{matchUpFormat:m,description:d,...l}});return et({eventMatchUpFormatTiming:p,info:i})}function Kf(t){let e=X(t,[{[rt]:!0},{[$e]:g=>xr({matchUpFormat:g}),[Lr]:Kc,[Sl]:!0}]);if(e.error)return e;let{tournamentRecord:r,matchUpFormat:n,event:o}=t,{extension:i}=ot({name:pi,element:o}),s=i?.value,{extension:a}=ot({element:r,name:pi}),c=a?.value,u=s?.matchUpAverageTimes&&nd({...s,matchUpFormat:n}),p=c?.matchUpAverageTimes&&nd({...c,matchUpFormat:n}),m=[u,p].find(g=>g),d=s?.matchUpRecoveryTimes&&od({...s,matchUpFormat:n}),l=c?.matchUpRecoveryTimes&&od({...c,matchUpFormat:n}),f=[d,l].find(g=>g);return{matchUpFormat:n,recoveryTimes:f,averageTimes:m}}var sQ=Hs[gn].predictionModel;function aQ(t,e){if(t)return t;if(e){let{policy:r}=go({policyType:gn,tournamentRecord:e});if(r?.predictionModel)return r.predictionModel}return sQ}function RP({tournamentRecord:t,predictionModel:e,side1Rating:r,side2Rating:n}){if(typeof r!="number"||typeof n!="number")return{competitive:0,decisive:0,routine:0,error:O};let o=aQ(e,t),i=Math.abs(r-n);return{...Tf(i,o),delta:i}}var _c=({scheduleAttributes:t=["scheduledDate","scheduledTime"],schedule:e={}})=>!!Object.keys(e).filter(n=>t.includes(n)).filter(n=>e[n]).length;function bP({scheduleAttributes:t=["scheduledDate","scheduledTime"],matchUps:e=[]}){if(!Rr(e))return{error:Bn};if(!Array.isArray(t))return{error:O};let r=e.filter(Boolean).filter(({schedule:o})=>_c({schedule:o,scheduleAttributes:t})).reduce((o,i)=>{let{schedule:s}=i,a=mt(s?.scheduledDate),c=$t(s?.scheduledTime);return a&&c&&(o[a]?o[a].push(i):o[a]=[i]),o},{});return Object.keys(r).forEach(o=>{r[o].sort((i,s)=>ny($t(i.schedule?.scheduledTime),$t(s.schedule?.scheduledTime)))}),{...P,scheduledMatchUps:r}}function CP({tournamentRecords:t}){return PP({extensionName:Np,tournamentRecords:t})}function _k({tournamentRecords:t}){let e={},r=[];for(let n of Object.values(t))for(let o of n.events??[]){let i=Cr({event:o}),s=i?.drawDetails;Tt(s)?(Object.assign(e,s),r.push(...Object.keys(s).filter(a=>Bp({drawId:a,drawDetails:s})))):i?.drawIds?.length&&r.push(...i.drawIds)}return{drawIds:r,detailsMap:e}}function zf({schedulingProfile:t,matchUps:e=[]}){let r={},n=({eventId:a,drawId:c,structureId:u,roundNumber:p})=>`${a}|${c}|${u}${p}`;t?.length&&t.flatMap(({venues:c})=>c.map(({rounds:u})=>u)).forEach(c=>{c.sort((p,m)=>(p.sortOrder||0)-(m.sortOrder||0)).forEach(({eventId:p,drawId:m,structureId:d,roundNumber:l},f)=>{let g=n({eventId:p,drawId:m,structureId:d,roundNumber:l});r[g]=f})});let o=[],i={noScheduledDate:[]};for(let a of e){let c=a.schedule??{},u=c.scheduledDate&&mt(c.scheduledDate)||c.scheduledTime&&mt(c.scheduledTime)||"noScheduledDate";i[u]||(i[u]=[]),i[u].push(a)}let s=Object.keys(i).sort((a,c)=>a.localeCompare(c));for(let a of s){let c=i[a],u={noScheduledTime:[]};for(let m of c){let d=m.schedule??{},l=d.scheduledTime&&$t(d.scheduledTime)||"noScheduledTime";u[l]||(u[l]=[]),u[l].push(m)}for(let m of Object.keys(u)){let l=u[m].sort((f,g)=>(f.roundNumber||0)-(g.roundNumber||0));u[m]=l}let p=Object.keys(u).sort((m,d)=>m.localeCompare(d));for(let m of p){let d=u[m];d.sort((l,f)=>{let g=r[n(l)]||0,I=r[n(f)]||0;return g-I}),o.push(...d)}}return o}function Qf(t){let{participants:e,contextContent:r,participantMap:n}=t,{tournamentAppliedPolicies:o,scheduleVisibilityFilters:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,usePublishState:m,contextFilters:d,matchUpFilters:l,contextProfile:f,nextMatchUps:g,tournamentId:I,inContext:S,context:h,event:T}=t;if(!T)return{error:le};let{eventId:y,eventName:E,endDate:A,eventType:N,category:D,gender:R}=T??{},U={...h,...et({surfaceCategory:T.surfaceCategory??p?.surfaceCategory,indoorOutDoor:T.indoorOutdoor??p?.indoorOutdoor,tournamentId:I??p?.tournamentId,endDate:A??p?.endDate,eventName:E,eventType:N,category:D,eventId:y,gender:R})},b;!e&&p&&({participants:e,participantMap:n,groupInfo:b}=di({participantsProfile:s,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,contextProfile:f,inContext:S})),f&&!r&&(r=eo({policyDefinitions:c,tournamentRecord:p,contextProfile:f,event:T}));let C=Cr({event:T});return{...(T.drawDefinitions??[]).reduce((w,L)=>{let F=Ga({hydrateParticipants:t.hydrateParticipants,context:U,tournamentAppliedPolicies:o,scheduleVisibilityFilters:i,tournamentParticipants:e,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,usePublishState:m,contextContent:r,contextFilters:d,matchUpFilters:l,participantMap:n,publishStatus:C,contextProfile:f,drawDefinition:L,nextMatchUps:g,inContext:S,event:T});return Object.keys(F)?.forEach(k=>{Array.isArray(F[k])&&(w[k]||(w[k]=[]),w[k]=w[k].concat(F[k]))}),w},{}),...P,groupInfo:b}}function Xf(t){if(!t?.tournamentRecord)return{error:j};let e=t.contextContent,{scheduleVisibilityFilters:r,participantsProfile:n,afterRecoveryTimes:o,policyDefinitions:i,tournamentRecord:s,inContext:a=!0,usePublishState:c,contextFilters:u,matchUpFilters:p,contextProfile:m,nextMatchUps:d,context:l}=t,f=t.tournamentId??s.tournamentId,g=s?.events??[],{participants:I,participantMap:S,groupInfo:h}=di({participantsProfile:n,policyDefinitions:i,tournamentRecord:s,contextProfile:m,inContext:a});m&&!e&&(e=eo({policyDefinitions:i,tournamentRecord:s,contextProfile:m}));let{appliedPolicies:T}=ft({tournamentRecord:s}),y=u?.eventIds??[];return{...g.filter(N=>!y.includes(N.eventId)).map(N=>{let R={eventDrawsCount:Bt({event:N}).flightProfile?.flights?.length||N.drawDefinitions?.length||0,...l};return Qf({hydrateParticipants:t.hydrateParticipants,context:R,tournamentAppliedPolicies:T,scheduleVisibilityFilters:r,participantsProfile:n,afterRecoveryTimes:o,policyDefinitions:i,tournamentRecord:s,usePublishState:c,contextFilters:u,contextProfile:m,contextContent:e,matchUpFilters:p,participantMap:S,participants:I,tournamentId:f,nextMatchUps:d,inContext:a,event:N})}).reduce((N,D)=>((D&&Object.keys(D).filter(U=>!["success","matchUpsMap"].includes(U)))?.forEach(U=>{Array.isArray(D[U])&&(N[U]||(N[U]=[]),N[U]=N[U].concat(D[U]),N.matchUpsCount!==void 0?N.matchUpsCount+=D[U].length:N.matchUpsCount=D[U].length)}),N),{matchUpsCount:0}),groupInfo:h,participants:I}}function wd({scheduleVisibilityFilters:t,hydrateParticipants:e,participantsProfile:r,tournamentRecords:n,useParticipantMap:o,policyDefinitions:i,usePublishState:s,matchUpFilters:a,contextFilters:c,nextMatchUps:u,inContext:p}){if(typeof n!="object"||!Object.keys(n).length)return{error:kt};let d=Object.keys(n).map(I=>{let S=n[I];return Xf({scheduleVisibilityFilters:t,hydrateParticipants:e,participantsProfile:r,useParticipantMap:o,policyDefinitions:i,tournamentRecord:S,usePublishState:s,matchUpFilters:a,contextFilters:c,nextMatchUps:u,inContext:p})}),l={},f={};return{...d.reduce((I,S)=>(Object.keys(S).forEach(T=>{if(T==="groupInfo")Object.assign(f,S[T]);else if(T==="participants")for(let y of S[T]??[])l[y.participantId]=y;else Array.isArray(S[T])&&(I[T]||(I[T]=[]),I[T]=I[T].concat(S[T]))}),I),{}),groupInfo:f,mappedParticipants:l}}function am(t){if(typeof t?.tournamentRecords!="object"||!Object.keys(t?.tournamentRecords).length)return{error:kt};let{courts:e,venues:r}=kn(t),o=bo(t).schedulingProfile,{sortDateMatchUps:i=!0,courtCompletedMatchUps:s,alwaysReturnCompleted:a,activeTournamentId:c,tournamentRecords:u,withCourtGridRows:p,minCourtGridRows:m,usePublishState:d,status:l=br,sortCourtsData:f}=t,g=c??Fs()??Object.keys(u)[0],I=d?Uc({tournamentRecord:u[g],status:l}):void 0,S=a?wd({...t,matchUpFilters:{...t.matchUpFilters,matchUpStatuses:[ie]},contextFilters:t.contextFilters}).completedMatchUps:[];if(d&&!ro(I?.orderOfPlay))return{completedMatchUps:S,dateMatchUps:[],courtsData:[],venues:r};let h,T;d&&({drawIds:h,detailsMap:T}=_k({tournamentRecords:u})),h?.length&&(t.contextFilters??={},t.contextFilters.drawIds?t.contextFilters.drawIds=t.contextFilters.drawIds.filter(F=>h.includes(F)):t.contextFilters.drawIds=h);let y=I?.orderOfPlay;cQ(t,y);let E=uQ(t,y,{allCompletedMatchUps:S,alwaysReturnCompleted:a,venues:r});if(E)return E;pQ(t,a);let{completedMatchUps:A,upcomingMatchUps:N,pendingMatchUps:D,abandonedMatchUps:R,groupInfo:U,mappedParticipants:b}=wd({...t,matchUpFilters:t.matchUpFilters,contextFilters:t.contextFilters}),C=[...N??[],...D??[]];T&&(!h?.length||Object.keys(T).length)&&(C=C.filter(F=>mQ(F,T))),T&&d&&(C=C.filter(F=>dQ(F,T)));let _=i?zf({matchUps:C,schedulingProfile:o}):C,v=e?.map(F=>{let x=L(F);return{surfaceCategory:F?.surfaceCategory??"",matchUps:x,...F}}),w={completedMatchUps:a?S:A,mappedParticipants:t.hydrateParticipants?void 0:b,dateMatchUps:_,courtsData:v,groupInfo:U,venues:r};if(p){let F=t.matchUpFilters?.scheduledDate,{rows:x,courtPrefix:k}=qf({minRowsCount:Math.max(m||0,_.length||0),scheduledDate:F,courtsData:v});w.courtPrefix=k,w.rows=x}return{...w,...P};function L({courtId:F}){let k=(s?_.concat(A??[],R??[]):_).filter(G=>G.schedule?.courtId===F||G.schedule?.allocatedCourts?.map(({courtId:V})=>V).includes(F));return f?zf({matchUps:k,schedulingProfile:o}):k}}function cQ(t,e){e?.eventIds?.length&&(t.matchUpFilters??={},t.matchUpFilters?.eventIds&&t.matchUpFilters.eventIds.length?t.matchUpFilters.eventIds=t.matchUpFilters.eventIds.filter(r=>e.eventIds.includes(r)):t.matchUpFilters.eventIds=e.eventIds)}function uQ(t,e,{allCompletedMatchUps:r,alwaysReturnCompleted:n,venues:o}){if(!e?.scheduledDates?.length)return;t.matchUpFilters??={},t.matchUpFilters.scheduledDate&&!t.matchUpFilters.scheduledDates&&(t.matchUpFilters.scheduledDates=[t.matchUpFilters.scheduledDate]);let i=t.matchUpFilters.scheduledDates&&t.matchUpFilters.scheduledDates.length>0;if(t.matchUpFilters.scheduledDates&&t.matchUpFilters.scheduledDates.length?t.matchUpFilters.scheduledDates=t.matchUpFilters.scheduledDates.filter(s=>e.scheduledDates.includes(s)):t.matchUpFilters.scheduledDates=e.scheduledDates,i&&!t.matchUpFilters.scheduledDates?.length)return{completedMatchUps:n?r:[],dateMatchUps:[],courtsData:[],venues:o,...P};delete t.matchUpFilters.scheduledDate}function pQ(t,e){e&&(t.matchUpFilters??={},t.matchUpFilters?.excludeMatchUpStatuses?.length?t.matchUpFilters.excludeMatchUpStatuses.includes(ie)||t.matchUpFilters.excludeMatchUpStatuses.push(ie):t.matchUpFilters.excludeMatchUpStatuses=[ie])}function mQ(t,e){let{drawId:r,structureId:n,stage:o}=t;if(!ro(e?.[r]?.publishingDetail))return!1;let i=Object.keys(e[r].stageDetails??{});if(i.length){let a=i.filter(u=>!ro(e[r].stageDetails[u])),c=i.filter(u=>ro(e[r].stageDetails[u]));return a.length&&a.includes(o)?!1:c.length&&c.includes(o)?!0:a.length&&!a.includes(o)&&!c.length}let s=Object.keys(e[r].structureDetails??{});if(s.length){let a=s.filter(u=>!ro(e[r].structureDetails[u])),c=s.filter(u=>ro(e[r].structureDetails[u]));return a.length&&a.includes(n)?!1:c.length&&c.includes(n)?!0:a.length&&!a.includes(n)&&!c.length}return!0}function dQ(t,e){let{drawId:r,structureId:n,roundNumber:o}=t;if(!yt(o))return!0;let i=e[r]?.structureDetails?.[n];if(!i)return!0;let{scheduledRounds:s,roundLimit:a}=i;if(yt(a)&&o>a)return!1;if(s){let c=s[o];if(!c)return!0;if(!c.published)return!1;if(Uo(c))return t.schedule=void 0,!0}return!0}function ss(t,e){if(!Tt(t))return{error:O};if(!Array.isArray(e))return{error:O};let r={};for(let{param:n,error:o,attr:i}of e){let s=lQ({params:t,param:n,attr:i,error:o});if(s?.error)return s;r[n]=s}return r}function lQ({params:t,param:e,attr:r,error:n}){if(e===mc&&Tt(t.drawDefinition)&&wt(t.structureId)){let o=(t.drawDefinition.structures??[]).find(({structureId:i})=>i===t.structureId);return!o.length&&n?{error:n}:{structure:o}}if(e===Rn){let o=ev({...t,...r});return o.error&&n?{...o,error:n}:o}return{error:fe,info:{param:e}}}function MP(t){let{structureId:e,matchUpId:r,event:n}=t,o=t.drawDefinition,i=X(t,[{[rt]:!0},{[yp]:{[mo]:!1,[wr]:!1,[dc]:!1,[ce]:!1}}]);if(i[jr])return i;let a=ss(t,[{[Gi]:Rn,[jr]:nt}])?.matchUp;if(r&&a?.error)return a;!o&&a?.drawDefinition&&(o=a?.drawDefinition);let c=a?.structure;if(!c&&e&&!r){if(!o)return{error:Nn};let l=tt({drawDefinition:o,structureId:e});if(l.error)return l;c=l.structure}let u=c?.competitionFormat,p=o?.competitionFormat,m=n?.competitionFormat;return{...P,structureDefaultCompetitionFormat:u,drawDefaultCompetitionFormat:p,eventDefaultCompetitionFormat:m,competitionFormat:u||p||m}}function Jf({tournamentRecords:t,tournamentId:e}){if(typeof t!="object"||!Object.keys(t).length)return{error:kt};let r=Object.keys(t).filter(o=>!e||o===e),n;return r.forEach(o=>{let i=t[o],{matchUpDailyLimits:s}=fQ({tournamentRecord:i});n=s}),{matchUpDailyLimits:n}}function fQ(t){let e=X(t,[{[rt]:!0}]);if(e.error)return e;let{tournamentRecord:r}=t,{policy:n}=go({policyType:ko,tournamentRecord:r}),{extension:o}=ot({element:r,name:Np}),i=o?.value?.dailyLimits,s=n?.defaultDailyLimits;return{matchUpDailyLimits:i||s}}function vP(t){let{matchUps:e}=t,{singlesForDoubles:r,tournamentRecord:n,drawDefinition:o,excludeMargin:i,exclusionRule:s,zoneDoubling:a,matchUpType:c,scaleName:u,eventId:p,zonePct:m,drawId:d,event:l}=t;if(!n&&!e)return{error:j};if(c&&![Ct,Rt].includes(c))return{error:O,info:{matchUpType:c}};if(e&&!Rr(e))return{error:O,context:{matchUps:e}};let f=Ke[u],g=f?.ascending??t.ascending??!1,I=f?.accessor??t.valueAccessor,S=Array.isArray(f?.range)?Math.abs(f.range[0]-f.range[1]):0,h=yt(m)&&S?(m??0/100)*S:t.zoneMargin??S,T={withScaleValues:!0,withCompetitiveness:!0},y={matchUpTypes:c?[c]:[Ct,Rt]},E=n?.participants;e?.[0]?.hasContext?d?e=e.filter(v=>v.drawId===d):p&&(e=e.filter(v=>v.eventId===p)):e??=d&&!o&&[]||!d&&p&&!l&&[]||d&&rr({inContext:!0,drawDefinition:o,contextFilters:y,contextProfile:T,participants:E})?.matchUps||!d&&p&&vn({inContext:!0,contextFilters:y,contextProfile:T,participants:E,event:l})?.matchUps||qt({tournamentRecord:n,contextFilters:y,contextProfile:T})?.matchUps||[],c&&(e=e.filter(v=>v.matchUpType===c));let A=e.filter(({winningSide:v,score:w,sides:L,matchUpStatus:F})=>![De,Mt,vt,Rp,Fr].includes(F??"")&&ue({score:w})&&L?.length===2&&v),N=IQ({matchUps:A,excludeMargin:i,exclusionRule:s,valueAccessor:I,ascending:g,scaleName:u}),D=!a||re(Ct)(c)?h:(h||0)*2,R=h?A.map(({competitiveProfile:v,matchUpType:w,score:L,sides:F})=>{let x=wk({singlesForDoubles:r,valueAccessor:I,matchUpType:w,scaleName:u,sides:F}),k=Math.abs(x[0].value-x[1].value);return{competitiveness:v?.competitiveness,valuesGap:k,score:L}}).filter(({valuesGap:v})=>v<=D):[],U=gQ({zoneData:R}),b=U&&Object.values(U).flat().length,C=b&&Object.assign({},...Object.keys(U).map(v=>({[v]:Math.round(1e4*U[v].length/b)/100}))),_=A.length-(R?.length||0);return{...P,relevantMatchUps:A,zoneDistribution:C,zoneData:R,accuracy:N,nonZone:_}}function gQ({zoneData:t}){let e={[xl]:[],[gu]:[],[Iu]:[]};for(let r of t){let{competitiveness:n,score:o,valuesGap:i}=r;e[n]&&e[n].push({score:o,valuesGap:i})}return e}function wk({singlesForDoubles:t,exclusionRule:e,valueAccessor:r,matchUpType:n,scaleName:o,sides:i}){let s=e?.range.slice().sort((c,u)=>c-u),a=c=>{let u=c?.[e?.valueAccessor];return{exclude:e&&u>=s[0]&&u<=s[1],exclusionValue:u}};return i.sort((c,u)=>c.sideNumber-u.sideNumber).map(({participant:c})=>{let u=[],p=c?.individualParticipants;if(p?.length){let m=[],d=0;for(let l of p){let{scaleValue:f,value:g}=xk({singlesForDoubles:t,valueAccessor:r,participant:l,matchUpType:n,scaleName:o}),{exclude:I,exclusionValue:S}=a(f);I&&u.push(S),m.push(f),g&&!Number.isNaN(Number(d))?d+=g:d=void 0}return{participantName:c.participantName,exclusionValues:u,scaleValues:m,value:d}}else if(c){let{scaleValue:m,value:d}=xk({singlesForDoubles:t,valueAccessor:r,matchUpType:n,participant:c,scaleName:o}),{exclude:l,exclusionValue:f}=a(m);return l&&u.push(f),{participantName:c.participantName,exclusionValues:u,scaleValue:m,value:d}}else return{}})}function xk({singlesForDoubles:t,valueAccessor:e,matchUpType:r,participant:n,scaleName:o}){let i=t?Ct:r,s=n?.rankings?.[i]?.find(p=>p.scaleName===o),c=(n?.ratings?.[i]?.find(p=>p.scaleName===o)||s)?.scaleValue,u=e?c?.[e]:c;return{scaleValue:c,value:u}}function IQ({excludeMargin:t,exclusionRule:e,valueAccessor:r,ascending:n,scaleName:o,matchUps:i}){let s={affirmative:[],negative:[],excluded:[]};for(let u of i)SQ({matchUp:u,accuracy:s,excludeMargin:t,exclusionRule:e,valueAccessor:r,ascending:n,scaleName:o});let a=s.affirmative.length+s.negative.length,c=a&&s.affirmative.length/a*100;return s.percent=c?Math.round(100*c)/100:0,s}function SQ({matchUp:t,accuracy:e,excludeMargin:r,exclusionRule:n,valueAccessor:o,ascending:i,scaleName:s}){let{matchUpType:a,sides:c,score:u,winningSide:p}=t;if(!p)return;if(n&&(!n.valueAccessor||!n.range)){e.error={info:"exclusionRule requires valueAccessor and range",error:nt};return}let m=p-1,d=wk({exclusionRule:n,valueAccessor:o,matchUpType:a,scaleName:s,sides:c});if(hQ({exclusionRule:n,sideValues:d,accuracy:e,score:u,winningSide:p}))return;if(TQ(d)){e.excluded.push({scoreString:u?.scoreStringSide1,missingValues:!0,winningSide:p,sideValues:d});return}let l=d[m].value-d[1-m].value;if(yQ({excludeMargin:r,valuesGap:l})){e.excluded.push({scoreString:u?.scoreStringSide1,excludeMargin:r,winningSide:p,excludeGap:!0,sideValues:d,valuesGap:l});return}let f=i?l:l*-1,g=p===1?u?.scoreStringSide1:u?.scoreStringSide2;f>0?e.affirmative.push({winningScoreString:g,winningSide:p,sideValues:d,valuesGap:l,score:u}):e.negative.push({winningScoreString:g,winningSide:p,sideValues:d,valuesGap:l,score:u})}function hQ({exclusionRule:t,sideValues:e,accuracy:r,score:n,winningSide:o}){if(t){let i=e.flatMap(({exclusionValues:s})=>s);if(i.length)return r.excluded.push({scoreString:n?.scoreStringSide1,exclusionValues:i,winningSide:o,sideValues:e}),!0}return!1}function TQ(t){return t.filter(e=>![void 0,"",null].includes(e.value)).length<2}function yQ({excludeMargin:t,valuesGap:e}){let r=Number.parseFloat(t||0);return r&&Math.abs(e)<r}function OP({matchUps:t,matchUpId:e}){if(!Rr(t))return{error:O};let r=t.find(a=>a.matchUpId===e),{drawId:n,eventId:o,structureId:i,tournamentId:s}=r??{};return{matchUpId:e,drawId:n,eventId:o,structureId:i,tournamentId:s}}function _P(t){let{timeStamp:e,schedule:r,matchUp:n}=t,o=X(t,[{[Rn]:!0}]);if(o.error)return o;let{itemValue:i,timeStamp:s}=Ii({timeItems:n?.timeItems??[],itemType:Wl});return!r||s&&e&&new Date(s).getTime()>new Date(e).getTime()?{homeParticipantId:i}:r}function ua({collectionDefinitions:t=[],collectionGroups:e=[]}){let r=0,{groupValueNumbers:n}=eA({collectionGroups:e}),o;for(let s of t??[]){let{collectionValueProfiles:a,collectionGroupNumber:c,collectionValue:u,matchUpCount:p,matchUpValue:m,scoreValue:d,setValue:l}=s,f=c&&n.includes(c);if(yt(l||d))o=!0;else{if(f)continue;if(typeof u=="number"&&yt(u))r+=u;else if(Array.isArray(a)&&a?.length)for(let g of a)r+=g.matchUpValue;else typeof m=="number"&&yt(m)&&(r+=(p??0)*m)}}for(let s of e)r+=s.groupValue??0;return o||!r?{aggregateValue:!0,...P}:{valueGoal:Math.floor(r/2)+1,...P}}function xP(t){let{structureId:e,matchUpId:r,event:n}=t,o=t.drawDefinition,i=X(t,[{[rt]:!0},{[yp]:{[mo]:!1,[wr]:!1,[dc]:!1,[ce]:!1}}]);if(i[jr])return i;let a=ss(t,[{[Gi]:Rn,[jr]:nt}])?.matchUp;if(r&&a?.error)return a;!o&&a?.drawDefinition&&(o=a?.drawDefinition);let c=a?.structure;if(!c&&e&&!r){if(!o)return{error:Nn};let l=tt({drawDefinition:o,structureId:e});if(l.error)return l;c=l.structure}let u=c?.matchUpFormat,p=o?.matchUpFormat,m=n?.matchUpFormat,d=a?.matchUp?.matchUpFormat||u||p||m;return{structureDefaultMatchUpFormat:u,eventDefaultMatchUpFormat:m,drawDefaultMatchUpFormat:p,matchUpFormat:d}}function wP({profileBands:t,tournamentRecord:e,matchUps:r}){if(!Rr(r))return{error:Bn};let n=!t&&go({policyType:gn,tournamentRecord:e}).policy,o=t||n?.profileBands||Hs[gn].profileBands,i=r.filter(({winningSide:l})=>l),s=i.filter(({matchUpStatus:l})=>l===vt||l===Mt).length,a=i.map(Fl),c=(l,f)=>{let g=iE(f,o);return l[g]+=1,l},u=sE(a).reduce((l,f)=>c(l,f),{[xl]:0,[gu]:0,[Iu]:0,[rE]:s}),p=Object.keys(u).reduce((l,f)=>(u[f]||0)+l,0),m=Object.keys(u).map(l=>{let f=Number.parseFloat((u[l]/p).toFixed(4));return{[l]:f*100}}),d=i.filter(({matchUpStatus:l})=>l===Ib).length;return m.push({[Ib]:Number.parseFloat((d/p).toFixed(4))*100}),{competitiveBands:Object.assign({},...m),...P}}var{stageOrder:Lk}=zw;function Fk(t,e){return t.eventName.localeCompare(e.eventName)||t.eventId.localeCompare(e.eventId)||(Lk[t?.stage]||0)-(Lk[e?.stage]||0)||e.matchUpsCount-t.matchUpsCount||`${t.stageSequence}-${t.roundNumber}-${t.minFinishingSum}`.localeCompare(`${e.stageSequence}-${e.roundNumber}-${e.minFinishingSum}`)}function LP({excludeScheduleDateProfileRounds:t,excludeScheduledRounds:e,excludeCompletedRounds:r,inContextMatchUps:n,tournamentRecords:o,schedulingProfile:i,tournamentRecord:s,withSplitRounds:a,matchUpFilters:c,scheduleDate:u,withRoundId:p,venueId:m,context:d}){if(n&&!Array.isArray(n||typeof n[0]!="object"))return{error:O,inContextMatchUps:n};if(s&&!o)if(typeof s=="object")o={[s.tournamentId]:s};else return{error:Hc};let l=typeof o!="object"||!Object.keys(o).length;if((m||u||!n||!i&&(t||r||i||a))&&l)return{error:kt};let g=Object.assign({},...Object.values(o??{}).map(({venues:N=[],tournamentId:D})=>({[D]:N?.map(({venueId:R})=>R)}))),I=Object.values(o??{}).flatMap(({events:N=[],tournamentId:D,startDate:R,endDate:U})=>N.map(b=>({...b,validVenueIds:g[D],startDate:b.startDate??R,endDate:b.endDate??U}))),{segmentedRounds:S,profileRounds:h}=o&&(t||r||i||a)&&jf({tournamentRecords:o,schedulingProfile:i})||{},T=t&&Object.assign({},...h.map(N=>({[N.id]:N}))),y=n||o&&cn({tournamentRecords:o,matchUpFilters:c})?.matchUps||[],E=[],A=y&&Object.values(y.reduce((N,D)=>{let R=uh(D).id,U=S?.[R],b=[...N[R]?.matchUps??[],D],{containerStructureId:C,stageSequence:_,structureName:v,tournamentId:w,isRoundRobin:L,matchUpType:F,roundNumber:x,roundOffset:k,structureId:G,eventName:V,roundName:B,drawName:z,eventId:H,drawId:K}=D,Y=L?C:G;return{...N,[R]:{id:p?R:void 0,structureId:Y,stageSequence:_,segmentsCount:U,structureName:v,tournamentId:w,matchUpType:F,roundNumber:x,roundOffset:k,eventName:V,roundName:B,drawName:z,matchUps:b,eventId:H,drawId:K}}},{})).flatMap(N=>{let{minFinishingSum:D,winnerFinishingPositionRange:R}=Mk(N.matchUps),U=N.segmentsCount;if(U){let x=N.matchUps.length/U;return he(N.matchUps.sort((G,V)=>G.roundPosition-V.roundPosition),x).map((G,V)=>{let{unscheduledCount:B,incompleteCount:z,matchUpsCount:H,isScheduled:K,isComplete:Y,byeCount:J}=sv(G),ct=iv({matchUps:N.matchUps,tournamentRecords:o,events:I,round:N});return et({...N,...d,roundSegment:{segmentsCount:U,segmentNumber:V+1},winnerFinishingPositionRange:R,unscheduledCount:B,incompleteCount:z,minFinishingSum:D,matchUpsCount:H,isScheduled:K,roundTiming:ct,isComplete:Y,byeCount:J,matchUps:G})})}let{unscheduledCount:b,incompleteCount:C,matchUpsCount:_,isScheduled:v,isComplete:w,byeCount:L}=sv(N.matchUps),F=iv({matchUps:N.matchUps,tournamentRecords:o,events:I,round:N});return et({...N,...d,winnerFinishingPositionRange:R,unscheduledCount:b,incompleteCount:C,minFinishingSum:D,matchUpsCount:_,isScheduled:v,roundTiming:F,isComplete:w,byeCount:L})}).filter(N=>{if(t){let G=mt(t),V=p?N.id:uh(N).id;if(G&&T[V]&&mt(T[V].scheduleDate)===G)return!1}let{isComplete:D,isScheduled:R}=N,U=!r||!D,b=!e||!R,C=m||u?I?.find(({eventId:G})=>G===N.eventId):void 0,_=C?.startDate??s?.startDate,v=C?.endDate??s?.endDate,w=!u||!_||new Date(u)>=new Date(_),L=!u||!v||new Date(u)<=new Date(v),F=w&&L,x=!m||C?.validVenueIds.includes(m),k=U&&b&&x&&F;return k||E.push(N),k}).sort(Fk)||[];return{...P,rounds:A,excludedRounds:E}}function FP({participants:t,tournamentAppliedPolicies:e,scheduleVisibilityFilters:r,participantsProfile:n,afterRecoveryTimes:o,policyDefinitions:i,useParticipantMap:s,tournamentRecord:a,usePublishState:c,contextFilters:u,contextContent:p,matchUpFilters:m,participantMap:d,publishStatus:l,contextProfile:f,drawDefinition:g,nextMatchUps:I,tournamentId:S,inContext:h,context:T,event:y}){let{eventId:E,eventName:A,endDate:N,eventType:D,category:R,gender:U}=y??{},b={...T,...et({surfaceCategory:y?.surfaceCategory??a?.surfaceCategory,indoorOutDoor:y?.indoorOutdoor??a?.indoorOutdoor,endDate:N??y?.endDate??a?.endDate,tournamentId:S??a?.tournamentId,eventName:A,eventType:D,category:R,eventId:E,gender:U})},C;return!t?.length&&a&&({participants:t,participantMap:d,groupInfo:C}=di({participantsProfile:n,policyDefinitions:i,useParticipantMap:s,tournamentRecord:a,contextProfile:f,inContext:h})),y&&f&&!p&&(p=eo({policyDefinitions:i,tournamentRecord:a,contextProfile:f,drawDefinition:g,event:y})),{...Ga({context:b,tournamentAppliedPolicies:e,scheduleVisibilityFilters:r,tournamentParticipants:t,participantsProfile:n,afterRecoveryTimes:o,policyDefinitions:i,tournamentRecord:a,usePublishState:c,participantMap:d,contextContent:p,contextFilters:u,matchUpFilters:m,publishStatus:l,contextProfile:f,drawDefinition:g,nextMatchUps:I,inContext:h,event:y}),groupInfo:C}}function Ld(t){let{matchUp:e,sideNumber:r,setNumber:n,isTiebreakValue:o,isPointValue:i}=t??{},{matchUpFormat:s}=t??{};if(!e)return{error:Xe};s=s||e?.matchUpFormat;let a=oe(s),c=!!e?.winningSide,u=e.score?.sets,p=u?.length,m=n&&n-1,d=!!u?.find((Y,J)=>Y.setNumber===n&&J===m),l=u?.filter(Y=>Y?.winningSide)??[],f=l?.length||0,g=(n&&u?.slice(n))??[],I=!!(p&&n&&g?.reduce((Y,J)=>(!J||!J.side1Score&&!J.side2Score&&!J.side1TiebreakScore&&!J.side2TiebreakScore&&!J.side1PointScore&&!J.side2PointScore)&&Y,!0)),S=n<=p&&u.find(Y=>Y.setNumber===n),h=S&&om({setObject:S,matchUpScoringFormat:a}),{isCompletedSet:T,sideGameScores:y,sideTiebreakScores:E}=h??{},A=!!(S&&!T&&I||n&&n===p+1&&!c),N=[1,2].includes(r),D=N?r-1:0,R=S&&N&&(!o&&!i&&y[D]!==void 0&&y[D]||o&&E[D]!==void 0&&E[D]),U=!!R,b=l?.map(Y=>om({setObject:Y,matchUpScoringFormat:a}).isValidSetOutcome).reduce((Y,J)=>Y&&J,!0),C=l.reduce((Y,J)=>{let{winningSide:ct}=J,Et=ct-1;return Y[Et]++,Y},[0,0]),_=e?.winningSide,v=_&&_-1,w=1-v,L=C[v],F=C[w],x=Math.max(...C),k=mn(C)[x],{bestOf:G,exactly:V}=a??{},B=Math.ceil((G||V||1)/2),z=x===B&&k===1&&C.indexOf(x)+1||void 0,H=L>F&&_===z;return{completedSetsHaveValidOutcomes:b,validMatchUpWinningSide:H,calculatedWinningSide:z,matchUpScoringFormat:a,validMatchUpOutcome:z&&b&&H,isLastSetWithValues:I,completedSetsCount:f,isCompletedMatchUp:c,isValidSideNumber:N,hasExistingValue:U,existingValue:R,isExistingSet:d,isActiveSet:A,...h}}var lv={};Gt(lv,{getCompetitionVenues:()=>hd,getCourts:()=>kP,getVenuesAndCourts:()=>kn,publicFindVenue:()=>IE});function kP({tournamentRecord:t,venueId:e,venueIds:r}){return t?{courts:(t.venues??[]).filter(o=>e?o.venueId===e:r?r.includes(o.venueId):!0).map(o=>{let{venueId:i}=o,s=q(o.courts??[]);return s.forEach(a=>Object.assign(a,{venueId:i})),s}).flat()}:{error:j}}var gv={};Gt(gv,{categoryCanContain:()=>fp,getCategoryAgeDetails:()=>gs,getEvent:()=>BP,getEventProperties:()=>GP,getEventStructures:()=>RS,getEventTimeItem:()=>xp,getEvents:()=>VP,getFlightProfile:()=>Bt,getScaledEntries:()=>Xa});function GP({tournamentRecord:t,event:e}){let r=dt({tournamentRecord:t,event:e},[rt,ce]);if(r.error)return r;let n=e.entries??[],o=t.participants??[],i=e.category?.categoryName||e.category?.ageCategoryCode,{eventType:s}=e,a=new Set(n.map(l=>l.participantId)),c=o.filter(l=>a.has(l.participantId)),u,p,m;return{entryScaleAttributes:c.map(l=>{let{participantId:f,participantName:g,name:I}=l,S={scaleType:sS,eventType:s,scaleName:i},h=Po({participant:l,scaleAttributes:S})?.scaleItem?.scaleValue;S={scaleType:Eb,eventType:s,scaleName:i};let T=Po({participant:l,scaleAttributes:S})?.scaleItem?.scaleValue;S={scaleType:yb,eventType:s,scaleName:i};let y=Po({participant:l,scaleAttributes:S})?.scaleItem?.scaleValue;return u=!!(u||h),p=!!(p||T),m=!!(m||y),{participantId:f,participantName:g||I,seed:h,ranking:T,rating:y}}),hasSeededParticipants:u,hasRankedParticipants:p,hasRatedParticipants:m}}function EQ(t){return t.reduce((e,r)=>e+Number.parseFloat(r),0)}function kk(t){let e={};for(let r of Object.keys(t)){let n=t[r];if(!n.length)continue;let o=iw(n)?.toFixed(2);e[r]={avg:Number.parseFloat((EQ(n)/n.length).toFixed(2)),median:o?Number.parseFloat(o):void 0,max:Math.max(...n),min:Math.min(...n)}}return e}function Gk(t,e,r){if(t?.ratings?.[e])for(let n of t?.ratings?.[e]??[]){let o=n.scaleName;r.ratings[o]||(r.ratings[o]=[]);let i=Ke[o]?.accessor;if(i){let s=Number.parseFloat(n.scaleValue?.[i]);s&&r.ratings[o].push(s)}}if(t?.rankings?.[e])for(let n of t?.rankings?.[e]??[]){let o=n.scaleName;r.ranking[o]||(r.ranking[o]=[]),n.scaleValue&&r.ranking[o].push(n.scaleValue)}}function fv(t,e,r,n){for(let o of t.filter(Boolean)){let i=e?.[o]?.participant;if(i?.participantType===St)Gk(i,r,n);else for(let s of i?.individualParticipantIds??[]){let a=e?.[s]?.participant;Gk(a,r,n)}}}function AQ({eventCopies:t,scaleEventType:e,tournamentRecord:r,drawIds:n}){let o={},i=bt({withScaleValues:!0,tournamentRecord:r}).participantMap;for(let s of t){let a=e??s.eventType,c=s.eventId;o[c]||(o[c]={ratingsStats:{},ratings:{},ranking:{},draws:{}});let p=(s.entries??[]).filter(({entryStatus:f})=>yr.includes(f)).map(gt);fv(p,i,a,o[c]),o[c].ratingsStats=kk(o[c].ratings);let m=[],d=f=>n?.length&&n.includes(f)||m.includes(f);for(let f of s.drawDefinitions??[]){let g=f.drawId;if(d(g))continue;let I=Ji({drawDefinition:f}).assignedParticipantIds??[];o[c].draws[g]||(o[c].draws[g]={ratingsStats:{},ratings:{},ranking:{}}),m.push(g),fv(I,i,a,o[c].draws[g])}let l=Bt({event:s}).flightProfile;for(let f of l?.flights??[]){let g=f.drawId;if(d(g))continue;let I=f.drawEntries.map(gt);fv(I,i,a,o[c].draws[g])}for(let f of m)o[c].draws[f].ratingsStats=kk(o[c].draws[f].ratings)}return o}function VP({tournamentRecord:t,withScaleValues:e,scaleEventType:r,inContext:n,eventIds:o,drawIds:i,context:s}){if(!t)return{error:j};let{tournamentId:a}=t,c=(t.events??[]).filter(({eventId:p})=>!o||Array.isArray(o)&&o.includes(p)).map(p=>{let m=p.drawDefinitions?.map(Tc);if(i?.length&&!Yt(i,m).length)return;let d=q(p);return n&&Object.assign(d,{tournamentId:a}),s&&Object.assign(d,s),d}).filter(Boolean),u=e?AQ({eventCopies:c,scaleEventType:r,tournamentRecord:t,drawIds:i}):{};return et({eventScaleValues:u,events:c,...P})}function BP({tournamentRecord:t,drawDefinition:e,context:r,event:n}){let o=dt({tournamentRecord:t,event:n},[rt,ce]);if(o.error)return o;let i=q(n);r&&Object.assign(i,r);let s=e&&i.drawDefinitions?.find(({drawId:a})=>e.drawId===a);return et({drawDefinition:s,event:i})}function Vk(t){let e="validateAndDeriveDrawValues",{appliedPolicies:r,policyDefinitions:n}=DQ(t),o=UQ({...t,policyDefinitions:n,appliedPolicies:r}),i=NQ(t),s=RQ({...t,consideredEntries:i,appliedPolicies:r});if(s?.error)return M({result:s,stack:e});let a=bQ({...t,consideredEntries:i}),c=PQ({...t,appliedPolicies:r,policyDefinitions:n,drawSize:a});if(c.error)return M({result:c,stack:e});let u=c.drawType;if(Number.isNaN(a)&&!yn(u))return M({result:{error:$c},stack:e});let p=n?.[Hn]??r?.[Hn],m=t.seedingProfile??p?.seedingProfile?.drawTypes?.[u??""]??p?.seedingProfile;t.seedingProfile&&(n[Hn]||(n[Hn]={...oh[Hn]}),n[Hn].seedingProfile=m);let d=CQ({...t,drawType:u});return d?.error?M({result:d,stack:e}):{drawSize:a,drawType:u,enforceGender:o,seedingProfile:m,appliedPolicies:r,policyDefinitions:n}}function PQ(t){let{policyDefinitions:e,appliedPolicies:r,enforceMinimumDrawSize:n=!0,drawSize:o}=t,i=t.drawTypeCoercion??em({drawType:t.drawType,policyDefinitions:e,appliedPolicies:r}),s=MA({drawType:t.drawType,enforceMinimumDrawSize:n,drawTypeCoercion:i,drawSize:o});return s.error?s:{drawType:s.drawType}}function Sv(t){return t?.filter(e=>e.entryStatus&&[...yr,Ll].includes(e.entryStatus))}function NQ({considerEventEntries:t=!0,drawEntries:e,eventEntries:r,qualifyingOnly:n}){return(n&&[]||Sv(e)||(t?r:[])).filter(({entryStage:o})=>!o||o===W)}function DQ(t){let{tournamentRecord:e,event:r}=t,n={...t?.appliedPolicies,...ft({tournamentRecord:e,event:r}).appliedPolicies},o=q(t.policyDefinitions??{},!1,!0);return{appliedPolicies:n,policyDefinitions:o}}function UQ({enforceGender:t,policyDefinitions:e,appliedPolicies:r}){return t??e?.[He]?.participants?.enforceGender??r?.[He]?.participants?.enforceGender}function RQ(t){let{consideredEntries:e,appliedPolicies:r,policyDefinitions:n,enforceGender:o,participantMap:i,participants:s,event:a}=t;return a&&s&&Nf({consideredEntries:e,policyDefinitions:n,appliedPolicies:r,participantMap:i,enforceGender:o,participants:s,event:a})}function bQ(t){return!t.drawSize&&t.consideredEntries.length&&![Ni,Gs,pc,hr,Tr,Bs].includes(t.drawType??"")&&Pi(t.consideredEntries.length)||t.drawSize&&st(t.drawSize)||!1}function CQ(t){let{tournamentRecord:e,event:r,ignoreAllowedDrawTypes:n,drawType:o}=t,i=!n&&e&&kf({tournamentRecord:e,categoryType:r?.category?.categoryType,categoryName:r?.category?.categoryName});return i?.length&&!i.includes(o)?{error:ol}:{...P}}function xc(t){let{voluntaryConsolation:e,withPlayoffs:r,targetMatchUpIds:n,tournamentRecord:o,event:i}=t,s="generateDrawDefinition",{participants:a,participantMap:c}=bt({withIndividualParticipants:!0,convertExtensions:!0,internalUse:!0,tournamentRecord:o}),u=Sv(i?.entries)??[],p=Vk({...t,participantMap:c,participants:a,eventEntries:u});if(p.error)return M({result:p,stack:s});let{appliedPolicies:m,policyDefinitions:d,drawSize:l,drawType:f,enforceGender:g,seedingProfile:I}=p,S=i?.eventType,h=t.matchUpType??S,T=ok({...t,enforceGender:g,eventType:S,matchUpType:h});if(T.error)return M({result:T,stack:s});let{matchUpFormat:y,tieFormat:E}=T;if(t.drawId&&typeof t.drawId!="string")return M({result:{error:O},stack:s});let N=Ik({...t,policyDefinitions:d,tournamentRecord:o,appliedPolicies:m,matchUpFormat:y,seedingProfile:I,participants:a,eventEntries:u,matchUpType:h,tieFormat:E,drawSize:l,drawType:f,event:i});if(N.error)return M({result:N,stack:s});let{existingDrawDefinition:D,positioningReports:R,drawDefinition:U,structureId:b,conflicts:C,entries:_}=N;if(!U)return M({result:{error:O},stack:s});let v=Sk({...t,existingDrawDefinition:D,positioningReports:R,appliedPolicies:m,drawDefinition:U,seedingProfile:I,participants:a,structureId:b,entries:_,params:t,stack:s});if(v.error)return v;let{qualifyingConflicts:w}=v;if(U.drawName=t.drawName??(f&&xe(f)),l&&typeof e=="object"&&l>=4&&gS({...e,drawDefinition:U,matchUpType:h}),r&&b){let L=Bk({withPlayoffs:r,tournamentRecord:o,drawDefinition:U,structureId:b,event:i,idPrefix:t.idPrefix,isMock:t.isMock});if(L?.error)return M({result:L,stack:s})}return t.hydrateRoundNames&&m?.[Fo]&&tP({drawDefinition:U,appliedPolicies:m}),n?.length&&DS({targetMatchUpIds:n,drawDefinition:U}),{existingDrawDefinition:!!D,qualifyingConflicts:w,positioningReports:R,drawDefinition:U,structureId:b,...P,conflicts:C}}function Bk({withPlayoffs:t,drawDefinition:e,structureId:r,...n}){let{roundPlayoffs:o,...i}=t,s=new Set(e.links?.filter(c=>c.linkType===ir&&c.source?.structureId===r).map(c=>c.source?.roundNumber)??[]),a=GS({...i,drawDefinition:e,structureId:r,...n});if(a?.error)return a;if(o){let c=e.links?.filter(u=>u.linkType===ir&&u.source?.structureId===r&&!s.has(u.source?.roundNumber))??[];for(let[u,p]of Object.entries(o)){let m=Number(u),d=c.find(l=>l.source?.roundNumber===m);if(d){let l=Bk({withPlayoffs:p,structureId:d.target?.structureId,drawDefinition:e,...n});if(l?.error)return l}}}return a}function Wk({participantIds:t,adHocRatings:e,allowDraws:r,matchUps:n}){let o=n.filter(f=>f.winningSide),{scoreGroups:i,records:s}=Pf({matchUps:o,participantIds:t,allowDraws:r}),{encounters:a}=_A({matchUps:[...n]}),c=new Set(a),u=o.length===0,p,m=[...t];if(m.length%2!==0){p=MQ({scoreGroups:i,records:s,adHocRatings:e});let f=m.indexOf(p);f>=0&&m.splice(f,1);for(let g of i){let I=g.participantIds.indexOf(p);if(I>=0){g.participantIds.splice(I,1);break}}}let d=[],l=new Set;if(u){let f=Hk(m,e),g=Math.floor(f.length/2);for(let I=0;I<g;I++)d.push({participantIds:[f[I],f[g+I]]}),l.add(f[I]),l.add(f[g+I])}else{let f=i.map(I=>[...I.participantIds]);for(let I=0;I<f.length;I++){let S=f[I].filter(T=>!l.has(T));if(S.length%2!==0&&I<f.length-1){let T=vQ({group:S,adHocRatings:e}),y=S.indexOf(T);S.splice(y,1),f[I+1].push(T)}let h=OQ({participantIds:S,encounterSet:c,adHocRatings:e});for(let T of h)d.push(T),l.add(T.participantIds[0]),l.add(T.participantIds[1])}let g=m.filter(I=>!l.has(I));for(let I=0;I<g.length-1;I+=2)d.push({participantIds:[g[I],g[I+1]]})}return{participantIdPairings:d,scoreGroups:i,records:s,byeParticipantId:p}}function Hk(t,e){return[...t].sort((r,n)=>{let o=e?.[r]??0;return(e?.[n]??0)-o})}function MQ({scoreGroups:t,records:e,adHocRatings:r}){let n=t.at(-1);return n?[...n.participantIds].sort((i,s)=>{let a=e.get(i),c=e.get(s),u=(a?.points??0)-(c?.points??0);return u!==0?u:(r?.[i]??0)-(r?.[s]??0)})[0]:""}function vQ({group:t,adHocRatings:e}){return[...t].sort((n,o)=>{let i=e?.[n]??0,s=e?.[o]??0;return i-s})[0]}function OQ({participantIds:t,encounterSet:e,adHocRatings:r}){if(t.length<2)return[];let n=Hk(t,r),o=Math.floor(n.length/2),i=n.slice(0,o),s=n.slice(o),a=[],c=new Set;for(let u of i){let p=-1,m=1/0;for(let d=0;d<s.length;d++){if(c.has(d))continue;let l=s[d],f=sa(u,l);if(e.has(f))continue;let g=Math.abs((r?.[u]??0)-(r?.[l]??0));g<m&&(m=g,p=d)}if(p===-1){for(let d=0;d<s.length;d++)if(!c.has(d)){p=d;break}}p>=0&&(c.add(p),a.push({participantIds:[u,s[p]]}))}return a}function Yk(t){let{drawDefinition:e,tournamentRecord:r,event:n}=t;if(!e)return{error:$};let o=t.structureId?tt({drawDefinition:e,structureId:t.structureId}).structure:e.structures?.find(h=>h.stage==="MAIN"&&Ae({structure:h}))??e.structures?.find(h=>Ae({structure:h}));if(!o)return{error:Nt};let i=wf({...t,restrictEntryStatus:!0,targetStage:o.stage});if(i.error)return i;let s=i.participantIds??[],a=o.positionAssignments?.map(h=>h.participantId).filter(h=>!!h)??[],c=_Q({drawDefinition:e,targetStructureId:o.structureId}),u=Array.from(new Set([...s,...a,...c])),{competitionPolicy:p}=Ao({tournamentRecord:r,drawDefinition:e,event:n}),{competitionState:m}=p?Wo({drawDefinition:e}):{competitionState:void 0},d;if(p&&m&&p.pairingPolicy.ratingSource==="DYNAMIC_FORM"){d={};for(let[h,T]of Object.entries(m.participantStates))d[h]=T.dynamicFormRating}else d=Ul({participantIds:u,tournamentRecord:r,scaleName:t.scaleName,event:n});let l=t.swissPolicy??ot({element:e,name:"swissPolicy"})?.extension?.value,f=o.matchUps??[],{participantIdPairings:g,byeParticipantId:I}=Wk({allowDraws:l?.allowDraws,matchUps:f,participantIds:u,adHocRatings:d}),S=Mc({structureId:o.structureId,participantIdPairings:g,matchUpIds:t.matchUpIds,idPrefix:t.idPrefix,isMock:t.isMock,drawDefinition:e,newRound:!0,event:n});return S.error?S:{roundNumber:S.roundNumber,matchUps:S.matchUps,byeParticipantId:I,...P}}function _Q({drawDefinition:t,targetStructureId:e}){let n=(t.links??[]).filter(i=>i.linkType===Pr&&i.target?.structureId===e),o=[];for(let i of n){let s=t.structures?.find(u=>u.structureId===i.source?.structureId);if(s?.stage!==Z)continue;let a=i.source?.roundNumber;if(!a)continue;let{matchUps:c}=ht({matchUpFilters:{roundNumbers:[a],isCollectionMatchUp:!1,hasWinningSide:!0},afterRecoveryTimes:!1,structure:s,inContext:!0});for(let u of c??[]){let p=u.sides?.find(m=>m?.sideNumber===u.winningSide);p?.participantId&&o.push(p.participantId)}}return o}function qk({matchUps:t,matchUpType:e}){if(!t)return{error:Bn};let r=[],n=[],o=0;e&&(t=t.filter(_=>_.matchUpType===e));let i=pt(t.map(({matchUpType:_})=>_));if(i.length>1)if(_s(i,xt))t=t.filter(re(xt));else if(_s(i,Ct))t=t.filter(re(Ct));else if(_s(i,Rt))t=t.filter(re(Rt));else return{};if(!Rr(t)||!t.length)return{};let s=(_,v)=>st(_)-st(v),a=pt(t.flatMap(_=>_.drawPositions).filter(Boolean)).sort(s),u=Q(1,Math.max(...a)+1).filter(_=>!a.includes(_)).sort(s),{roundMatchUps:p}=Ue({matchUps:t}),m=p?.[1],d=p?.[2]??[],l=m?.[0],f=l?.drawId,g=l?.structureId,I=p?Object.keys(p).map(_=>st(_)):[],S=Math.max(...I),h=p?.[S]?.length??0,T=Math.ceil(Math.log(h)/Math.log(2)),y=Q(1,T+1).map(_=>{let v=Math.pow(2,_-1),w=S+T-_+1;return Q(1,v+1).map(L=>({drawId:f,structureId:g,matchUpId:it(),drawPositions:[],sides:[],roundNumber:w,roundPosition:L,finishingRound:_}))});T&&(t=t.concat(...y.flat()));let A=m?.map(_=>_.drawPositions)?.flat(1/0),D=d.map(_=>_.drawPositions).flat(1/0).filter(_=>!A?.includes(_)).sort(s),R=d.filter(_=>_.drawPositions?.find(v=>D.includes(v))).map(_=>{let v=_.drawPositions?.find(F=>D.includes(F)),w=v&&_.drawPositions?.indexOf(v),L=w!==void 0&&_.sides?.[w];return v&&{[v]:L}});if(u?.length&&D?.length===u?.length){let _=D.map((F,x)=>[F,u[x]].sort(s)),v=Object.assign({},...R),w=q(m?.[0].finishingRound,!1,!0),L=q(m?.[0].finishingPositionRange,!1,!0);n=_.map((F,x)=>{let k=Math.max(...F??[])/2,G=F?.map(V=>v[V]||{bye:!0,drawPosition:V});return{finishingPositionRange:L,sideNumber:x+1,matchUpStatus:"BYE",matchUpId:it(),finishingRound:w,roundNumber:1,drawPositions:F,roundPosition:k,structureId:g,drawId:f,sides:G}}),t=t.concat(...n)}let U=S+T;return Q(1,U+1).forEach(_=>{let v=[],w=jk({matchUps:t,roundNumber:_}),L=jk({matchUps:t,roundNumber:_-1}),F=new Set(L.map(xQ).filter(Boolean)),x=w?.length===r?.length,k=w?.length===r?.length/2;_===1&&w.forEach(G=>{let V=G.drawPositions??[],{matchUpId:B,structureId:z}=G,H=[{...G.sides[0],drawPosition:V[0],matchUpId:B,structureId:z},{...G.sides[1],drawPosition:V[1],matchUpId:B,structureId:z}],K={...G,children:H};v.push(K)}),x?(o++,w.forEach((G,V)=>{let B=G.drawPositions??[],{matchUpId:z,structureId:H}=G,K=B.filter(Boolean).reduce((Et,Ht)=>A?.includes(Ht)?Et:Ht,void 0),J=[{...G.sides.filter(Boolean).reduce((Et,Ht)=>Ht.participantId&&!F.has(Ht.participantId)?Ht:Et,void 0),drawPosition:K,feedRoundNumber:o,sides:G.sides,matchUpId:z,structureId:H},r[V]],ct={...G,children:J};v.push(ct)})):k&&w.forEach((G,V)=>{let B=[r[V*2],r[V*2+1]],z={...G,children:B};v.push(z)}),r=v}),{hierarchy:r[0],missingMatchUps:n,maxRound:S,finalRound:U,matchUps:t}}function jk({matchUps:t,roundNumber:e}){return t.filter(r=>r.roundNumber===e).sort((r,n)=>r.roundPosition-n.roundPosition)}function xQ(t){if(t.matchUpStatus==="BYE")return t.sides.reduce((e,r)=>r.participantId||e,void 0);if(t.winningSide)return t.sides.reduce((e,r)=>r.sideNumber===t.winningSide?r.participantId:e,void 0)}function WP({scaleAttributes:t,scaledEntries:e,stageEntries:r,seedsCount:n,scaleName:o}){if(!t)return{error:nt,info:"missing scaleAttributes"};let i=Object.assign({},...(e??[]).slice(0,n).map(({participantId:c},u)=>({[c]:u+1})));o=o||t.scaleName;let s=new Date().toISOString();return{scaleItemsWithParticipantIds:r.map(({participantId:c})=>({scaleItems:[{scaleValue:i[c],eventType:t.eventType,scaleType:Eo,scaleName:o,scaleDate:s}],participantId:c}))}}function $k({tournamentRecord:t,drawDefinition:e,policyDefinitions:r,scaleAttributes:n,scaleName:o,drawSize:i,drawId:s,event:a,stage:c,sortDescending:u,scaleSortMethod:p}){let m=$f({policyDefinitions:r,drawDefinition:e,drawSize:i,drawId:s,event:a,stage:c});if(m.error)return m;let{entries:d,seedsCount:l,stageEntries:f}=m;if(!f||!l)return{error:O};let g=Xa({tournamentRecord:t,scaleAttributes:n,scaleSortMethod:p,sortDescending:u,entries:d,stage:c}).scaledEntries??[],{scaleItemsWithParticipantIds:I}=WP({scaleAttributes:n,scaledEntries:g,stageEntries:f,seedsCount:l,scaleName:o});return{scaleItemsWithParticipantIds:I}}var Uv={};Gt(Uv,{addDrawEntries:()=>mS,addEventEntries:()=>jn,addEventEntryPairs:()=>Pv,destroyPairEntries:()=>Zb,destroyPairEntry:()=>fS,getEntriesAndSeedsCount:()=>$f,getMaxEntryPosition:()=>AP,modifyEntriesStatus:()=>Xl,modifyEventEntries:()=>Nv,mutate:()=>Dv,promoteAlternate:()=>yv,promoteAlternates:()=>YP,query:()=>cv,removeDrawEntries:()=>Av,removeEventEntries:()=>Du,removeStageEntries:()=>Ev,setEntryPosition:()=>HP,setEntryPositions:()=>Tv});var Dv={};Gt(Dv,{addDrawEntries:()=>mS,addEventEntries:()=>jn,addEventEntryPairs:()=>Pv,destroyPairEntries:()=>Zb,destroyPairEntry:()=>fS,modifyEntriesStatus:()=>Xl,modifyEventEntries:()=>Nv,promoteAlternate:()=>yv,promoteAlternates:()=>YP,removeDrawEntries:()=>Av,removeEventEntries:()=>Du,removeStageEntries:()=>Ev,setEntryPosition:()=>HP,setEntryPositions:()=>Tv});function HP({tournamentRecord:t,drawDefinition:e,participantId:r,entryPosition:n,skipRefresh:o,event:i}){let s=dt({tournamentRecord:t,participantId:r},[rt,sr]);if(s.error)return s;if(n!==void 0&&!Number.isSafeInteger(n))return{error:O,entryPosition:n};(i?.entries??[]).forEach(c=>{c.participantId===r&&(c.entryPosition=n)}),(e?.entries??[]).forEach(c=>{c.participantId===r&&(c.entryPosition=n)});let a=c=>{c.entries.forEach(u=>{u.entryPosition===n&&u.participantId!==r&&(u.entryPosition+=.1)})};return o||(i?.entries&&(a(i),i.entries=no({entries:i.entries})),e?.entries&&(a(e),e.entries=no({entries:e.entries}))),{...P}}function Tv({tournamentRecord:t,entryPositions:e,drawDefinition:r,event:n}){let o=dt({tournamentRecord:t},[rt]);if(o.error)return o;if(!Array.isArray(e))return{error:O};for(let i of e){let{participantId:s,entryPosition:a}=i,c=HP({skipRefresh:!0,tournamentRecord:t,drawDefinition:r,participantId:s,entryPosition:a,event:n});if(c.error)return c}return n?.entries&&(n.entries=no({entries:n.entries})),r?.entries&&(r.entries=no({entries:r.entries})),{...P}}function yv(t){let{participantId:e}=t;return e&&typeof e!="string"?{error:O,participantId:e}:YP({...t,participantIds:[e].filter(Boolean)})}function YP({tournamentRecord:t,drawDefinition:e,participantIds:r,stageSequence:n,stage:o=W,eventId:i,event:s}){let a=dt({tournamentRecord:t,event:s},[rt,ce]);if(a.error)return a;if(!Array.isArray(r))return{error:O,participantIds:r};let c="promoteAlternates";if(s){let u=Kk({element:s,participantIds:r,stageSequence:n,stage:o});if(u.error)return u}if(e){let u=Kk({element:e,participantIds:r,stageSequence:n,stage:o});if(u.error)return i?M({context:{drawPromotionError:u.error,drawId:e.drawId},result:{...P},stack:c}):u}return{...P}}function Kk({participantIds:t,stageSequence:e,element:r,stage:n}){let o=(r.entries??[]).filter(m=>m.entryStatus===Zr),i=(r.entries??[]).filter(m=>t.includes(m.participantId)),s=o.reduce((m,d)=>{let{entryPosition:l}=d;return Number.isNaN(Number(l))&&m||(!m||l<m.entryPosition)&&d||m},void 0),a=i.length?i:[s].filter(Boolean);if(!a?.length)return{error:jT};let c=a.filter(({entryStatus:m})=>m!==Zr);if(c.length)return{error:Qg,invalidEntryStatus:c};let u=a.filter(({entryStage:m})=>m&&m!==n);if(u.length)return{error:Tw,invalidStage:u};let p=e&&a.filter(m=>m.stageSequence!==e);if(p?.length)return{error:yw,invalidStageSequence:p};for(let m of a){m.entryStatus=kr;let d=m?.entryPosition;Number.isNaN(Number(d))||r.entries.forEach(f=>{f.entryStatus===Zr&&f.entryPosition>d&&(f.entryPosition=f.entryPosition-1)});let l=Math.max(...r.entries.filter(f=>f.entryStatus===kr&&!Number.isNaN(Number(f.entryPosition))).map(({entryPosition:f})=>st(f||0)),0);m.entryPosition=l||0}return{...P}}function Ev({drawDefinition:t,entryStage:e}){return t?e?(t.entries&&(t.entries=t.entries.filter(r=>r.entryStage!==e)),{...P}):{error:O}:{error:$}}function Av({autoEntryPositions:t=!0,participantIds:e,drawDefinition:r,drawId:n,stages:o,event:i}){if(!i)return{error:le};if(!n)return{error:Nn};if(!e?.length)return{error:Mo};let s=Ji({drawDefinition:r,stages:o}).assignedParticipantIds??[];if(Re(s,e))return{error:Pa};let c=m=>{let d=m.participantId;return!e.includes(d)},{flightProfile:u}=Bt({event:i}),p=u?.flights?.find(m=>m.drawId===n);return p?.drawEntries&&(p.drawEntries=p.drawEntries.filter(c),t&&(p.drawEntries=no({entries:p.drawEntries}))),r?.entries&&(r.entries=r.entries.filter(c),t&&(r.entries=no({entries:r.entries}))),{...P}}function wQ(t,e){if(!t)return{error:Aa};t.participantId??=it(),e.participants??=[];let{participantId:r}=t;if(e.participants.reduce((s,a)=>a.participantId===r||s,!1))return{error:lU};let{participantType:o,participantRole:i}=t;if(!o||!Object.keys(Op).includes(o))return{error:Dn,participantType:o};if(!i)return{error:mU};if(o!==St&&t.person)return{error:O,person:t.person};if(t.individualParticipantIds&&!Array.isArray(t.individualParticipantIds))return{error:O,individualParticipantIds:t.individualParticipantIds}}function LQ({participant:t,tournamentParticipants:e,pairOverride:r,allowDuplicateParticipantIdPairs:n,returnParticipant:o}){let i="addParticipant";if(t.person)return{error:O,person:t.person};if(!t.individualParticipantIds)return M({result:{error:Mo},stack:i});if(t.individualParticipantIds.length!==2&&!r)return M({info:"PAIR must be 2 individualParticipantIds",result:{error:_r},stack:i});let s=new Set(e.filter(p=>p.participantType===St).map(p=>p.participantId));if(!Array.isArray(t.individualParticipantIds))return M({result:{error:_r},stack:i});if(!t.individualParticipantIds.reduce((p,m)=>s.has(m)&&p,!0))return M({result:{error:_r},stack:i});let u=e.filter(p=>p.participantType===lt).map(p=>({individualParticipantIds:p.individualParticipantIds,participant:p})).find(p=>Yt(p.individualParticipantIds,t.individualParticipantIds).length===2);if(u&&!n)return{earlyReturn:!0,...P,existingParticipant:!0,participant:o&&q(u.participant)};if(!t.participantName){let p=e.filter(d=>t.individualParticipantIds?.includes(d.participantId)),m=p.map(d=>d.person?.standardFamilyName||d.participantOtherName||d.participantName||"").filter(Boolean).join("/");p.length===1&&(m+="/Unknown"),t.participantName=m}}function FQ({participant:t,tournamentIndividualParticipantIds:e}){let r="addParticipant";if(t.individualParticipantIds??=[],t.individualParticipantIds?.length)for(let n of t.individualParticipantIds){if(typeof n!="string")return M({result:{participantId:n,error:O},stack:r});if(!e.includes(n))return M({result:{participantId:n,error:ee},stack:r})}}function Gn(t){let e="addParticipant",{allowDuplicateParticipantIdPairs:r,returnParticipant:n,disableNotice:o,pairOverride:i,participant:s}=t,a=t.tournamentId?t.tournamentRecords?.[t.tournamentId]:t.tournamentRecord??(t.activeTournamentId&&t.tournamentRecords?.[t.activeTournamentId]);if(!a)return{error:j};let c=wQ(s,a);if(c)return M({result:c,stack:e});let{participantType:u}=s,p=a.participants??[],m=p.filter(l=>l.participantType===St).map(l=>l.participantId);if(u===lt){let l=LQ({participant:s,tournamentParticipants:p,pairOverride:i,allowDuplicateParticipantIdPairs:r,returnParticipant:n});if(l?.earlyReturn){let{earlyReturn:f,...g}=l;return g}if(l)return l}else if(u===St){let l=s.person?.standardFamilyName&&s.person?.standardGivenName,f=s.participantOtherName||s.participantName;if(!l&&!f)return{error:SU};s.participantName||(s.participantName=l?`${s.person.standardGivenName} ${s.person.standardFamilyName}`:s.participantOtherName??"")}else if(u&&[_t,$r].includes(u)){let l=FQ({participant:s,tournamentIndividualParticipantIds:m});if(l)return l}else return{error:Dn};a.participants?.push(s),o||at({payload:{tournamentId:a.tournamentId,participants:[s]},topic:Di});let d={participant:n&&q(s),...P};return et(d)}function un({allowDuplicateParticipantIdPairs:t,returnParticipants:e,tournamentRecord:r,participants:n=[]}){if(!r)return{error:j};r.participants??=[];let i=r.participants.map(d=>d.participantId)??[];n.forEach(d=>{d.participantId??=it()});let s=n.filter(d=>!i.includes(d.participantId)),a=n.filter(d=>i.includes(d.participantId)),c=s.filter(d=>d.participantType===St),u=s.filter(d=>d.participantType!==St),p=c.concat(...u),m=[];if(p.length){for(let l of p){let f=Gn({allowDuplicateParticipantIdPairs:t,returnParticipant:!0,disableNotice:!0,tournamentRecord:r,participant:l});if(f.error)return f;f.success&&!f.existingParticipant&&m.push(f.participant)}m.length&&at({topic:Di,payload:{tournamentId:r.tournamentId,participants:m}});let d={participants:e&&q(m),addedCount:m.length,...P};return a.length&&Object.assign(d,{notAdded:a,info:_m}),et(d)}else return{info:"No new participants to add",addedCount:0,...P}}function Pv(t){let e=X(t,[{[rt]:!0,[ce]:!0}]);if(e.error)return e;let{allowDuplicateParticipantIdPairs:r,entryStatus:n=Zr,participantIdPairs:o=[],entryStage:i=W,tournamentRecord:s,enforceCategory:a,drawDefinition:c,event:u,uuids:p}=t;if(u.eventType!==Rt)return{error:zn};let m=[],d=new Map;for(let E of s.participants??[]){let{participantType:A,participantId:N,person:D,individualParticipantIds:R}=E;A===St&&D?.sex?d.set(N,D.sex):A===lt&&R&&m.push(R)}let l=o.filter(E=>{if(E.length!==2)return!0;if(!u.gender||Oo(u.gender))return!1;if(!d.has(E[0])||!d.has(E[1]))return!0;let A=E.map(D=>d.get(D)),N=Da(u.gender)&&(!Da(A[0])||!Da(A[1]))||ls(u.gender)&&(!ls(A[0])||!ls(A[1]));return nn(u.gender)&&(A.sort(Wp),(!ls(A[0])||!Da(A[1]))&&(N=!0)),N});if(l.length)return{error:_r,invalidParticipantIdPairs:l};let f=o.map(E=>({participantId:p?.pop()??it(),participantRole:Ve,individualParticipantIds:E,participantType:lt})),g=r?f:f.filter(E=>!m.some(A=>Yt(A,E.individualParticipantIds).length===2)),I,S=[];if(g){let E=un({allowDuplicateParticipantIdPairs:r,participants:g,returnParticipants:!0,tournamentRecord:s});if(E.error)return E;S=E.participants??[],I=E.info}let h=o.map(E=>{let A=S.find(D=>Yt(D.individualParticipantIds,E).length===2);if(A)return A;let{participant:N}=Tn({tournamentRecord:s,participantIds:E});return N}).map(E=>E.participantId),T=jn({participantIds:h,tournamentRecord:s,enforceCategory:a,drawDefinition:c,entryStatus:n,entryStage:i,event:u});g.length&&at({payload:{participants:g},topic:Di});let y=g.map(gt);return{...T,info:I,newParticipantIds:y}}function Nv({entryStatus:t=kr,unpairedParticipantIds:e=[],participantIdPairs:r=[],entryStage:n=W,tournamentRecord:o,event:i}){let s=dt({tournamentRecord:o,event:i},[rt,ce]);if(s.error)return s;let a=o.participants??[],c=a.filter(h=>h.participantType===St).map(h=>h.participantId),p=e.concat(...r).flat(1/0).filter(h=>!c.includes(h));if(p.length)return{error:_r,invalidParticipantIds:p};let m=r.filter(h=>h.length!==2);if(m.length)return{error:_r,invalidParticipantIdPairs:m};let d=a.filter(h=>h.participantType===lt).map(h=>h.individualParticipantIds),f=r.filter(h=>!d.find(T=>Yt(T,h).length===2)).map(h=>({participantType:lt,participantRole:Ve,individualParticipantIds:h})),g=un({participants:f,tournamentRecord:o});if(g.error)return g;let I=r.map(h=>{let{participant:T}=Tn({tournamentRecord:o,participantIds:h});return T}).map(h=>({participantId:h,entryStatus:t,entryStage:n})),S=e.map(h=>({entryStatus:Gr,participantId:h,entryStage:n}));return i.entries=(i.entries??[]).filter(h=>h.entryStage===n),i.entries=i.entries.concat(...I,...S),{...P}}var Vv={};Gt(Vv,{addDrawDefinition:()=>Gu,addEvent:()=>tc,addFlight:()=>kd,assignSeedPositions:()=>wv,attachFlightProfile:()=>gh,categoryCanContain:()=>fp,deleteDrawDefinitions:()=>Fd,deleteEvents:()=>Fv,deleteFlightAndFlightDraw:()=>_v,deleteFlightProfileAndFlightDraws:()=>vv,generate:()=>bv,generateEventsFromTieFormat:()=>Rv,getCategoryAgeDetails:()=>gs,getEvent:()=>BP,getEventProperties:()=>GP,getEventStructures:()=>RS,getEventTimeItem:()=>xp,getEvents:()=>VP,getFlightProfile:()=>Bt,getScaledEntries:()=>Xa,modifyEvent:()=>kv,modifyEventMatchUpFormatTiming:()=>Ov,modifyPairAssignment:()=>xv,mutate:()=>Gv,query:()=>gv,refreshEventDrawOrder:()=>fh,removeEventMatchUpFormatTiming:()=>Zf,removeScaleValues:()=>Ih,removeSeeding:()=>Lv,setEventDates:()=>dh,setEventDisplay:()=>tg,setEventEndDate:()=>QP,setEventStartDate:()=>zP,updateDrawIdsOrder:()=>lh,validateCategory:()=>lp});var bv={};Gt(bv,{generateEventsFromTieFormat:()=>Rv});function zk({tournamentId:t,event:e}){return e?(at({payload:{tournamentId:t,event:e},key:e.eventId,topic:sb}),{...P}):{error:le}}var Qk={collectionDefinitions:[{collectionName:"Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"College D3",winCriteria:{valueGoal:5}};var Xk={collectionDefinitions:[{collectionName:"Doubles",collectionValue:1,matchUpCount:3,matchUpFormat:"SET1-S:6/TB7",matchUpType:"DOUBLES"},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"College Default",winCriteria:{valueGoal:5}};var Jk={collectionDefinitions:[{collectionName:"Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"College JUCO",winCriteria:{valueGoal:5}};var jP={COLLEGE_D3:Qk,COLLEGE_DEFAULT:Xk,COLLEGE_JUCO:Jk,DOMINANT_DUO:Iy,DOMINANT_DUO_MIXED:ly,LAVER_CUP:Ey,TEAM_DOUBLES_3_AGGREGATION:uy,USTA_BREWER_CUP:fy,USTA_OZAKI_CUP:gy,USTA_COLLEGE:Sy,USTA_GOLD_TEAM_CHALLENGE:cy,USTA_INTERSECTIONAL:dy,USTA_LEVEL_1:hy,USTA_SECTION_BATTLE:my,USTA_SOUTHERN_LEVEL_5:py,USTA_TOC:Ay,USTA_WTT_ITT:Ty,USTA_ZONAL:yy};function tc({suppressNotifications:t,tournamentRecord:e,internalUse:r,event:n}){let o=dt({tournamentRecord:e,event:n},[rt,ce]);if(o.error)return o;e.events??=[];let{startDate:i,endDate:s}=e;if(!r&&(n.entries?.length||n.drawDefinitions?.length)){let p=et({drawDefinitions:!!n.drawDefinitions?.length,entries:!!n.entries?.length});return{info:"entries/drawDefinitions cannot exist",error:O,context:p}}let a={eventType:ba,drawDefinitions:[],entries:[],startDate:i,endDate:s,...n};if(n.eventType===Ze){if(n.tieFormat){let p=or({tieFormat:n.tieFormat});if(p.error)return p}else if(n.tieFormatName){if(!jP[n.tieFormatName])return{context:{tieFormatName:n.tieFormatName},error:O};let p=uo({isMock:e?.isMock,namedFormat:n.tieFormatName,event:n});a.tieFormat=p}}if(a.eventId??=it(),e.events.reduce((p,m)=>p||m.eventId===a.eventId,void 0))return{error:YD};let u=a;if(e.events.push(u),!t){let{topics:p}=vr();if(p.includes(Zm)){let l=vn({event:n}).matchUps??[];Ho({tournamentId:e?.tournamentId,eventId:n.eventId,matchUps:l})}let{drawDefinitions:m,...d}=n;for(let l of m??[])yc({drawDefinition:l});zk({tournamentId:e?.tournamentId,event:d})}return{...P,event:a}}function Rv(t){let e=X(t,[{[_a]:{[Tl]:!0,[by]:!0}},{[rt]:!0}]);if(e.error)return e;let r=t.tieFormat||uo({namedFormat:t.tieFormatName}),n=t.uuids||[ay(r.collectionDefinitions.length)],o=t.addEntriesFromTeams?BQ(t.tournamentRecord):{[Ce]:[],[Je]:[]},i=[];for(let s of r.collectionDefinitions??[]){let a=n?.pop()?.toString()||it(),c={matchUpFormat:s.matchUpFormat,eventName:s.collectionName,category:s.category,gender:s.gender,eventType:s.matchUpType,eventId:a};if(t.addEntriesFromTeams){let u=WQ({genderedParticipants:o,collectionDefinition:s,entryStatus:t.entryStatus,event:c});if(u?.error)return u}if(i.push(c),t.addEvents!==!1){let u=tc({internalUse:!0,tournamentRecord:t.tournamentRecord,event:c});if(u.error)return u}}return{...P,events:i}}function BQ(t){let e={[Ce]:[],[Je]:[]},r=t.participants?.filter(o=>o.participantType===ur),n=new Set(r?.flatMap(o=>o.individualParticipantIds??[]));for(let o of t.participants??[])if(n.has(o.participantId)){let i=o.person?.sex;if(i&&Un(i)){let s=Ar(i);s&&e[s].push(o.participantId)}}return e}function WQ({genderedParticipants:t,collectionDefinition:e,entryStatus:r,event:n}){let o=e.matchUpType,i=e.gender,s=o===si?Gr:r||kr,a=nn(i)?[...t[Ce],...t[Je]]:t[Ar(i)||ii]??[];if(a.length)return jn({participantIds:a,entryStatus:s,event:n})}var Gv={};Gt(Gv,{addDrawDefinition:()=>Gu,addEvent:()=>tc,addFlight:()=>kd,assignSeedPositions:()=>wv,attachFlightProfile:()=>gh,deleteDrawDefinitions:()=>Fd,deleteEvents:()=>Fv,deleteFlightAndFlightDraw:()=>_v,deleteFlightProfileAndFlightDraws:()=>vv,modifyEvent:()=>kv,modifyEventMatchUpFormatTiming:()=>Ov,modifyPairAssignment:()=>xv,refreshEventDrawOrder:()=>fh,removeEventMatchUpFormatTiming:()=>Zf,removeScaleValues:()=>Ih,removeSeeding:()=>Lv,setEventDates:()=>dh,setEventDisplay:()=>tg,setEventEndDate:()=>QP,setEventStartDate:()=>zP,updateDrawIdsOrder:()=>lh,validateCategory:()=>lp});function ec({removePriorValues:t=!0,status:e=br,statusObject:r,event:n}){if(!Tt(r))return{error:O};let o=Cr({event:n,status:e}),i=`${qo}.${$o}`,s={itemValue:{[e]:{...o,...r}},itemType:i};return Rs({timeItem:s,removePriorValues:t,event:n})}function rc(t){let e=X(t,[{[rt]:!0,[ce]:!0},{eventDataParams:!1,[Ge]:qr}]);if(e.error)return e;let{includePositionAssignments:r,removePriorValues:n,tournamentRecord:o,status:i=br,event:s,drawIdsToRemove:a,drawIdsToAdd:c}=t,{appliedPolicies:u}=ft({tournamentRecord:o,event:s}),p={...u,...t.policyDefinitions},m=s?.drawDefinitions?.map(({drawId:A})=>A)??[],d=t.drawDetails?Object.keys(t.drawDetails):[],l=d.length?[]:t.drawIds,f=(c??[]).concat(...a??[],...l??[],...d),g=HQ({drawIdsToValidate:f,eventDrawIds:m});if(g?.error)return g;let I=YQ(t.drawDetails);if(I?.error)return I;let S=Cr({event:s,status:i}),h=qQ({pubStatus:S,eventDrawIds:m});$Q({drawDetails:h,eventDrawIds:m,drawIdsToValidate:f,drawIdsToRemove:a,drawIdsToAdd:c,specifiedDrawIds:l});for(let A of m)if(t.drawDetails?.[A]){let N=KQ({drawDetails:h,drawId:A,newDetail:t.drawDetails[A],event:s});if(N?.error)return N}ec({statusObject:{drawDetails:h},removePriorValues:n,status:i,event:s});let{topics:T}=vr(),y=T.includes(zy),E=y||t.returnEventData?tm({includePositionAssignments:r,...t.eventDataParams,usePublishState:!0,tournamentRecord:o,policyDefinitions:p,event:s})?.eventData:void 0;return y&&at({payload:{eventData:E,tournamentId:o.tournamentId},topic:zy}),{...P,eventData:E}}function HQ({drawIdsToValidate:t,eventDrawIds:e}){let r=t.filter(n=>!e.includes(n));if(r.length)return M({result:{error:Mr},context:{invalidDrawIds:r}})}function Cv(t){return!!t&&!Ra(t)}function YQ(t){if(t)for(let e of Object.keys(t)){let r=t[e];if(Cv(r.publishingDetail?.embargo))return{error:ip};let n=Zk(r.stageDetails);if(n)return n;let o=jQ(r.structureDetails);if(o)return o}}function Zk(t){if(t){for(let e of Object.keys(t))if(Cv(t[e].embargo))return{error:ip}}}function jQ(t){if(t)for(let e of Object.keys(t)){let r=t[e];if(Cv(r.embargo))return{error:ip};if(r.scheduledRounds){let n=Zk(r.scheduledRounds);if(n)return n}}}function qQ({pubStatus:t,eventDrawIds:e}){return Object.keys(t?.drawDetails??{}).filter(r=>e.includes(r)).reduce((r,n)=>(r[n]=t.drawDetails[n],r),{})}function $Q({drawDetails:t,eventDrawIds:e,drawIdsToValidate:r,drawIdsToRemove:n,drawIdsToAdd:o,specifiedDrawIds:i}){for(let s of e)(!r.length||r.includes(s))&&(n?.includes(s)||i?.length&&!i.includes(s)?t[s]={...t[s],publishingDetail:{published:!1}}:(o?.includes(s)||i?.includes(s)||!i?.length)&&(t[s]={...t[s],publishingDetail:{published:!0}}))}function KQ({drawDetails:t,drawId:e,newDetail:r,event:n}){let o=r.structureDetails??t[e].structureDetails,i=r.stageDetails??t[e].stageDetails??{},{structureIdsToRemove:s=[],structureIdsToAdd:a=[],publishingDetail:c={},stagesToRemove:u=[],stagesToAdd:p=[]}=r;if((a||p)&&(c.published=!0),t[e]={publishingDetail:c,structureDetails:o,stageDetails:i},a.length||s.length){let d=zQ({drawDetails:t,drawId:e,structureIdsToAdd:a,structureIdsToRemove:s,structureDetails:o,event:n});if(d?.error)return d}let m=(n?.drawDefinitions?.find(d=>d.drawId===e)?.structures??[]).map(({stage:d})=>d);QQ({stageDetails:i,stagesToAdd:p,stagesToRemove:u,drawStages:m}),(p.length||u.length)&&(t[e].stageDetails=i)}function zQ({drawDetails:t,drawId:e,structureIdsToAdd:r,structureIdsToRemove:n,structureDetails:o,event:i}){let s=(i?.drawDefinitions?.find(u=>u.drawId===e)?.structures??[]).map(({structureId:u})=>u),c=(r??[]).concat(n??[]).filter(u=>!s.includes(u));if(c.length)return M({result:{error:Nt},context:{invalidStructureIds:c}});o=o??{};for(let u of s)n.includes(u)?o[u]={published:!1}:o[u]={published:!0};t[e].structureDetails=o}function QQ({stageDetails:t,stagesToAdd:e,stagesToRemove:r,drawStages:n}){if(e.length){for(let o of e)t[o]={published:!0};for(let o of n)t[o]||(t[o]={published:!1})}if(e.length||r.length){for(let o of r)t[o]={published:!1};for(let o of n)t[o]||(t[o]={published:!0})}}var Mv="deleteDrawDefinitions",qP="autoSchedulingAudit",ph="deleteEvents",tG={AUTO_SCHEDULING_AUDIT:qP,DELETE_EVENTS:ph,DELETE_DRAW_DEFINITIONS:Mv};function Fd(t){if(!t.tournamentRecord)return{error:j};let e="deleteDrawDefinitions",r=t.drawIds??[],n=t.event,{autoPublish:o=!0,tournamentRecord:i,auditData:s,eventId:a,force:c}=t,{appliedPolicies:u}=ft({tournamentRecord:i,event:n}),p={...u,...t.policyDefinitions},m=Array.isArray(r)?r[0]:void 0;if(!n){let D=_e({tournamentRecord:i,eventId:a,drawId:m});if(D.error)return D;n=D.event}let d=[],l=[],f=[];if(!n?.drawDefinitions)return M({info:"event has no drawDefinition",result:{...P},stack:e});let g=n.drawDefinitions.map(({drawId:D})=>D);if(r.length||(r=g),r=r.filter(D=>g.includes(D)),!r.length)return M({info:"nothing to do; no matching drawIds in event.",result:{...P},stack:e});let I=q(Bt({event:n}).flightProfile,!1,!0),S=({participantId:D,drawPosition:R,qualifier:U,bye:b})=>({bye:b,qualifier:U,drawPosition:R,participantId:D}),h=c??u?.[Qr]?.allowDeletionWithScoresPresent?.drawDefinitions,T=Cr({event:n})??{},y=T.drawIds??(T.drawDetails&&Object.keys(T.drawDetails))??[],E,A=[],N=n.drawDefinitions.filter(D=>{if(r.includes(D.drawId)){let R=rr({event:n,drawDefinition:D})?.matchUps??[];if(R.some(({score:V})=>ue({score:V}))&&!h)return A.push(D.drawId),!0;let{drawId:b,drawType:C,drawName:_}=D,v=I?.flights?.find(V=>V.drawId===D.drawId);v&&(v.drawEntries=v.drawEntries?.filter(V=>yr.includes(V.entryStatus))),y.includes(b)&&(y=y.filter(V=>V!==b),E=!0);let w=Sn({stageSequence:1,drawDefinition:D,stage:W})?.structures?.[0],F=(w?xu({structureId:w.structureId,tournamentRecord:i,drawDefinition:D}):void 0)?.positionAssignments?.map(S),x=Sn({stage:Z,drawDefinition:D})?.structures,k=x?.length?x.map(V=>{let B=V.stageSequence;return{positionAssignments:xu({structureId:V.structureId,tournamentRecord:i,drawDefinition:D})?.positionAssignments.map(S),stageSequence:B}}):void 0,G={action:Mv,payload:{drawDefinitions:[D],eventId:a??n?.eventId,auditData:s}};f.push(G),d.push(et({tournamentId:i.tournamentId,eventId:a??n?.eventId,qualifyingPositionAssignments:k,positionAssignments:F,auditData:s,drawType:C,drawName:_,drawId:b})),R?.forEach(({matchUpId:V})=>l.push(V))}return!r.includes(D.drawId)});if(A.length&&!c)return M({context:{drawIdsWithScoresPresent:A},result:{error:Zc},stack:e});if(n.drawDefinitions=N,I&&Go({event:n,extension:{name:on,value:I}}),ku({tournamentRecord:i}),E){let D={};for(let U of y)D[U]=T.drawDetails?.[U]??{published:!0};let R=ec({statusObject:{drawDetails:D},event:n});if(R.error)return{error:R.error}}if(f.length)if(tu(Yi)){let D=i.tournamentId;at({topic:Yi,payload:{tournamentId:D,detail:f}});let U=(Jr({element:n,itemType:Ic})?.timeItem?.itemValue||0)+1;oo({element:n,timeItem:{itemType:Ic,itemValue:U},removePriorValues:!0})}else XQ({appliedPolicies:u,event:n,deletedDrawsDetail:d,auditData:s});if(l.length&&wn({tournamentId:i?.tournamentId,matchUpIds:l}),r.forEach(D=>AL({drawId:D})),o&&E){let D=rc({...t.eventDataParams,drawIdsToRemove:r,policyDefinitions:p,tournamentRecord:i,event:n});if(D.error)return{...P,info:D.error}}return{...P}}function XQ({appliedPolicies:t,event:e,deletedDrawsDetail:r,auditData:n}){if(t?.audit?.[Ic]===!1)return;let{extension:o}=ot({name:Ic,element:e}),i={...n,deletedDrawsDetail:r},s={value:Array.isArray(o?.value)?o?.value.concat(i):[i],name:Ic};ut({element:e,extension:s})}function vv({autoPublish:t=!0,tournamentRecord:e,auditData:r,event:n,force:o}){let i=dt({tournamentRecord:e,event:n},[rt,ce]);if(i.error)return i;let{flightProfile:s}=Bt({event:n});if(s){let a=s.flights?.map(({drawId:u})=>u).filter(Boolean),c=Fd({eventId:n.eventId,tournamentRecord:e,autoPublish:t,auditData:r,drawIds:a,event:n,force:o});return c.error?c:Qm({event:n,name:on})}return{...P}}function mh(t){let{matchUpFormat:e,recoveryTimes:r,averageTimes:n,tournamentId:o,eventId:i}=t,s=t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{};if(!Object.keys(s).length)return{error:kt};let a=Object.keys(s).filter(u=>!o||o===u);if(o&&!a.includes(o))return{error:O};let c;for(let u of a){let p=s[u],{event:m}=_e({tournamentRecord:p,eventId:i});i&&m&&(c=!0);let d=JQ({tournamentRecord:p,event:m,matchUpFormat:e,averageTimes:n,recoveryTimes:r});if(d.error)return d}return!i||c?{...P}:{error:Wr}}function JQ({tournamentRecord:t,recoveryTimes:e,matchUpFormat:r,averageTimes:n,event:o}){if(!t)return{error:j};if(n&&!Array.isArray(n))return{error:O};if(e&&!Array.isArray(e))return{error:O};let i=pi;if(o){let{extension:s}=ot({element:o,name:i}),a=s?.value??{},c=eG({...a,matchUpFormat:r,averageTimes:n,recoveryTimes:e});ut({element:o,extension:{name:i,value:c}})}else{let{extension:s}=ot({element:t,name:i}),a=s?.value??{},c=eG({...a,matchUpFormat:r,averageTimes:n,recoveryTimes:e});ut({extension:{name:i,value:c},element:t})}return{...P}}function eG(t){let{matchUpRecoveryTimes:e=[],matchUpAverageTimes:r=[],matchUpFormat:n}=t,{averageTimes:o,recoveryTimes:i}=t;o=(o??[]).filter(c=>c?.categoryNames?.length||c?.categoryTypes?.length);let s=o?.length&&r.map(c=>c?.matchUpFormatCodes.includes(n)?{...c,matchUpFormatCodes:c.matchUpFormatCodes?.filter(u=>u!==n)}:c).filter(({matchUpFormatCodes:c})=>c?.length).concat({matchUpFormatCodes:[n],averageTimes:o});i=(i??[]).filter(c=>c?.categoryNames?.length||c?.categoryTypes?.length);let a=i?.length&&e.map(c=>c?.matchUpFormatCodes.includes(n)?{...c,matchUpFormatCodes:c.matchUpFormatCodes?.filter(u=>u!==n)}:c).filter(({matchUpFormatCodes:c,averageTimes:u})=>c?.length||u).concat({matchUpFormatCodes:[n],recoveryTimes:i});return{matchUpAverageTimes:s?.length&&s||r,matchUpRecoveryTimes:a?.length&&a||e}}function Ov(t){let{tournamentRecord:e,recoveryMinutes:r,averageMinutes:n,matchUpFormat:o,categoryType:i,eventId:s,event:a}=t,c=dt({tournamentRecord:e},[rt]);if(c.error)return c;if(!xr({matchUpFormat:o}))return{error:O};let u=dt({event:a},[ce]);if(u.error)return u;let{averageTimes:p=[],recoveryTimes:m=[]}=Kf({tournamentRecord:e,matchUpFormat:o,event:a}),d=a.category,l=d?.categoryName||d?.ageCategoryCode||a?.eventId,f={categoryNames:[l],minutes:{}},g={categoryNames:[l],minutes:{}},I=E=>{if(E.categoryTypes?.includes(i)&&console.log("encountered:",{categoryType:i}),!(E.categoryNames?.includes(l)&&(E.categoryNames=E.categoryNames.filter(A=>A!==l),f={minutes:E.minutes,categoryNames:[l]},!E.categoryNames.length)))return E},S=n&&!isNaN(st(n)),h=r&&!isNaN(st(r)),T=p.map(I).filter(E=>E?.categoryNames?.length),y=m.map(I).filter(E=>E?.categoryNames?.length);return S&&(Object.assign(f.minutes,{[a?.eventType||Ct]:n}),T.push(f)),h&&(Object.assign(g.minutes,{[a?.eventType||Ct]:r}),y.push(g)),!S&&!h?{error:O}:mh({averageTimes:S&&T,recoveryTimes:h&&y,tournamentRecord:e,matchUpFormat:o,eventId:s,event:a})}function Zf(t){if(t.event)return rG({event:t.event});{t.tournamentRecord&&!t.tournamentRecords&&(t.tournamentRecords={[t.tournamentRecord.tournamentId]:t.tournamentRecord});let e=X(t,[{[Ee]:!0,[My]:!0}]);if(e.error)return e;let{tournamentRecords:r,eventId:n}=t;for(let o of Object.values(r??{})){let{event:i}=_e({tournamentRecord:o,eventId:n});if(i)return rG({event:i})}}return{error:Wr}}function rG({event:t}){return Qm({event:t,name:pi})}var $P={MON:"MON",TUE:"TUE",WED:"WED",THU:"THU",FRI:"FRI",SAT:"SAT",SUN:"SUN"};function KP(t){return!Array.isArray(t)||pt(t).length!==t.length?!1:t.every(e=>Object.keys($P).includes(e))}function zP({tournamentRecord:t,event:e,startDate:r}){let n=dt({tournamentRecord:t,event:e},[rt,ce]);if(n.error)return n;if(!_o.test(r))return{error:ae};let o=nG(t),i="setEventStartDate";if(o.error)return M({result:o,stack:i});let{tournamentStartDate:s,tournamentEndDate:a}=o,c=new Date(mt(r)).getTime();if(!s||!a||c<s||c>a)return M({result:{error:ae},stack:i,info:"startDate must be within tournament start and end dates"});let u=e.endDate&&new Date(mt(e.endDate)).getTime();return u&&c>u&&(e.endDate=r),e.startDate=r,{...P}}function QP(t){let{tournamentRecord:e,event:r,endDate:n}=t,o=dt({tournamentRecord:e,event:r},[rt,ce]);if(o.error)return o;if(!_o.test(n))return{error:ae};let i=nG(e);if(i.error)return i;let{tournamentStartDate:s,tournamentEndDate:a}=i,c=new Date(mt(n)).getTime();if(!s||!a||c<s||c>a)return{error:ae};let u=r.startDate&&new Date(mt(r.startDate)).getTime();return u&&c<u&&(r.startDate=n),r.endDate=n,{...P}}function dh(t){let e="setEventDates",r=X(t,[{tournamentRecord:!0,event:!0},{[$e]:u=>_o.test(u),[Lr]:ae,startDate:!1,endDate:!1},{[$e]:u=>u.filter(Boolean).every(p=>_o.test(p)),[Lr]:ae,activeDates:!1},{[$e]:KP,weekdays:!1}]);if(r.error)return r;let{tournamentRecord:n,weekdays:o,event:i,startDate:s,endDate:a}=t,c=t.activeDates?.filter(Boolean);if(s&&a){let u=new Date(mt(s)).getTime(),p=new Date(mt(a)).getTime();if(u>p)return M({result:{error:O},stack:e,info:"startDate cannot be after endDate"})}if(c){let u=s||n.startDate,p=a||n.endDate,m=!u||c.every(l=>new Date(l)>=new Date(u)),d=!p||c.every(l=>new Date(l)<=new Date(p));if(!m||!d)return M({result:{error:ae},stack:e})}if(s){let u=zP({tournamentRecord:n,event:i,startDate:s});if(u.error)return M({result:u,stack:e})}if(a){let u=QP({tournamentRecord:n,event:i,endDate:a});if(u.error)return M({result:u,stack:e})}return c&&(i.activeDates=c),o&&(i.weekdays=o),{...P}}function nG(t){let{startDate:e,endDate:r}=t;return!_o.test(e)||!_o.test(r)?M({result:{error:sU},context:{startDate:e,endDate:r}}):{tournamentStartDate:new Date(mt(e)).getTime(),tournamentEndDate:new Date(mt(r)).getTime()}}function lh({event:t,orderedDrawIdsMap:e}){if(typeof t!="object")return{error:le};if(!e)return{error:nt,info:"Missing drawIdsOrderMap"};if(typeof e!="object")return{error:O,info:"orderedDrawIdsMap must be an object"};let r=Object.values(e);if(!r.every(i=>!Number.isNaN(Number(i))))return{error:O,info:"drawOrder must be numeric"};if(pt(r).length!==r.length)return{info:"drawOrder values must be unique",error:O};if(t.drawDefinitions?.length){let i=(t.drawDefinitions??[]).map(({drawId:a})=>a),s=Object.keys(e);if(s?.length&&Yt(i,s).length!==i.length)return{error:O,info:"Missing drawIds"};t.drawDefinitions.forEach(a=>{a.drawOrder=e[a.drawId]})}let{flightProfile:o}=Bt({event:t});return o?.flights?.forEach(i=>{i.flightNumber=e[i.drawId]}),{...P}}function fh({tournamentRecord:t,event:e}){let r=dt({tournamentRecord:t,event:e},[rt,ce]);if(r.error)return r;let{flightProfile:n}=Bt({event:e}),o=n?.flights?.sort((a,c)=>a.flightNumber-c.flightNumber).map(a=>a.drawId).filter(Boolean),i=e.drawDefinitions?.sort((a,c)=>a.drawOrder-c.drawOrder).map(a=>a.drawId).filter(Boolean).filter(a=>!o?.includes(a)),s=Object.assign({},...[...o??[],...i??[]].map((a,c)=>({[a]:c+1})));return s?lh({event:e,orderedDrawIdsMap:s}):{...P}}function _v({autoPublish:t=!0,tournamentRecord:e,auditData:r,drawId:n,event:o,force:i}){let s=dt({tournamentRecord:e,drawId:n,event:o},[rt,dc,ce]);if(s.error)return s;let{flightProfile:a}=Bt({event:o});if(a&&a.flights?.find(p=>p.drawId===n)){let p=a.flights.filter(d=>d.drawId!==n),m={name:on,value:{...a,flights:p}};Go({event:o,extension:m})}if(o.drawDefinitions?.find(u=>u.drawId===n)){let u=Fd({drawIds:[n],eventId:o.eventId,tournamentRecord:e,autoPublish:t,auditData:r,event:o,force:i});if(u.error)return u}return fh({tournamentRecord:e,event:o})}function xv(t){let e=X(t,[{[ce]:!0,[rt]:!0,[MI]:!1},{replacementIndividualParticipantId:!0,[$e]:S=>wt(S),existingIndividualParticipantId:!0,[jr]:We,participantId:!0}]),{replacementIndividualParticipantId:r,existingIndividualParticipantId:n,tournamentRecord:o,drawDefinition:i,participantId:s,event:a,uuids:c}=t;if(e.error)return e;if(a?.eventType!==Lt)return{error:zn};if(!(a?.entries?.filter(({entryStatus:S})=>[Gr,qi].includes(S)).map(({participantId:S})=>S)??[]).includes(r))return{error:Hr};let p=(o.participants??[]).find(S=>S.participantId===s);if(p?.participantType!==lt)return{error:xi,participant:p};let m=p.individualParticipantIds,d=[r,...m.filter(S=>S!==n)],{participant:l}=Tn({participantIds:d,tournamentRecord:o}),f;if(l)f=l.participantId;else{let S={participantId:c?.pop(),participantRole:Ve,individualParticipantIds:d,participantType:lt},h=Gn({participant:S,returnParticipant:!0,tournamentRecord:o});if(h.error)return h;f=h.participant.participantId}let{flightProfile:g}=Bt({event:a});if(i){let S=g?.flights?.find(({drawId:h})=>h===i.drawId);S&&(S.drawEntries=S.drawEntries.map(h=>h.participantId===s?{...h,participantId:f}:h)),i.entries=i.entries.map(h=>h.participantId===s?{...h,participantId:f}:h);for(let h of i.structures??[])if(h.structures){h.positionAssignments=void 0;for(let T of h.structures)T.positionAssignments=T.positionAssignments.map(y=>y.participantId===s?{...y,participantId:f}:y)}else h.positionAssignments&&(h.positionAssignments=h.positionAssignments.map(T=>T.participantId===s?{...T,participantId:f}:T))}a.entries=a.entries.map(S=>S.participantId===s&&{...S,participantId:f}||S.participantId===r&&{...S,participantId:n}||S);let I=o.events.some(({entries:S,eventId:h,drawDefinitions:T})=>a.eventId===h?T.some(({drawId:y,entries:E})=>y===i?.drawId?!1:E?.find(A=>A.participantId===s)):S?.find(y=>y.participantId===s));if(!I){let S=Ds({addIndividualParticipantsToEvents:!1,participantIds:[s],tournamentRecord:o});if(S.error)return S}return{...P,participantOtherEntries:I,newPairParticipantId:f}}function Gu(t){let{flight:e,suppressNotifications:r,modifyEventEntries:n,existingDrawCount:o,allowReplacement:i,checkEntryStatus:s,tournamentRecord:a,drawDefinition:c,event:u}=t;if(!c)return{error:$};if(!u)return{error:le};u.drawDefinitions??=[];let{drawId:p,drawName:m,entries:d}=c,{entries:l}=u,f=0;if(o!==void 0&&o!==u.drawDefinitions.length)return{error:O,info:"drawDefintions count mismatch"};let{flightProfile:g}=Bt({event:u}),I=e&&g?.flights?.find(v=>v.flightNumber===e.flightNumber),S=g?.links?.find(v=>v?.target?.drawId===p)?.source?.drawId;if(S&&!u.drawDefinitions.some(v=>v.drawId===S))return M({result:{error:$},info:{sourceDrawId:S}});if(I&&I.drawId!==c.drawId)return M({result:{error:ha},info:{relevantFlight:I}});let y=ZQ({drawEntries:d,eventEntries:l,relevantFlight:I,checkEntryStatus:s});if(y?.error)return y;let{matchingEventEntries:E}=y;if(n&&(f=t9({drawEntries:d,eventEntries:l})),l&&!E)return M({result:{info:"Draw entries do not match event entryStatuses",context:{matchingEventEntries:E,eventEntries:l},error:ha}});let A=g?.flights?.map(({flightNumber:v})=>!Number.isNaN(Number(v))&&st(v))?.filter(Boolean)??[],N=u.drawDefinitions.map(({drawOrder:v})=>v&&st(v))?.filter(Boolean)||[],D=Math.max(0,...N,...A)+1,R=g?.flights?.find(v=>v.drawId===p),U;if(R){R.drawName=c.drawName,U={name:on,value:{...g,flights:g.flights}};let v=R.flightNumber;v&&!N.includes(v)?D=v:R.flightNumber=D}else{let v=g?.flights??[];v.push({manuallyAdded:!0,flightNumber:D,drawEntries:d,drawName:m,drawId:p}),U={name:on,value:{...g,flights:v}}}Go({event:u,extension:U}),Object.assign(c,{drawOrder:D});let b=u.drawDefinitions.find(v=>v.drawId===p),C=a?.tournamentId,_=u.eventId;if(b){if(!i)return{error:xD};e9({existingDrawDefinition:b,suppressNotifications:r,drawDefinition:c,tournamentId:C,eventId:_,event:u,drawId:p})}else r9({suppressNotifications:r,tournamentRecord:a,drawDefinition:c,tournamentId:C,eventId:_,event:u});return{...P,modifiedEventEntryStatusCount:f}}function ZQ({drawEntries:t,eventEntries:e,relevantFlight:r,checkEntryStatus:n}){let o=t?.every(({participantId:s,entryStatus:a})=>{let c=r?.drawEntries.find(u=>u.participantId===s);return!a||c?.entryStatus===a}),i=!n||e&&t?.every(({participantId:s,entryStatus:a,entryStage:c})=>e.find(p=>p.participantId===s&&(!p.entryStage||p.entryStage===c))?.entryStatus===a);return r&&!o?M({result:{error:ha},context:{drawEntriesPresentInFlight:o,matchingEventEntries:i,relevantFlight:r},info:"Draw entries are not present in flight or do not match entryStatuses"}):{drawEntriesPresentInFlight:o,matchingEventEntries:i}}function t9({drawEntries:t,eventEntries:e}){let r=0;return t?.filter(Boolean).forEach(n=>{if(n?.entryStatus&&yr.includes(n?.entryStatus)){let o=e?.filter(Boolean).find(i=>i.participantId===n.participantId);o&&n.entryStatus&&o?.entryStatus!==n.entryStatus&&(o.entryStatus=n.entryStatus,r+=1)}}),r}function e9({existingDrawDefinition:t,suppressNotifications:e,drawDefinition:r,tournamentId:n,eventId:o,event:i,drawId:s}){let c=rr({drawDefinition:t})?.matchUps?.map(Te)??[],u=rr({drawDefinition:r})?.matchUps;if(!e){c?.length&&wn({matchUpIds:c,action:"modifyDrawDefinition",tournamentId:n,eventId:o}),u?.length&&Ho({matchUps:u,tournamentId:n,eventId:o}),i.drawDefinitions=i.drawDefinitions.map(m=>m.drawId===s?r:m);let p=r.structures?.map(({structureId:m})=>m);Ft({drawDefinition:r,tournamentId:n,structureIds:p,eventId:o})}}function r9({suppressNotifications:t,tournamentRecord:e,drawDefinition:r,tournamentId:n,eventId:o,event:i}){if(i.drawDefinitions.push(r),!t){let{matchUps:s}=rr({drawDefinition:r,event:i});s&&Ho({tournamentId:e?.tournamentId,matchUps:s}),yc({drawDefinition:r,tournamentId:n,eventId:o})}}function wv(t){let{provisionalPositioning:e,useExistingSeedLimit:r,tournamentRecord:n,drawDefinition:o,seedingProfile:i,structureId:s,assignments:a,drawId:c,event:u}=t,p=0;if(!a?.length)return{error:Bg};let m=dt({tournamentRecord:n,drawId:c},[rt,dc]);if(m.error)return m;let d=Ur({provisionalPositioning:e,drawDefinition:o,structureId:s});if(d.error)return d;let{seedAssignments:l,seedLimit:f}=d,g=Object.assign({},...(l??[]).filter(h=>h.seedNumber).map(h=>({[h.seedNumber]:h})));a.forEach(h=>{let{seedNumber:T}=h;f&&T<=f&&(!r||g[T])&&(g[T]=h)});let I=Object.values(g),S=I.map(h=>h?.participantId).filter(Boolean);if(S.length!==_T(S).length)return{error:wD};for(let h of I){let T=Wa({...h,provisionalPositioning:e,tournamentRecord:n,drawDefinition:o,seedingProfile:i,structureId:s,event:u});if(T?.error)return T;T?.success&&p++}return p?{...P,modifications:p}:{error:Na}}function gh({deleteExisting:t,event:e,flightProfile:r}){let n="attachFlightProfile";if(!r)return M({result:{error:nt},stack:n});if(!e)return M({result:{error:le},stack:n});let{flightProfile:o}=Bt({event:e});return o&&!t?M({result:{error:sI},stack:n}):e.drawDefinitions?.length?M({result:{error:CD},stack:n}):(Go({event:e,extension:{name:on,value:r}}),{flightProfile:q(r,!1,!0),...P})}function oG({tournamentRecord:t,scaleAttributes:e,participantIds:r}){let n=dt({tournamentRecord:t},[rt]);if(n.error)return n;if(!r)return{error:Mo};if(!e)return{error:nt,info:"scaleAttributes required"};let{scaleType:o,eventType:i,scaleName:s}=e,a=[Tb,o,i,s].join(".");return t.participants?.forEach(c=>{r.includes(c.participantId)&&c.timeItems&&(c.timeItems=c.timeItems.filter(u=>u&&u?.itemType!==a))}),{...P}}function Ih({tournamentRecord:t,scaleAttributes:e,drawDefinition:r,entryStatuses:n,drawId:o,event:i,stage:s}){if(!i)return{error:le};if(n&&!Array.isArray(n))return M({result:{error:O},info:Ri("entryStatus"),stack:"removeScaleValues"});let a=i.entries;if(o){let{flightProfile:p}=Bt({event:i}),m=p?.flights?.find(d=>d.drawId===o);m?a=m.drawEntries:a=r?.entries}let u=(a??[]).filter(p=>(!s||!p.entryStage||p.entryStage===s)&&(!n||n.includes(p.entryStatus))).map(gt);return oG({tournamentRecord:t,scaleAttributes:e,participantIds:u})}function tg({removePriorValues:t,tournamentRecord:e,displaySettings:r,status:n=br,event:o}){if(!e)return M({result:{error:j}});if(!o)return M({result:{error:le}});if(!Tt(r))return M({result:{error:nt}});if(Tt(r.draws))for(let s of Object.keys(r.draws)){let a=r.draws[s].scheduleDetails??[];if(a.length){let c=[];for(let u of a){let p=c.find(m=>rw(m.attributes,u.attributes));p?.dates&&u.dates?p.dates.push(...u.dates):c.push(u)}r.draws[s].scheduleDetails=c}}let i=ec({statusObject:{displaySettings:r},removePriorValues:t,status:n,event:o});return i.error?i:{...P}}function Lv({tournamentRecord:t,drawDefinition:e,entryStatuses:r,scaleName:n,drawId:o,event:i,stage:s}){let a=dt({tournamentRecord:t,event:i},[rt,ce]);if(a.error)return a;n=n||i.category?.categoryName||i.category?.ageCategoryCode;let c={eventType:i.eventType,scaleType:Eo,scaleName:n};return Ih({tournamentRecord:t,scaleAttributes:c,drawDefinition:e,entryStatuses:r,drawId:o,event:i,stage:s})}function Fv(t){let e=X(t,[{[rt]:!0},{eventIds:!0,[Ge]:ke}]);if(e.error)return e;let{removePairParticipants:r,tournamentRecord:n,eventIds:o}=t,i=[],s=[],a=[],c=[];if(n.events=(n.events??[]).filter(u=>{if(o.includes(u.eventId)){let d={action:ph,payload:{events:[u]}};i.push(d),s.push({tournamentId:n.tournamentId,eventName:u.eventName,eventType:u.eventType,category:u.category,eventId:u.eventId,gender:u.gender})}let p=u.eventType===Lt?(u.entries??[]).map(({entryStatus:d,participantId:l})=>d!==Gr&&l).filter(Boolean):[],m=o.includes(u.eventId);return m?c.push(...p):a.push(...p),!m}),r){let u=new Set(c.filter(p=>!a.includes(p)));n.participants=n.participants.filter(({participantId:p})=>!u.has(p))}if(ku({tournamentRecord:n}),i.length)if(tu(Yi)){let u=n.tournamentId;at({topic:Yi,payload:{type:ph,tournamentId:u,detail:i}})}else vu({tournamentRecord:n,timeItem:{itemValue:s,itemType:ph}});return{...P}}function kv(t){let e=X(t,[{tournamentRecord:!0,eventId:!0,event:!0},{eventUpdates:!0,_ofType:qr}]);if(e.error)return e;let{eventUpdates:r,event:n}=t,o="modifyEvent",i=a9(t),s=c9({enteredParticipants:i}),{enteredParticipantGenders:a,enteredParticipantTypes:c}=s,u=Bt({event:n})?.flightProfile?.flights,p=!n.drawDefinitions?.length&&!u?.length,m=u9({noFlightsNoDraws:p,enteredParticipantGenders:a,eventUpdates:r,stack:o});if(m.error)return m;let d=p9({enteredParticipantTypes:c,eventUpdates:r,stack:o});if(d.error)return d;let l=n9({...t,...s,enteredParticipants:i,stack:o});if(l.error)return l;let f=s9({...t,stack:o});return f.error?f:(r.eventType&&(n.eventType=r.eventType),r.eventName&&(n.eventName=r.eventName),r.gender&&(n.gender=r.gender),{...P})}function n9(t){let e=t.eventUpdates?.category;if(!e)return{...P};let r=lp({category:e});if(r.error)return r;if(t.event.eventType===Oe){let n=o9(t);if(n.error)return n}if(t.enteredParticipants?.length){let n=i9(t,e);if(n.error)return n}return{...P}}function o9(t){let e=t.event?.drawDefinitions?.map(a=>Yo(a))??[],r=Yo(t.event),o=(vn(t)?.matchUps??[]).map(a=>Yo(a))??[];return[r,...e,...o].filter(Boolean).every(a=>a.collectionDefinitions.every(c=>!c.category||fp({category:t.eventUpdates.category,childCategory:c.category})))?{...P}:M({result:{error:cp},stack:t.stack})}function i9(t,e){let r=t.eventUpdates.startDate||t.event.startDate||t.tournamentRecord.startDate,n=t.eventUpdates.endDate||t.event.endDate||t.tournamentRecord.endDate,o=t.enteredParticipants.flatMap(a=>a.participantType===St?[a]:a.individualParticpants??[]),i=gs({category:e,consideredDate:r}),s=gs({category:e,consideredDate:n});if(i?.ageMinDate||i?.ageMaxDate||s?.ageMinDate||s?.ageMaxDate)for(let a of o){let c=a.person?.birthDate;if(!c)return M({result:{error:nU},stack:t.stack});let u=new Date(c).getTime(),p=iG(u,i,t.stack);if(p)return p;let m=iG(u,s,t.stack);if(m)return m}return{...P}}function iG(t,e,r){if(!e)return null;if(e.ageMinDate||e.ageMaxDate){let n=new Date(e.ageMinDate).getTime(),o=new Date(e.ageMaxDate).getTime();if(t<n||t>o)return M({result:{error:uU},stack:r})}return null}function s9(t){let{tournamentRecord:e,eventUpdates:r,event:n,stack:o}=t;if(r.startDate||r.endDate){let i=dh({startDate:r.startDate||n.startDate||e.startDate,endDate:r.endDate||n.endDate||e.endDate,tournamentRecord:e,event:n});if(i.error)return M({result:i,stack:o})}return{...P}}function a9(t){let{tournamentRecord:e,event:r}=t,n=r?.entries?.filter(({entryStatus:o})=>{let i=o;return[...yr,Zr].includes(i)}).map(({participantId:o})=>o)??[];return n?bt({participantFilters:{participantIds:n},withIndividualParticipants:!0,tournamentRecord:e}).participants??[]:[]}function c9({enteredParticipants:t}){let e=[],r=t.reduce((o,i)=>{let s=i.person?.sex?[i.person.sex]:i.individualParticpants?.map(a=>a.person?.sex)??[];return e.push(...s),o.includes(i.participantType)?o:o.concat(i.participantType)},[]),n=pt(e);return{enteredParticipantTypes:r,enteredParticipantGenders:n}}function u9({noFlightsNoDraws:t,enteredParticipantGenders:e,eventUpdates:r,stack:n}){let o=!e.length||!r.gender||Oo(r.gender)||e.length===1&&e[0]===r.gender||t&&nn(r.gender);return r.gender&&!o?M({context:{gender:r.gender,validGender:o},result:{error:wm},stack:n}):{...P}}function p9({enteredParticipantTypes:t,eventUpdates:e,stack:r}){let i=(t.includes(St)&&t.includes(lt)&&[Ip]||t.includes(Oe)&&[Oe]||t.includes(St)&&[Dt,Ip]||t.includes(lt)&&[Lt,Ip]||[Lt,Dt,Oe,Ip]).includes(e.eventType??"");return e.eventType&&!i?M({context:{participantType:e.eventType,validEventType:i},result:{error:zn},stack:r}):{...P}}function kd({qualifyingPositions:t,drawEntries:e=[],drawName:r,drawId:n,event:o,stage:i}){let s="addFlight";if(!o)return M({result:{error:le},stack:s});if(!r)return M({result:{error:nt},stack:s});if(e?.length){let g=(o.entries??[]).map(gt),I=e.map(gt);if(Yt(I,g).length!==I.length)return M({result:{error:O},stack:s})}let a=Bt({event:o})?.flightProfile,c=a?.flights?.map(({flightNumber:g})=>!Number.isNaN(Number(g))&&st(g))?.filter(Boolean)??[],u=Math.max(0,...c)+1,m={drawId:n||it(),flightNumber:u,drawEntries:e,drawName:r};if(i&&(m.stage=i),t&&(m.qualifyingPositions=t),(a?.flights??[]).find(({drawId:g})=>g===m.drawId))return M({result:{error:kU},stack:s});let l=(a?.flights??[]).concat(m),f={name:on,value:{...a,flights:l}};return Go({event:o,extension:f})}var jv={};Gt(jv,{drawMatic:()=>im,garman:()=>Yv,generateAdHocMatchUps:()=>Mc,generateAdHocRounds:()=>Lf,generateAndPopulatePlayoffStructures:()=>Sf,generateCourts:()=>Sh,generateDrawDefinition:()=>xc,generateDrawMaticRound:()=>bf,generateDrawStructuresAndLinks:()=>Df,generateDrawTypeAndModifyDrawDefinition:()=>Uf,generateFlightProfile:()=>aG,generateLineUps:()=>JP,generateQualifyingStructure:()=>lf,generateSeedingScaleItems:()=>WP,generateStatCrew:()=>mG,generateVoluntaryConsolation:()=>xA,roundRobinGroups:()=>k0});var m9="splitLevelBased",Bv="splitWaterfall",Wv="splitShuttle",sG={SPLIT_LEVEL_BASED:m9,SPLIT_WATERFALL:Bv,SPLIT_SHUTTLE:Wv};function aG(t){let{drawNameRoot:e="Flight",attachFlightProfile:r,tournamentRecord:n,scaleAttributes:o,scaleSortMethod:i,deleteExisting:s,sortDescending:a,drawNames:c=[],flightsCount:u,splitMethod:p,uuids:m=[],random:d,event:l,stage:f}=t;if(!l)return{error:le};let g=l.entries??[],{flightProfile:I}=Bt({event:l});if(I&&r&&!s)return{error:sI};let S=t.scaledEntries??Xa({tournamentRecord:n,scaleAttributes:o,scaleSortMethod:i,sortDescending:a,event:l,stage:f}).scaledEntries,h=new Set(S.map(gt)),T=ar(g.filter(({participantId:b})=>!h.has(b)).filter(b=>(!f||!b.entryStage||b.entryStage===f)&&(!b.entryStatus||$i.includes(b.entryStatus))),d),y=S.concat(...T),E=y.length,A=Math.ceil(E/u),N=he(y,A);p===Bv?N=wg(y,u):p===Wv&&(N=wg(y,u,!0));function D(b){return(b??[]).map(({participantId:C,scaleValue:_})=>{let v=g.find(w=>w.participantId===C);return v?.scaleValue&&_&&(v.scaleValue=_),v}).sort((C,_)=>C.scaleValue-_.scaleValue).map((C,_)=>(C.scaleValue&&(C.seedNumber=_+1),C))}let R=Q(0,u).map(b=>{let C=b+1;return{flightNumber:C,drawId:m?.pop()??it(void 0,d),drawEntries:D(N[b]),drawName:c?.length&&c[b]||`${e} ${C}`}}),U={scaleAttributes:o,splitMethod:p,flights:R};if(r){let b=gh({flightProfile:U,deleteExisting:s,event:l});return{splitEntries:je()&&N||void 0,...b}}else return{flightProfile:U,...P}}function Hv({json:t,tagName:e}){let r=Object.keys(t).filter(i=>Array.isArray(t[i])).map(i=>({key:i,value:t[i].filter(s=>typeof s=="object"&&Object.keys(s).length===1)})),n=Object.keys(t).filter(i=>typeof t[i]=="object"&&!Array.isArray(t[i])).map(i=>({key:i,value:t[i]})),o=Object.keys(t).filter(i=>["string","number"].includes(typeof t[i])).map(i=>({key:i,value:t[i]}));return cG({tagName:e,attributes:o,childArrays:r,childObjects:n})}function cG(t){let{tagName:e,attributes:r=[],childArrays:n=[],childObjects:o}=t,i=`\r
|
|
24
|
+
`}var KM={};Gt(KM,{filterParticipants:()=>Hp,getCompetitionParticipants:()=>eP,getPairedParticipant:()=>Tn,getParticipantEventDetails:()=>rP,getParticipantMembership:()=>nP,getParticipantScaleItem:()=>Zi,getParticipantSchedules:()=>oP,getParticipantSignInStatus:()=>iP,getParticipantTimeItem:()=>tE,getParticipants:()=>bt,getScaleValues:()=>lc,participantScaleItem:()=>Po,validateLineUp:()=>sf});function eP(t){let{tournamentRecords:e}=t??{};if(typeof e!="object"||!Object.keys(e).length)return{error:kt};let r=[],n={},o={},i={},s=[],a={},c=[];for(let u of Object.values(e)){let{participantIdsWithConflicts:p,mappedMatchUps:m,participantMap:d,participants:l,matchUps:f,derivedEventInfo:g,derivedDrawInfo:I}=bt({...t,tournamentRecord:u});Object.assign(a,m),Object.assign(n,d),Object.assign(o,g),Object.assign(i,I),r.push(...l??[]),s.push(...f??[]),p?.forEach(S=>{c.includes(S)||c.push(S)})}return{participantIdsWithConflicts:c,derivedEventInfo:o,derivedDrawInfo:i,participantMap:n,mappedMatchUps:a,participants:r,...P,matchUps:s}}function rP({tournamentRecord:t,participantId:e}){let r=dt({tournamentRecord:t,participantId:e},[rt,sr]);if(r.error)return r;let n=[e].concat((t.participants??[]).filter(i=>i?.participantType&&[_t,lt].includes(i.participantType)&&i.individualParticipantIds?.includes(e)).map(i=>i.participantId));return{eventDetails:(t.events??[]).filter(i=>{let s=(i?.entries??[]).map(a=>a.participantId);return Re(s,n)}).map(i=>({eventName:i.eventName,eventId:i.eventId}))}}function nP({tournamentRecord:t,participantId:e}){let r=dt({tournamentRecord:t,participantId:e},[rt,sr]);if(r.error)return r;let{participants:n}=bt({participantFilters:{participantTypes:[_t,lt,$r]},tournamentRecord:t});return(n??[]).filter(i=>i.individualParticipantIds?.includes(e)).reduce((i,s)=>{let a=s.participantType;return a&&(i[a]||(i[a]=[]),i[a].push(s)),i},{})}function oP({participantFilters:t={},tournamentRecord:e}){if(!e)return{error:j};if(typeof t!="object")return{error:yo,context:{participantFilters:t}};let r={eventIds:t.eventIds},n=qt({tournamentRecord:e,contextFilters:r}).matchUps??[],o=Object.assign({},...n.map(p=>({[p.matchUpId]:p}))),i=n.filter(({schedule:p})=>p&&Object.keys(p).length),s=tn({tournamentRecord:e,matchUps:n}).sourceMatchUpIds??[],a={};for(let p of i){let{sides:m}=p,d,l=m?.map(g=>{if(g.participant)return[g.participant].concat(...g.participant.individualParticipants??[]);s[p.matchUpId]&&!d&&(d=(s[p.matchUpId]??[]).map(I=>o[I]).filter(({winningSide:I,bye:S})=>!I&&!S))}).filter(Boolean).flat()??[];for(let g of l){let{participantId:I}=g;a[I]||(a[I]={potentialMatchUps:[],participant:g,matchUps:[]}),a[I].matchUps.push(p)}let f=d?.map(({sides:g})=>g).flat().map(({participant:g})=>g&&[g].concat(...g.individualParticipants??[])).filter(Boolean).flat()??[];for(let g of f){let{participantId:I}=g;a[I]||(a[I]={potentialMatchUps:[],participant:g,matchUps:[]}),a[I].potentialMatchUps.push(p)}}return{participantSchedules:Object.values(a).filter(({participant:p})=>!(t.participantIds&&!t.participantIds.includes(p.participantId)||t.participantTypes&&!t.participantTypes.includes(p.participantType))),...P}}function iP({tournamentRecord:t,participantId:e}){let r=dt({tournamentRecord:t,participantId:e},[rt,sr]);if(r.error)return r;let{participant:n}=Do({tournamentRecord:t,participantId:e});if(!n)return{error:ee};let{timeItem:o}=Jr({itemType:fu,element:n});return o&&o.itemValue===vp&&vp}var tv={};Gt(tv,{analyzeDraws:()=>Xp,analyzeTournament:()=>IP,cleanExpiredMutationLocks:()=>aP,getAggregateTeamResults:()=>pP,getAllowedDrawTypes:()=>kf,getAllowedMatchUpFormats:()=>sP,getApplicableAwardProfileLevels:()=>vd,getAppliedPolicies:()=>ft,getCompetitionDateRange:()=>Vf,getCompetitionPenalties:()=>cP,getEventRankingPoints:()=>Od,getMutationLocks:()=>SP,getPolicyDefinitions:()=>fo,getRegistrationProfile:()=>uP,getTournamentInfo:()=>ia,getTournamentPenalties:()=>Gf,getTournamentPersons:()=>mP,getTournamentPoints:()=>Ja,getTournamentStructures:()=>jE,getTournamentTimeItem:()=>_l,suggestFormatPlans:()=>gP});function sP({tournamentRecord:t,categoryName:e,categoryType:r}){if(!t)return{error:j};let{appliedPolicies:n}=ft({tournamentRecord:t});return(n?.[Qr]?.matchUpFormats??[]).filter(({categoryNames:s,categoryTypes:a})=>!e&&!a||e&&s?.includes(e)||r&&a?.includes(r))}function kf({tournamentRecord:t,categoryName:e,categoryType:r}){if(!t)return{error:j};let{appliedPolicies:n}=ft({tournamentRecord:t});return(n?.[El]?.allowedDrawTypes??[]).filter(({categoryNames:s,categoryTypes:a})=>!e&&!a||e&&s?.includes(e)||r&&a?.includes(r))}var b8="RANKING_POINTS",C8="QUALITY_WIN",M8="fullToEach",zM="splitEven",v8="teamOnly",QM=["ageCategoryCodes","genders","categoryNames","categoryTypes","ratingTypes","ballTypes","wheelchairClasses","subTypes"],XM=["eventTypes","drawTypes","drawSizes","maxDrawSize","stages","stageSequences","levels","maxLevel","flights","maxFlightNumber","participationOrder","dateRanges"],Tk={RANKING_POINTS:b8,QUALITY_WIN:C8,FULL_TO_EACH:M8,SPLIT_EVEN:zM,TEAM_ONLY:v8,CATEGORY_SCOPE_FIELDS:QM,PROFILE_SCOPE_FIELDS:XM};function Md(t){let{participation:e={},awardProfiles:r,wheelchairClass:n,startDate:o,eventType:i,drawSize:s,drawType:a,category:c,endDate:u,gender:p,level:m}=t,{participationOrder:d,flightNumber:l,rankingStage:f}=e,g=E=>!o&&!u||!E.dateRanges?!0:E.dateRanges.some(A=>{let N=!o||!A.startDate||new Date(o)>new Date(A.startDate),D=!u||!A.endDate||new Date(u)<=new Date(A.endDate);return N&&D}),I=E=>{if(!E)return!0;let A=c??{};return!(E.ageCategoryCodes?.length&&!E.ageCategoryCodes.includes(A.ageCategoryCode)||E.genders?.length&&!E.genders.includes(p)||E.categoryNames?.length&&!E.categoryNames.includes(A.categoryName)||E.categoryTypes?.length&&!E.categoryTypes.includes(A.type)||E.ratingTypes?.length&&!E.ratingTypes.includes(A.ratingType)||E.ballTypes?.length&&!E.ballTypes.includes(A.ballType)||E.wheelchairClasses?.length&&!E.wheelchairClasses.includes(n)||E.subTypes?.length&&!E.subTypes.includes(A.subType))},S=E=>g(E)&&(!E.maxFlightNumber||l<=E.maxFlightNumber)&&(!E.drawTypes?.length||E.drawTypes?.includes(a))&&(!E.drawSizes?.length||E.drawSizes.includes(s))&&(!E.stages?.length||E.stages.includes(f))&&(!E.levels?.length||E.levels.includes(m))&&(!E.maxDrawSize||s<=E.maxDrawSize)&&(!E.drawSize||E.drawSize===s)&&(!E.maxLevel||m<=E.maxLevel)&&(!l||!E.flights?.flightNumbers?.length||E.flights.flightNumbers.includes(l))&&(!E.participationOrder||E.participationOrder===d)&&I(E.category)&&(!E.eventTypes?.length||E.eventTypes?.includes(i)),h=r.filter(S);if(h.length===0)return{awardProfile:void 0};if(h.length===1)return{awardProfile:h[0]};let T=h.filter(E=>E.priority!==void 0);if(T.length){let E=Math.max(...T.map(N=>N.priority));return{awardProfile:T.find(N=>N.priority===E)}}let y=h.map((E,A)=>({profile:E,score:O8(E),index:A}));return y.sort((E,A)=>A.score-E.score||E.index-A.index),{awardProfile:y[0].profile}}function O8(t){let e=0;for(let r of XM){let n=t[r];if(n!=null){if(Array.isArray(n)&&n.length===0)continue;e+=1}}if(t.category)for(let r of QM){let n=t.category[r];Array.isArray(n)&&n.length>0&&(e+=1)}return e}var _8=[{rankingStage:W,participationOrder:1,flightNumber:1},{rankingStage:W,participationOrder:2,flightNumber:1},{rankingStage:Z,participationOrder:1,flightNumber:1},{rankingStage:Z,participationOrder:2,flightNumber:1}];function vd({policyDefinitions:t,tournamentRecord:e,eventId:r,drawId:n}){if(!e)return{error:j};let{policyDefinitions:o}=fo({policyTypes:[gr],tournamentRecord:e}),i=t?.[gr]??o?.[gr];if(!i)return{error:Ea};let s=i.awardProfiles;if(!s?.length)return{levels:[],...P};let a=x8(s);if(!r&&!n)return{levels:a,...P};let c=w8({tournamentRecord:e,eventId:r,drawId:n});return{levels:L8(a,s,c),...P}}function x8(t){let e=new Set;for(let n of t)if(n.levels?.length)for(let o of n.levels)e.add(o);let r=t.filter(n=>n.maxLevel!==void 0).map(n=>n.maxLevel);if(r.length){let n=Math.max(...r);for(let o=1;o<=n;o++)e.add(o)}return[...e].sort((n,o)=>n-o)}function w8({tournamentRecord:t,eventId:e,drawId:r}){let n=_e({tournamentRecord:t,eventId:e,drawId:r}),o=n.event,i=n.drawDefinition;return{eventType:o?.eventType,category:o?.category,gender:o?.gender,drawType:i?.drawType}}function L8(t,e,r){let{eventType:n,drawType:o,category:i,gender:s}=r;return t.filter(a=>_8.some(c=>Md({awardProfiles:e,participation:c,eventType:n,drawType:o,category:i,gender:s,level:a}).awardProfile))}function aP(t){let{tournamentRecord:e}=t;if(!e)return{error:j};let r=new Date().toISOString(),n=0,o=a=>{let{extension:c}=ot({element:a,name:sn});if(!c?.value?.locks?.length)return;let u=c.value,p=u.locks.length;u.locks=u.locks.filter(d=>d.expiresAt===null||d.expiresAt>r);let m=p-u.locks.length;m>0&&(n+=m,ut({element:a,extension:{name:sn,value:u},creationTime:!1}))};o(e);let i=e.events??[];for(let a of i){o(a);let c=a.drawDefinitions??[];for(let u of c)o(u)}let s=e.venues??[];for(let a of s)o(a);return{...P,removedCount:n}}function Gf({tournamentRecord:t}){if(!t)return{error:j};let r=(t?.participants??[]).reduce((n,o)=>{let{participantId:i}=o;return(o.penalties??[]).forEach(s=>{let{penaltyId:a}=s??{};n[a]?n[a].participants.push(i):n[a]={...s,participantIds:[i]}}),n},{});return{penalties:Object.values(r)}}function cP({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:kt};let e=[];for(let r of Object.values(t)){let{penalties:n}=Gf({tournamentRecord:r});e.push(...n??[])}return{penalties:e}}function Vf({tournamentRecords:t}){if(!Tt(t))return{error:kt};let r=Object.keys(t??{}).reduce((i,s)=>{let a=t[s],{tournamentInfo:{startDate:c,endDate:u}}=ia({tournamentRecord:a}),p=c&&mt(c),m=p&&new Date(p);(!i.startDate||m&&m<i.startDate)&&(i.startDate=m);let d=u&&mt(u),l=d&&new Date(d);return(!i.endDate||l&&l>i.endDate)&&(i.endDate=l),i},{startDate:void 0,endDate:void 0}),n=r.startDate&&mt(r.startDate.toISOString()),o=r.endDate&&mt(r.endDate.toISOString());return!n||!o?{error:oU}:{startDate:n,endDate:o}}function uP(t){if(!t?.tournamentRecord)return{error:j};let{tournamentRecord:e}=t;return{registrationProfile:e.registrationProfile?q(e.registrationProfile):void 0}}function pP(t){let e=X(t,[{[rt]:!0}]);if(e.error)return e;let r=t.finishingPositionRangeBounsPoints??{},n={},o=m=>{let d=m?.individualParticipants?.map(l=>l.teams?.length===1&&l.teams[0]);return m?.teams?.length===1&&m?.teams?.[0]||d?.[0].participantId===d?.[1].participantId&&d?.[0]},{matchUps:i,participants:s}=bt({participantFilters:{participantTypes:[St]},withRankingProfile:!0,withStatistics:!0,...t});for(let m of s??[]){if(m.participantType===ur)continue;m.draws?.[0]?.drawId==="draw-0-3"&&console.log(m.participantType,m.draws[0].finishingPositionRange);let d=o(m);if(d)for(let l of m?.draws??[]){let f=l?.finishingPositionRange?.join("-");if(f&&r?.[f]){let g=d?.participantId,I=l?.drawId,S=`${g}|${I}|${f}`;n[S]=r[f]}}}let a=m=>({teamName:m,standingPoints:0,pointsPlayed:0,pointsPct:0,points:0,bonus:0,diff:0,loss:0,win:0}),c=(m,d,l)=>{m[d]===void 0&&(m[d]=0),m[d]+=l},{individualResults:u,teamResults:p}=F8({getTeamParticipant:o,initializeResults:a,increment:c,matchUps:i});return G8({teamBonusPointHashes:n,teamResults:p}),V8(u),{...P,individualResults:u,teamResults:p}}function F8({getTeamParticipant:t,initializeResults:e,increment:r,matchUps:n}){let o={},i={};for(let s of n??[]){let{sides:a,matchUpFormat:c}=s,u=c&&oe(c);if(a?.length===2&&u.setFormat?.timed&&(!u.finalSetFormat||u.finalSetFormat?.timed))for(let p of a)k8({side:p,matchUp:s,getTeamParticipant:t,initializeResults:e,increment:r,individualResults:o,teamResults:i})}return{individualResults:o,teamResults:i}}function k8({side:t,matchUp:e,getTeamParticipant:r,initializeResults:n,increment:o,individualResults:i,teamResults:s}){let a=r(t.participant),c=a?.participantId,u=t.participant?.participantId,p=a?.participantName,m=t.sideNumber,d=t.participant?.individualParticipantIds||((u&&[u])??[]);if(d.forEach(l=>{l&&!i[l]&&(i[l]=n(p))}),c&&m){s[c]||(s[c]=n(p));let l=[...d.map(g=>i[g]),s[c]];e.winningSide&&(m===e.winningSide?l.forEach(g=>o(g,"win",1)):l.forEach(g=>o(g,"loss",1)));let f=e.score?.sets??[];for(let g of f){let I=g?.[`side${3-m}Score`]||0,S=g?.[`side${m}Score`]||0,h=S-I;l.forEach(T=>o(T,"pointsPlayed",S+I)),l.forEach(T=>o(T,"points",S)),l.forEach(T=>o(T,"diff",h))}}}function G8({teamBonusPointHashes:t,teamResults:e}){for(let r of Object.keys(t)){let[n]=r.split("|");e[n]&&(e[n].bonus+=t[r],e[n].pointsPct=parseFloat((e[n].points/e[n].pointsPlayed).toFixed(2)),e[n].standingPoints=e[n].win+e[n].bonus)}}function V8(t){for(let e of Object.keys(t))t[e].pointsPct=parseFloat((t[e].points/t[e].pointsPlayed).toFixed(2))}function mP({tournamentRecord:t,participantFilters:e}){if(!t)return{error:j};let r=t.participants??[];e&&(r=Hp({participants:r,participantFilters:e,tournamentRecord:t}));let n={},o=i=>{if(i.person){let{personId:s}=i.person;n[s]?n[s].participantIds.push(i.participantId):n[s]={...i.person,participantIds:[i.participantId]}}};return r.forEach(i=>{i.person&&o(i)}),{tournamentPersons:Object.values(n)}}function Lu(t,e){return t&&e&&Array.isArray(e)&&e[t-1]||typeof e=="object"&&e[t]}function ih({qualityWinProfiles:t,wonMatchUpIds:e,mappedMatchUps:r,participantSideMap:n,tournamentParticipants:o,tournamentStartDate:i,level:s}){let a=0,c=[],u={};for(let p of o)u[p.participantId]=p;for(let p of t){let{rankingScaleName:m,rankingSnapshot:d="latestAvailable",includeWalkovers:l=!1,rankingRanges:f=[],maxBonusPerTournament:g}=p,I=0;for(let S of e){let h=W8({matchUpId:S,mappedMatchUps:r,participantSideMap:n,participantById:u,includeWalkovers:l,rankingScaleName:m,rankingSnapshot:d,tournamentStartDate:i,rankingRanges:f,level:s});h&&(I+=h.points,c.push(h))}g!==void 0&&I>g&&(I=g),a+=I}return{qualityWinPoints:a,qualityWins:c}}function B8({participant:t,rankingScaleName:e,rankingSnapshot:r,tournamentStartDate:n}){let i=(t.timeItems??[]).filter(u=>{if(!u?.itemType)return!1;let p=u.itemType.split(".");return p[0]===ci&&p[1]===Jn&&p[3]===e});if(!i.length)return;let s=i;if(r==="tournamentStart"&&n){let u=new Date(n).getTime();s=i.filter(p=>(p.itemDate?new Date(p.itemDate).getTime():0)<=u)}if(!s.length)return;s.sort((u,p)=>(u.createdAt?new Date(u.createdAt).getTime():0)-(p.createdAt?new Date(p.createdAt).getTime():0));let c=s.at(-1)?.itemValue;return typeof c=="number"?c:void 0}function W8({matchUpId:t,mappedMatchUps:e,participantSideMap:r,participantById:n,includeWalkovers:o,rankingScaleName:i,rankingSnapshot:s,tournamentStartDate:a,rankingRanges:c,level:u}){let p=e[t];if(!p)return;let{matchUpStatus:m,sides:d=[],winningSide:l}=p;if(!o&&(m===vt||m===Mt))return;let f=r[t];if(!f||l!==f)return;let I=d.find(E=>E.sideNumber!==f)?.participantId;if(!I)return;let S=n[I];if(!S)return;let h=B8({participant:S,rankingScaleName:i,rankingSnapshot:s,tournamentStartDate:a});if(!h)return;let T=c.find(E=>h>=E.rankRange[0]&&h<=E.rankRange[1]);if(!T)return;let y;if(typeof T.value=="number")y=T.value;else if(typeof T.value=="object"){let E=Lu(u,T.value.level??T.value);typeof E=="number"&&(y=E)}if(y)return{opponentParticipantId:I,opponentRank:h,points:y,matchUpId:t}}function Bf({participantWon:t,flightNumber:e,valueObj:r,drawSize:n,flights:o,level:i}){let s=(f,g)=>{if(f){if(Array.isArray(g)){let I=g.find(S=>S.flight===f||S.f===f);return I.value||I.v}if(typeof g=="object"){let I=g.flights||g.f;if(Array.isArray(I))return I[f-1]}}},a=(f,g)=>{let I=f?.value||f?.v||(yt(f)?f:0),S=Lu(i,f?.level);return{value:s(g,S)||yt(S)&&S||I}},c=0,u,p,m,d,l=t&&"won"||t===!1&&"lost"||void 0;if(Array.isArray(r)){let f=r.find(S=>S.drawSize===n||S.drawSizes?.includes(n)),g=r.find(S=>S.drawSize&&S.threshold&&n>S.drawSize),I=r.find(S=>!S.drawSize&&!S.drawSizes?.length);l!==void 0&&(f=f?.[l],g=g?.[l],I=I?.[l]),p=a(f,e).value,m=a(g,e).value,d=a(I,e).value,c=p||m||d,u=p&&f.requireWin||m&&g.requireWin||I?.requireWin}else if(typeof r=="object"){let f=r?.drawSizes?.[n],g=r;l!==void 0&&(f=f?.[l],g=g?.[l]),p=a(f,e).value,d=a(g,e).value,c=p||d,u=p?f.requireWin:g?.requireWin}else yt(r)&&l===void 0&&(c=r);return e&&o?.pct?.[e]&&(c=Math.round(c*o.pct[e])),{awardPoints:c,requireWin:u}}function H8(t,e,r){let n=0;if(t?.bonusPoints&&e!==void 0){for(let o of t.bonusPoints)if(o.finishingPositions?.includes(e)){let i=o.value;if(typeof i=="number")n=i;else if(typeof i=="object"){let s=Lu(r,i.level??i);typeof s=="number"&&(n=s)}break}}return n}function Y8(t,e){if(typeof t=="object"&&t.line)return t.limit&&e>t.limit?void 0:t.line[e-1];if(typeof t=="number")return t}function j8({tieMatchUp:t,lineValue:e,participantIndividualIdsMap:r,participantPersonMap:n,personPoints:o,eventType:i,drawId:s}){let{collectionPosition:a}=t;for(let c of t.sides??[]){if(c.sideNumber!==t.winningSide)continue;let u=c.participantId;if(!u)continue;let m=r[u]||[u];for(let d of m){let l=n[d];l&&(o[l]||(o[l]=[]),o[l].push({linePoints:e,collectionPosition:a,eventType:i,drawId:s}))}}}function q8({participantType:t,participantId:e,awardProfile:r,participant:n,participation:o,mappedMatchUps:i,levelValue:s,participantIndividualIdsMap:a,participantPersonMap:c,personPoints:u,eventType:p,drawId:m}){if(t!==ur||!r||!s)return;let d=(n.matchUps??[]).filter(({structureId:l})=>l===o.structureId);for(let{matchUpId:l}of d){let f=i[l],g=f?.sides?.find(I=>I.participantId===e)?.sideNumber;if(!(!g||f.winningSide!==g))for(let I of f.tieMatchUps??[]){if(!I.winningSide)continue;let S=Y8(s,I.collectionPosition);S&&j8({tieMatchUp:I,lineValue:S,participantIndividualIdsMap:a,participantPersonMap:c,personPoints:u,eventType:p,drawId:m})}}}function $8({qualityWinProfiles:t,participant:e,drawId:r,mappedMatchUps:n,participantId:o,person:i,tournamentRecord:s,level:a,personPoints:c,eventType:u}){if(!t?.length||!e.matchUps)return;let p=Object.values(e.matchUps).filter(g=>g.drawId===r&&g.participantWon);if(!p.length)return;let m=p.map(g=>g.matchUpId),d={};for(let g of p)d[g.matchUpId]=g.sideNumber;let{qualityWinPoints:l,qualityWins:f}=ih({qualityWinProfiles:t,wonMatchUpIds:m,mappedMatchUps:n,participantId:o,participantSideMap:d,tournamentParticipants:s.participants??[],tournamentStartDate:s.startDate,level:a});if(l>0){let g=i?.personId;g&&(c[g]||(c[g]=[]),c[g].push({qualityWinPoints:l,qualityWins:f,eventType:u,drawId:r}))}}function K8(t,e,r){if(r!==void 0||t.maxCountableMatches===void 0)return r;let n=t.maxCountableMatches;if(typeof n=="number")return n;if(typeof n=="object"){let o=Lu(e,n.level??n);if(typeof o=="number")return o}return r}function z8({awardProfile:t,participation:e,level:r,drawSize:n}){let{finishingPositionRange:o,participationOrder:i,participantWon:s,flightNumber:a,rankingStage:c}=e,u=Array.isArray(o)&&Math.max(...o);c===Z&&u&&e.finishingRound&&(u=s?1:Math.pow(2,e.finishingRound));let{finishingPositionPoints:p={},finishingPositionRanges:m,finishingRound:d,flights:l}=t,f=p.participationOrders,g=!f||f.includes(i),I=0,S;if(g&&m&&u){let h=m[u];h&&({awardPoints:I,requireWin:S}=Bf({flightNumber:a,valueObj:h,drawSize:n,flights:l,level:r}))}if(!I&&d&&i===1&&u){let h=d[u];h&&({awardPoints:I,requireWin:S}=Bf({participantWon:s,flightNumber:a,valueObj:h,drawSize:n,flights:l,level:r}))}return{awardPoints:I,winRequired:S,accessor:u}}function Q8({awardProfile:t,participation:e,level:r,maxCountable:n,countedWins:o}){let{participationOrder:i,winCount:s}=e,{pointsPerWin:a}=t,c=n!==void 0&&n>0?Math.min(s||0,Math.max(0,n-o)):s,u=pt(e.finishingPositionRange??[]).join("-"),p=0,m=0,d;a&&c&&(p+=c*a,m+=c,d=u);let l=Array.isArray(t.perWinPoints)?t.perWinPoints?.find(f=>f.participationOrders?.includes(i)):t.perWinPoints;if(s&&l){let f=Lu(r,l?.level);typeof f=="number"?(p+=(c||0)*f,m+=c||0):!f&&l.value&&(p+=(c||0)*l.value,m+=c||0)}return{perWin:p,counted:m,rangeAccessor:d}}function X8({award:t,participantType:e,participantId:r,person:n,personPoints:o,pairPoints:i,teamPoints:s,doublesAttribution:a,participantIndividualIdsMap:c,participantPersonMap:u}){let p=n?.personId;if(p)o[p]||(o[p]=[]),o[p].push(t);else if(e===lt){if(i[r]||(i[r]=[]),i[r].push(t),a){let m=a===zM?.5:1,d=c[r]??[];for(let l of d){let f=u[l];if(!f)continue;let g={...t,points:Math.round(t.points*m),positionPoints:Math.round(t.positionPoints*m),perWinPoints:Math.round(t.perWinPoints*m),bonusPoints:Math.round(t.bonusPoints*m),doublesParticipantId:r};o[f]||(o[f]=[]),o[f].push(g)}}}else e===ur&&(s[r]||(s[r]=[]),s[r].push(t))}function J8({participation:t,awardProfiles:e,wheelchairClass:r,eventType:n,startDate:o,category:i,drawInfo:s,drawType:a,endDate:c,gender:u,level:p,accum:m}){let{finishingPositionRange:d,rankingStage:l,winCount:f}=t;if(m.totalWinsCount+=f||0,Array.isArray(d)&&d.length){let S=Math.min(...d);(m.bestFinishingPosition===void 0||S<m.bestFinishingPosition)&&(m.bestFinishingPosition=S)}let g=s?.drawSize,{awardProfile:I}=Md({wheelchairClass:r,awardProfiles:e,participation:t,eventType:n,startDate:o,category:i,drawSize:g,drawType:a,endDate:c,gender:u,level:p});if(I){if(!g)return{awardProfile:I,skip:!0};I.profileName&&(m.profileName=I.profileName),m.primaryAwardProfile??=I,m.maxCountable=K8(I,p,m.maxCountable);let{awardPoints:S,winRequired:h,accessor:T}=z8({awardProfile:I,participation:t,drawSize:g,level:p}),y=T&&l!==Z&&d?.includes(g);if(I.requireWinForPoints!==void 0&&(m.requireWin=I.requireWinForPoints),I.requireWinFirstRound!==void 0&&(m.requireWinFirstRound=I.requireWinFirstRound),y&&m.requireWinFirstRound!==void 0&&(m.requireWin=m.requireWinFirstRound),h!==void 0&&(m.requireWin=h),S>m.positionPoints&&(!m.requireWin||f)&&(m.positionPoints=S,m.rangeAccessor=T,m.primaryAwardProfile=I),!S){let E=Q8({awardProfile:I,participation:t,maxCountable:m.maxCountable,countedWins:m.countedWins,level:p});m.perWinPoints+=E.perWin,m.countedWins+=E.counted,E.rangeAccessor&&(m.rangeAccessor=E.rangeAccessor)}}return{awardProfile:I,skip:!1}}function Z8({participant:t,draw:e,eventInfo:r,drawInfo:n,mappedMatchUps:o,awardProfiles:i,requireWinForPoints:s,requireWinFirstRound:a,doublesAttribution:c,qualityWinProfiles:u,personPoints:p,pairPoints:m,teamPoints:d,participantPersonMap:l,participantIndividualIdsMap:f,level:g,devContext:I,tournamentRecord:S}){let{participantType:h,participantId:T,person:y}=t,{drawId:E,structureParticipation:A}=e,N=n?.drawType,{category:D,eventType:R,gender:U,wheelchairClass:b}=r??{},C=e.startDate||r.startDate||S.startDate,_=e.endDate||r.endDate||S.endDate;if(R===Ze&&h!==ur)return;let v;if(i&&A){let w=t7({initialRequireWinFirstRound:a,requireWinForPoints:s});e7({structureParticipation:A,awardProfiles:i,wheelchairClass:b,participantType:h,participantId:T,participant:t,eventType:R,startDate:C,category:D,drawInfo:n,drawType:N,endDate:_,gender:U,level:g,accum:w,mappedMatchUps:o,participantIndividualIdsMap:f,participantPersonMap:l,personPoints:p,drawId:E});let L=H8(w.primaryAwardProfile,w.bestFinishingPosition,g);v=w.positionPoints+w.perWinPoints+L,(w.perWinPoints||w.positionPoints||L)&&r7({accum:w,bonusPoints:L,points:v,eventType:R,drawId:E,category:D,drawType:N,startDate:C,endDate:_,level:g,devContext:I,participantType:h,participantId:T,person:y,personPoints:p,pairPoints:m,teamPoints:d,doublesAttribution:c,participantIndividualIdsMap:f,participantPersonMap:l}),$8({qualityWinProfiles:u,participant:t,drawId:E,mappedMatchUps:o,participantId:T,person:y,tournamentRecord:S,level:g,personPoints:p,eventType:R})}}function t7({initialRequireWinFirstRound:t,requireWinForPoints:e}){return{requireWinFirstRound:t,requireWin:e,bestFinishingPosition:void 0,primaryAwardProfile:void 0,maxCountable:void 0,rangeAccessor:void 0,profileName:void 0,totalWinsCount:0,positionPoints:0,perWinPoints:0,countedWins:0}}function e7({structureParticipation:t,awardProfiles:e,wheelchairClass:r,participantType:n,participantId:o,participant:i,eventType:s,startDate:a,category:c,drawInfo:u,drawType:p,endDate:m,gender:d,level:l,accum:f,mappedMatchUps:g,participantIndividualIdsMap:I,participantPersonMap:S,personPoints:h,drawId:T}){for(let y of t){let{awardProfile:E,skip:A}=J8({participation:y,awardProfiles:e,wheelchairClass:r,eventType:s,startDate:a,category:c,drawInfo:u,drawType:p,endDate:m,gender:d,level:l,accum:f});if(!A&&n===ur&&E){let N=Array.isArray(E.perWinPoints)?E.perWinPoints?.find(R=>R.participationOrders?.includes(y.participationOrder)):E.perWinPoints,D=N&&Lu(l,N.level);q8({participantType:n,participantId:o,awardProfile:E,participant:i,participation:y,mappedMatchUps:g,levelValue:D,participantIndividualIdsMap:I,participantPersonMap:S,personPoints:h,eventType:s,drawId:T})}}}function r7({accum:t,bonusPoints:e,points:r,eventType:n,drawId:o,category:i,drawType:s,startDate:a,endDate:c,level:u,devContext:p,participantType:m,participantId:d,person:l,personPoints:f,pairPoints:g,teamPoints:I,doublesAttribution:S,participantIndividualIdsMap:h,participantPersonMap:T}){let y={winCount:t.totalWinsCount,positionPoints:t.positionPoints,rangeAccessor:t.rangeAccessor,perWinPoints:t.perWinPoints,bonusPoints:e,eventType:n,drawId:o,points:r,category:i,drawType:s,startDate:a,endDate:c,level:u};p&&t.profileName&&(y.profileName=t.profileName),X8({award:y,participantType:m,participantId:d,person:l,personPoints:f,pairPoints:g,teamPoints:I,doublesAttribution:S,participantIndividualIdsMap:h,participantPersonMap:T})}function Ja({participantFilters:t,policyDefinitions:e,tournamentRecord:r,level:n}){if(!r)return{error:j};let o=je(),{policyDefinitions:i}=fo({policyTypes:[gr],tournamentRecord:r}),s=e?.[gr]??i?.[gr];if(!s)return{error:Ea};let a=s.awardProfiles,c=s.requireWinFirstRound,u=s.requireWinForPoints,p=s.doublesAttribution,m=s.qualityWinProfiles,{participants:d,derivedEventInfo:l,derivedDrawInfo:f,mappedMatchUps:g}=bt({withRankingProfile:!0,participantFilters:t,tournamentRecord:r}),I=d?.filter(A=>A.draws?.length),S={},h={};for(let A of r.participants??[])A.person?.personId&&(S[A.participantId]=A.person.personId),A.individualParticipantIds?.length&&(h[A.participantId]=A.individualParticipantIds);let T={},y={},E={};for(let A of I??[])for(let N of A.draws){let D=l[N.eventId],R=f[N.drawId];Z8({participant:A,draw:N,eventInfo:D,drawInfo:R,mappedMatchUps:g,awardProfiles:a,requireWinForPoints:u,requireWinFirstRound:c,doublesAttribution:p,qualityWinProfiles:m,personPoints:T,pairPoints:E,teamPoints:y,participantPersonMap:S,participantIndividualIdsMap:h,level:n,devContext:o,tournamentRecord:r})}return{participantsWithOutcomes:I,personPoints:T,pairPoints:E,teamPoints:y,...P}}function Od({policyDefinitions:t,tournamentRecord:e,eventId:r,level:n}){if(!e)return{error:j};if(!r)return{error:le};let o=e.events?.find(I=>I.eventId===r);if(!o)return{error:le};if(!t?.[gr])return{error:Ea};let i=n??o7(o.eventTier??e.tournamentTier,t?.[gr]),s=Ja({participantFilters:{eventIds:[r]},level:i,policyDefinitions:t,tournamentRecord:e});if(s.error)return s;let{personPoints:a={},pairPoints:c={},teamPoints:u={}}=s,{participants:p}=bt({tournamentRecord:e}),m={},d={};for(let I of p??[])d[I.participantId]={participantName:I.participantName??"",personId:I.person?.personId},I.person?.personId&&(m[I.person.personId]={participantId:I.participantId,participantName:I.participantName??""});let l=new Set((o.drawDefinitions??[]).map(I=>I.drawId)),f=[];n7({personPoints:a,personToParticipant:m,eventDrawIds:l,eventAwards:f}),yk({points:c,participantLookup:d,eventDrawIds:l,eventAwards:f}),yk({points:u,participantLookup:d,eventDrawIds:l,eventAwards:f}),f.sort((I,S)=>(S.points||0)-(I.points||0)||(I.participantName??"").localeCompare(S.participantName??""));let g=o.eventType===Lt;return{eventAwards:f,eventName:o.eventName,eventType:o.eventType,isDoubles:g,...P}}function n7({personPoints:t,personToParticipant:e,eventDrawIds:r,eventAwards:n}){for(let[o,i]of Object.entries(t)){let s=e[o];if(s)for(let a of i)r.has(a.drawId)&&n.push({...a,participantId:s.participantId,participantName:s.participantName,personId:o})}}function o7(t,e){if(!(!t?.system||!t?.value||!e?.tierToLevel))return e.tierToLevel[t.system]?.[t.value]}function yk({points:t,participantLookup:e,eventDrawIds:r,eventAwards:n}){for(let[o,i]of Object.entries(t)){let s=e[o];if(s)for(let a of i)r.has(a.drawId)&&n.push({...a,participantId:o,participantName:s.participantName})}}var i7=.5,s7=.5,a7={histogram:[],count:0,stddev:0,median:0,mean:0,iqr:0,min:0,max:0,gaps:[]};function JM(t,e){if(t.length===0)return 0;if(t.length===1)return t[0];let r=(t.length-1)*e,n=Math.floor(r),o=Math.ceil(r);if(n===o)return t[n];let i=r-n;return t[n]+(t[o]-t[n])*i}function c7(t,e,r,n){if(t.length===0||n<=0)return[];let o=Math.floor(e/n)*n,i=Math.ceil(r/n)*n,s=[];for(let a=o;(a<i||a===o)&&(s.push({binStart:a,binEnd:a+n,count:0}),!(a>=i));a+=n);for(let a of t){let c=Math.min(s.length-1,Math.floor((a-o)/n));s[c].count++}return s}function u7(t,e){let r=[];for(let n=1;n<t.length;n++){let o=t[n]-t[n-1];o>=e&&r.push({start:t[n-1],end:t[n],size:o})}return r.sort((n,o)=>o.size-n.size)}function dP({binWidth:t=i7,gapThreshold:e=s7,ratings:r}){if(!Array.isArray(r)||r.length===0)return a7;let n=[...r].sort((f,g)=>f-g),o=n.length,i=n[0],s=n[o-1],a=n.reduce((f,g)=>f+g,0)/o,c=JM(n,.5),u=n.reduce((f,g)=>f+(g-a)**2,0)/o,p=Math.sqrt(u),m=JM(n,.25),l=JM(n,.75)-m;return{histogram:c7(n,i,s,t),gaps:u7(n,e),count:o,stddev:p,median:c,mean:a,iqr:l,min:i,max:s}}var p7=[2,3,4,6],m7=[.5,1],Ek=4,lP=4;function d7(t){return t<=8?1:t<=16?2:t<=32?4:t<=64?6:8}function l7(t){return[...t].sort((e,r)=>r.rating-e.rating)}function fP(t,e){return{participantIds:e.map(r=>r.participantId),ratings:e.map(r=>r.rating),label:t}}function Ak(t,e,r){return`${t} ${e+1} of ${r}`}function f7(t,e){if(e<=0)return[];let r=[],n=Math.floor(t.length/e),o=t.length%e,i=0;for(let s=0;s<e;s++){let a=n+(s<o?1:0);r.push(t.slice(i,i+a)),i+=a}return r}function g7(t,e){if(e>t.length)return;let r=f7(t,e);if(r.some(o=>o.length<lP))return;let n=r.map((o,i)=>fP(Ak("Tier",i,e),o));return{type:"EQUAL_COUNT",variant:`k=${e}`,flights:n}}function I7(t,e){if(t.length===0||e<=0)return;let r=t[0].rating,n=t.at(-1)?.rating??0,o=new Map;for(let a of t){let c=Math.floor((r-a.rating)/e);o.has(c)||o.set(c,[]),o.get(c).push(a)}let i=[...o.keys()].sort((a,c)=>a-c),s=[];for(let a of i){let c=o.get(a);if(c.length<lP)continue;let u=r-a*e,m=`${Math.max(n,u-e).toFixed(2)} \u2013 ${u.toFixed(2)}`;s.push(fP(m,c))}if(!(s.length<2))return{type:"EQUAL_BAND",variant:`width=${e}`,flights:s}}function S7(t){if(t.length<lP*2)return;let e=t.map(u=>u.rating),n=dP({ratings:e}).gaps.map(u=>u.start),o=new Set;for(let u of n)o.add(u);let i=[],s=[];for(let u of t)o.has(u.rating)&&s.length>=Ek&&(i.push(s),s=[]),s.push(u);s.length>0&&i.push(s);let a=h7(i);return a.length<2?void 0:{type:"NATURAL_CLUSTER",flights:a.map((u,p)=>fP(Ak("Cluster",p,a.length),u))}}function h7(t){let e=[];for(let r of t)if(r.length>=Ek||e.length===0)e.push(r);else{let n=e.at(-1);n&&n.push(...r)}return e}function T7(t){return{type:"STAGGERED_SINGLE",flights:[fP("All Levels",t)]}}function Pk(t){if(!Array.isArray(t)||t.length<lP)return[];let e=l7(t),r=d7(t.length),n=[];for(let i of p7){if(i>r)continue;let s=g7(e,i);s&&n.push(s)}for(let i of m7){let s=I7(e,i);s&&s.flights.length<=r&&n.push(s)}let o=S7(e);return o&&o.flights.length<=r&&n.push(o),n.push(T7(e)),n}var sh=2,y7=[4,6,8],E7=[3,5,7],A7=[3,5],P7=.5,N7={NONE:["SINGLE_ELIMINATION","ROUND_ROBIN","SWISS","DRAW_MATIC","LUCKY_DRAW","FEED_IN"],LIGHT:["SINGLE_ELIMINATION","ROUND_ROBIN","SWISS","DRAW_MATIC","LUCKY_DRAW","FEED_IN","FIRST_MATCH_LOSER_CONSOLATION","ROUND_ROBIN_WITH_PLAYOFF","DOUBLE_ELIMINATION"],FULL:["SINGLE_ELIMINATION","ROUND_ROBIN","SWISS","DRAW_MATIC","LUCKY_DRAW","FEED_IN","FIRST_MATCH_LOSER_CONSOLATION","ROUND_ROBIN_WITH_PLAYOFF","DOUBLE_ELIMINATION","FIRST_ROUND_LOSER_CONSOLATION","COMPASS","ADAPTIVE"]},D7={ROUND_ROBIN:0,ROUND_ROBIN_WITH_PLAYOFF:0,SWISS:0,SINGLE_ELIMINATION:0,FEED_IN:.05,DOUBLE_ELIMINATION:.1,DRAW_MATIC:.1,LUCKY_DRAW:.1,FIRST_MATCH_LOSER_CONSOLATION:.2,FIRST_ROUND_LOSER_CONSOLATION:.25,COMPASS:.3,ADAPTIVE:.3};function ZM(t){return t<=1?1:2**Math.ceil(Math.log2(t))}function U7(t){return t>0&&(t&t-1)===0}function To(t,e,r,n={}){return{withdrawalRiskFactor:D7[t],minMatchesPerPlayer:e,totalMatches:r,kind:t,...n}}function R7(t){if(t<sh)return[];let e=ZM(t),r=t-1,n=Math.max(1,Math.ceil(Math.log2(e)));return[To("SINGLE_ELIMINATION",1,r),To("FIRST_MATCH_LOSER_CONSOLATION",2,Math.round(r*1.5),{variantId:"FMLC"}),To("FIRST_ROUND_LOSER_CONSOLATION",n,Math.round(r*1.7),{variantId:"FRLC",rounds:n}),To("DOUBLE_ELIMINATION",2,r*2-1)]}function b7(t){return t>=7&&t<=8?[To("COMPASS",3,12,{variantId:"COMPASS_8"})]:t>=13&&t<=16?[To("COMPASS",4,28,{variantId:"COMPASS_16"})]:[]}function C7(t){if(t<sh||t>8)return[];let e=t*(t-1)/2;return[To("ROUND_ROBIN",t-1,e,{groupSize:t})]}function M7(t,e){if(t<e*2||t%e!==0)return[];let r=t/e,o=e*(e-1)/2*r,i=ZM(r),s=i-1;return[To("ROUND_ROBIN",e-1,o,{variantId:`RR_${e}x${r}`,groupSize:e}),To("ROUND_ROBIN_WITH_PLAYOFF",e-1+Math.max(0,Math.ceil(Math.log2(i))),o+s,{variantId:`RR_${e}x${r}_PLAYOFF`,groupSize:e})]}function v7(t){let e=y7.flatMap(r=>M7(t,r));return[...C7(t),...e]}function O7(t){if(t<sh)return[];let e=Math.max(3,Math.ceil(Math.log2(t)));return E7.filter(r=>r<=t-1).map(r=>{let n=Math.floor(t*r/2);return To("SWISS",r,n,{variantId:`SWISS_R${r}${r===e?"_REC":""}`,rounds:r})})}function _7(t){return t<sh?[]:A7.filter(e=>e<=t-1).map(e=>To("DRAW_MATIC",e,Math.floor(t*e/2),{variantId:`DRAW_MATIC_R${e}`,rounds:e}))}function x7(t){if(t<sh)return[];if(U7(t))return[];let e=t-1;return[To("LUCKY_DRAW",1,e)]}function w7(t){if(t<4)return[];let e=Math.max(2,Math.ceil(Math.log2(t))),r=Math.round(t*1.6);return[To("ADAPTIVE",e,r)]}function L7(t){if(t<8)return[];let e=Math.max(2,Math.ceil(Math.log2(t))),r=t-1,n=[To("FEED_IN",1,r,{rounds:e,variantId:`FEED_IN_${e}_TIERS`})];return t>=8&&n.push(To("FEED_IN",2,Math.round(r*1.4),{rounds:e,variantId:"FIC_SF"})),t>=12&&n.push(To("FEED_IN",2,Math.round(r*1.6),{rounds:e,variantId:"FIC_QF"})),t>=16&&(n.push(To("FEED_IN",3,Math.round(r*1.8),{rounds:e,variantId:"FIC_R16"})),n.push(To("FEED_IN",3,Math.round(r*2),{rounds:e,variantId:"FIC"})),n.push(To("FEED_IN",2,Math.round(r*1.7),{rounds:e,variantId:"MFIC"}))),n}function F7(t,e){if(t.length===0||e<4)return[];let r=Math.max(2,Math.floor(e*P7)),n=ZM(r),o=Math.max(0,n-1);return t.map(i=>({...i,voluntaryConsolation:!0,totalMatches:i.totalMatches+o,variantId:i.variantId?`${i.variantId}_VC`:"VC"}))}function k7(t,e){let r=[...R7(t),...b7(t),...v7(t),...O7(t),..._7(t),...x7(t),...w7(t)];return e&&r.push(...L7(t)),r}function Nk({consolationAppetite:t="LIGHT",voluntaryConsolation:e=!1,allowedDrawTypes:r,singleFlight:n=!0,flightSize:o}){let i=new Set(N7[t]),s=r&&r.length>0?new Set(r):void 0,a=k7(o,n).filter(c=>!(!i.has(c.kind)||s&&!s.has(c.kind)));return e?[...a,...F7(a,o)]:a}var G7=90,V7=8,B7=.2,W7={SINGLE_ELIMINATION:Nr,FIRST_MATCH_LOSER_CONSOLATION:wo,FIRST_ROUND_LOSER_CONSOLATION:Ma,DOUBLE_ELIMINATION:Gs,COMPASS:xo,LUCKY_DRAW:ai,ADAPTIVE:ki,ROUND_ROBIN:hr,ROUND_ROBIN_WITH_PLAYOFF:Tr,SWISS:Bs},ah={competitive:60,floor:20,utilization:15,withdrawal:5};function H7({predictionModel:t,structure:e,flight:r}){let{kind:n}=e,o=r.ratings;if(n==="DRAW_MATIC")return Zp({ratings:o,projectionMode:"MIN_DELTA",predictionModel:t});if(n==="FEED_IN")return Zp({ratings:o,projectionMode:"BALANCED_BRACKET",predictionModel:t});let i=W7[n];return i?Zp({ratings:o,drawType:i,groupSize:e.groupSize,predictionModel:t}):Tf(0,t??{competitiveAnchors:[],decisiveAnchors:[]})}function Y7(t){let e=t.reduce((r,n)=>{let o=n.structure.totalMatches;return r.competitive+=n.predictedBands.competitive*o,r.decisive+=n.predictedBands.decisive*o,r.routine+=n.predictedBands.routine*o,r.totalMatches+=o,r},{competitive:0,decisive:0,routine:0,totalMatches:0});return e.totalMatches===0?{competitive:0,decisive:0,routine:0,totalMatches:0}:{competitive:e.competitive/e.totalMatches,decisive:e.decisive/e.totalMatches,routine:e.routine/e.totalMatches,totalMatches:e.totalMatches}}function j7(t){if(t.length===0)return{minMatchesPerPlayer:0};let e=1/0;for(let r of t)r.structure.minMatchesPerPlayer<e&&(e=r.structure.minMatchesPerPlayer);return{minMatchesPerPlayer:e}}function q7(t,e){let r=e.avgMinutes??G7,n=e.hoursPerDay??V7,o=t*r/60,i=e.courts*e.days*n,s=i>0?o/i:1/0;return{courtHoursRequired:o,courtHoursAvailable:i,courtUtilization:s}}function $7({minMatchesPerPlayer:t,flightStructures:e,courtUtilization:r,constraints:n}){let o=[];return typeof n.targetMatchesPerPlayer=="number"&&t<n.targetMatchesPerPlayer&&o.push("BELOW_FLOOR"),r>1&&o.push("OVER_CAPACITY"),e.some(i=>i.structure.withdrawalRiskFactor>=B7)&&o.push("WITHDRAWAL_RISK"),o}function K7(t,e){if(typeof t!="number")return e;let r=Math.abs(e-t);return Math.max(0,1-r)}function z7(t,e){return typeof e!="number"||t>=e?1:Math.max(0,t/e)}function Q7(t){return Number.isFinite(t)?t>1?Math.max(0,2-t):t:0}function X7(t){return t.length===0?1:1-Math.max(...t.map(r=>r.structure.withdrawalRiskFactor))}function J7({minMatchesPerPlayer:t,flightStructures:e,courtUtilization:r,constraints:n,competitive:o}){let i=K7(n.targetCompetitivePct,o),s=z7(t,n.targetMatchesPerPlayer),a=Q7(r),c=X7(e),u=i*ah.competitive+s*ah.floor+a*ah.utilization+c*ah.withdrawal,p=Object.values(ah).reduce((m,d)=>m+d,0);return u/p}function Dk({recommendationsByFlightSize:t,predictionModel:e,constraints:r,strategy:n}){if(n.flights.length===0)return[];let o=n.flights.length===1,i=new Set(n.flights.map(u=>u.participantIds.length)),s=new Map;for(let u of i)s.set(u,t(u,o));let a=Z7(n.flights,s),c=[];for(let u of a){let p=n.flights.map(d=>{let l=s.get(d.participantIds.length).find(f=>Uk(f,u));return{predictedBands:H7({flight:d,structure:l,predictionModel:e}),structure:l,flight:d}}),m=tQ({strategy:n,flightStructures:p,constraints:r});c.push(m)}return c}function Uk(t,e){return t.kind===e.kind&&(t.variantId??"")===(e.variantId??"")&&(t.groupSize??0)===(e.groupSize??0)}function Z7(t,e){if(t.length===0)return[];let r=t[0].participantIds.length;return(e.get(r)??[]).filter(o=>t.every(i=>(e.get(i.participantIds.length)??[]).some(a=>Uk(a,o))))}function tQ({flightStructures:t,constraints:e,strategy:r}){let n=Y7(t),o=j7(t),i=q7(n.totalMatches,e),s={minMatchesPerPlayer:o.minMatchesPerPlayer,courtHoursRequired:i.courtHoursRequired,courtHoursAvailable:i.courtHoursAvailable,courtUtilization:i.courtUtilization,totalMatches:n.totalMatches,competitive:n.competitive,decisive:n.decisive,routine:n.routine},a=$7({minMatchesPerPlayer:o.minMatchesPerPlayer,courtUtilization:i.courtUtilization,flightStructures:t,constraints:e}),c=J7({minMatchesPerPlayer:o.minMatchesPerPlayer,courtUtilization:i.courtUtilization,competitive:n.competitive,flightStructures:t,constraints:e});return{strategy:r.type,variant:r.variant,flightStructures:t,aggregate:s,warnings:a,score:c}}var eQ=Hs[gn].predictionModel,Rk={histogram:[],count:0,stddev:0,median:0,mean:0,iqr:0,min:0,max:0,gaps:[]};function rQ(t,e){if(t)return t;if(e){let{policy:r}=go({policyType:gn,tournamentRecord:e});if(r?.predictionModel)return r.predictionModel}return eQ}function nQ(t){return[...t].sort((r,n)=>n.score-r.score).map((r,n)=>({...r,rank:n+1}))}function gP({predictionModel:t,tournamentRecord:e,participants:r,governance:n,constraints:o}){if(!Array.isArray(r)||r.length<2)return{plans:[],distribution:Rk,error:O};if(!o||typeof o.courts!="number"||typeof o.days!="number")return{plans:[],distribution:Rk,error:O};let i=r.map(d=>d.rating),s=dP({ratings:i}),a=Pk(r),c=rQ(t,e),u=(d,l)=>Nk({consolationAppetite:o.consolationAppetite,voluntaryConsolation:o.voluntaryConsolation,allowedDrawTypes:n?.allowedDrawTypes,singleFlight:l,flightSize:d}),p=[],m=[];for(let d of a){let l=Dk({recommendationsByFlightSize:u,predictionModel:c,constraints:o,strategy:d});if(l.length===0){p.push({strategy:d.type,reason:"NO_ELIGIBLE_STRUCTURE"});continue}m.push(...l)}return{rejected:p.length>0?p:void 0,plans:nQ(m),distribution:s}}function bk(t){let r=t.participants?.filter(({participantType:a})=>a===_t)?.length===2,n=t.events?.length===1&&t.events[0],o=n?.drawDefinitions?.length===1&&n.drawDefinitions[0],s=(o?.structures?.length===1&&o.structures[0])?.positionAssignments?.length===2;return!!(n.tieFormat&&r&&s)}function IP({tournamentRecord:t}){if(!t)return{error:j};let{drawsAnalysis:e}=Xp({tournamentRecord:t}),r={isDual:bk(t),drawsAnalysis:e},n=bt({tournamentRecord:t});return n.missingParticipantIds?.length&&(r.missingParticipantIds=n.missingParticipantIds),{...P,analysis:r}}function SP(t){let{tournamentRecord:e,scope:r}=t;if(!e)return{error:j};let n=new Date().toISOString(),o=[],i=(c,u)=>{let{extension:p}=ot({element:c,name:sn}),m=p?.value??{locks:[]};for(let d of m.locks)d.expiresAt!==null&&d.expiresAt<=n||r&&d.scope!==r||o.push({...d,...u})};i(e);let s=e.events??[];for(let c of s){i(c,{eventId:c.eventId});let u=c.drawDefinitions??[];for(let p of u)i(p,{eventId:c.eventId,drawId:p.drawId})}let a=e.venues??[];for(let c of a)i(c,{venueId:c.venueId});return{...P,mutationLocks:o}}var rv={};Gt(rv,{compareTieFormats:()=>Ti,getTieFormat:()=>Hf,tieFormatGenderValidityCheck:()=>ml,validateCollectionDefinition:()=>gp});function Wf(t){if(!t)return{};let e=[],r=t.tieFormatName,n=t.collectionDefinitions?.map(o=>{let{matchUpType:i,matchUpFormat:s,matchUpCount:a,category:c,gender:u}=o;e.includes(s)||e.push(s);let p=c?.ageCategoryCode;return[a,i===ei?"D":"S",p,s,u].join(";")}).join("|");return{tieFormatName:t&&r||"UNNAMED",matchUpFormats:e,tieFormatDesc:n}}function Ti({considerations:t={},descendant:e,ancestor:r}){let n={},o={},{matchUpFormats:i,tieFormatDesc:s}=Wf(e),{matchUpFormats:a,tieFormatDesc:c}=Wf(r),u=pt((i??[]).filter(E=>!(a??[]).includes(E)).concat((a??[]).filter(E=>!(i??[]).includes(E)))),p=!!(t?.collectionName&&e.collectionDefinitions.map(({collectionName:E})=>E).join("|")!==r.collectionDefinitions.map(({collectionName:E})=>E).join("|")),m=!!(t?.collectionOrder&&e.collectionDefinitions.map(({collectionOrder:E})=>E).join("|")!==r.collectionDefinitions.map(({collectionOrder:E})=>E).join("|")),d=Object.assign({},...(e?.collectionDefinitions??[]).map(E=>({[E.collectionId]:E}))),l=Object.assign({},...(r?.collectionDefinitions??[]).map(E=>({[E.collectionId]:E})));n.collectionIds=DD(Object.keys(d),Object.keys(l)),o.collectionIds=DD(Object.keys(l),Object.keys(d)),n.collectionsValue=Ck(d),o.collectionsValue=Ck(l),n.groupsCount=r?.collectionGroups?.length??(0-(e?.collectionGroups?.length??0)||0),o.groupsCount=n.groupsCount?-1*n.groupsCount:0;let f=n.collectionsValue.totalValue-o.collectionsValue.totalValue,g=n.collectionsValue.totalMatchUps-o.collectionsValue.totalMatchUps,I=o.collectionsValue.assignmentValues.length!==n.collectionsValue.assignmentValues.length,S=o.collectionsValue.assignmentValues.some((E,A)=>{let N=n.collectionsValue.assignmentValues[A];return!N||E.valueKey!==N.valueKey||E.value!==N.value?!0:Array.isArray(E.value)?E.value.every((D,R)=>N.value[R]===D):!1}),h=p||m||c!==s||I||S||f!==0,T=[...o.collectionsValue.invalidValues,...n.collectionsValue.invalidValues],y=T.length&&T;return{matchUpFormatDifferences:u,matchUpCountDifference:g,descendantDifferences:n,ancestorDifferences:o,orderDifference:m,valueDifference:f,nameDifference:p,descendantDesc:s,ancestorDesc:c,...P,different:h,invalid:y}}function Ck(t){let e=[],r=[],n=0;return{totalValue:Object.keys(t).sort(Wp).reduce((s,a)=>{let c=t[a],{collectionValueProfiles:u,collectionValue:p,matchUpCount:m,matchUpValue:d,scoreValue:l,setValue:f}=c,g={collectionValueProfiles:u,collectionValue:p,matchUpValue:d,scoreValue:l,setValue:f},I=Object.keys(g).filter(h=>![void 0,null].includes(g[h])&&(!Array.isArray(g[h])||g[h].length>0));I.length!==1&&e.push({collectionId:a});let S=I[0];if(S){let h=S==="collectionValueProfiles"?Object.values(u):g[S];r.push({valueKey:S,value:h})}return n+=m,u?.length?s+u.reduce((h,T)=>h+T.value,0):m?yt(d)?s+d*m:yt(l)?s+l*m:yt(f)?s+f*m:s+p:s},0),totalMatchUps:n,invalidValues:e,assignmentValues:r}}function ch(t){Object.assign(t,{inContext:!0});let{matchUp:e,error:r}=ev(t);return{matchUp:q(e,!0,!0),error:r}}function ev({participantsProfile:t,afterRecoveryTimes:e,tournamentRecord:r,contextContent:n,contextProfile:o,drawDefinition:i,nextMatchUps:s,matchUpId:a,inContext:c,eventId:u,drawId:p,event:m}){if(!r)return{error:j};if(typeof a!="string")return{error:mr};if(!i||!m){let g=(qt({tournamentRecord:r,nextMatchUps:s}).matchUps??[]).find(I=>I.matchUpId===a);if(!g)return{error:Be};({eventId:u,drawId:p}=g),{event:m,drawDefinition:i}=_e({tournamentRecord:r,eventId:u,drawId:p})}if(!i)return{error:Mr};o&&!n&&(n=eo({tournamentRecord:r,contextProfile:o}));let d={surfaceCategory:m?.surfaceCategory??r.surfaceCategory,indoorOutDoor:m?.indoorOutdoor??r.indoorOutdoor,endDate:m?.endDate??r.endDate,tournamentId:r.tournamentId,eventId:u??m?.eventId,drawId:p},{participants:l=[]}=di({participantsProfile:t,tournamentRecord:r,contextProfile:o,inContext:c});if(s){let g=(rr({context:c?d:void 0,participants:l,afterRecoveryTimes:e,contextContent:n,contextProfile:o,drawDefinition:i,nextMatchUps:s,inContext:c,event:m}).matchUps??[]).find(S=>S.matchUpId===a);if(!g)return{error:Be};let I=i?.structures?.find(S=>S.structureId===g.structureId);return{drawDefinition:i,structure:I,matchUp:g}}else{let{matchUp:f,structure:g}=Wt({context:c?d:void 0,tournamentParticipants:l,participantsProfile:t,afterRecoveryTimes:e,contextContent:n,drawDefinition:i,contextProfile:o,matchUpId:a,inContext:c,event:m});return{matchUp:f,structure:g,drawDefinition:i}}}function Hf({tournamentRecord:t,drawDefinition:e,structureId:r,matchUpId:n,structure:o,eventId:i,drawId:s,event:a}){if(!t)return{error:j};if(!s&&!a&&!r&&!n)return M({result:{error:nt},stack:"getTieFormat"});i&&!a&&(a=t.events?.find(l=>l.eventId===i));let c=ch({tournamentRecord:t,drawDefinition:e,matchUpId:n,drawId:s,event:a});if(n&&c?.error)return c;if(!e&&c?.drawDefinition&&(e=c?.drawDefinition),o=o??c?.structure,!o&&r&&!n){if(!e)return{error:Nn};let l=tt({drawDefinition:e,structureId:r});if(l.error)return l;o=l.structure}let u=(o?.tieFormat||o?.tieFormatId)&&ze({structure:o,drawDefinition:e,event:a})?.tieFormat,p=(e?.tieFormat||e?.tieFormatId)&&ze({drawDefinition:e,event:a})?.tieFormat,m=ze({event:a})?.tieFormat,d=ze({matchUp:c?.matchUp,drawDefinition:e,structure:o,event:a})?.tieFormat;return{...P,matchUp:c?.matchUp,structureDefaultTieFormat:nr(u),eventDefaultTieFormat:nr(m),drawDefaultTieFormat:nr(p),tieFormat:nr(d),structure:o}}var nv={};Gt(nv,{bulkUpdatePublishedEventIds:()=>hP,getAllEventData:()=>yP,getCourtInfo:()=>$l,getDrawData:()=>yf,getEventData:()=>tm,getEventPublishStatus:()=>Cr,getPublishState:()=>ra,getRoundVisibilityState:()=>TP,getTournamentPublishStatus:()=>Uc,getVenueData:()=>Eu,isEmbargoed:()=>Uo,isVisiblyPublished:()=>ro});function hP({tournamentRecord:t,outcomes:e}){if(!t)return{error:j};if(!e?.length)return{error:nt,info:"Missing outcomes"};let r=e.reduce((s,a)=>{let{drawId:c,eventId:u}=a;return u&&c&&(s[u]?s[u].includes(c)||s[u].push(c):s[u]=[c]),s},{}),n=Object.keys(r);return{publishedEventIds:(t.events?.filter(s=>n.includes(s.eventId))).filter(s=>{let a=Cr({event:s}),{drawDetails:c,drawIds:u}=a??{},{eventId:p}=s;return r[p].filter(d=>{let l=c?Object.keys(a.drawDetails).filter(f=>Bp({drawId:f,drawDetails:c})):[];return u?.includes(d)||l.includes(d)}).length}).map(s=>s.eventId),eventIdPublishedDrawIdsMap:r}}function TP(t,e){if(!t||!e?.length)return;let r=t.roundLimit,n=t.scheduledRounds??{},o=e.reduce((a,c)=>Math.max(a,c.roundNumber||0),0);if(o===0)return;let i={},s=!1;for(let a=1;a<=o;a++){let c={};r!=null&&a>r&&(c.hidden=!0,s=!0);let u=n[a];u&&Uo(u)&&(c.embargoed=!0,s=!0),(c.hidden||c.embargoed)&&(i[a]=c)}return s?i:void 0}function yP({tournamentRecord:t,policyDefinitions:e}){if(!t)return{error:j};let r=t.events??[],n=t?.participants??[],{tournamentInfo:o}=ia({tournamentRecord:t}),{venues:i}=kn({tournamentRecord:t}),s=r.map(c=>{let{eventId:u}=c,p=aA({event:c}).eventInfo,m=Ac({tournamentRecord:t,event:c}).scheduleTiming,d=(c.drawDefinitions??[]).map(f=>{let{drawId:g,drawName:I,matchUpFormat:S,updatedAt:h}=f,T={drawId:g,drawName:I,matchUpFormat:S,updatedAt:h},{abandonedMatchUps:y,completedMatchUps:E,upcomingMatchUps:A,pendingMatchUps:N}=Ga({requireParticipants:!0,tournamentParticipants:n,context:{eventId:u},policyDefinitions:e,tournamentRecord:t,inContext:!0,scheduleTiming:m,drawDefinition:f,event:c});return{drawInfo:T,matchUps:{abandonedMatchUps:y,completedMatchUps:E,upcomingMatchUps:A,pendingMatchUps:N}}}),l=Cr({event:c});return Object.assign(p,{drawsData:d,publish:l}),p});return{allEventData:{tournamentInfo:o,venuesData:i,eventsData:s}}}var av={};Gt(av,{courtGridRows:()=>qf,findVenue:()=>Ln,getMatchUpsToSchedule:()=>Yf,getPersonRequests:()=>is,getProfileRounds:()=>jf,getScheduledRoundsDetails:()=>sm,getSchedulingProfile:()=>bo,getSchedulingProfileIssues:()=>EP,publicFindCourt:()=>SE});function Za({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:e,timeAfterRecovery:r,matchUp:n}){let{individualParticipantIds:o}=Mp(n);r=r??n.schedule?.timeAfterRecovery;let i=u=>{t[u]||(t[u]=[]),t[u]=pt(t[u].concat(...o))},s=u=>{r&&(!e[u]||r>e[u])&&(e[u]=r)},a=n.winnerTo?.matchUpId||n.winnerMatchUpId;a&&(r&&s(a),i(a));let c=n.loserTo?.matchUpId||n.loserMatchUpId;c&&(r&&s(c),i(c)),n.sidesTo?.length&&n.sidesTo.forEach(({matchUpId:u})=>{u&&(r&&s(u),i(u))})}function Yf(t){let e=X(t,[{[CI]:!0}]);if(e.error)return e;let{matchUpPotentialParticipantIds:r,dateScheduledMatchUpIds:n=[],scheduleCompletedMatchUps:o,matchUpNotBeforeTimes:i,matchUpScheduleTimes:s,orderedMatchUpIds:a,clearDate:c,matchUps:u}=t,p=s?Object.keys(s):[],m=(a??[]).map(l=>u.find(f=>f.matchUpId===l)).filter(Boolean).filter(l=>{let f=!c&&(n.includes(l.matchUpId)||p.includes(l.matchUpId)),g=["BYE",Mt,ie,Fr,De,vt,Qt,ge].includes(l?.matchUpStatus);return o||!f&&!l.winningSide&&!g}),d=r&&i?m.reduce((l,f)=>{let{drawId:g,tournamentId:I}=f;return l.matchUpMap[I]||(l.matchUpMap[I]={}),l.matchUpMap[I][g]?l.matchUpMap[I][g].push(f):l.matchUpMap[I][g]=[f],Za({matchUpPotentialParticipantIds:r,matchUpNotBeforeTimes:i,matchUp:f}),l},{matchUpMap:{}}).matchUpMap:{};return{matchUpsToSchedule:m,matchUpMap:d}}function _d({defaultRecoveryMinutes:t=0,defaultAverageMinutes:e,tournamentRecords:r,matchUpFormat:n,categoryName:o,categoryType:i,tournamentId:s,eventType:a,eventId:c}){if(!xr({matchUpFormat:n}))return{error:Kc};let u=Object.keys(r).filter(m=>!s||m===s),p;return u.forEach(m=>{if(p)return;let d=r[m],l=c?_e({tournamentRecord:d,eventId:c})?.event:void 0;return p=Fp({tournamentRecord:d,matchUpFormat:n,categoryName:o,categoryType:i,eventType:a,event:l}),p?.averageMinutes||p?.recoveryMinutes}),{recoveryMinutes:p?.recoveryMinutes||t,averageMinutes:p?.averageMinutes||e,typeChangeRecoveryMinutes:p?.typeChangeRecoveryMinutes||p?.recoveryMinutes||t}}function sm(t){let e=X(t,[{[yp]:{tournamentRecords:!1,tournamentRecord:!1}},{rounds:!0,[Ge]:ke}]);if(e.error)return e;let{scheduleCompletedMatchUps:r,periodLength:n=30}=t,o=t.tournamentRecords||t.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord}||{};if(typeof o!="object")return{error:kt};let i={},s=[],a=[],c=t.rounds.toSorted((I,S)=>(I.sortOrder??0)-(S.sortOrder??0)),u=t.containedStructureIds??Object.assign({},...Object.values(o).map(I=>ji({tournamentRecord:I}).containedStructures)),p=t.matchUps??cn({nextMatchUps:!0,tournamentRecords:o}).matchUps,m=0,d={},l={},f={};return{scheduledRoundsDetails:c.flatMap(I=>{let S=I.periodLength||n,h=[];u?.[I.structureId]?h.push(...u[I.structureId]):h.push(I.structureId);let T=p?zi({tournamentIds:[I.tournamentId],roundNumbers:[I.roundNumber],matchUpIds:I.matchUpIds,eventIds:[I.eventId],drawIds:[I.drawId],processContext:!0,structureIds:h,matchUps:p}).sort(Qi):[],{segmentNumber:y,segmentsCount:E}=I.roundSegment??{};if(yt(y)&&en(T?.length)&&en(E)&&y>0&&y<=E&&E<T?.length&&!I.matchUpIds?.length){let R=T.length/E,U=R*(y-1);T=T.slice(U,U+R)}let A=o[I.tournamentId],N=_e({drawId:I.drawId,tournamentRecord:A}).event,D=[];for(let R of T){let U=R.matchUpFormat;U&&(i[U]||(i[U]=[],i[U].push(R)),D.push(U))}for(let R of D){let{eventType:U,category:b}=N??{},{categoryName:C,ageCategoryCode:_}=b??{},{typeChangeRecoveryMinutes:v,recoveryMinutes:w,averageMinutes:L,error:F}=_d({categoryName:C??_,categoryType:b?.categoryType,tournamentId:I.tournamentId,eventId:I.eventId,tournamentRecords:o,matchUpFormat:R,eventType:U});if(F)return{error:F,round:I};let x=T.filter(G=>(r||!Ot.includes(G.matchUpStatus))&&G.matchUpStatus!=="BYE").map(Te);x.forEach(G=>{f[G]={typeChangeRecoveryMinutes:v,recoveryMinutes:w,averageMinutes:L},d[G]=w,l[G]=L}),a.push(...x),m=Math.max(L||0,m);let k=`${L}|${S}`;return s.includes(k)||s.push(k),{roundPeriodLength:S,recoveryMinutes:w,averageMinutes:L,matchUpIds:x,hash:k}}}),greatestAverageMinutes:m,matchUpFormatCohorts:i,recoveryMinutesMap:d,averageMinutesMap:l,orderedMatchUpIds:a,minutesMap:f,...P}}function ov({schedulingProfile:t,venueIds:e,eventIds:r,drawIds:n}){let o=[],i=t?.map(a=>{let c=mt(a?.scheduleDate);if(!c){o.push(`Invalid date: ${a?.scheduledDate}`);return}let u=(a?.venues??[]).map(p=>{let{rounds:m,venueId:d}=p;if(!e?.includes(d)){o.push(`Missing venueId: ${d}`);return}let f=m.filter(g=>{let I=r.includes(g.eventId)&&n.includes(g.drawId);return I||o.push(`Invalid eventId: ${g.eventId} or drawId: ${g.drawId}`),I});if(f.length)return{venueId:d,rounds:f}}).filter(Boolean);return u.length&&c&&{...a,venues:u}}).filter(Boolean),s=o.length;return{updatedSchedulingProfile:i,modifications:s,issues:o}}function xd({tournamentRecords:t,schedulingProfile:e}){if(!e)return{valid:!0};if(!Array.isArray(e))return{valid:!1,error:O};let{venueIds:r,tournamentsMap:n}=iQ({tournamentRecords:t}),o,i,s=e.every(a=>{let{scheduleDate:c,venues:u}=a;return Me(c)?u.every(p=>{let{venueId:m,rounds:d}=p;return typeof m!="string"?(i="venueId should be a string",!1):Array.isArray(d)?r.includes(m)?!!d.every(f=>{if(!f)return i="empty round",!1;let{roundSegment:g,tournamentId:I,structureId:S,roundNumber:h,eventId:T,drawId:y}=f,A=n?.[I]?.[T]?.[y]?.[S]?.includes(h);A||(i="Invalid rounds");let{segmentNumber:N,segmentsCount:D}=g??{},R=!g||yt(N)&&en(D)&&N<=D;return R||(i="Invalid segment"),A&&R}):(o=wi,!1):(i="rounds should be an array",!1)}):!1});return!s&&!o&&(o=O),{valid:!!s,error:o,info:i}}function oQ(t){let{tournamentRecord:e={},tournamentMap:r={},requireCourts:n}=t,o=[],i=[],s=[],a=[],c=(e?.venues??[]).map(({venueId:p,courts:m})=>(!n||m?.length)&&p),u=e?.tournamentId;if(u){o.push(u),r[u]={};let p=e?.events??[];for(let m of p){let d=m.eventId;s.push(d),r[u][d]={};let l=f=>parseInt(f);for(let f of m.drawDefinitions??[]){let g=f.drawId;a.push(g),r[u][d][g]={};let{structures:I}=Sn({drawDefinition:f});for(let S of I??[]){let h=S.structureId,{matchUps:T}=ht({structure:S}),{roundMatchUps:y}=Ue({matchUps:T}),E=y&&Object.keys(y).map(l);if(r[u][d][g][h]=E,i.push(h),S.structures?.length)for(let A of S.structures)i.push(A.structureId),r[u][d][g][A.structureId]=E}}}}return{tournamentMap:r,tournamentIds:o,structureIds:i,venueIds:c,eventIds:s,drawIds:a}}function iQ(t){let e=(t?.tournamentRecords&&Object.values(t?.tournamentRecords))??[],r={},{venueIds:n,eventIds:o,drawIds:i,structureIds:s,tournamentIds:a}=e.reduce((c,u)=>{let{tournamentIds:p,tournamentMap:m,structureIds:d,venueIds:l,eventIds:f,drawIds:g}=oQ({tournamentRecord:u});return l.forEach(I=>{c.venueIds.includes(I)||c.venueIds.push(I)}),c.tournamentIds.push(...p),c.structureIds.push(...d),c.eventIds.push(...f),c.drawIds.push(...g),Object.assign(r,m),c},{tournamentIds:[],structureIds:[],venueIds:[],eventIds:[],drawIds:[]});return{tournamentsMap:r,tournamentIds:a,structureIds:s,venueIds:n,eventIds:o,drawIds:i}}function bo({tournamentRecords:t,tournamentRecord:e}){if(typeof t!="object"||!Object.keys(t).length)return{error:kt};let{extension:r}=ot({element:e,name:hc,tournamentRecords:t,discover:!0}),n=r?.value??[];if(n.length){let{venueIds:o}=hd({requireCourts:!0,tournamentRecords:t}),{eventIds:i,drawIds:s}=kS({tournamentRecords:t}),{updatedSchedulingProfile:a,modifications:c,issues:u}=ov({schedulingProfile:n,venueIds:o,eventIds:i,drawIds:s});if(c){n=a;let p=Fu({tournamentRecords:t,tournamentRecord:e,schedulingProfile:n});return p.error?p:{schedulingProfile:n,modifications:c,issues:u}}}return{schedulingProfile:n,modifications:0}}function Fu({tournamentRecords:t,tournamentRecord:e,schedulingProfile:r}){let n=xd({tournamentRecords:t,schedulingProfile:r});return n.error?n:r?ut({tournamentRecords:t,discover:!0,extension:{name:hc,value:r}}):dr({element:e,name:hc,tournamentRecords:t,discover:!0})}function ku(t){let{tournamentRecord:e}=t,r=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!t.schedulingProfile){let{modifications:u,issues:p}=bo({tournamentRecords:r,tournamentRecord:e});return{success:!u,modifications:u,issues:p}}let{venueIds:n}=hd({tournamentRecords:r}),{eventIds:o,drawIds:i}=kS({tournamentRecords:r}),{updatedSchedulingProfile:s,modifications:a,issues:c}=ov({schedulingProfile:t.schedulingProfile,venueIds:n,eventIds:o,drawIds:i});return a?{...Fu({schedulingProfile:s,tournamentRecords:r}),modifications:a,issues:c}:{...P,modifications:a,issues:c}}function EP(t){let{scheduleDates:e=[],tournamentRecords:r,periodLength:n=30}=t??{};if(typeof r!="object")return{error:Hc};if(!Array.isArray(e))return{error:O};if(!e.every(Me))return{error:ae};let i=[],s=0,a={},{schedulingProfile:c}=bo({tournamentRecords:r});if(!c)return{issues:i,...P};let{matchUps:u}=cn({nextMatchUps:!0,tournamentRecords:r});for(let m of c){let{scheduleDate:d,venues:l=[]}=m;if(!e?.length||e.includes(d)){for(let f of l??[])if(f){let{rounds:g}=f,I=[],{orderedMatchUpIds:S,scheduledRoundsDetails:h}=sm({tournamentRecords:r,periodLength:n,matchUps:u,rounds:g}),{matchUpDependencies:T}=tn({tournamentRecords:r,matchUps:u}),y=E=>{let A;return h?.find((N,D)=>{let R=N.matchUpIds.includes(E);return R&&(A=D),R}),A};if(S?.forEach((E,A)=>{let N=S.slice(A+1),D=Yt(N,T?.[E]?.matchUpIds??[]);D.length&&I.push({matchUpId:E,shouldBeAfter:D})}),I.length){s+=I.length;let E=I.map(({matchUpId:A,shouldBeAfter:N})=>{let D=y(A),R=pt(N.map(y));return a[d]||(a[d]={}),a[d][D]||(a[d][D]=[]),R.forEach(U=>{a[d][D].includes(U)||a[d][D].push(U)}),{matchUpId:A,matchUpRoundIndex:D,earlierRoundIndices:R,shouldBeAfter:N}});i.push(...E)}}}}let p={matchUpIdShouldBeAfter:Object.assign({},...i.map(m=>{let{matchUpId:d,shouldBeAfter:l,earlierRoundIndices:f}=m;return{[d]:{earlierRoundIndices:f,shouldBeAfter:l}}}))};return{issuesCount:s,profileIssues:p,roundIndexShouldBeAfter:a,...P}}function is(t){let{tournamentRecords:e,requestType:r}=t,n=X(t,[{[Ee]:!0}]);if(n.error)return n;let o={};for(let i of Object.values(e)){let{extension:s}=ot({element:i,name:Sc}),a=s?.value??[];for(let c of a){let{personId:u,requests:p}=c??{};o[u]||(o[u]=[]);for(let m of p)r&&m.requestType!==r||o[u].push(m)}}return{personRequests:o,...P}}function uh(t){let{containerStructureId:e,roundSegment:r,isRoundRobin:n,tournamentId:o,roundNumber:i,structureId:s,eventId:a,drawId:c}=t,u=n?e:s,p=[o,a,c,u,i].join("|");return et({structureId:u,roundSegment:r,tournamentId:o,roundNumber:i,eventId:a,drawId:c,id:p})}function iv({round:t,matchUps:e,events:r,tournamentRecords:n}){let o=r.find(d=>d.eventId===t.eventId),{eventType:i,category:s,categoryType:a}=o??{},{categoryName:c,ageCategoryCode:u}=s??{},p=mn(e.map(({matchUpFormat:d})=>d)),m=0;return Object.keys(p).forEach(d=>{let l=p[d],f=_d({categoryName:c||u,tournamentId:t.tournamentId,eventId:t.eventId,tournamentRecords:n,matchUpFormat:d,categoryType:a,eventType:i});if(f.error)return f;let g=f.averageMinutes*l;isNaN(m)||(m+=g)}),{roundMinutes:m}}function Mk(t){return(t??[]).reduce((e,r)=>{let n=(r.finishingPositionRange?.winner??[]).reduce((i,s)=>i+s,0),o=(r.finishingPositionRange?.winner??[]).join("-")||"";return!e.minFinishingSum||n<e.minFinishingSum?{minFinishingSum:n,winnerFinishingPositionRange:o}:e},{minFinishingSum:0,winnerFinishingPositionRange:""})}function sv(t){let e=t.length,r=t.filter(({sides:p})=>p?.some(({bye:m})=>m)).length||0,n=t.filter(({winningSide:p,matchUpStatus:m})=>p||Ot.includes(m)).length||0,o=t.filter(({schedule:p,matchUpStatus:m})=>p?.scheduledDate&&p?.scheduledTime&&m!=="BYE").length||0,i=e-r,s=i===n,a=i-o,c=i-o;return{unscheduledCount:a,incompleteCount:c,scheduledCount:o,completedCount:n,matchUpsCount:e,isScheduled:i===o,isComplete:s,byeCount:r}}function jf({tournamentRecords:t,schedulingProfile:e,tournamentRecord:r,withRoundId:n}){if(r&&!t){if(typeof r!="object")return{error:Hc};t={[r.tournamentId]:r}}if(e){let s=xd({tournamentRecords:t,schedulingProfile:e});if(s.error)return s}if(!e&&t){let s=bo({tournamentRecords:t});if(s.error)return s;e=s.schedulingProfile}if(!e)return{error:fe};let o={};return{profileRounds:e.map(({venues:s,scheduleDate:a})=>s.map(({rounds:c})=>c.map(u=>{let p=uh(u);return p.roundSegment?.segmentsCount&&(o[p.id]=p.roundSegment.segmentsCount),et({id:n?p.id:void 0,scheduleDate:a,...p})}))).flat(1/0),segmentedRounds:o}}function Qo({court:t,date:e}){let r=e&&t.dateAvailability?.find(o=>Xn(o.date,e)),n=t.dateAvailability?.find(o=>!o.date);return r||n}function vk({court:t,date:e}){let r=Qo({court:t,date:e}),n=new Map,o=[];return(r?.bookings??[]).forEach(i=>{if(typeof i.courtOrder=="number"){let s=i.rowCount||1;for(let a=0;a<s;a++)n.set(i.courtOrder+a,i)}else o.push(i)}),{gridBookings:n,timeBookings:o}}function qf({courtPrefix:t="C|",minRowsCount:e,courtsData:r,scheduledDate:n}){if(!Array.isArray(r))return{error:O};let o=r?.reduce((a,c)=>{let u=c.matchUps??[],p=Math.max(0,...u.map(m=>m.schedule.courtOrder||0));return Math.max(p,a)},1),i=Math.max(e||0,o),s=Q(0,i).map(a=>({matchUps:Q(0,r.length).map(c=>{let u=r[c],{courtId:p,venueId:m}=u;if(n){let{gridBookings:d}=vk({court:u,date:n});if(d.has(a+1)){let l=d.get(a+1);return{schedule:{courtOrder:a+1,venueId:m,courtId:p},isBlocked:!0,booking:l}}}return{schedule:{courtOrder:a+1,venueId:m,courtId:p}}})}));return r.forEach((a,c)=>{for(let u of a.matchUps){let p=u.schedule?.courtOrder;p&&(s[p-1].matchUps[c]=u)}}),{courtPrefix:t,rows:s.map((a,c)=>Object.assign({rowId:`rowId-${c+1}`},...a.matchUps.map((u,p)=>({[`${t}${p}`]:u}))))}}var cv={};Gt(cv,{getEntriesAndSeedsCount:()=>$f,getMaxEntryPosition:()=>AP});function $f({policyDefinitions:t,drawDefinition:e,drawSize:r,drawId:n,event:o,stage:i}){if(!o)return{error:le};let{entries:s,stageEntries:a}=UE({drawDefinition:e,drawId:n,stage:i,event:o}),c=a.length,{drawSize:u}=bA({participantsCount:c}),p=rm({drawSize:r??u,participantsCount:c,policyDefinitions:t});if(p.error)return M({result:p,stack:"getEntriesAndSeedsCount"});let{seedsCount:m}=p;return{entries:s,seedsCount:m,stageEntries:a}}function AP(t){let{entries:e=[],entryStatus:r,stage:n}=t;return Math.max(...e.filter(o=>(!n||n===o.entryStage)&&(!r||o.entryStatus===r)&&!isNaN(o.entryPosition)).map(({entryPosition:o})=>st(o||0)),0)}var dv={};Gt(dv,{allCompetitionMatchUps:()=>cn,allDrawMatchUps:()=>rr,allEventMatchUps:()=>vn,allTournamentMatchUps:()=>qt,analyzeMatchUp:()=>Ld,calculateMatchUpMargin:()=>Id,calculateWinCriteria:()=>ua,checkMatchUpIsComplete:()=>Js,competitionScheduleMatchUps:()=>am,drawMatchUps:()=>FP,eventMatchUps:()=>Qf,filterMatchUps:()=>zi,getAllDrawMatchUps:()=>te,getAllStructureMatchUps:()=>ht,getCheckedInParticipantIds:()=>$s,getCompetitionFormat:()=>MP,getCompetitionMatchUps:()=>wd,getEventMatchUpFormatTiming:()=>UP,getHomeParticipantId:()=>_P,getMatchUpCompetitiveProfile:()=>js,getMatchUpContextIds:()=>OP,getMatchUpDailyLimits:()=>Jf,getMatchUpDailyLimitsUpdate:()=>CP,getMatchUpDependencies:()=>tn,getMatchUpFormat:()=>xP,getMatchUpFormatTiming:()=>Fp,getMatchUpFormatTimingUpdate:()=>NP,getMatchUpScheduleDetails:()=>Kl,getMatchUpType:()=>zl,getMatchUpsStats:()=>wP,getModifiedMatchUpFormatTiming:()=>Kf,getParticipantResults:()=>Vp,getPredictiveAccuracy:()=>vP,getRoundMatchUps:()=>Ue,getRounds:()=>LP,isValidMatchUpFormat:()=>xr,matchUpActions:()=>Af,participantScheduledMatchUps:()=>bP,predictMatchUpCompetitiveBands:()=>RP,tallyParticipantResults:()=>ea,tournamentMatchUps:()=>Xf,validMatchUp:()=>rS,validMatchUps:()=>Rr});function PP({tournamentRecords:t,extensionName:e}){if(typeof t!="object"||!Object.keys(t).length)return{error:kt};let r=[],n;for(let o of Object.values(t)){let{extension:i}=ot({element:o,name:e});i&&!n&&(r.push({params:{extension:i,discover:!0},method:"addExtension"}),n=!0);let s=o.events??[];for(let a of s){let{eventId:c}=a,{extension:u}=ot({name:e,element:a});u&&r.push({params:{eventId:c,extension:u},method:"addEventExtension"})}}return{methods:r}}function NP({tournamentRecords:t}){return PP({extensionName:pi,tournamentRecords:t})}var uv="ADULT",pv="JUNIOR",DP="WHEELCHAIR",mv={[ko]:{allowModificationWhenMatchUpsScheduled:{courts:!1,venues:!1},defaultTimes:{averageTimes:[{categoryNames:[],minutes:{default:90}}],recoveryTimes:[{minutes:{[Rt]:30,default:60}}]},defaultDailyLimits:{[Ct]:2,[Rt]:2,total:3},matchUpAverageTimes:[{matchUpFormatCodes:[xn],averageTimes:[{categoryNames:[],minutes:{default:90}},{categoryTypes:[DP],minutes:{default:120}}]},{matchUpFormatCodes:["SET3-S:6/TB7-F:TB10"],averageTimes:[{categoryNames:[],minutes:{default:85}}]},{matchUpFormatCodes:["SET3-S:6/TB7-F:TB7"],averageTimes:[{categoryNames:[],minutes:{default:70}}]},{matchUpFormatCodes:["SET3-S:4NOAD-F:TB7"],averageTimes:[{categoryNames:[],minutes:{default:55}}]},{matchUpFormatCodes:["SET3-S:4/TB7"],averageTimes:[{categoryNames:[],minutes:{default:60}}]},{matchUpFormatCodes:["SET3-S:4/TB7-F:TB7"],averageTimes:[{categoryNames:[],minutes:{default:50}}]},{matchUpFormatCodes:["SET3-S:4/TB7-F:TB10"],averageTimes:[{categoryNames:[],minutes:{default:55}}]},{matchUpFormatCodes:["SET3-S:4/TB5@3"],averageTimes:[{categoryNames:[],minutes:{default:45}}]},{matchUpFormatCodes:["SET1-S:8/TB7","SET1-S:8/TB7@7"],averageTimes:[{categoryNames:[],minutes:{default:40}}]},{matchUpFormatCodes:["SET1-S:5/TB9@4"],averageTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:6/TB7"],averageTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:6NOAD"],averageTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:4/TB7","SET1-S:4/TB5@3","SET3-S:TB10","SET1-S:T20"],averageTimes:[{categoryNames:[],minutes:{default:20}}]},{matchUpFormatCodes:["SET1-S:4NOAD"],averageTimes:[{categoryNames:[],minutes:{default:20}}]},{matchUpFormatCodes:["SET1-S:TB10"],averageTimes:[{categoryNames:[],minutes:{default:10}}]}],matchUpRecoveryTimes:[{matchUpFormatCodes:["SET3-S:6/TB7","SET3-S:6/TB7-F:TB10","SET3-S:6/TB7-F:TB7"],recoveryTimes:[{categoryTypes:[uv,DP],minutes:{default:60,[Rt]:30}},{categoryTypes:[pv],minutes:{default:60,[Rt]:60}}]},{matchUpFormatCodes:["SET3-S:4/TB7-F:TB7","SET3-S:4/TB7-F:TB10","SET3-S:4NOAD-F:TB7","SET3-S:4/TB7","SET3-S:4/TB5@3"],recoveryTimes:[{categoryTypes:[uv,DP],minutes:{default:30}},{categoryTypes:[pv],minutes:{default:60}}]},{matchUpFormatCodes:["SET1-S:8/TB7","SET1-S:8/TB7@7","SET1-S:5/TB9@4","SET1-S:6/TB7","SET1-S:6NOAD","SET1-S:4/TB7","SET1-S:4NOAD","SET3-S:TB10","SET1-S:T20"],recoveryTimes:[{categoryNames:[],minutes:{default:30}}]},{matchUpFormatCodes:["SET1-S:4/TB5@3"],recoveryTimes:[{categoryTypes:[uv,pv],minutes:{default:30}},{categoryTypes:[DP],minutes:{default:15}}]},{matchUpFormatCodes:["SET1-S:TB10"],recoveryTimes:[{categoryNames:[],minutes:{default:15}}]}],matchUpDailyLimits:[]}},Ok=mv;function UP({tournamentRecord:t,matchUpFormats:e,categoryType:r,event:n}){if(!n)return{error:le};let o,i;if(e?.length){let m=[];o=e.map(d=>{let l=typeof d=="string"?{matchUpFormat:d}:d;if(!m.includes(l?.matchUpFormat)&&xr({matchUpFormat:l?.matchUpFormat}))return m.push(l.matchUpFormat),l}).filter(Boolean)}else{let{policy:m}=go({policyType:Qr,tournamentRecord:t,event:n});if(m?.matchUpFormats)o=m?.matchUpFormats;else{let{extension:d}=ot({name:pi,element:n}),l,f;d?.value?{matchUpAverageTimes:l,matchUpRecoveryTimes:f}=d.value:{matchUpAverageTimes:l,matchUpRecoveryTimes:f}=Ok[ko],o=pt([...(l??[]).map(g=>g.matchUpFormatCodes),...(f??[]).map(g=>g.matchUpFormatCodes)].flat()).map(g=>({matchUpFormat:g})),i="default scheduling policy in use"}}let{eventType:s,eventId:a,category:c}=n,u=c?.categoryName??c?.ageCategoryCode??a;if(!a)return{error:le};let p=o.map(({matchUpFormat:m,description:d})=>{let l=Fp({tournamentRecord:t,matchUpFormat:m,categoryName:u,categoryType:r,eventType:s,event:n});return{matchUpFormat:m,description:d,...l}});return et({eventMatchUpFormatTiming:p,info:i})}function Kf(t){let e=X(t,[{[rt]:!0},{[$e]:g=>xr({matchUpFormat:g}),[Lr]:Kc,[Sl]:!0}]);if(e.error)return e;let{tournamentRecord:r,matchUpFormat:n,event:o}=t,{extension:i}=ot({name:pi,element:o}),s=i?.value,{extension:a}=ot({element:r,name:pi}),c=a?.value,u=s?.matchUpAverageTimes&&nd({...s,matchUpFormat:n}),p=c?.matchUpAverageTimes&&nd({...c,matchUpFormat:n}),m=[u,p].find(g=>g),d=s?.matchUpRecoveryTimes&&od({...s,matchUpFormat:n}),l=c?.matchUpRecoveryTimes&&od({...c,matchUpFormat:n}),f=[d,l].find(g=>g);return{matchUpFormat:n,recoveryTimes:f,averageTimes:m}}var sQ=Hs[gn].predictionModel;function aQ(t,e){if(t)return t;if(e){let{policy:r}=go({policyType:gn,tournamentRecord:e});if(r?.predictionModel)return r.predictionModel}return sQ}function RP({tournamentRecord:t,predictionModel:e,side1Rating:r,side2Rating:n}){if(typeof r!="number"||typeof n!="number")return{competitive:0,decisive:0,routine:0,error:O};let o=aQ(e,t),i=Math.abs(r-n);return{...Tf(i,o),delta:i}}var _c=({scheduleAttributes:t=["scheduledDate","scheduledTime"],schedule:e={}})=>!!Object.keys(e).filter(n=>t.includes(n)).filter(n=>e[n]).length;function bP({scheduleAttributes:t=["scheduledDate","scheduledTime"],matchUps:e=[]}){if(!Rr(e))return{error:Bn};if(!Array.isArray(t))return{error:O};let r=e.filter(Boolean).filter(({schedule:o})=>_c({schedule:o,scheduleAttributes:t})).reduce((o,i)=>{let{schedule:s}=i,a=mt(s?.scheduledDate),c=$t(s?.scheduledTime);return a&&c&&(o[a]?o[a].push(i):o[a]=[i]),o},{});return Object.keys(r).forEach(o=>{r[o].sort((i,s)=>ny($t(i.schedule?.scheduledTime),$t(s.schedule?.scheduledTime)))}),{...P,scheduledMatchUps:r}}function CP({tournamentRecords:t}){return PP({extensionName:Np,tournamentRecords:t})}function _k({tournamentRecords:t}){let e={},r=[];for(let n of Object.values(t))for(let o of n.events??[]){let i=Cr({event:o}),s=i?.drawDetails;Tt(s)?(Object.assign(e,s),r.push(...Object.keys(s).filter(a=>Bp({drawId:a,drawDetails:s})))):i?.drawIds?.length&&r.push(...i.drawIds)}return{drawIds:r,detailsMap:e}}function zf({schedulingProfile:t,matchUps:e=[]}){let r={},n=({eventId:a,drawId:c,structureId:u,roundNumber:p})=>`${a}|${c}|${u}${p}`;t?.length&&t.flatMap(({venues:c})=>c.map(({rounds:u})=>u)).forEach(c=>{c.sort((p,m)=>(p.sortOrder||0)-(m.sortOrder||0)).forEach(({eventId:p,drawId:m,structureId:d,roundNumber:l},f)=>{let g=n({eventId:p,drawId:m,structureId:d,roundNumber:l});r[g]=f})});let o=[],i={noScheduledDate:[]};for(let a of e){let c=a.schedule??{},u=c.scheduledDate&&mt(c.scheduledDate)||c.scheduledTime&&mt(c.scheduledTime)||"noScheduledDate";i[u]||(i[u]=[]),i[u].push(a)}let s=Object.keys(i).sort((a,c)=>a.localeCompare(c));for(let a of s){let c=i[a],u={noScheduledTime:[]};for(let m of c){let d=m.schedule??{},l=d.scheduledTime&&$t(d.scheduledTime)||"noScheduledTime";u[l]||(u[l]=[]),u[l].push(m)}for(let m of Object.keys(u)){let l=u[m].sort((f,g)=>(f.roundNumber||0)-(g.roundNumber||0));u[m]=l}let p=Object.keys(u).sort((m,d)=>m.localeCompare(d));for(let m of p){let d=u[m];d.sort((l,f)=>{let g=r[n(l)]||0,I=r[n(f)]||0;return g-I}),o.push(...d)}}return o}function Qf(t){let{participants:e,contextContent:r,participantMap:n}=t,{tournamentAppliedPolicies:o,scheduleVisibilityFilters:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,usePublishState:m,contextFilters:d,matchUpFilters:l,contextProfile:f,nextMatchUps:g,tournamentId:I,inContext:S,context:h,event:T}=t;if(!T)return{error:le};let{eventId:y,eventName:E,endDate:A,eventType:N,category:D,gender:R}=T??{},U={...h,...et({surfaceCategory:T.surfaceCategory??p?.surfaceCategory,indoorOutDoor:T.indoorOutdoor??p?.indoorOutdoor,tournamentId:I??p?.tournamentId,endDate:A??p?.endDate,eventName:E,eventType:N,category:D,eventId:y,gender:R})},b;!e&&p&&({participants:e,participantMap:n,groupInfo:b}=di({participantsProfile:s,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,contextProfile:f,inContext:S})),f&&!r&&(r=eo({policyDefinitions:c,tournamentRecord:p,contextProfile:f,event:T}));let C=Cr({event:T});return{...(T.drawDefinitions??[]).reduce((w,L)=>{let F=Ga({hydrateParticipants:t.hydrateParticipants,context:U,tournamentAppliedPolicies:o,scheduleVisibilityFilters:i,tournamentParticipants:e,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,usePublishState:m,contextContent:r,contextFilters:d,matchUpFilters:l,participantMap:n,publishStatus:C,contextProfile:f,drawDefinition:L,nextMatchUps:g,inContext:S,event:T});return Object.keys(F)?.forEach(k=>{Array.isArray(F[k])&&(w[k]||(w[k]=[]),w[k]=w[k].concat(F[k]))}),w},{}),...P,groupInfo:b}}function Xf(t){if(!t?.tournamentRecord)return{error:j};let e=t.contextContent,{scheduleVisibilityFilters:r,participantsProfile:n,afterRecoveryTimes:o,policyDefinitions:i,tournamentRecord:s,inContext:a=!0,usePublishState:c,contextFilters:u,matchUpFilters:p,contextProfile:m,nextMatchUps:d,context:l}=t,f=t.tournamentId??s.tournamentId,g=s?.events??[],{participants:I,participantMap:S,groupInfo:h}=di({participantsProfile:n,policyDefinitions:i,tournamentRecord:s,contextProfile:m,inContext:a});m&&!e&&(e=eo({policyDefinitions:i,tournamentRecord:s,contextProfile:m}));let{appliedPolicies:T}=ft({tournamentRecord:s}),y=u?.eventIds??[];return{...g.filter(N=>!y.includes(N.eventId)).map(N=>{let R={eventDrawsCount:Bt({event:N}).flightProfile?.flights?.length||N.drawDefinitions?.length||0,...l};return Qf({hydrateParticipants:t.hydrateParticipants,context:R,tournamentAppliedPolicies:T,scheduleVisibilityFilters:r,participantsProfile:n,afterRecoveryTimes:o,policyDefinitions:i,tournamentRecord:s,usePublishState:c,contextFilters:u,contextProfile:m,contextContent:e,matchUpFilters:p,participantMap:S,participants:I,tournamentId:f,nextMatchUps:d,inContext:a,event:N})}).reduce((N,D)=>((D&&Object.keys(D).filter(U=>!["success","matchUpsMap"].includes(U)))?.forEach(U=>{Array.isArray(D[U])&&(N[U]||(N[U]=[]),N[U]=N[U].concat(D[U]),N.matchUpsCount!==void 0?N.matchUpsCount+=D[U].length:N.matchUpsCount=D[U].length)}),N),{matchUpsCount:0}),groupInfo:h,participants:I}}function wd({scheduleVisibilityFilters:t,hydrateParticipants:e,participantsProfile:r,tournamentRecords:n,useParticipantMap:o,policyDefinitions:i,usePublishState:s,matchUpFilters:a,contextFilters:c,nextMatchUps:u,inContext:p}){if(typeof n!="object"||!Object.keys(n).length)return{error:kt};let d=Object.keys(n).map(I=>{let S=n[I];return Xf({scheduleVisibilityFilters:t,hydrateParticipants:e,participantsProfile:r,useParticipantMap:o,policyDefinitions:i,tournamentRecord:S,usePublishState:s,matchUpFilters:a,contextFilters:c,nextMatchUps:u,inContext:p})}),l={},f={};return{...d.reduce((I,S)=>(Object.keys(S).forEach(T=>{if(T==="groupInfo")Object.assign(f,S[T]);else if(T==="participants")for(let y of S[T]??[])l[y.participantId]=y;else Array.isArray(S[T])&&(I[T]||(I[T]=[]),I[T]=I[T].concat(S[T]))}),I),{}),groupInfo:f,mappedParticipants:l}}function am(t){if(typeof t?.tournamentRecords!="object"||!Object.keys(t?.tournamentRecords).length)return{error:kt};let{courts:e,venues:r}=kn(t),o=bo(t).schedulingProfile,{sortDateMatchUps:i=!0,courtCompletedMatchUps:s,alwaysReturnCompleted:a,activeTournamentId:c,tournamentRecords:u,withCourtGridRows:p,minCourtGridRows:m,usePublishState:d,status:l=br,sortCourtsData:f}=t,g=c??Fs()??Object.keys(u)[0],I=d?Uc({tournamentRecord:u[g],status:l}):void 0,S=a?wd({...t,matchUpFilters:{...t.matchUpFilters,matchUpStatuses:[ie]},contextFilters:t.contextFilters}).completedMatchUps:[];if(d&&!ro(I?.orderOfPlay))return{completedMatchUps:S,dateMatchUps:[],courtsData:[],venues:r};let h,T;d&&({drawIds:h,detailsMap:T}=_k({tournamentRecords:u})),h?.length&&(t.contextFilters??={},t.contextFilters.drawIds?t.contextFilters.drawIds=t.contextFilters.drawIds.filter(F=>h.includes(F)):t.contextFilters.drawIds=h);let y=I?.orderOfPlay;cQ(t,y);let E=uQ(t,y,{allCompletedMatchUps:S,alwaysReturnCompleted:a,venues:r});if(E)return E;pQ(t,a);let{completedMatchUps:A,upcomingMatchUps:N,pendingMatchUps:D,abandonedMatchUps:R,groupInfo:U,mappedParticipants:b}=wd({...t,matchUpFilters:t.matchUpFilters,contextFilters:t.contextFilters}),C=[...N??[],...D??[]];T&&(!h?.length||Object.keys(T).length)&&(C=C.filter(F=>mQ(F,T))),T&&d&&(C=C.filter(F=>dQ(F,T)));let _=i?zf({matchUps:C,schedulingProfile:o}):C,v=e?.map(F=>{let x=L(F);return{surfaceCategory:F?.surfaceCategory??"",matchUps:x,...F}}),w={completedMatchUps:a?S:A,mappedParticipants:t.hydrateParticipants?void 0:b,dateMatchUps:_,courtsData:v,groupInfo:U,venues:r};if(p){let F=t.matchUpFilters?.scheduledDate,{rows:x,courtPrefix:k}=qf({minRowsCount:Math.max(m||0,_.length||0),scheduledDate:F,courtsData:v});w.courtPrefix=k,w.rows=x}return{...w,...P};function L({courtId:F}){let k=(s?_.concat(A??[],R??[]):_).filter(G=>G.schedule?.courtId===F||G.schedule?.allocatedCourts?.map(({courtId:V})=>V).includes(F));return f?zf({matchUps:k,schedulingProfile:o}):k}}function cQ(t,e){e?.eventIds?.length&&(t.matchUpFilters??={},t.matchUpFilters?.eventIds&&t.matchUpFilters.eventIds.length?t.matchUpFilters.eventIds=t.matchUpFilters.eventIds.filter(r=>e.eventIds.includes(r)):t.matchUpFilters.eventIds=e.eventIds)}function uQ(t,e,{allCompletedMatchUps:r,alwaysReturnCompleted:n,venues:o}){if(!e?.scheduledDates?.length)return;t.matchUpFilters??={},t.matchUpFilters.scheduledDate&&!t.matchUpFilters.scheduledDates&&(t.matchUpFilters.scheduledDates=[t.matchUpFilters.scheduledDate]);let i=t.matchUpFilters.scheduledDates&&t.matchUpFilters.scheduledDates.length>0;if(t.matchUpFilters.scheduledDates&&t.matchUpFilters.scheduledDates.length?t.matchUpFilters.scheduledDates=t.matchUpFilters.scheduledDates.filter(s=>e.scheduledDates.includes(s)):t.matchUpFilters.scheduledDates=e.scheduledDates,i&&!t.matchUpFilters.scheduledDates?.length)return{completedMatchUps:n?r:[],dateMatchUps:[],courtsData:[],venues:o,...P};delete t.matchUpFilters.scheduledDate}function pQ(t,e){e&&(t.matchUpFilters??={},t.matchUpFilters?.excludeMatchUpStatuses?.length?t.matchUpFilters.excludeMatchUpStatuses.includes(ie)||t.matchUpFilters.excludeMatchUpStatuses.push(ie):t.matchUpFilters.excludeMatchUpStatuses=[ie])}function mQ(t,e){let{drawId:r,structureId:n,stage:o}=t;if(!ro(e?.[r]?.publishingDetail))return!1;let i=Object.keys(e[r].stageDetails??{});if(i.length){let a=i.filter(u=>!ro(e[r].stageDetails[u])),c=i.filter(u=>ro(e[r].stageDetails[u]));return a.length&&a.includes(o)?!1:c.length&&c.includes(o)?!0:a.length&&!a.includes(o)&&!c.length}let s=Object.keys(e[r].structureDetails??{});if(s.length){let a=s.filter(u=>!ro(e[r].structureDetails[u])),c=s.filter(u=>ro(e[r].structureDetails[u]));return a.length&&a.includes(n)?!1:c.length&&c.includes(n)?!0:a.length&&!a.includes(n)&&!c.length}return!0}function dQ(t,e){let{drawId:r,structureId:n,roundNumber:o}=t;if(!yt(o))return!0;let i=e[r]?.structureDetails?.[n];if(!i)return!0;let{scheduledRounds:s,roundLimit:a}=i;if(yt(a)&&o>a)return!1;if(s){let c=s[o];if(!c)return!0;if(!c.published)return!1;if(Uo(c))return t.schedule=void 0,!0}return!0}function ss(t,e){if(!Tt(t))return{error:O};if(!Array.isArray(e))return{error:O};let r={};for(let{param:n,error:o,attr:i}of e){let s=lQ({params:t,param:n,attr:i,error:o});if(s?.error)return s;r[n]=s}return r}function lQ({params:t,param:e,attr:r,error:n}){if(e===mc&&Tt(t.drawDefinition)&&wt(t.structureId)){let o=(t.drawDefinition.structures??[]).find(({structureId:i})=>i===t.structureId);return!o.length&&n?{error:n}:{structure:o}}if(e===Rn){let o=ev({...t,...r});return o.error&&n?{...o,error:n}:o}return{error:fe,info:{param:e}}}function MP(t){let{structureId:e,matchUpId:r,event:n}=t,o=t.drawDefinition,i=X(t,[{[rt]:!0},{[yp]:{[mo]:!1,[wr]:!1,[dc]:!1,[ce]:!1}}]);if(i[jr])return i;let a=ss(t,[{[Gi]:Rn,[jr]:nt}])?.matchUp;if(r&&a?.error)return a;!o&&a?.drawDefinition&&(o=a?.drawDefinition);let c=a?.structure;if(!c&&e&&!r){if(!o)return{error:Nn};let l=tt({drawDefinition:o,structureId:e});if(l.error)return l;c=l.structure}let u=c?.competitionFormat,p=o?.competitionFormat,m=n?.competitionFormat;return{...P,structureDefaultCompetitionFormat:u,drawDefaultCompetitionFormat:p,eventDefaultCompetitionFormat:m,competitionFormat:u||p||m}}function Jf({tournamentRecords:t,tournamentId:e}){if(typeof t!="object"||!Object.keys(t).length)return{error:kt};let r=Object.keys(t).filter(o=>!e||o===e),n;return r.forEach(o=>{let i=t[o],{matchUpDailyLimits:s}=fQ({tournamentRecord:i});n=s}),{matchUpDailyLimits:n}}function fQ(t){let e=X(t,[{[rt]:!0}]);if(e.error)return e;let{tournamentRecord:r}=t,{policy:n}=go({policyType:ko,tournamentRecord:r}),{extension:o}=ot({element:r,name:Np}),i=o?.value?.dailyLimits,s=n?.defaultDailyLimits;return{matchUpDailyLimits:i||s}}function vP(t){let{matchUps:e}=t,{singlesForDoubles:r,tournamentRecord:n,drawDefinition:o,excludeMargin:i,exclusionRule:s,zoneDoubling:a,matchUpType:c,scaleName:u,eventId:p,zonePct:m,drawId:d,event:l}=t;if(!n&&!e)return{error:j};if(c&&![Ct,Rt].includes(c))return{error:O,info:{matchUpType:c}};if(e&&!Rr(e))return{error:O,context:{matchUps:e}};let f=Ke[u],g=f?.ascending??t.ascending??!1,I=f?.accessor??t.valueAccessor,S=Array.isArray(f?.range)?Math.abs(f.range[0]-f.range[1]):0,h=yt(m)&&S?(m??0/100)*S:t.zoneMargin??S,T={withScaleValues:!0,withCompetitiveness:!0},y={matchUpTypes:c?[c]:[Ct,Rt]},E=n?.participants;e?.[0]?.hasContext?d?e=e.filter(v=>v.drawId===d):p&&(e=e.filter(v=>v.eventId===p)):e??=d&&!o&&[]||!d&&p&&!l&&[]||d&&rr({inContext:!0,drawDefinition:o,contextFilters:y,contextProfile:T,participants:E})?.matchUps||!d&&p&&vn({inContext:!0,contextFilters:y,contextProfile:T,participants:E,event:l})?.matchUps||qt({tournamentRecord:n,contextFilters:y,contextProfile:T})?.matchUps||[],c&&(e=e.filter(v=>v.matchUpType===c));let A=e.filter(({winningSide:v,score:w,sides:L,matchUpStatus:F})=>![De,Mt,vt,Rp,Fr].includes(F??"")&&ue({score:w})&&L?.length===2&&v),N=IQ({matchUps:A,excludeMargin:i,exclusionRule:s,valueAccessor:I,ascending:g,scaleName:u}),D=!a||re(Ct)(c)?h:(h||0)*2,R=h?A.map(({competitiveProfile:v,matchUpType:w,score:L,sides:F})=>{let x=wk({singlesForDoubles:r,valueAccessor:I,matchUpType:w,scaleName:u,sides:F}),k=Math.abs(x[0].value-x[1].value);return{competitiveness:v?.competitiveness,valuesGap:k,score:L}}).filter(({valuesGap:v})=>v<=D):[],U=gQ({zoneData:R}),b=U&&Object.values(U).flat().length,C=b&&Object.assign({},...Object.keys(U).map(v=>({[v]:Math.round(1e4*U[v].length/b)/100}))),_=A.length-(R?.length||0);return{...P,relevantMatchUps:A,zoneDistribution:C,zoneData:R,accuracy:N,nonZone:_}}function gQ({zoneData:t}){let e={[xl]:[],[gu]:[],[Iu]:[]};for(let r of t){let{competitiveness:n,score:o,valuesGap:i}=r;e[n]&&e[n].push({score:o,valuesGap:i})}return e}function wk({singlesForDoubles:t,exclusionRule:e,valueAccessor:r,matchUpType:n,scaleName:o,sides:i}){let s=e?.range.slice().sort((c,u)=>c-u),a=c=>{let u=c?.[e?.valueAccessor];return{exclude:e&&u>=s[0]&&u<=s[1],exclusionValue:u}};return i.sort((c,u)=>c.sideNumber-u.sideNumber).map(({participant:c})=>{let u=[],p=c?.individualParticipants;if(p?.length){let m=[],d=0;for(let l of p){let{scaleValue:f,value:g}=xk({singlesForDoubles:t,valueAccessor:r,participant:l,matchUpType:n,scaleName:o}),{exclude:I,exclusionValue:S}=a(f);I&&u.push(S),m.push(f),g&&!Number.isNaN(Number(d))?d+=g:d=void 0}return{participantName:c.participantName,exclusionValues:u,scaleValues:m,value:d}}else if(c){let{scaleValue:m,value:d}=xk({singlesForDoubles:t,valueAccessor:r,matchUpType:n,participant:c,scaleName:o}),{exclude:l,exclusionValue:f}=a(m);return l&&u.push(f),{participantName:c.participantName,exclusionValues:u,scaleValue:m,value:d}}else return{}})}function xk({singlesForDoubles:t,valueAccessor:e,matchUpType:r,participant:n,scaleName:o}){let i=t?Ct:r,s=n?.rankings?.[i]?.find(p=>p.scaleName===o),c=(n?.ratings?.[i]?.find(p=>p.scaleName===o)||s)?.scaleValue,u=e?c?.[e]:c;return{scaleValue:c,value:u}}function IQ({excludeMargin:t,exclusionRule:e,valueAccessor:r,ascending:n,scaleName:o,matchUps:i}){let s={affirmative:[],negative:[],excluded:[]};for(let u of i)SQ({matchUp:u,accuracy:s,excludeMargin:t,exclusionRule:e,valueAccessor:r,ascending:n,scaleName:o});let a=s.affirmative.length+s.negative.length,c=a&&s.affirmative.length/a*100;return s.percent=c?Math.round(100*c)/100:0,s}function SQ({matchUp:t,accuracy:e,excludeMargin:r,exclusionRule:n,valueAccessor:o,ascending:i,scaleName:s}){let{matchUpType:a,sides:c,score:u,winningSide:p}=t;if(!p)return;if(n&&(!n.valueAccessor||!n.range)){e.error={info:"exclusionRule requires valueAccessor and range",error:nt};return}let m=p-1,d=wk({exclusionRule:n,valueAccessor:o,matchUpType:a,scaleName:s,sides:c});if(hQ({exclusionRule:n,sideValues:d,accuracy:e,score:u,winningSide:p}))return;if(TQ(d)){e.excluded.push({scoreString:u?.scoreStringSide1,missingValues:!0,winningSide:p,sideValues:d});return}let l=d[m].value-d[1-m].value;if(yQ({excludeMargin:r,valuesGap:l})){e.excluded.push({scoreString:u?.scoreStringSide1,excludeMargin:r,winningSide:p,excludeGap:!0,sideValues:d,valuesGap:l});return}let f=i?-l:l,g=p===1?u?.scoreStringSide1:u?.scoreStringSide2;f>0?e.affirmative.push({winningScoreString:g,winningSide:p,sideValues:d,valuesGap:l,score:u}):e.negative.push({winningScoreString:g,winningSide:p,sideValues:d,valuesGap:l,score:u})}function hQ({exclusionRule:t,sideValues:e,accuracy:r,score:n,winningSide:o}){if(t){let i=e.flatMap(({exclusionValues:s})=>s);if(i.length)return r.excluded.push({scoreString:n?.scoreStringSide1,exclusionValues:i,winningSide:o,sideValues:e}),!0}return!1}function TQ(t){return t.filter(e=>![void 0,"",null].includes(e.value)).length<2}function yQ({excludeMargin:t,valuesGap:e}){let r=Number.parseFloat(t||0);return r&&Math.abs(e)<r}function OP({matchUps:t,matchUpId:e}){if(!Rr(t))return{error:O};let r=t.find(a=>a.matchUpId===e),{drawId:n,eventId:o,structureId:i,tournamentId:s}=r??{};return{matchUpId:e,drawId:n,eventId:o,structureId:i,tournamentId:s}}function _P(t){let{timeStamp:e,schedule:r,matchUp:n}=t,o=X(t,[{[Rn]:!0}]);if(o.error)return o;let{itemValue:i,timeStamp:s}=Ii({timeItems:n?.timeItems??[],itemType:Wl});return!r||s&&e&&new Date(s).getTime()>new Date(e).getTime()?{homeParticipantId:i}:r}function ua({collectionDefinitions:t=[],collectionGroups:e=[]}){let r=0,{groupValueNumbers:n}=eA({collectionGroups:e}),o;for(let s of t??[]){let{collectionValueProfiles:a,collectionGroupNumber:c,collectionValue:u,matchUpCount:p,matchUpValue:m,scoreValue:d,setValue:l}=s,f=c&&n.includes(c);if(yt(l||d))o=!0;else{if(f)continue;if(typeof u=="number"&&yt(u))r+=u;else if(Array.isArray(a)&&a?.length)for(let g of a)r+=g.matchUpValue;else typeof m=="number"&&yt(m)&&(r+=(p??0)*m)}}for(let s of e)r+=s.groupValue??0;return o||!r?{aggregateValue:!0,...P}:{valueGoal:Math.floor(r/2)+1,...P}}function xP(t){let{structureId:e,matchUpId:r,event:n}=t,o=t.drawDefinition,i=X(t,[{[rt]:!0},{[yp]:{[mo]:!1,[wr]:!1,[dc]:!1,[ce]:!1}}]);if(i[jr])return i;let a=ss(t,[{[Gi]:Rn,[jr]:nt}])?.matchUp;if(r&&a?.error)return a;!o&&a?.drawDefinition&&(o=a?.drawDefinition);let c=a?.structure;if(!c&&e&&!r){if(!o)return{error:Nn};let l=tt({drawDefinition:o,structureId:e});if(l.error)return l;c=l.structure}let u=c?.matchUpFormat,p=o?.matchUpFormat,m=n?.matchUpFormat,d=a?.matchUp?.matchUpFormat||u||p||m;return{structureDefaultMatchUpFormat:u,eventDefaultMatchUpFormat:m,drawDefaultMatchUpFormat:p,matchUpFormat:d}}function wP({profileBands:t,tournamentRecord:e,matchUps:r}){if(!Rr(r))return{error:Bn};let n=!t&&go({policyType:gn,tournamentRecord:e}).policy,o=t||n?.profileBands||Hs[gn].profileBands,i=r.filter(({winningSide:l})=>l),s=i.filter(({matchUpStatus:l})=>l===vt||l===Mt).length,a=i.map(Fl),c=(l,f)=>{let g=iE(f,o);return l[g]+=1,l},u=sE(a).reduce((l,f)=>c(l,f),{[xl]:0,[gu]:0,[Iu]:0,[rE]:s}),p=Object.keys(u).reduce((l,f)=>(u[f]||0)+l,0),m=Object.keys(u).map(l=>{let f=Number.parseFloat((u[l]/p).toFixed(4));return{[l]:f*100}}),d=i.filter(({matchUpStatus:l})=>l===Ib).length;return m.push({[Ib]:Number.parseFloat((d/p).toFixed(4))*100}),{competitiveBands:Object.assign({},...m),...P}}var{stageOrder:Lk}=zw;function Fk(t,e){return t.eventName.localeCompare(e.eventName)||t.eventId.localeCompare(e.eventId)||(Lk[t?.stage]||0)-(Lk[e?.stage]||0)||e.matchUpsCount-t.matchUpsCount||`${t.stageSequence}-${t.roundNumber}-${t.minFinishingSum}`.localeCompare(`${e.stageSequence}-${e.roundNumber}-${e.minFinishingSum}`)}function LP({excludeScheduleDateProfileRounds:t,excludeScheduledRounds:e,excludeCompletedRounds:r,inContextMatchUps:n,tournamentRecords:o,schedulingProfile:i,tournamentRecord:s,withSplitRounds:a,matchUpFilters:c,scheduleDate:u,withRoundId:p,venueId:m,context:d}){if(n&&!Array.isArray(n||typeof n[0]!="object"))return{error:O,inContextMatchUps:n};if(s&&!o)if(typeof s=="object")o={[s.tournamentId]:s};else return{error:Hc};let l=typeof o!="object"||!Object.keys(o).length;if((m||u||!n||!i&&(t||r||i||a))&&l)return{error:kt};let g=Object.assign({},...Object.values(o??{}).map(({venues:N=[],tournamentId:D})=>({[D]:N?.map(({venueId:R})=>R)}))),I=Object.values(o??{}).flatMap(({events:N=[],tournamentId:D,startDate:R,endDate:U})=>N.map(b=>({...b,validVenueIds:g[D],startDate:b.startDate??R,endDate:b.endDate??U}))),{segmentedRounds:S,profileRounds:h}=o&&(t||r||i||a)&&jf({tournamentRecords:o,schedulingProfile:i})||{},T=t&&Object.assign({},...h.map(N=>({[N.id]:N}))),y=n||o&&cn({tournamentRecords:o,matchUpFilters:c})?.matchUps||[],E=[],A=y&&Object.values(y.reduce((N,D)=>{let R=uh(D).id,U=S?.[R],b=[...N[R]?.matchUps??[],D],{containerStructureId:C,stageSequence:_,structureName:v,tournamentId:w,isRoundRobin:L,matchUpType:F,roundNumber:x,roundOffset:k,structureId:G,eventName:V,roundName:B,drawName:z,eventId:H,drawId:K}=D,Y=L?C:G;return{...N,[R]:{id:p?R:void 0,structureId:Y,stageSequence:_,segmentsCount:U,structureName:v,tournamentId:w,matchUpType:F,roundNumber:x,roundOffset:k,eventName:V,roundName:B,drawName:z,matchUps:b,eventId:H,drawId:K}}},{})).flatMap(N=>{let{minFinishingSum:D,winnerFinishingPositionRange:R}=Mk(N.matchUps),U=N.segmentsCount;if(U){let x=N.matchUps.length/U;return he(N.matchUps.sort((G,V)=>G.roundPosition-V.roundPosition),x).map((G,V)=>{let{unscheduledCount:B,incompleteCount:z,matchUpsCount:H,isScheduled:K,isComplete:Y,byeCount:J}=sv(G),ct=iv({matchUps:N.matchUps,tournamentRecords:o,events:I,round:N});return et({...N,...d,roundSegment:{segmentsCount:U,segmentNumber:V+1},winnerFinishingPositionRange:R,unscheduledCount:B,incompleteCount:z,minFinishingSum:D,matchUpsCount:H,isScheduled:K,roundTiming:ct,isComplete:Y,byeCount:J,matchUps:G})})}let{unscheduledCount:b,incompleteCount:C,matchUpsCount:_,isScheduled:v,isComplete:w,byeCount:L}=sv(N.matchUps),F=iv({matchUps:N.matchUps,tournamentRecords:o,events:I,round:N});return et({...N,...d,winnerFinishingPositionRange:R,unscheduledCount:b,incompleteCount:C,minFinishingSum:D,matchUpsCount:_,isScheduled:v,roundTiming:F,isComplete:w,byeCount:L})}).filter(N=>{if(t){let G=mt(t),V=p?N.id:uh(N).id;if(G&&T[V]&&mt(T[V].scheduleDate)===G)return!1}let{isComplete:D,isScheduled:R}=N,U=!r||!D,b=!e||!R,C=m||u?I?.find(({eventId:G})=>G===N.eventId):void 0,_=C?.startDate??s?.startDate,v=C?.endDate??s?.endDate,w=!u||!_||new Date(u)>=new Date(_),L=!u||!v||new Date(u)<=new Date(v),F=w&&L,x=!m||C?.validVenueIds.includes(m),k=U&&b&&x&&F;return k||E.push(N),k}).sort(Fk)||[];return{...P,rounds:A,excludedRounds:E}}function FP({participants:t,tournamentAppliedPolicies:e,scheduleVisibilityFilters:r,participantsProfile:n,afterRecoveryTimes:o,policyDefinitions:i,useParticipantMap:s,tournamentRecord:a,usePublishState:c,contextFilters:u,contextContent:p,matchUpFilters:m,participantMap:d,publishStatus:l,contextProfile:f,drawDefinition:g,nextMatchUps:I,tournamentId:S,inContext:h,context:T,event:y}){let{eventId:E,eventName:A,endDate:N,eventType:D,category:R,gender:U}=y??{},b={...T,...et({surfaceCategory:y?.surfaceCategory??a?.surfaceCategory,indoorOutDoor:y?.indoorOutdoor??a?.indoorOutdoor,endDate:N??y?.endDate??a?.endDate,tournamentId:S??a?.tournamentId,eventName:A,eventType:D,category:R,eventId:E,gender:U})},C;return!t?.length&&a&&({participants:t,participantMap:d,groupInfo:C}=di({participantsProfile:n,policyDefinitions:i,useParticipantMap:s,tournamentRecord:a,contextProfile:f,inContext:h})),y&&f&&!p&&(p=eo({policyDefinitions:i,tournamentRecord:a,contextProfile:f,drawDefinition:g,event:y})),{...Ga({context:b,tournamentAppliedPolicies:e,scheduleVisibilityFilters:r,tournamentParticipants:t,participantsProfile:n,afterRecoveryTimes:o,policyDefinitions:i,tournamentRecord:a,usePublishState:c,participantMap:d,contextContent:p,contextFilters:u,matchUpFilters:m,publishStatus:l,contextProfile:f,drawDefinition:g,nextMatchUps:I,inContext:h,event:y}),groupInfo:C}}function Ld(t){let{matchUp:e,sideNumber:r,setNumber:n,isTiebreakValue:o,isPointValue:i}=t??{},{matchUpFormat:s}=t??{};if(!e)return{error:Xe};s=s||e?.matchUpFormat;let a=oe(s),c=!!e?.winningSide,u=e.score?.sets,p=u?.length,m=n&&n-1,d=!!u?.find((Y,J)=>Y.setNumber===n&&J===m),l=u?.filter(Y=>Y?.winningSide)??[],f=l?.length||0,g=(n&&u?.slice(n))??[],I=!!(p&&n&&g?.reduce((Y,J)=>(!J||!J.side1Score&&!J.side2Score&&!J.side1TiebreakScore&&!J.side2TiebreakScore&&!J.side1PointScore&&!J.side2PointScore)&&Y,!0)),S=n<=p&&u.find(Y=>Y.setNumber===n),h=S&&om({setObject:S,matchUpScoringFormat:a}),{isCompletedSet:T,sideGameScores:y,sideTiebreakScores:E}=h??{},A=!!(S&&!T&&I||n&&n===p+1&&!c),N=[1,2].includes(r),D=N?r-1:0,R=S&&N&&(!o&&!i&&y[D]!==void 0&&y[D]||o&&E[D]!==void 0&&E[D]),U=!!R,b=l?.map(Y=>om({setObject:Y,matchUpScoringFormat:a}).isValidSetOutcome).reduce((Y,J)=>Y&&J,!0),C=l.reduce((Y,J)=>{let{winningSide:ct}=J,Et=ct-1;return Y[Et]++,Y},[0,0]),_=e?.winningSide,v=_&&_-1,w=1-v,L=C[v],F=C[w],x=Math.max(...C),k=mn(C)[x],{bestOf:G,exactly:V}=a??{},B=Math.ceil((G||V||1)/2),z=x===B&&k===1&&C.indexOf(x)+1||void 0,H=L>F&&_===z;return{completedSetsHaveValidOutcomes:b,validMatchUpWinningSide:H,calculatedWinningSide:z,matchUpScoringFormat:a,validMatchUpOutcome:z&&b&&H,isLastSetWithValues:I,completedSetsCount:f,isCompletedMatchUp:c,isValidSideNumber:N,hasExistingValue:U,existingValue:R,isExistingSet:d,isActiveSet:A,...h}}var lv={};Gt(lv,{getCompetitionVenues:()=>hd,getCourts:()=>kP,getVenuesAndCourts:()=>kn,publicFindVenue:()=>IE});function kP({tournamentRecord:t,venueId:e,venueIds:r}){return t?{courts:(t.venues??[]).filter(o=>e?o.venueId===e:r?r.includes(o.venueId):!0).map(o=>{let{venueId:i}=o,s=q(o.courts??[]);return s.forEach(a=>Object.assign(a,{venueId:i})),s}).flat()}:{error:j}}var gv={};Gt(gv,{categoryCanContain:()=>fp,getCategoryAgeDetails:()=>gs,getEvent:()=>BP,getEventProperties:()=>GP,getEventStructures:()=>RS,getEventTimeItem:()=>xp,getEvents:()=>VP,getFlightProfile:()=>Bt,getScaledEntries:()=>Xa});function GP({tournamentRecord:t,event:e}){let r=dt({tournamentRecord:t,event:e},[rt,ce]);if(r.error)return r;let n=e.entries??[],o=t.participants??[],i=e.category?.categoryName||e.category?.ageCategoryCode,{eventType:s}=e,a=new Set(n.map(l=>l.participantId)),c=o.filter(l=>a.has(l.participantId)),u,p,m;return{entryScaleAttributes:c.map(l=>{let{participantId:f,participantName:g,name:I}=l,S={scaleType:sS,eventType:s,scaleName:i},h=Po({participant:l,scaleAttributes:S})?.scaleItem?.scaleValue;S={scaleType:Eb,eventType:s,scaleName:i};let T=Po({participant:l,scaleAttributes:S})?.scaleItem?.scaleValue;S={scaleType:yb,eventType:s,scaleName:i};let y=Po({participant:l,scaleAttributes:S})?.scaleItem?.scaleValue;return u=!!(u||h),p=!!(p||T),m=!!(m||y),{participantId:f,participantName:g||I,seed:h,ranking:T,rating:y}}),hasSeededParticipants:u,hasRankedParticipants:p,hasRatedParticipants:m}}function EQ(t){return t.reduce((e,r)=>e+Number.parseFloat(r),0)}function kk(t){let e={};for(let r of Object.keys(t)){let n=t[r];if(!n.length)continue;let o=iw(n)?.toFixed(2);e[r]={avg:Number.parseFloat((EQ(n)/n.length).toFixed(2)),median:o?Number.parseFloat(o):void 0,max:Math.max(...n),min:Math.min(...n)}}return e}function Gk(t,e,r){if(t?.ratings?.[e])for(let n of t?.ratings?.[e]??[]){let o=n.scaleName;r.ratings[o]||(r.ratings[o]=[]);let i=Ke[o]?.accessor;if(i){let s=Number.parseFloat(n.scaleValue?.[i]);s&&r.ratings[o].push(s)}}if(t?.rankings?.[e])for(let n of t?.rankings?.[e]??[]){let o=n.scaleName;r.ranking[o]||(r.ranking[o]=[]),n.scaleValue&&r.ranking[o].push(n.scaleValue)}}function fv(t,e,r,n){for(let o of t.filter(Boolean)){let i=e?.[o]?.participant;if(i?.participantType===St)Gk(i,r,n);else for(let s of i?.individualParticipantIds??[]){let a=e?.[s]?.participant;Gk(a,r,n)}}}function AQ({eventCopies:t,scaleEventType:e,tournamentRecord:r,drawIds:n}){let o={},i=bt({withScaleValues:!0,tournamentRecord:r}).participantMap;for(let s of t){let a=e??s.eventType,c=s.eventId;o[c]||(o[c]={ratingsStats:{},ratings:{},ranking:{},draws:{}});let p=(s.entries??[]).filter(({entryStatus:f})=>yr.includes(f)).map(gt);fv(p,i,a,o[c]),o[c].ratingsStats=kk(o[c].ratings);let m=[],d=f=>n?.length&&n.includes(f)||m.includes(f);for(let f of s.drawDefinitions??[]){let g=f.drawId;if(d(g))continue;let I=Ji({drawDefinition:f}).assignedParticipantIds??[];o[c].draws[g]||(o[c].draws[g]={ratingsStats:{},ratings:{},ranking:{}}),m.push(g),fv(I,i,a,o[c].draws[g])}let l=Bt({event:s}).flightProfile;for(let f of l?.flights??[]){let g=f.drawId;if(d(g))continue;let I=f.drawEntries.map(gt);fv(I,i,a,o[c].draws[g])}for(let f of m)o[c].draws[f].ratingsStats=kk(o[c].draws[f].ratings)}return o}function VP({tournamentRecord:t,withScaleValues:e,scaleEventType:r,inContext:n,eventIds:o,drawIds:i,context:s}){if(!t)return{error:j};let{tournamentId:a}=t,c=(t.events??[]).filter(({eventId:p})=>!o||Array.isArray(o)&&o.includes(p)).map(p=>{let m=p.drawDefinitions?.map(Tc);if(i?.length&&!Yt(i,m).length)return;let d=q(p);return n&&Object.assign(d,{tournamentId:a}),s&&Object.assign(d,s),d}).filter(Boolean),u=e?AQ({eventCopies:c,scaleEventType:r,tournamentRecord:t,drawIds:i}):{};return et({eventScaleValues:u,events:c,...P})}function BP({tournamentRecord:t,drawDefinition:e,context:r,event:n}){let o=dt({tournamentRecord:t,event:n},[rt,ce]);if(o.error)return o;let i=q(n);r&&Object.assign(i,r);let s=e&&i.drawDefinitions?.find(({drawId:a})=>e.drawId===a);return et({drawDefinition:s,event:i})}function Vk(t){let e="validateAndDeriveDrawValues",{appliedPolicies:r,policyDefinitions:n}=DQ(t),o=UQ({...t,policyDefinitions:n,appliedPolicies:r}),i=NQ(t),s=RQ({...t,consideredEntries:i,appliedPolicies:r});if(s?.error)return M({result:s,stack:e});let a=bQ({...t,consideredEntries:i}),c=PQ({...t,appliedPolicies:r,policyDefinitions:n,drawSize:a});if(c.error)return M({result:c,stack:e});let u=c.drawType;if(Number.isNaN(a)&&!yn(u))return M({result:{error:$c},stack:e});let p=n?.[Hn]??r?.[Hn],m=t.seedingProfile??p?.seedingProfile?.drawTypes?.[u??""]??p?.seedingProfile;t.seedingProfile&&(n[Hn]||(n[Hn]={...oh[Hn]}),n[Hn].seedingProfile=m);let d=CQ({...t,drawType:u});return d?.error?M({result:d,stack:e}):{drawSize:a,drawType:u,enforceGender:o,seedingProfile:m,appliedPolicies:r,policyDefinitions:n}}function PQ(t){let{policyDefinitions:e,appliedPolicies:r,enforceMinimumDrawSize:n=!0,drawSize:o}=t,i=t.drawTypeCoercion??em({drawType:t.drawType,policyDefinitions:e,appliedPolicies:r}),s=MA({drawType:t.drawType,enforceMinimumDrawSize:n,drawTypeCoercion:i,drawSize:o});return s.error?s:{drawType:s.drawType}}function Sv(t){return t?.filter(e=>e.entryStatus&&[...yr,Ll].includes(e.entryStatus))}function NQ({considerEventEntries:t=!0,drawEntries:e,eventEntries:r,qualifyingOnly:n}){return(n&&[]||Sv(e)||(t?r:[])).filter(({entryStage:o})=>!o||o===W)}function DQ(t){let{tournamentRecord:e,event:r}=t,n={...t?.appliedPolicies,...ft({tournamentRecord:e,event:r}).appliedPolicies},o=q(t.policyDefinitions??{},!1,!0);return{appliedPolicies:n,policyDefinitions:o}}function UQ({enforceGender:t,policyDefinitions:e,appliedPolicies:r}){return t??e?.[He]?.participants?.enforceGender??r?.[He]?.participants?.enforceGender}function RQ(t){let{consideredEntries:e,appliedPolicies:r,policyDefinitions:n,enforceGender:o,participantMap:i,participants:s,event:a}=t;return a&&s&&Nf({consideredEntries:e,policyDefinitions:n,appliedPolicies:r,participantMap:i,enforceGender:o,participants:s,event:a})}function bQ(t){return!t.drawSize&&t.consideredEntries.length&&![Ni,Gs,pc,hr,Tr,Bs].includes(t.drawType??"")&&Pi(t.consideredEntries.length)||t.drawSize&&st(t.drawSize)||!1}function CQ(t){let{tournamentRecord:e,event:r,ignoreAllowedDrawTypes:n,drawType:o}=t,i=!n&&e&&kf({tournamentRecord:e,categoryType:r?.category?.categoryType,categoryName:r?.category?.categoryName});return i?.length&&!i.includes(o)?{error:ol}:{...P}}function xc(t){let{voluntaryConsolation:e,withPlayoffs:r,targetMatchUpIds:n,tournamentRecord:o,event:i}=t,s="generateDrawDefinition",{participants:a,participantMap:c}=bt({withIndividualParticipants:!0,convertExtensions:!0,internalUse:!0,tournamentRecord:o}),u=Sv(i?.entries)??[],p=Vk({...t,participantMap:c,participants:a,eventEntries:u});if(p.error)return M({result:p,stack:s});let{appliedPolicies:m,policyDefinitions:d,drawSize:l,drawType:f,enforceGender:g,seedingProfile:I}=p,S=i?.eventType,h=t.matchUpType??S,T=ok({...t,enforceGender:g,eventType:S,matchUpType:h});if(T.error)return M({result:T,stack:s});let{matchUpFormat:y,tieFormat:E}=T;if(t.drawId&&typeof t.drawId!="string")return M({result:{error:O},stack:s});let N=Ik({...t,policyDefinitions:d,tournamentRecord:o,appliedPolicies:m,matchUpFormat:y,seedingProfile:I,participants:a,eventEntries:u,matchUpType:h,tieFormat:E,drawSize:l,drawType:f,event:i});if(N.error)return M({result:N,stack:s});let{existingDrawDefinition:D,positioningReports:R,drawDefinition:U,structureId:b,conflicts:C,entries:_}=N;if(!U)return M({result:{error:O},stack:s});let v=Sk({...t,existingDrawDefinition:D,positioningReports:R,appliedPolicies:m,drawDefinition:U,seedingProfile:I,participants:a,structureId:b,entries:_,params:t,stack:s});if(v.error)return v;let{qualifyingConflicts:w}=v;if(U.drawName=t.drawName??(f&&xe(f)),l&&typeof e=="object"&&l>=4&&gS({...e,drawDefinition:U,matchUpType:h}),r&&b){let L=Bk({withPlayoffs:r,tournamentRecord:o,drawDefinition:U,structureId:b,event:i,idPrefix:t.idPrefix,isMock:t.isMock});if(L?.error)return M({result:L,stack:s})}return t.hydrateRoundNames&&m?.[Fo]&&tP({drawDefinition:U,appliedPolicies:m}),n?.length&&DS({targetMatchUpIds:n,drawDefinition:U}),{existingDrawDefinition:!!D,qualifyingConflicts:w,positioningReports:R,drawDefinition:U,structureId:b,...P,conflicts:C}}function Bk({withPlayoffs:t,drawDefinition:e,structureId:r,...n}){let{roundPlayoffs:o,...i}=t,s=new Set(e.links?.filter(c=>c.linkType===ir&&c.source?.structureId===r).map(c=>c.source?.roundNumber)??[]),a=GS({...i,drawDefinition:e,structureId:r,...n});if(a?.error)return a;if(o){let c=e.links?.filter(u=>u.linkType===ir&&u.source?.structureId===r&&!s.has(u.source?.roundNumber))??[];for(let[u,p]of Object.entries(o)){let m=Number(u),d=c.find(l=>l.source?.roundNumber===m);if(d){let l=Bk({withPlayoffs:p,structureId:d.target?.structureId,drawDefinition:e,...n});if(l?.error)return l}}}return a}function Wk({participantIds:t,adHocRatings:e,allowDraws:r,matchUps:n}){let o=n.filter(f=>f.winningSide),{scoreGroups:i,records:s}=Pf({matchUps:o,participantIds:t,allowDraws:r}),{encounters:a}=_A({matchUps:[...n]}),c=new Set(a),u=o.length===0,p,m=[...t];if(m.length%2!==0){p=MQ({scoreGroups:i,records:s,adHocRatings:e});let f=m.indexOf(p);f>=0&&m.splice(f,1);for(let g of i){let I=g.participantIds.indexOf(p);if(I>=0){g.participantIds.splice(I,1);break}}}let d=[],l=new Set;if(u){let f=Hk(m,e),g=Math.floor(f.length/2);for(let I=0;I<g;I++)d.push({participantIds:[f[I],f[g+I]]}),l.add(f[I]),l.add(f[g+I])}else{let f=i.map(I=>[...I.participantIds]);for(let I=0;I<f.length;I++){let S=f[I].filter(T=>!l.has(T));if(S.length%2!==0&&I<f.length-1){let T=vQ({group:S,adHocRatings:e}),y=S.indexOf(T);S.splice(y,1),f[I+1].push(T)}let h=OQ({participantIds:S,encounterSet:c,adHocRatings:e});for(let T of h)d.push(T),l.add(T.participantIds[0]),l.add(T.participantIds[1])}let g=m.filter(I=>!l.has(I));for(let I=0;I<g.length-1;I+=2)d.push({participantIds:[g[I],g[I+1]]})}return{participantIdPairings:d,scoreGroups:i,records:s,byeParticipantId:p}}function Hk(t,e){return[...t].sort((r,n)=>{let o=e?.[r]??0;return(e?.[n]??0)-o})}function MQ({scoreGroups:t,records:e,adHocRatings:r}){let n=t.at(-1);return n?[...n.participantIds].sort((i,s)=>{let a=e.get(i),c=e.get(s),u=(a?.points??0)-(c?.points??0);return u!==0?u:(r?.[i]??0)-(r?.[s]??0)})[0]:""}function vQ({group:t,adHocRatings:e}){return[...t].sort((n,o)=>{let i=e?.[n]??0,s=e?.[o]??0;return i-s})[0]}function OQ({participantIds:t,encounterSet:e,adHocRatings:r}){if(t.length<2)return[];let n=Hk(t,r),o=Math.floor(n.length/2),i=n.slice(0,o),s=n.slice(o),a=[],c=new Set;for(let u of i){let p=-1,m=1/0;for(let d=0;d<s.length;d++){if(c.has(d))continue;let l=s[d],f=sa(u,l);if(e.has(f))continue;let g=Math.abs((r?.[u]??0)-(r?.[l]??0));g<m&&(m=g,p=d)}if(p===-1){for(let d=0;d<s.length;d++)if(!c.has(d)){p=d;break}}p>=0&&(c.add(p),a.push({participantIds:[u,s[p]]}))}return a}function Yk(t){let{drawDefinition:e,tournamentRecord:r,event:n}=t;if(!e)return{error:$};let o=t.structureId?tt({drawDefinition:e,structureId:t.structureId}).structure:e.structures?.find(h=>h.stage==="MAIN"&&Ae({structure:h}))??e.structures?.find(h=>Ae({structure:h}));if(!o)return{error:Nt};let i=wf({...t,restrictEntryStatus:!0,targetStage:o.stage});if(i.error)return i;let s=i.participantIds??[],a=o.positionAssignments?.map(h=>h.participantId).filter(h=>!!h)??[],c=_Q({drawDefinition:e,targetStructureId:o.structureId}),u=Array.from(new Set([...s,...a,...c])),{competitionPolicy:p}=Ao({tournamentRecord:r,drawDefinition:e,event:n}),{competitionState:m}=p?Wo({drawDefinition:e}):{competitionState:void 0},d;if(p&&m&&p.pairingPolicy.ratingSource==="DYNAMIC_FORM"){d={};for(let[h,T]of Object.entries(m.participantStates))d[h]=T.dynamicFormRating}else d=Ul({participantIds:u,tournamentRecord:r,scaleName:t.scaleName,event:n});let l=t.swissPolicy??ot({element:e,name:"swissPolicy"})?.extension?.value,f=o.matchUps??[],{participantIdPairings:g,byeParticipantId:I}=Wk({allowDraws:l?.allowDraws,matchUps:f,participantIds:u,adHocRatings:d}),S=Mc({structureId:o.structureId,participantIdPairings:g,matchUpIds:t.matchUpIds,idPrefix:t.idPrefix,isMock:t.isMock,drawDefinition:e,newRound:!0,event:n});return S.error?S:{roundNumber:S.roundNumber,matchUps:S.matchUps,byeParticipantId:I,...P}}function _Q({drawDefinition:t,targetStructureId:e}){let n=(t.links??[]).filter(i=>i.linkType===Pr&&i.target?.structureId===e),o=[];for(let i of n){let s=t.structures?.find(u=>u.structureId===i.source?.structureId);if(s?.stage!==Z)continue;let a=i.source?.roundNumber;if(!a)continue;let{matchUps:c}=ht({matchUpFilters:{roundNumbers:[a],isCollectionMatchUp:!1,hasWinningSide:!0},afterRecoveryTimes:!1,structure:s,inContext:!0});for(let u of c??[]){let p=u.sides?.find(m=>m?.sideNumber===u.winningSide);p?.participantId&&o.push(p.participantId)}}return o}function qk({matchUps:t,matchUpType:e}){if(!t)return{error:Bn};let r=[],n=[],o=0;e&&(t=t.filter(_=>_.matchUpType===e));let i=pt(t.map(({matchUpType:_})=>_));if(i.length>1)if(_s(i,xt))t=t.filter(re(xt));else if(_s(i,Ct))t=t.filter(re(Ct));else if(_s(i,Rt))t=t.filter(re(Rt));else return{};if(!Rr(t)||!t.length)return{};let s=(_,v)=>st(_)-st(v),a=pt(t.flatMap(_=>_.drawPositions).filter(Boolean)).sort(s),u=Q(1,Math.max(...a)+1).filter(_=>!a.includes(_)).sort(s),{roundMatchUps:p}=Ue({matchUps:t}),m=p?.[1],d=p?.[2]??[],l=m?.[0],f=l?.drawId,g=l?.structureId,I=p?Object.keys(p).map(_=>st(_)):[],S=Math.max(...I),h=p?.[S]?.length??0,T=Math.ceil(Math.log(h)/Math.log(2)),y=Q(1,T+1).map(_=>{let v=Math.pow(2,_-1),w=S+T-_+1;return Q(1,v+1).map(L=>({drawId:f,structureId:g,matchUpId:it(),drawPositions:[],sides:[],roundNumber:w,roundPosition:L,finishingRound:_}))});T&&(t=t.concat(...y.flat()));let A=m?.map(_=>_.drawPositions)?.flat(1/0),D=d.map(_=>_.drawPositions).flat(1/0).filter(_=>!A?.includes(_)).sort(s),R=d.filter(_=>_.drawPositions?.find(v=>D.includes(v))).map(_=>{let v=_.drawPositions?.find(F=>D.includes(F)),w=v&&_.drawPositions?.indexOf(v),L=w!==void 0&&_.sides?.[w];return v&&{[v]:L}});if(u?.length&&D?.length===u?.length){let _=D.map((F,x)=>[F,u[x]].sort(s)),v=Object.assign({},...R),w=q(m?.[0].finishingRound,!1,!0),L=q(m?.[0].finishingPositionRange,!1,!0);n=_.map((F,x)=>{let k=Math.max(...F??[])/2,G=F?.map(V=>v[V]||{bye:!0,drawPosition:V});return{finishingPositionRange:L,sideNumber:x+1,matchUpStatus:"BYE",matchUpId:it(),finishingRound:w,roundNumber:1,drawPositions:F,roundPosition:k,structureId:g,drawId:f,sides:G}}),t=t.concat(...n)}let U=S+T;return Q(1,U+1).forEach(_=>{let v=[],w=jk({matchUps:t,roundNumber:_}),L=jk({matchUps:t,roundNumber:_-1}),F=new Set(L.map(xQ).filter(Boolean)),x=w?.length===r?.length,k=w?.length===r?.length/2;_===1&&w.forEach(G=>{let V=G.drawPositions??[],{matchUpId:B,structureId:z}=G,H=[{...G.sides[0],drawPosition:V[0],matchUpId:B,structureId:z},{...G.sides[1],drawPosition:V[1],matchUpId:B,structureId:z}],K={...G,children:H};v.push(K)}),x?(o++,w.forEach((G,V)=>{let B=G.drawPositions??[],{matchUpId:z,structureId:H}=G,K=B.filter(Boolean).reduce((Et,Ht)=>A?.includes(Ht)?Et:Ht,void 0),J=[{...G.sides.filter(Boolean).reduce((Et,Ht)=>Ht.participantId&&!F.has(Ht.participantId)?Ht:Et,void 0),drawPosition:K,feedRoundNumber:o,sides:G.sides,matchUpId:z,structureId:H},r[V]],ct={...G,children:J};v.push(ct)})):k&&w.forEach((G,V)=>{let B=[r[V*2],r[V*2+1]],z={...G,children:B};v.push(z)}),r=v}),{hierarchy:r[0],missingMatchUps:n,maxRound:S,finalRound:U,matchUps:t}}function jk({matchUps:t,roundNumber:e}){return t.filter(r=>r.roundNumber===e).sort((r,n)=>r.roundPosition-n.roundPosition)}function xQ(t){if(t.matchUpStatus==="BYE")return t.sides.reduce((e,r)=>r.participantId||e,void 0);if(t.winningSide)return t.sides.reduce((e,r)=>r.sideNumber===t.winningSide?r.participantId:e,void 0)}function WP({scaleAttributes:t,scaledEntries:e,stageEntries:r,seedsCount:n,scaleName:o}){if(!t)return{error:nt,info:"missing scaleAttributes"};let i=Object.assign({},...(e??[]).slice(0,n).map(({participantId:c},u)=>({[c]:u+1})));o=o||t.scaleName;let s=new Date().toISOString();return{scaleItemsWithParticipantIds:r.map(({participantId:c})=>({scaleItems:[{scaleValue:i[c],eventType:t.eventType,scaleType:Eo,scaleName:o,scaleDate:s}],participantId:c}))}}function $k({tournamentRecord:t,drawDefinition:e,policyDefinitions:r,scaleAttributes:n,scaleName:o,drawSize:i,drawId:s,event:a,stage:c,sortDescending:u,scaleSortMethod:p}){let m=$f({policyDefinitions:r,drawDefinition:e,drawSize:i,drawId:s,event:a,stage:c});if(m.error)return m;let{entries:d,seedsCount:l,stageEntries:f}=m;if(!f||!l)return{error:O};let g=Xa({tournamentRecord:t,scaleAttributes:n,scaleSortMethod:p,sortDescending:u,entries:d,stage:c}).scaledEntries??[],{scaleItemsWithParticipantIds:I}=WP({scaleAttributes:n,scaledEntries:g,stageEntries:f,seedsCount:l,scaleName:o});return{scaleItemsWithParticipantIds:I}}var Uv={};Gt(Uv,{addDrawEntries:()=>mS,addEventEntries:()=>jn,addEventEntryPairs:()=>Pv,destroyPairEntries:()=>Zb,destroyPairEntry:()=>fS,getEntriesAndSeedsCount:()=>$f,getMaxEntryPosition:()=>AP,modifyEntriesStatus:()=>Xl,modifyEventEntries:()=>Nv,mutate:()=>Dv,promoteAlternate:()=>yv,promoteAlternates:()=>YP,query:()=>cv,removeDrawEntries:()=>Av,removeEventEntries:()=>Du,removeStageEntries:()=>Ev,setEntryPosition:()=>HP,setEntryPositions:()=>Tv});var Dv={};Gt(Dv,{addDrawEntries:()=>mS,addEventEntries:()=>jn,addEventEntryPairs:()=>Pv,destroyPairEntries:()=>Zb,destroyPairEntry:()=>fS,modifyEntriesStatus:()=>Xl,modifyEventEntries:()=>Nv,promoteAlternate:()=>yv,promoteAlternates:()=>YP,removeDrawEntries:()=>Av,removeEventEntries:()=>Du,removeStageEntries:()=>Ev,setEntryPosition:()=>HP,setEntryPositions:()=>Tv});function HP({tournamentRecord:t,drawDefinition:e,participantId:r,entryPosition:n,skipRefresh:o,event:i}){let s=dt({tournamentRecord:t,participantId:r},[rt,sr]);if(s.error)return s;if(n!==void 0&&!Number.isSafeInteger(n))return{error:O,entryPosition:n};(i?.entries??[]).forEach(c=>{c.participantId===r&&(c.entryPosition=n)}),(e?.entries??[]).forEach(c=>{c.participantId===r&&(c.entryPosition=n)});let a=c=>{c.entries.forEach(u=>{u.entryPosition===n&&u.participantId!==r&&(u.entryPosition+=.1)})};return o||(i?.entries&&(a(i),i.entries=no({entries:i.entries})),e?.entries&&(a(e),e.entries=no({entries:e.entries}))),{...P}}function Tv({tournamentRecord:t,entryPositions:e,drawDefinition:r,event:n}){let o=dt({tournamentRecord:t},[rt]);if(o.error)return o;if(!Array.isArray(e))return{error:O};for(let i of e){let{participantId:s,entryPosition:a}=i,c=HP({skipRefresh:!0,tournamentRecord:t,drawDefinition:r,participantId:s,entryPosition:a,event:n});if(c.error)return c}return n?.entries&&(n.entries=no({entries:n.entries})),r?.entries&&(r.entries=no({entries:r.entries})),{...P}}function yv(t){let{participantId:e}=t;return e&&typeof e!="string"?{error:O,participantId:e}:YP({...t,participantIds:[e].filter(Boolean)})}function YP({tournamentRecord:t,drawDefinition:e,participantIds:r,stageSequence:n,stage:o=W,eventId:i,event:s}){let a=dt({tournamentRecord:t,event:s},[rt,ce]);if(a.error)return a;if(!Array.isArray(r))return{error:O,participantIds:r};let c="promoteAlternates";if(s){let u=Kk({element:s,participantIds:r,stageSequence:n,stage:o});if(u.error)return u}if(e){let u=Kk({element:e,participantIds:r,stageSequence:n,stage:o});if(u.error)return i?M({context:{drawPromotionError:u.error,drawId:e.drawId},result:{...P},stack:c}):u}return{...P}}function Kk({participantIds:t,stageSequence:e,element:r,stage:n}){let o=(r.entries??[]).filter(m=>m.entryStatus===Zr),i=(r.entries??[]).filter(m=>t.includes(m.participantId)),s=o.reduce((m,d)=>{let{entryPosition:l}=d;return Number.isNaN(Number(l))&&m||(!m||l<m.entryPosition)&&d||m},void 0),a=i.length?i:[s].filter(Boolean);if(!a?.length)return{error:jT};let c=a.filter(({entryStatus:m})=>m!==Zr);if(c.length)return{error:Qg,invalidEntryStatus:c};let u=a.filter(({entryStage:m})=>m&&m!==n);if(u.length)return{error:Tw,invalidStage:u};let p=e&&a.filter(m=>m.stageSequence!==e);if(p?.length)return{error:yw,invalidStageSequence:p};for(let m of a){m.entryStatus=kr;let d=m?.entryPosition;Number.isNaN(Number(d))||r.entries.forEach(f=>{f.entryStatus===Zr&&f.entryPosition>d&&(f.entryPosition=f.entryPosition-1)});let l=Math.max(...r.entries.filter(f=>f.entryStatus===kr&&!Number.isNaN(Number(f.entryPosition))).map(({entryPosition:f})=>st(f||0)),0);m.entryPosition=l||0}return{...P}}function Ev({drawDefinition:t,entryStage:e}){return t?e?(t.entries&&(t.entries=t.entries.filter(r=>r.entryStage!==e)),{...P}):{error:O}:{error:$}}function Av({autoEntryPositions:t=!0,participantIds:e,drawDefinition:r,drawId:n,stages:o,event:i}){if(!i)return{error:le};if(!n)return{error:Nn};if(!e?.length)return{error:Mo};let s=Ji({drawDefinition:r,stages:o}).assignedParticipantIds??[];if(Re(s,e))return{error:Pa};let c=m=>{let d=m.participantId;return!e.includes(d)},{flightProfile:u}=Bt({event:i}),p=u?.flights?.find(m=>m.drawId===n);return p?.drawEntries&&(p.drawEntries=p.drawEntries.filter(c),t&&(p.drawEntries=no({entries:p.drawEntries}))),r?.entries&&(r.entries=r.entries.filter(c),t&&(r.entries=no({entries:r.entries}))),{...P}}function wQ(t,e){if(!t)return{error:Aa};t.participantId??=it(),e.participants??=[];let{participantId:r}=t;if(e.participants.reduce((s,a)=>a.participantId===r||s,!1))return{error:lU};let{participantType:o,participantRole:i}=t;if(!o||!Object.keys(Op).includes(o))return{error:Dn,participantType:o};if(!i)return{error:mU};if(o!==St&&t.person)return{error:O,person:t.person};if(t.individualParticipantIds&&!Array.isArray(t.individualParticipantIds))return{error:O,individualParticipantIds:t.individualParticipantIds}}function LQ({participant:t,tournamentParticipants:e,pairOverride:r,allowDuplicateParticipantIdPairs:n,returnParticipant:o}){let i="addParticipant";if(t.person)return{error:O,person:t.person};if(!t.individualParticipantIds)return M({result:{error:Mo},stack:i});if(t.individualParticipantIds.length!==2&&!r)return M({info:"PAIR must be 2 individualParticipantIds",result:{error:_r},stack:i});let s=new Set(e.filter(p=>p.participantType===St).map(p=>p.participantId));if(!Array.isArray(t.individualParticipantIds))return M({result:{error:_r},stack:i});if(!t.individualParticipantIds.reduce((p,m)=>s.has(m)&&p,!0))return M({result:{error:_r},stack:i});let u=e.filter(p=>p.participantType===lt).map(p=>({individualParticipantIds:p.individualParticipantIds,participant:p})).find(p=>Yt(p.individualParticipantIds,t.individualParticipantIds).length===2);if(u&&!n)return{earlyReturn:!0,...P,existingParticipant:!0,participant:o&&q(u.participant)};if(!t.participantName){let p=e.filter(d=>t.individualParticipantIds?.includes(d.participantId)),m=p.map(d=>d.person?.standardFamilyName||d.participantOtherName||d.participantName||"").filter(Boolean).join("/");p.length===1&&(m+="/Unknown"),t.participantName=m}}function FQ({participant:t,tournamentIndividualParticipantIds:e}){let r="addParticipant";if(t.individualParticipantIds??=[],t.individualParticipantIds?.length)for(let n of t.individualParticipantIds){if(typeof n!="string")return M({result:{participantId:n,error:O},stack:r});if(!e.includes(n))return M({result:{participantId:n,error:ee},stack:r})}}function Gn(t){let e="addParticipant",{allowDuplicateParticipantIdPairs:r,returnParticipant:n,disableNotice:o,pairOverride:i,participant:s}=t,a=t.tournamentId?t.tournamentRecords?.[t.tournamentId]:t.tournamentRecord??(t.activeTournamentId&&t.tournamentRecords?.[t.activeTournamentId]);if(!a)return{error:j};let c=wQ(s,a);if(c)return M({result:c,stack:e});let{participantType:u}=s,p=a.participants??[],m=p.filter(l=>l.participantType===St).map(l=>l.participantId);if(u===lt){let l=LQ({participant:s,tournamentParticipants:p,pairOverride:i,allowDuplicateParticipantIdPairs:r,returnParticipant:n});if(l?.earlyReturn){let{earlyReturn:f,...g}=l;return g}if(l)return l}else if(u===St){let l=s.person?.standardFamilyName&&s.person?.standardGivenName,f=s.participantOtherName||s.participantName;if(!l&&!f)return{error:SU};s.participantName||(s.participantName=l?`${s.person.standardGivenName} ${s.person.standardFamilyName}`:s.participantOtherName??"")}else if(u&&[_t,$r].includes(u)){let l=FQ({participant:s,tournamentIndividualParticipantIds:m});if(l)return l}else return{error:Dn};a.participants?.push(s),o||at({payload:{tournamentId:a.tournamentId,participants:[s]},topic:Di});let d={participant:n&&q(s),...P};return et(d)}function un({allowDuplicateParticipantIdPairs:t,returnParticipants:e,tournamentRecord:r,participants:n=[]}){if(!r)return{error:j};r.participants??=[];let i=r.participants.map(d=>d.participantId)??[];n.forEach(d=>{d.participantId??=it()});let s=n.filter(d=>!i.includes(d.participantId)),a=n.filter(d=>i.includes(d.participantId)),c=s.filter(d=>d.participantType===St),u=s.filter(d=>d.participantType!==St),p=c.concat(...u),m=[];if(p.length){for(let l of p){let f=Gn({allowDuplicateParticipantIdPairs:t,returnParticipant:!0,disableNotice:!0,tournamentRecord:r,participant:l});if(f.error)return f;f.success&&!f.existingParticipant&&m.push(f.participant)}m.length&&at({topic:Di,payload:{tournamentId:r.tournamentId,participants:m}});let d={participants:e&&q(m),addedCount:m.length,...P};return a.length&&Object.assign(d,{notAdded:a,info:_m}),et(d)}else return{info:"No new participants to add",addedCount:0,...P}}function Pv(t){let e=X(t,[{[rt]:!0,[ce]:!0}]);if(e.error)return e;let{allowDuplicateParticipantIdPairs:r,entryStatus:n=Zr,participantIdPairs:o=[],entryStage:i=W,tournamentRecord:s,enforceCategory:a,drawDefinition:c,event:u,uuids:p}=t;if(u.eventType!==Rt)return{error:zn};let m=[],d=new Map;for(let E of s.participants??[]){let{participantType:A,participantId:N,person:D,individualParticipantIds:R}=E;A===St&&D?.sex?d.set(N,D.sex):A===lt&&R&&m.push(R)}let l=o.filter(E=>{if(E.length!==2)return!0;if(!u.gender||Oo(u.gender))return!1;if(!d.has(E[0])||!d.has(E[1]))return!0;let A=E.map(D=>d.get(D)),N=Da(u.gender)&&(!Da(A[0])||!Da(A[1]))||ls(u.gender)&&(!ls(A[0])||!ls(A[1]));return nn(u.gender)&&(A.sort(Wp),(!ls(A[0])||!Da(A[1]))&&(N=!0)),N});if(l.length)return{error:_r,invalidParticipantIdPairs:l};let f=o.map(E=>({participantId:p?.pop()??it(),participantRole:Ve,individualParticipantIds:E,participantType:lt})),g=r?f:f.filter(E=>!m.some(A=>Yt(A,E.individualParticipantIds).length===2)),I,S=[];if(g){let E=un({allowDuplicateParticipantIdPairs:r,participants:g,returnParticipants:!0,tournamentRecord:s});if(E.error)return E;S=E.participants??[],I=E.info}let h=o.map(E=>{let A=S.find(D=>Yt(D.individualParticipantIds,E).length===2);if(A)return A;let{participant:N}=Tn({tournamentRecord:s,participantIds:E});return N}).map(E=>E.participantId),T=jn({participantIds:h,tournamentRecord:s,enforceCategory:a,drawDefinition:c,entryStatus:n,entryStage:i,event:u});g.length&&at({payload:{participants:g},topic:Di});let y=g.map(gt);return{...T,info:I,newParticipantIds:y}}function Nv({entryStatus:t=kr,unpairedParticipantIds:e=[],participantIdPairs:r=[],entryStage:n=W,tournamentRecord:o,event:i}){let s=dt({tournamentRecord:o,event:i},[rt,ce]);if(s.error)return s;let a=o.participants??[],c=a.filter(h=>h.participantType===St).map(h=>h.participantId),p=e.concat(...r).flat(1/0).filter(h=>!c.includes(h));if(p.length)return{error:_r,invalidParticipantIds:p};let m=r.filter(h=>h.length!==2);if(m.length)return{error:_r,invalidParticipantIdPairs:m};let d=a.filter(h=>h.participantType===lt).map(h=>h.individualParticipantIds),f=r.filter(h=>!d.find(T=>Yt(T,h).length===2)).map(h=>({participantType:lt,participantRole:Ve,individualParticipantIds:h})),g=un({participants:f,tournamentRecord:o});if(g.error)return g;let I=r.map(h=>{let{participant:T}=Tn({tournamentRecord:o,participantIds:h});return T}).map(h=>({participantId:h,entryStatus:t,entryStage:n})),S=e.map(h=>({entryStatus:Gr,participantId:h,entryStage:n}));return i.entries=(i.entries??[]).filter(h=>h.entryStage===n),i.entries=i.entries.concat(...I,...S),{...P}}var Vv={};Gt(Vv,{addDrawDefinition:()=>Gu,addEvent:()=>tc,addFlight:()=>kd,assignSeedPositions:()=>wv,attachFlightProfile:()=>gh,categoryCanContain:()=>fp,deleteDrawDefinitions:()=>Fd,deleteEvents:()=>Fv,deleteFlightAndFlightDraw:()=>_v,deleteFlightProfileAndFlightDraws:()=>vv,generate:()=>bv,generateEventsFromTieFormat:()=>Rv,getCategoryAgeDetails:()=>gs,getEvent:()=>BP,getEventProperties:()=>GP,getEventStructures:()=>RS,getEventTimeItem:()=>xp,getEvents:()=>VP,getFlightProfile:()=>Bt,getScaledEntries:()=>Xa,modifyEvent:()=>kv,modifyEventMatchUpFormatTiming:()=>Ov,modifyPairAssignment:()=>xv,mutate:()=>Gv,query:()=>gv,refreshEventDrawOrder:()=>fh,removeEventMatchUpFormatTiming:()=>Zf,removeScaleValues:()=>Ih,removeSeeding:()=>Lv,setEventDates:()=>dh,setEventDisplay:()=>tg,setEventEndDate:()=>QP,setEventStartDate:()=>zP,updateDrawIdsOrder:()=>lh,validateCategory:()=>lp});var bv={};Gt(bv,{generateEventsFromTieFormat:()=>Rv});function zk({tournamentId:t,event:e}){return e?(at({payload:{tournamentId:t,event:e},key:e.eventId,topic:sb}),{...P}):{error:le}}var Qk={collectionDefinitions:[{collectionName:"Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"College D3",winCriteria:{valueGoal:5}};var Xk={collectionDefinitions:[{collectionName:"Doubles",collectionValue:1,matchUpCount:3,matchUpFormat:"SET1-S:6/TB7",matchUpType:"DOUBLES"},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"College Default",winCriteria:{valueGoal:5}};var Jk={collectionDefinitions:[{collectionName:"Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"College JUCO",winCriteria:{valueGoal:5}};var jP={COLLEGE_D3:Qk,COLLEGE_DEFAULT:Xk,COLLEGE_JUCO:Jk,DOMINANT_DUO:Iy,DOMINANT_DUO_MIXED:ly,LAVER_CUP:Ey,TEAM_DOUBLES_3_AGGREGATION:uy,USTA_BREWER_CUP:fy,USTA_OZAKI_CUP:gy,USTA_COLLEGE:Sy,USTA_GOLD_TEAM_CHALLENGE:cy,USTA_INTERSECTIONAL:dy,USTA_LEVEL_1:hy,USTA_SECTION_BATTLE:my,USTA_SOUTHERN_LEVEL_5:py,USTA_TOC:Ay,USTA_WTT_ITT:Ty,USTA_ZONAL:yy};function tc({suppressNotifications:t,tournamentRecord:e,internalUse:r,event:n}){let o=dt({tournamentRecord:e,event:n},[rt,ce]);if(o.error)return o;e.events??=[];let{startDate:i,endDate:s}=e;if(!r&&(n.entries?.length||n.drawDefinitions?.length)){let p=et({drawDefinitions:!!n.drawDefinitions?.length,entries:!!n.entries?.length});return{info:"entries/drawDefinitions cannot exist",error:O,context:p}}let a={eventType:ba,drawDefinitions:[],entries:[],startDate:i,endDate:s,...n};if(n.eventType===Ze){if(n.tieFormat){let p=or({tieFormat:n.tieFormat});if(p.error)return p}else if(n.tieFormatName){if(!jP[n.tieFormatName])return{context:{tieFormatName:n.tieFormatName},error:O};let p=uo({isMock:e?.isMock,namedFormat:n.tieFormatName,event:n});a.tieFormat=p}}if(a.eventId??=it(),e.events.reduce((p,m)=>p||m.eventId===a.eventId,void 0))return{error:YD};let u=a;if(e.events.push(u),!t){let{topics:p}=vr();if(p.includes(Zm)){let l=vn({event:n}).matchUps??[];Ho({tournamentId:e?.tournamentId,eventId:n.eventId,matchUps:l})}let{drawDefinitions:m,...d}=n;for(let l of m??[])yc({drawDefinition:l});zk({tournamentId:e?.tournamentId,event:d})}return{...P,event:a}}function Rv(t){let e=X(t,[{[_a]:{[Tl]:!0,[by]:!0}},{[rt]:!0}]);if(e.error)return e;let r=t.tieFormat||uo({namedFormat:t.tieFormatName}),n=t.uuids||[ay(r.collectionDefinitions.length)],o=t.addEntriesFromTeams?BQ(t.tournamentRecord):{[Ce]:[],[Je]:[]},i=[];for(let s of r.collectionDefinitions??[]){let a=n?.pop()?.toString()||it(),c={matchUpFormat:s.matchUpFormat,eventName:s.collectionName,category:s.category,gender:s.gender,eventType:s.matchUpType,eventId:a};if(t.addEntriesFromTeams){let u=WQ({genderedParticipants:o,collectionDefinition:s,entryStatus:t.entryStatus,event:c});if(u?.error)return u}if(i.push(c),t.addEvents!==!1){let u=tc({internalUse:!0,tournamentRecord:t.tournamentRecord,event:c});if(u.error)return u}}return{...P,events:i}}function BQ(t){let e={[Ce]:[],[Je]:[]},r=t.participants?.filter(o=>o.participantType===ur),n=new Set(r?.flatMap(o=>o.individualParticipantIds??[]));for(let o of t.participants??[])if(n.has(o.participantId)){let i=o.person?.sex;if(i&&Un(i)){let s=Ar(i);s&&e[s].push(o.participantId)}}return e}function WQ({genderedParticipants:t,collectionDefinition:e,entryStatus:r,event:n}){let o=e.matchUpType,i=e.gender,s=o===si?Gr:r||kr,a=nn(i)?[...t[Ce],...t[Je]]:t[Ar(i)||ii]??[];if(a.length)return jn({participantIds:a,entryStatus:s,event:n})}var Gv={};Gt(Gv,{addDrawDefinition:()=>Gu,addEvent:()=>tc,addFlight:()=>kd,assignSeedPositions:()=>wv,attachFlightProfile:()=>gh,deleteDrawDefinitions:()=>Fd,deleteEvents:()=>Fv,deleteFlightAndFlightDraw:()=>_v,deleteFlightProfileAndFlightDraws:()=>vv,modifyEvent:()=>kv,modifyEventMatchUpFormatTiming:()=>Ov,modifyPairAssignment:()=>xv,refreshEventDrawOrder:()=>fh,removeEventMatchUpFormatTiming:()=>Zf,removeScaleValues:()=>Ih,removeSeeding:()=>Lv,setEventDates:()=>dh,setEventDisplay:()=>tg,setEventEndDate:()=>QP,setEventStartDate:()=>zP,updateDrawIdsOrder:()=>lh,validateCategory:()=>lp});function ec({removePriorValues:t=!0,status:e=br,statusObject:r,event:n}){if(!Tt(r))return{error:O};let o=Cr({event:n,status:e}),i=`${qo}.${$o}`,s={itemValue:{[e]:{...o,...r}},itemType:i};return Rs({timeItem:s,removePriorValues:t,event:n})}function rc(t){let e=X(t,[{[rt]:!0,[ce]:!0},{eventDataParams:!1,[Ge]:qr}]);if(e.error)return e;let{includePositionAssignments:r,removePriorValues:n,tournamentRecord:o,status:i=br,event:s,drawIdsToRemove:a,drawIdsToAdd:c}=t,{appliedPolicies:u}=ft({tournamentRecord:o,event:s}),p={...u,...t.policyDefinitions},m=s?.drawDefinitions?.map(({drawId:A})=>A)??[],d=t.drawDetails?Object.keys(t.drawDetails):[],l=d.length?[]:t.drawIds,f=(c??[]).concat(...a??[],...l??[],...d),g=HQ({drawIdsToValidate:f,eventDrawIds:m});if(g?.error)return g;let I=YQ(t.drawDetails);if(I?.error)return I;let S=Cr({event:s,status:i}),h=qQ({pubStatus:S,eventDrawIds:m});$Q({drawDetails:h,eventDrawIds:m,drawIdsToValidate:f,drawIdsToRemove:a,drawIdsToAdd:c,specifiedDrawIds:l});for(let A of m)if(t.drawDetails?.[A]){let N=KQ({drawDetails:h,drawId:A,newDetail:t.drawDetails[A],event:s});if(N?.error)return N}ec({statusObject:{drawDetails:h},removePriorValues:n,status:i,event:s});let{topics:T}=vr(),y=T.includes(zy),E=y||t.returnEventData?tm({includePositionAssignments:r,...t.eventDataParams,usePublishState:!0,tournamentRecord:o,policyDefinitions:p,event:s})?.eventData:void 0;return y&&at({payload:{eventData:E,tournamentId:o.tournamentId},topic:zy}),{...P,eventData:E}}function HQ({drawIdsToValidate:t,eventDrawIds:e}){let r=t.filter(n=>!e.includes(n));if(r.length)return M({result:{error:Mr},context:{invalidDrawIds:r}})}function Cv(t){return!!t&&!Ra(t)}function YQ(t){if(t)for(let e of Object.keys(t)){let r=t[e];if(Cv(r.publishingDetail?.embargo))return{error:ip};let n=Zk(r.stageDetails);if(n)return n;let o=jQ(r.structureDetails);if(o)return o}}function Zk(t){if(t){for(let e of Object.keys(t))if(Cv(t[e].embargo))return{error:ip}}}function jQ(t){if(t)for(let e of Object.keys(t)){let r=t[e];if(Cv(r.embargo))return{error:ip};if(r.scheduledRounds){let n=Zk(r.scheduledRounds);if(n)return n}}}function qQ({pubStatus:t,eventDrawIds:e}){return Object.keys(t?.drawDetails??{}).filter(r=>e.includes(r)).reduce((r,n)=>(r[n]=t.drawDetails[n],r),{})}function $Q({drawDetails:t,eventDrawIds:e,drawIdsToValidate:r,drawIdsToRemove:n,drawIdsToAdd:o,specifiedDrawIds:i}){for(let s of e)(!r.length||r.includes(s))&&(n?.includes(s)||i?.length&&!i.includes(s)?t[s]={...t[s],publishingDetail:{published:!1}}:(o?.includes(s)||i?.includes(s)||!i?.length)&&(t[s]={...t[s],publishingDetail:{published:!0}}))}function KQ({drawDetails:t,drawId:e,newDetail:r,event:n}){let o=r.structureDetails??t[e].structureDetails,i=r.stageDetails??t[e].stageDetails??{},{structureIdsToRemove:s=[],structureIdsToAdd:a=[],publishingDetail:c={},stagesToRemove:u=[],stagesToAdd:p=[]}=r;if((a||p)&&(c.published=!0),t[e]={publishingDetail:c,structureDetails:o,stageDetails:i},a.length||s.length){let d=zQ({drawDetails:t,drawId:e,structureIdsToAdd:a,structureIdsToRemove:s,structureDetails:o,event:n});if(d?.error)return d}let m=(n?.drawDefinitions?.find(d=>d.drawId===e)?.structures??[]).map(({stage:d})=>d);QQ({stageDetails:i,stagesToAdd:p,stagesToRemove:u,drawStages:m}),(p.length||u.length)&&(t[e].stageDetails=i)}function zQ({drawDetails:t,drawId:e,structureIdsToAdd:r,structureIdsToRemove:n,structureDetails:o,event:i}){let s=(i?.drawDefinitions?.find(u=>u.drawId===e)?.structures??[]).map(({structureId:u})=>u),c=(r??[]).concat(n??[]).filter(u=>!s.includes(u));if(c.length)return M({result:{error:Nt},context:{invalidStructureIds:c}});o=o??{};for(let u of s)n.includes(u)?o[u]={published:!1}:o[u]={published:!0};t[e].structureDetails=o}function QQ({stageDetails:t,stagesToAdd:e,stagesToRemove:r,drawStages:n}){if(e.length){for(let o of e)t[o]={published:!0};for(let o of n)t[o]||(t[o]={published:!1})}if(e.length||r.length){for(let o of r)t[o]={published:!1};for(let o of n)t[o]||(t[o]={published:!0})}}var Mv="deleteDrawDefinitions",qP="autoSchedulingAudit",ph="deleteEvents",tG={AUTO_SCHEDULING_AUDIT:qP,DELETE_EVENTS:ph,DELETE_DRAW_DEFINITIONS:Mv};function Fd(t){if(!t.tournamentRecord)return{error:j};let e="deleteDrawDefinitions",r=t.drawIds??[],n=t.event,{autoPublish:o=!0,tournamentRecord:i,auditData:s,eventId:a,force:c}=t,{appliedPolicies:u}=ft({tournamentRecord:i,event:n}),p={...u,...t.policyDefinitions},m=Array.isArray(r)?r[0]:void 0;if(!n){let D=_e({tournamentRecord:i,eventId:a,drawId:m});if(D.error)return D;n=D.event}let d=[],l=[],f=[];if(!n?.drawDefinitions)return M({info:"event has no drawDefinition",result:{...P},stack:e});let g=n.drawDefinitions.map(({drawId:D})=>D);if(r.length||(r=g),r=r.filter(D=>g.includes(D)),!r.length)return M({info:"nothing to do; no matching drawIds in event.",result:{...P},stack:e});let I=q(Bt({event:n}).flightProfile,!1,!0),S=({participantId:D,drawPosition:R,qualifier:U,bye:b})=>({bye:b,qualifier:U,drawPosition:R,participantId:D}),h=c??u?.[Qr]?.allowDeletionWithScoresPresent?.drawDefinitions,T=Cr({event:n})??{},y=T.drawIds??(T.drawDetails&&Object.keys(T.drawDetails))??[],E,A=[],N=n.drawDefinitions.filter(D=>{if(r.includes(D.drawId)){let R=rr({event:n,drawDefinition:D})?.matchUps??[];if(R.some(({score:V})=>ue({score:V}))&&!h)return A.push(D.drawId),!0;let{drawId:b,drawType:C,drawName:_}=D,v=I?.flights?.find(V=>V.drawId===D.drawId);v&&(v.drawEntries=v.drawEntries?.filter(V=>yr.includes(V.entryStatus))),y.includes(b)&&(y=y.filter(V=>V!==b),E=!0);let w=Sn({stageSequence:1,drawDefinition:D,stage:W})?.structures?.[0],F=(w?xu({structureId:w.structureId,tournamentRecord:i,drawDefinition:D}):void 0)?.positionAssignments?.map(S),x=Sn({stage:Z,drawDefinition:D})?.structures,k=x?.length?x.map(V=>{let B=V.stageSequence;return{positionAssignments:xu({structureId:V.structureId,tournamentRecord:i,drawDefinition:D})?.positionAssignments.map(S),stageSequence:B}}):void 0,G={action:Mv,payload:{drawDefinitions:[D],eventId:a??n?.eventId,auditData:s}};f.push(G),d.push(et({tournamentId:i.tournamentId,eventId:a??n?.eventId,qualifyingPositionAssignments:k,positionAssignments:F,auditData:s,drawType:C,drawName:_,drawId:b})),R?.forEach(({matchUpId:V})=>l.push(V))}return!r.includes(D.drawId)});if(A.length&&!c)return M({context:{drawIdsWithScoresPresent:A},result:{error:Zc},stack:e});if(n.drawDefinitions=N,I&&Go({event:n,extension:{name:on,value:I}}),ku({tournamentRecord:i}),E){let D={};for(let U of y)D[U]=T.drawDetails?.[U]??{published:!0};let R=ec({statusObject:{drawDetails:D},event:n});if(R.error)return{error:R.error}}if(f.length)if(tu(Yi)){let D=i.tournamentId;at({topic:Yi,payload:{tournamentId:D,detail:f}});let U=(Jr({element:n,itemType:Ic})?.timeItem?.itemValue||0)+1;oo({element:n,timeItem:{itemType:Ic,itemValue:U},removePriorValues:!0})}else XQ({appliedPolicies:u,event:n,deletedDrawsDetail:d,auditData:s});if(l.length&&wn({tournamentId:i?.tournamentId,matchUpIds:l}),r.forEach(D=>AL({drawId:D})),o&&E){let D=rc({...t.eventDataParams,drawIdsToRemove:r,policyDefinitions:p,tournamentRecord:i,event:n});if(D.error)return{...P,info:D.error}}return{...P}}function XQ({appliedPolicies:t,event:e,deletedDrawsDetail:r,auditData:n}){if(t?.audit?.[Ic]===!1)return;let{extension:o}=ot({name:Ic,element:e}),i={...n,deletedDrawsDetail:r},s={value:Array.isArray(o?.value)?o?.value.concat(i):[i],name:Ic};ut({element:e,extension:s})}function vv({autoPublish:t=!0,tournamentRecord:e,auditData:r,event:n,force:o}){let i=dt({tournamentRecord:e,event:n},[rt,ce]);if(i.error)return i;let{flightProfile:s}=Bt({event:n});if(s){let a=s.flights?.map(({drawId:u})=>u).filter(Boolean),c=Fd({eventId:n.eventId,tournamentRecord:e,autoPublish:t,auditData:r,drawIds:a,event:n,force:o});return c.error?c:Qm({event:n,name:on})}return{...P}}function mh(t){let{matchUpFormat:e,recoveryTimes:r,averageTimes:n,tournamentId:o,eventId:i}=t,s=t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{};if(!Object.keys(s).length)return{error:kt};let a=Object.keys(s).filter(u=>!o||o===u);if(o&&!a.includes(o))return{error:O};let c;for(let u of a){let p=s[u],{event:m}=_e({tournamentRecord:p,eventId:i});i&&m&&(c=!0);let d=JQ({tournamentRecord:p,event:m,matchUpFormat:e,averageTimes:n,recoveryTimes:r});if(d.error)return d}return!i||c?{...P}:{error:Wr}}function JQ({tournamentRecord:t,recoveryTimes:e,matchUpFormat:r,averageTimes:n,event:o}){if(!t)return{error:j};if(n&&!Array.isArray(n))return{error:O};if(e&&!Array.isArray(e))return{error:O};let i=pi;if(o){let{extension:s}=ot({element:o,name:i}),a=s?.value??{},c=eG({...a,matchUpFormat:r,averageTimes:n,recoveryTimes:e});ut({element:o,extension:{name:i,value:c}})}else{let{extension:s}=ot({element:t,name:i}),a=s?.value??{},c=eG({...a,matchUpFormat:r,averageTimes:n,recoveryTimes:e});ut({extension:{name:i,value:c},element:t})}return{...P}}function eG(t){let{matchUpRecoveryTimes:e=[],matchUpAverageTimes:r=[],matchUpFormat:n}=t,{averageTimes:o,recoveryTimes:i}=t;o=(o??[]).filter(c=>c?.categoryNames?.length||c?.categoryTypes?.length);let s=o?.length&&r.map(c=>c?.matchUpFormatCodes.includes(n)?{...c,matchUpFormatCodes:c.matchUpFormatCodes?.filter(u=>u!==n)}:c).filter(({matchUpFormatCodes:c})=>c?.length).concat({matchUpFormatCodes:[n],averageTimes:o});i=(i??[]).filter(c=>c?.categoryNames?.length||c?.categoryTypes?.length);let a=i?.length&&e.map(c=>c?.matchUpFormatCodes.includes(n)?{...c,matchUpFormatCodes:c.matchUpFormatCodes?.filter(u=>u!==n)}:c).filter(({matchUpFormatCodes:c,averageTimes:u})=>c?.length||u).concat({matchUpFormatCodes:[n],recoveryTimes:i});return{matchUpAverageTimes:s?.length&&s||r,matchUpRecoveryTimes:a?.length&&a||e}}function Ov(t){let{tournamentRecord:e,recoveryMinutes:r,averageMinutes:n,matchUpFormat:o,categoryType:i,eventId:s,event:a}=t,c=dt({tournamentRecord:e},[rt]);if(c.error)return c;if(!xr({matchUpFormat:o}))return{error:O};let u=dt({event:a},[ce]);if(u.error)return u;let{averageTimes:p=[],recoveryTimes:m=[]}=Kf({tournamentRecord:e,matchUpFormat:o,event:a}),d=a.category,l=d?.categoryName||d?.ageCategoryCode||a?.eventId,f={categoryNames:[l],minutes:{}},g={categoryNames:[l],minutes:{}},I=E=>{if(E.categoryTypes?.includes(i)&&console.log("encountered:",{categoryType:i}),!(E.categoryNames?.includes(l)&&(E.categoryNames=E.categoryNames.filter(A=>A!==l),f={minutes:E.minutes,categoryNames:[l]},!E.categoryNames.length)))return E},S=n&&!isNaN(st(n)),h=r&&!isNaN(st(r)),T=p.map(I).filter(E=>E?.categoryNames?.length),y=m.map(I).filter(E=>E?.categoryNames?.length);return S&&(Object.assign(f.minutes,{[a?.eventType||Ct]:n}),T.push(f)),h&&(Object.assign(g.minutes,{[a?.eventType||Ct]:r}),y.push(g)),!S&&!h?{error:O}:mh({averageTimes:S&&T,recoveryTimes:h&&y,tournamentRecord:e,matchUpFormat:o,eventId:s,event:a})}function Zf(t){if(t.event)return rG({event:t.event});{t.tournamentRecord&&!t.tournamentRecords&&(t.tournamentRecords={[t.tournamentRecord.tournamentId]:t.tournamentRecord});let e=X(t,[{[Ee]:!0,[My]:!0}]);if(e.error)return e;let{tournamentRecords:r,eventId:n}=t;for(let o of Object.values(r??{})){let{event:i}=_e({tournamentRecord:o,eventId:n});if(i)return rG({event:i})}}return{error:Wr}}function rG({event:t}){return Qm({event:t,name:pi})}var $P={MON:"MON",TUE:"TUE",WED:"WED",THU:"THU",FRI:"FRI",SAT:"SAT",SUN:"SUN"};function KP(t){return!Array.isArray(t)||pt(t).length!==t.length?!1:t.every(e=>Object.keys($P).includes(e))}function zP({tournamentRecord:t,event:e,startDate:r}){let n=dt({tournamentRecord:t,event:e},[rt,ce]);if(n.error)return n;if(!_o.test(r))return{error:ae};let o=nG(t),i="setEventStartDate";if(o.error)return M({result:o,stack:i});let{tournamentStartDate:s,tournamentEndDate:a}=o,c=new Date(mt(r)).getTime();if(!s||!a||c<s||c>a)return M({result:{error:ae},stack:i,info:"startDate must be within tournament start and end dates"});let u=e.endDate&&new Date(mt(e.endDate)).getTime();return u&&c>u&&(e.endDate=r),e.startDate=r,{...P}}function QP(t){let{tournamentRecord:e,event:r,endDate:n}=t,o=dt({tournamentRecord:e,event:r},[rt,ce]);if(o.error)return o;if(!_o.test(n))return{error:ae};let i=nG(e);if(i.error)return i;let{tournamentStartDate:s,tournamentEndDate:a}=i,c=new Date(mt(n)).getTime();if(!s||!a||c<s||c>a)return{error:ae};let u=r.startDate&&new Date(mt(r.startDate)).getTime();return u&&c<u&&(r.startDate=n),r.endDate=n,{...P}}function dh(t){let e="setEventDates",r=X(t,[{tournamentRecord:!0,event:!0},{[$e]:u=>_o.test(u),[Lr]:ae,startDate:!1,endDate:!1},{[$e]:u=>u.filter(Boolean).every(p=>_o.test(p)),[Lr]:ae,activeDates:!1},{[$e]:KP,weekdays:!1}]);if(r.error)return r;let{tournamentRecord:n,weekdays:o,event:i,startDate:s,endDate:a}=t,c=t.activeDates?.filter(Boolean);if(s&&a){let u=new Date(mt(s)).getTime(),p=new Date(mt(a)).getTime();if(u>p)return M({result:{error:O},stack:e,info:"startDate cannot be after endDate"})}if(c){let u=s||n.startDate,p=a||n.endDate,m=!u||c.every(l=>new Date(l)>=new Date(u)),d=!p||c.every(l=>new Date(l)<=new Date(p));if(!m||!d)return M({result:{error:ae},stack:e})}if(s){let u=zP({tournamentRecord:n,event:i,startDate:s});if(u.error)return M({result:u,stack:e})}if(a){let u=QP({tournamentRecord:n,event:i,endDate:a});if(u.error)return M({result:u,stack:e})}return c&&(i.activeDates=c),o&&(i.weekdays=o),{...P}}function nG(t){let{startDate:e,endDate:r}=t;return!_o.test(e)||!_o.test(r)?M({result:{error:sU},context:{startDate:e,endDate:r}}):{tournamentStartDate:new Date(mt(e)).getTime(),tournamentEndDate:new Date(mt(r)).getTime()}}function lh({event:t,orderedDrawIdsMap:e}){if(typeof t!="object")return{error:le};if(!e)return{error:nt,info:"Missing drawIdsOrderMap"};if(typeof e!="object")return{error:O,info:"orderedDrawIdsMap must be an object"};let r=Object.values(e);if(!r.every(i=>!Number.isNaN(Number(i))))return{error:O,info:"drawOrder must be numeric"};if(pt(r).length!==r.length)return{info:"drawOrder values must be unique",error:O};if(t.drawDefinitions?.length){let i=(t.drawDefinitions??[]).map(({drawId:a})=>a),s=Object.keys(e);if(s?.length&&Yt(i,s).length!==i.length)return{error:O,info:"Missing drawIds"};t.drawDefinitions.forEach(a=>{a.drawOrder=e[a.drawId]})}let{flightProfile:o}=Bt({event:t});return o?.flights?.forEach(i=>{i.flightNumber=e[i.drawId]}),{...P}}function fh({tournamentRecord:t,event:e}){let r=dt({tournamentRecord:t,event:e},[rt,ce]);if(r.error)return r;let{flightProfile:n}=Bt({event:e}),o=n?.flights?.sort((a,c)=>a.flightNumber-c.flightNumber).map(a=>a.drawId).filter(Boolean),i=e.drawDefinitions?.sort((a,c)=>a.drawOrder-c.drawOrder).map(a=>a.drawId).filter(Boolean).filter(a=>!o?.includes(a)),s=Object.assign({},...[...o??[],...i??[]].map((a,c)=>({[a]:c+1})));return s?lh({event:e,orderedDrawIdsMap:s}):{...P}}function _v({autoPublish:t=!0,tournamentRecord:e,auditData:r,drawId:n,event:o,force:i}){let s=dt({tournamentRecord:e,drawId:n,event:o},[rt,dc,ce]);if(s.error)return s;let{flightProfile:a}=Bt({event:o});if(a&&a.flights?.find(p=>p.drawId===n)){let p=a.flights.filter(d=>d.drawId!==n),m={name:on,value:{...a,flights:p}};Go({event:o,extension:m})}if(o.drawDefinitions?.find(u=>u.drawId===n)){let u=Fd({drawIds:[n],eventId:o.eventId,tournamentRecord:e,autoPublish:t,auditData:r,event:o,force:i});if(u.error)return u}return fh({tournamentRecord:e,event:o})}function xv(t){let e=X(t,[{[ce]:!0,[rt]:!0,[MI]:!1},{replacementIndividualParticipantId:!0,[$e]:S=>wt(S),existingIndividualParticipantId:!0,[jr]:We,participantId:!0}]),{replacementIndividualParticipantId:r,existingIndividualParticipantId:n,tournamentRecord:o,drawDefinition:i,participantId:s,event:a,uuids:c}=t;if(e.error)return e;if(a?.eventType!==Lt)return{error:zn};if(!(a?.entries?.filter(({entryStatus:S})=>[Gr,qi].includes(S)).map(({participantId:S})=>S)??[]).includes(r))return{error:Hr};let p=(o.participants??[]).find(S=>S.participantId===s);if(p?.participantType!==lt)return{error:xi,participant:p};let m=p.individualParticipantIds,d=[r,...m.filter(S=>S!==n)],{participant:l}=Tn({participantIds:d,tournamentRecord:o}),f;if(l)f=l.participantId;else{let S={participantId:c?.pop(),participantRole:Ve,individualParticipantIds:d,participantType:lt},h=Gn({participant:S,returnParticipant:!0,tournamentRecord:o});if(h.error)return h;f=h.participant.participantId}let{flightProfile:g}=Bt({event:a});if(i){let S=g?.flights?.find(({drawId:h})=>h===i.drawId);S&&(S.drawEntries=S.drawEntries.map(h=>h.participantId===s?{...h,participantId:f}:h)),i.entries=i.entries.map(h=>h.participantId===s?{...h,participantId:f}:h);for(let h of i.structures??[])if(h.structures){h.positionAssignments=void 0;for(let T of h.structures)T.positionAssignments=T.positionAssignments.map(y=>y.participantId===s?{...y,participantId:f}:y)}else h.positionAssignments&&(h.positionAssignments=h.positionAssignments.map(T=>T.participantId===s?{...T,participantId:f}:T))}a.entries=a.entries.map(S=>S.participantId===s&&{...S,participantId:f}||S.participantId===r&&{...S,participantId:n}||S);let I=o.events.some(({entries:S,eventId:h,drawDefinitions:T})=>a.eventId===h?T.some(({drawId:y,entries:E})=>y===i?.drawId?!1:E?.find(A=>A.participantId===s)):S?.find(y=>y.participantId===s));if(!I){let S=Ds({addIndividualParticipantsToEvents:!1,participantIds:[s],tournamentRecord:o});if(S.error)return S}return{...P,participantOtherEntries:I,newPairParticipantId:f}}function Gu(t){let{flight:e,suppressNotifications:r,modifyEventEntries:n,existingDrawCount:o,allowReplacement:i,checkEntryStatus:s,tournamentRecord:a,drawDefinition:c,event:u}=t;if(!c)return{error:$};if(!u)return{error:le};u.drawDefinitions??=[];let{drawId:p,drawName:m,entries:d}=c,{entries:l}=u,f=0;if(o!==void 0&&o!==u.drawDefinitions.length)return{error:O,info:"drawDefintions count mismatch"};let{flightProfile:g}=Bt({event:u}),I=e&&g?.flights?.find(v=>v.flightNumber===e.flightNumber),S=g?.links?.find(v=>v?.target?.drawId===p)?.source?.drawId;if(S&&!u.drawDefinitions.some(v=>v.drawId===S))return M({result:{error:$},info:{sourceDrawId:S}});if(I&&I.drawId!==c.drawId)return M({result:{error:ha},info:{relevantFlight:I}});let y=ZQ({drawEntries:d,eventEntries:l,relevantFlight:I,checkEntryStatus:s});if(y?.error)return y;let{matchingEventEntries:E}=y;if(n&&(f=t9({drawEntries:d,eventEntries:l})),l&&!E)return M({result:{info:"Draw entries do not match event entryStatuses",context:{matchingEventEntries:E,eventEntries:l},error:ha}});let A=g?.flights?.map(({flightNumber:v})=>!Number.isNaN(Number(v))&&st(v))?.filter(Boolean)??[],N=u.drawDefinitions.map(({drawOrder:v})=>v&&st(v))?.filter(Boolean)||[],D=Math.max(0,...N,...A)+1,R=g?.flights?.find(v=>v.drawId===p),U;if(R){R.drawName=c.drawName,U={name:on,value:{...g,flights:g.flights}};let v=R.flightNumber;v&&!N.includes(v)?D=v:R.flightNumber=D}else{let v=g?.flights??[];v.push({manuallyAdded:!0,flightNumber:D,drawEntries:d,drawName:m,drawId:p}),U={name:on,value:{...g,flights:v}}}Go({event:u,extension:U}),Object.assign(c,{drawOrder:D});let b=u.drawDefinitions.find(v=>v.drawId===p),C=a?.tournamentId,_=u.eventId;if(b){if(!i)return{error:xD};e9({existingDrawDefinition:b,suppressNotifications:r,drawDefinition:c,tournamentId:C,eventId:_,event:u,drawId:p})}else r9({suppressNotifications:r,tournamentRecord:a,drawDefinition:c,tournamentId:C,eventId:_,event:u});return{...P,modifiedEventEntryStatusCount:f}}function ZQ({drawEntries:t,eventEntries:e,relevantFlight:r,checkEntryStatus:n}){let o=t?.every(({participantId:s,entryStatus:a})=>{let c=r?.drawEntries.find(u=>u.participantId===s);return!a||c?.entryStatus===a}),i=!n||e&&t?.every(({participantId:s,entryStatus:a,entryStage:c})=>e.find(p=>p.participantId===s&&(!p.entryStage||p.entryStage===c))?.entryStatus===a);return r&&!o?M({result:{error:ha},context:{drawEntriesPresentInFlight:o,matchingEventEntries:i,relevantFlight:r},info:"Draw entries are not present in flight or do not match entryStatuses"}):{drawEntriesPresentInFlight:o,matchingEventEntries:i}}function t9({drawEntries:t,eventEntries:e}){let r=0;return t?.filter(Boolean).forEach(n=>{if(n?.entryStatus&&yr.includes(n?.entryStatus)){let o=e?.filter(Boolean).find(i=>i.participantId===n.participantId);o&&n.entryStatus&&o?.entryStatus!==n.entryStatus&&(o.entryStatus=n.entryStatus,r+=1)}}),r}function e9({existingDrawDefinition:t,suppressNotifications:e,drawDefinition:r,tournamentId:n,eventId:o,event:i,drawId:s}){let c=rr({drawDefinition:t})?.matchUps?.map(Te)??[],u=rr({drawDefinition:r})?.matchUps;if(!e){c?.length&&wn({matchUpIds:c,action:"modifyDrawDefinition",tournamentId:n,eventId:o}),u?.length&&Ho({matchUps:u,tournamentId:n,eventId:o}),i.drawDefinitions=i.drawDefinitions.map(m=>m.drawId===s?r:m);let p=r.structures?.map(({structureId:m})=>m);Ft({drawDefinition:r,tournamentId:n,structureIds:p,eventId:o})}}function r9({suppressNotifications:t,tournamentRecord:e,drawDefinition:r,tournamentId:n,eventId:o,event:i}){if(i.drawDefinitions.push(r),!t){let{matchUps:s}=rr({drawDefinition:r,event:i});s&&Ho({tournamentId:e?.tournamentId,matchUps:s}),yc({drawDefinition:r,tournamentId:n,eventId:o})}}function wv(t){let{provisionalPositioning:e,useExistingSeedLimit:r,tournamentRecord:n,drawDefinition:o,seedingProfile:i,structureId:s,assignments:a,drawId:c,event:u}=t,p=0;if(!a?.length)return{error:Bg};let m=dt({tournamentRecord:n,drawId:c},[rt,dc]);if(m.error)return m;let d=Ur({provisionalPositioning:e,drawDefinition:o,structureId:s});if(d.error)return d;let{seedAssignments:l,seedLimit:f}=d,g=Object.assign({},...(l??[]).filter(h=>h.seedNumber).map(h=>({[h.seedNumber]:h})));a.forEach(h=>{let{seedNumber:T}=h;f&&T<=f&&(!r||g[T])&&(g[T]=h)});let I=Object.values(g),S=I.map(h=>h?.participantId).filter(Boolean);if(S.length!==_T(S).length)return{error:wD};for(let h of I){let T=Wa({...h,provisionalPositioning:e,tournamentRecord:n,drawDefinition:o,seedingProfile:i,structureId:s,event:u});if(T?.error)return T;T?.success&&p++}return p?{...P,modifications:p}:{error:Na}}function gh({deleteExisting:t,event:e,flightProfile:r}){let n="attachFlightProfile";if(!r)return M({result:{error:nt},stack:n});if(!e)return M({result:{error:le},stack:n});let{flightProfile:o}=Bt({event:e});return o&&!t?M({result:{error:sI},stack:n}):e.drawDefinitions?.length?M({result:{error:CD},stack:n}):(Go({event:e,extension:{name:on,value:r}}),{flightProfile:q(r,!1,!0),...P})}function oG({tournamentRecord:t,scaleAttributes:e,participantIds:r}){let n=dt({tournamentRecord:t},[rt]);if(n.error)return n;if(!r)return{error:Mo};if(!e)return{error:nt,info:"scaleAttributes required"};let{scaleType:o,eventType:i,scaleName:s}=e,a=[Tb,o,i,s].join(".");return t.participants?.forEach(c=>{r.includes(c.participantId)&&c.timeItems&&(c.timeItems=c.timeItems.filter(u=>u&&u?.itemType!==a))}),{...P}}function Ih({tournamentRecord:t,scaleAttributes:e,drawDefinition:r,entryStatuses:n,drawId:o,event:i,stage:s}){if(!i)return{error:le};if(n&&!Array.isArray(n))return M({result:{error:O},info:Ri("entryStatus"),stack:"removeScaleValues"});let a=i.entries;if(o){let{flightProfile:p}=Bt({event:i}),m=p?.flights?.find(d=>d.drawId===o);m?a=m.drawEntries:a=r?.entries}let u=(a??[]).filter(p=>(!s||!p.entryStage||p.entryStage===s)&&(!n||n.includes(p.entryStatus))).map(gt);return oG({tournamentRecord:t,scaleAttributes:e,participantIds:u})}function tg({removePriorValues:t,tournamentRecord:e,displaySettings:r,status:n=br,event:o}){if(!e)return M({result:{error:j}});if(!o)return M({result:{error:le}});if(!Tt(r))return M({result:{error:nt}});if(Tt(r.draws))for(let s of Object.keys(r.draws)){let a=r.draws[s].scheduleDetails??[];if(a.length){let c=[];for(let u of a){let p=c.find(m=>rw(m.attributes,u.attributes));p?.dates&&u.dates?p.dates.push(...u.dates):c.push(u)}r.draws[s].scheduleDetails=c}}let i=ec({statusObject:{displaySettings:r},removePriorValues:t,status:n,event:o});return i.error?i:{...P}}function Lv({tournamentRecord:t,drawDefinition:e,entryStatuses:r,scaleName:n,drawId:o,event:i,stage:s}){let a=dt({tournamentRecord:t,event:i},[rt,ce]);if(a.error)return a;n=n||i.category?.categoryName||i.category?.ageCategoryCode;let c={eventType:i.eventType,scaleType:Eo,scaleName:n};return Ih({tournamentRecord:t,scaleAttributes:c,drawDefinition:e,entryStatuses:r,drawId:o,event:i,stage:s})}function Fv(t){let e=X(t,[{[rt]:!0},{eventIds:!0,[Ge]:ke}]);if(e.error)return e;let{removePairParticipants:r,tournamentRecord:n,eventIds:o}=t,i=[],s=[],a=[],c=[];if(n.events=(n.events??[]).filter(u=>{if(o.includes(u.eventId)){let d={action:ph,payload:{events:[u]}};i.push(d),s.push({tournamentId:n.tournamentId,eventName:u.eventName,eventType:u.eventType,category:u.category,eventId:u.eventId,gender:u.gender})}let p=u.eventType===Lt?(u.entries??[]).map(({entryStatus:d,participantId:l})=>d!==Gr&&l).filter(Boolean):[],m=o.includes(u.eventId);return m?c.push(...p):a.push(...p),!m}),r){let u=new Set(c.filter(p=>!a.includes(p)));n.participants=n.participants.filter(({participantId:p})=>!u.has(p))}if(ku({tournamentRecord:n}),i.length)if(tu(Yi)){let u=n.tournamentId;at({topic:Yi,payload:{type:ph,tournamentId:u,detail:i}})}else vu({tournamentRecord:n,timeItem:{itemValue:s,itemType:ph}});return{...P}}function kv(t){let e=X(t,[{tournamentRecord:!0,eventId:!0,event:!0},{eventUpdates:!0,_ofType:qr}]);if(e.error)return e;let{eventUpdates:r,event:n}=t,o="modifyEvent",i=a9(t),s=c9({enteredParticipants:i}),{enteredParticipantGenders:a,enteredParticipantTypes:c}=s,u=Bt({event:n})?.flightProfile?.flights,p=!n.drawDefinitions?.length&&!u?.length,m=u9({noFlightsNoDraws:p,enteredParticipantGenders:a,eventUpdates:r,stack:o});if(m.error)return m;let d=p9({enteredParticipantTypes:c,eventUpdates:r,stack:o});if(d.error)return d;let l=n9({...t,...s,enteredParticipants:i,stack:o});if(l.error)return l;let f=s9({...t,stack:o});return f.error?f:(r.eventType&&(n.eventType=r.eventType),r.eventName&&(n.eventName=r.eventName),r.gender&&(n.gender=r.gender),{...P})}function n9(t){let e=t.eventUpdates?.category;if(!e)return{...P};let r=lp({category:e});if(r.error)return r;if(t.event.eventType===Oe){let n=o9(t);if(n.error)return n}if(t.enteredParticipants?.length){let n=i9(t,e);if(n.error)return n}return{...P}}function o9(t){let e=t.event?.drawDefinitions?.map(a=>Yo(a))??[],r=Yo(t.event),o=(vn(t)?.matchUps??[]).map(a=>Yo(a))??[];return[r,...e,...o].filter(Boolean).every(a=>a.collectionDefinitions.every(c=>!c.category||fp({category:t.eventUpdates.category,childCategory:c.category})))?{...P}:M({result:{error:cp},stack:t.stack})}function i9(t,e){let r=t.eventUpdates.startDate||t.event.startDate||t.tournamentRecord.startDate,n=t.eventUpdates.endDate||t.event.endDate||t.tournamentRecord.endDate,o=t.enteredParticipants.flatMap(a=>a.participantType===St?[a]:a.individualParticpants??[]),i=gs({category:e,consideredDate:r}),s=gs({category:e,consideredDate:n});if(i?.ageMinDate||i?.ageMaxDate||s?.ageMinDate||s?.ageMaxDate)for(let a of o){let c=a.person?.birthDate;if(!c)return M({result:{error:nU},stack:t.stack});let u=new Date(c).getTime(),p=iG(u,i,t.stack);if(p)return p;let m=iG(u,s,t.stack);if(m)return m}return{...P}}function iG(t,e,r){if(!e)return null;if(e.ageMinDate||e.ageMaxDate){let n=new Date(e.ageMinDate).getTime(),o=new Date(e.ageMaxDate).getTime();if(t<n||t>o)return M({result:{error:uU},stack:r})}return null}function s9(t){let{tournamentRecord:e,eventUpdates:r,event:n,stack:o}=t;if(r.startDate||r.endDate){let i=dh({startDate:r.startDate||n.startDate||e.startDate,endDate:r.endDate||n.endDate||e.endDate,tournamentRecord:e,event:n});if(i.error)return M({result:i,stack:o})}return{...P}}function a9(t){let{tournamentRecord:e,event:r}=t,n=r?.entries?.filter(({entryStatus:o})=>{let i=o;return[...yr,Zr].includes(i)}).map(({participantId:o})=>o)??[];return n?bt({participantFilters:{participantIds:n},withIndividualParticipants:!0,tournamentRecord:e}).participants??[]:[]}function c9({enteredParticipants:t}){let e=[],r=t.reduce((o,i)=>{let s=i.person?.sex?[i.person.sex]:i.individualParticpants?.map(a=>a.person?.sex)??[];return e.push(...s),o.includes(i.participantType)?o:o.concat(i.participantType)},[]),n=pt(e);return{enteredParticipantTypes:r,enteredParticipantGenders:n}}function u9({noFlightsNoDraws:t,enteredParticipantGenders:e,eventUpdates:r,stack:n}){let o=!e.length||!r.gender||Oo(r.gender)||e.length===1&&e[0]===r.gender||t&&nn(r.gender);return r.gender&&!o?M({context:{gender:r.gender,validGender:o},result:{error:wm},stack:n}):{...P}}function p9({enteredParticipantTypes:t,eventUpdates:e,stack:r}){let i=(t.includes(St)&&t.includes(lt)&&[Ip]||t.includes(Oe)&&[Oe]||t.includes(St)&&[Dt,Ip]||t.includes(lt)&&[Lt,Ip]||[Lt,Dt,Oe,Ip]).includes(e.eventType??"");return e.eventType&&!i?M({context:{participantType:e.eventType,validEventType:i},result:{error:zn},stack:r}):{...P}}function kd({qualifyingPositions:t,drawEntries:e=[],drawName:r,drawId:n,event:o,stage:i}){let s="addFlight";if(!o)return M({result:{error:le},stack:s});if(!r)return M({result:{error:nt},stack:s});if(e?.length){let g=(o.entries??[]).map(gt),I=e.map(gt);if(Yt(I,g).length!==I.length)return M({result:{error:O},stack:s})}let a=Bt({event:o})?.flightProfile,c=a?.flights?.map(({flightNumber:g})=>!Number.isNaN(Number(g))&&st(g))?.filter(Boolean)??[],u=Math.max(0,...c)+1,m={drawId:n||it(),flightNumber:u,drawEntries:e,drawName:r};if(i&&(m.stage=i),t&&(m.qualifyingPositions=t),(a?.flights??[]).find(({drawId:g})=>g===m.drawId))return M({result:{error:kU},stack:s});let l=(a?.flights??[]).concat(m),f={name:on,value:{...a,flights:l}};return Go({event:o,extension:f})}var jv={};Gt(jv,{drawMatic:()=>im,garman:()=>Yv,generateAdHocMatchUps:()=>Mc,generateAdHocRounds:()=>Lf,generateAndPopulatePlayoffStructures:()=>Sf,generateCourts:()=>Sh,generateDrawDefinition:()=>xc,generateDrawMaticRound:()=>bf,generateDrawStructuresAndLinks:()=>Df,generateDrawTypeAndModifyDrawDefinition:()=>Uf,generateFlightProfile:()=>aG,generateLineUps:()=>JP,generateQualifyingStructure:()=>lf,generateSeedingScaleItems:()=>WP,generateStatCrew:()=>mG,generateVoluntaryConsolation:()=>xA,roundRobinGroups:()=>k0});var m9="splitLevelBased",Bv="splitWaterfall",Wv="splitShuttle",sG={SPLIT_LEVEL_BASED:m9,SPLIT_WATERFALL:Bv,SPLIT_SHUTTLE:Wv};function aG(t){let{drawNameRoot:e="Flight",attachFlightProfile:r,tournamentRecord:n,scaleAttributes:o,scaleSortMethod:i,deleteExisting:s,sortDescending:a,drawNames:c=[],flightsCount:u,splitMethod:p,uuids:m=[],random:d,event:l,stage:f}=t;if(!l)return{error:le};let g=l.entries??[],{flightProfile:I}=Bt({event:l});if(I&&r&&!s)return{error:sI};let S=t.scaledEntries??Xa({tournamentRecord:n,scaleAttributes:o,scaleSortMethod:i,sortDescending:a,event:l,stage:f}).scaledEntries,h=new Set(S.map(gt)),T=ar(g.filter(({participantId:b})=>!h.has(b)).filter(b=>(!f||!b.entryStage||b.entryStage===f)&&(!b.entryStatus||$i.includes(b.entryStatus))),d),y=S.concat(...T),E=y.length,A=Math.ceil(E/u),N=he(y,A);p===Bv?N=wg(y,u):p===Wv&&(N=wg(y,u,!0));function D(b){return(b??[]).map(({participantId:C,scaleValue:_})=>{let v=g.find(w=>w.participantId===C);return v?.scaleValue&&_&&(v.scaleValue=_),v}).sort((C,_)=>C.scaleValue-_.scaleValue).map((C,_)=>(C.scaleValue&&(C.seedNumber=_+1),C))}let R=Q(0,u).map(b=>{let C=b+1;return{flightNumber:C,drawId:m?.pop()??it(void 0,d),drawEntries:D(N[b]),drawName:c?.length&&c[b]||`${e} ${C}`}}),U={scaleAttributes:o,splitMethod:p,flights:R};if(r){let b=gh({flightProfile:U,deleteExisting:s,event:l});return{splitEntries:je()&&N||void 0,...b}}else return{flightProfile:U,...P}}function Hv({json:t,tagName:e}){let r=Object.keys(t).filter(i=>Array.isArray(t[i])).map(i=>({key:i,value:t[i].filter(s=>typeof s=="object"&&Object.keys(s).length===1)})),n=Object.keys(t).filter(i=>typeof t[i]=="object"&&!Array.isArray(t[i])).map(i=>({key:i,value:t[i]})),o=Object.keys(t).filter(i=>["string","number"].includes(typeof t[i])).map(i=>({key:i,value:t[i]}));return cG({tagName:e,attributes:o,childArrays:r,childObjects:n})}function cG(t){let{tagName:e,attributes:r=[],childArrays:n=[],childObjects:o}=t,i=`\r
|
|
25
25
|
`,s=l=>{let f=Object.keys(l)[0],g=l[f];return{key:f,value:g}},a=n?.map(({key:l,value:f})=>cG({tagName:l,childObjects:f.map(s)})).join(`\r
|
|
26
26
|
`),c=o?.map(({key:l,value:f})=>Hv({tagName:l,json:f??[]})).join(`\r
|
|
27
27
|
`),u=r?.map(({key:l,value:f})=>`${l}="${f}"`).join(" "),p=u?` ${u}`:"";if(e==="childArray")return c;let m=c?.length?`${i}${c}${i}`:"",d=a?.length?`${i}${a}${i}`:"";return`<${e}${p}>${m}${d}</${e}>`}function mG(t){let e=X(t,[{[rt]:!0}]);if(e.error)return e;let{tournamentRecord:r}=t,{startDate:n,tournamentId:o,tournamentName:i}=r,{participantMap:s,matchUps:a,mappedMatchUps:c}=bt({withMatchUps:!0,withEvents:!0,tournamentRecord:r}),u=r.participants.filter(y=>y.participantType===_t),p=a?.filter(y=>y.matchUpType===_t)??[],m=p?.reduce((y,E)=>{let A=E?.tieMatchUps??[];return A&&[...y,...A]},[])??[],d=a?.filter(y=>y.matchUpType===Ct)??[],l=a?.filter(y=>y.matchUpType===Rt)??[],f=m.length===d.length+l.length,g=p.length===1&&f,S={mappedMatchUps:c,participantMap:s,tournamentName:i,tournamentId:o,tournament:f?"N":"Y",startDate:n},h=[],T=[];if(g){let y=p[0],{json:E,xml:A}=uG({teamParticipants:u,teamMatchUp:y,...S,doubles:l,singles:d});T.push(E),h.push(A)}else for(let y of p){let E=y?.sides?.map(({participant:R})=>R?.participantId).filter(Boolean);if(E?.length!==2)continue;let A=E.map(R=>R&&s?.[R]?.participant),{xml:N,json:D}=uG({doubles:y.tieMatchUps?.filter(R=>R.matchUpType===Rt),singles:y.tieMatchUps?.filter(R=>R.matchUpType===Ct),teamParticipants:A,teamMatchUp:y,...S});T.push(D),h.push(N)}return{json:T,xml:h,...P}}function uG({teamParticipants:t,mappedMatchUps:e,participantMap:r,tournamentName:n,tournamentId:o,teamMatchUp:i,tournament:s,startDate:a,doubles:c,singles:u}){let p=t?.find(y=>y.participantRoleResponsibilities?.includes("Home")),m=t?.filter(y=>y.participantId!==p?.participantId),d=Qn(a,"/","MDY"),l=p?.participantName||m?.[1]?.participantName,f=p?.participantId||m?.[1]?.participantId,g=m?.[0]?.participantName,I=m?.[0]?.participantId,S={},h=t.map(y=>({team:{...f9({teamParticipant:y,teamMatchUp:i,uniValues:S,participantMap:r,mappedMatchUps:e,homeid:f})}})),T=et({venue:{tournamentname:s?n:void 0,neutralgame:p?"N":"Y",gameid:o,officials:{},tournament:s,rules:{},homename:l,visname:g,homeid:f,visid:I,date:d},childArray:h,singles_matches:u?.map(y=>pG({matchUp:y,homeid:f,uniValues:S})),doubles_matches:c?.map(y=>pG({matchUp:y,homeid:f,uniValues:S}))});return{json:T,xml:Hv({json:T,tagName:"tngame"})}}function d9({homeid:t,uniValues:e,participant:r}){if(!r)return{};let n=r.individualParticipants?.length===2,o=n?pt(r.individualParticipants?.map(g=>g.teams?.[0]?.participantId)):[],i=n?pt(r.individualParticipants?.map(g=>g.teams?.[0]?.teamId)):[],s=!n&&r.teams?.[0]?.participantId||o?.length===1&&o[0]||void 0,a=!n&&r.teams?.[0]?.teamId||i?.length===1&&i[0]||s,c=n?void 0:r.participantName,u=r.individualParticipants?.[0]?.participantName,p=r.individualParticipants?.[1]?.participantName,m=t&&(s===t?"H":"V")||"",d=n?void 0:e[s][r.participantId],l=e[s][r.individualParticipants?.[0]?.participantId],f=e[s][r.individualParticipants?.[1]?.participantId];return et({vh:m,uni:d,uni_1:l,uni_2:f,team:a,name:c,name_1:u,name_2:p})}function l9({sets:t,sideNumber:e}){return Object.assign({},...t?.map(r=>{let{setNumber:n,side1Score:o,side2Score:i,side1TiebreakScore:s,side2TiebreakScore:a}=r,c=`set_${n}`,u=`tie_${n}`,p=e===1?o:i,m=e===1?s:a;return{[c]:p,[u]:m}})??[])}function f9({teamParticipant:t,teamMatchUp:e,participantMap:r,mappedMatchUps:n,homeid:o,uniValues:i}){let{participantId:s,participantName:a}=t,c=o&&(s===o?"H":"V")||"",u=r?.[s]?.matchUps,p=u&&Object.keys(u),m=e?.sides?.find(({participant:E})=>E.participantId===s)?.sideNumber,d=e?.score?.sets?.[0]?.[`side${m}Score`]??0;i[s]={};let l={SINGLES:{w:0,l:0},DOUBLES:{w:0,l:0}},f=[],g=[],I=0;for(let E of p??[]){let A=n?.[E],N=A.sides.find(({participant:R})=>R.participantId===s)?.sideNumber,D=A.score?.sets?.[0]?.[`side${N}Score`]??0;I+=D;for(let R of A.tieMatchUps??[]){let{matchUpType:U,winningSide:b}=R,C=b&&(b===N?"w":"l")||"";C&&(l[U][C]+=1);let _=C==="w"?"1":"0",v=C==="l"?"1":"0";if(U===Ct){let w=g.length+1;g.push({singles_pair:{pair:w,won:_,lost:v,tied:"0"}})}else if(U===Rt){let w=f.length+1;f.push({doubles_pair:{pair:w,won:_,lost:v,tied:"0"}})}}}let S=[{singles:{childArray:g,won:l.SINGLES.w,lost:l.SINGLES.l}},{doubles:{childArray:f,won:l.DOUBLES.w,lost:l.DOUBLES.l}}],h=[],T=1;for(let E of t.individualParticipantIds){let A=r?.[E];if(A){let{participant:N,counters:D}=A,R={won:D?.DOUBLES?.wins||0,lost:D?.DOUBLES?.losses||0},U={won:D?.SINGLES?.wins||0,lost:D?.SINGLES?.losses||0},{participantName:b,participantId:C}=N;i[s][C]=T,h.push({player:{name:b,uni:T,singles:U,doubles:R}})}T+=1}return{vh:c,id:s,name:a,score:d||I,totals:S,childArray:h}}function pG({matchUp:t,homeid:e,uniValues:r}){let{collectionPosition:n,orderOfFinish:o,matchUpType:i,sides:s}=t??{},a=s?.map(u=>{let{sideNumber:p,participant:m}=u,d=l9({sets:t.score?.sets,sideNumber:p});return{[i===Ct?"singles_score":"doubles_score"]:{...d9({homeid:e,uniValues:r,participant:m}),...d}}});return{[i===Ct?"singles_match":"doubles_match"]:{match:n,order:o,childArray:a}}}var g9="DESC",XP="DESC",dG={ASC:"ASC",ASCENDING:"ASC",DESC:g9,DESCENDING:XP};function JP(t){let{tieFormat:e}=t,{useDefaultEventRanking:r,tournamentRecord:n,drawDefinition:o,scaleAccessor:i,singlesOnly:s,attach:a,event:c}=t;if(c?.eventType!==Ze)return{error:zn};if(!n)return{error:j};if(!e&&!o)return{error:Mr};if(e=e??ze({drawDefinition:o,event:c})?.tieFormat,or({tieFormat:e}).error)return{error:ri};if(typeof i!="object"&&!r)return{error:O,context:{scaleAccessor:i}};let u={},m=(o?.entries??c?.entries??[]).filter(C=>C?.entryStatus===kr).map(gt),{participants:d=[]}=bt({withIndividualParticipants:!0,withScaleValues:!0,tournamentRecord:n}),l=d.filter(({participantId:C})=>m.includes(C)),f=C=>C===Jn?"rankings":"ratings",g=c?.category?.categoryName??c?.category?.ageCategoryCode,{scaleName:I=g,scaleType:S=Jn,sortOrder:h,accessor:T}=i??{},y=f(S),E=(C,_)=>{let v=C[y]?.[_];if(!v&&r&&(v=C[y]?.[Os]),Array.isArray(v)){let w=v.find(L=>L.scaleName===I)?.scaleValue;if(Le(w))return w;if(T&&typeof w=="object")return w[T]}return 0},A=(C,_,v)=>{let w=h===XP?_:C,L=h===XP?C:_;return E(w,v)-E(L,v)},N=(C,_)=>A(C,_,Os),D=(C,_)=>A(C,_,ei),R=[],U=e?.collectionDefinitions??[];for(let C of l){let _=C.individualParticipants?.sort(N)??[],v=s?_:C.individualParticipants?.sort(D)??[],w={};for(let F of U){let x=[],{collectionId:k,matchUpCount:G,matchUpType:V,gender:B}=F,z=re(Os)(V);Q(0,G).forEach(H=>{let K=z?_:v??[],Y=H+1,J=[];Q(0,z?1:2).forEach(ct=>{let Et=K?.find(Ht=>{let Ut=Ar(B),pe=Ut&&(Un(B)&&Ut||nn(B)&&[Ce,Je][ct]);return(!pe||pe===Ht.person?.sex)&&!x.includes(Ht.participantId)})?.participantId;Et&&(J.push(Et),x.push(Et),w[Et]||(w[Et]=[]),w[Et].push({collectionPosition:Y,collectionId:k}))}),z||R.push(J)})}let L=Object.keys(w).map(F=>({collectionAssignments:w[F],participantId:F}));u[C.participantId]=L}let b=[];for(let C of R){let{participant:_}=Tn({tournamentParticipants:d,participantIds:C});if(!_){let v={individualParticipantIds:C,participantRole:Ve,participantType:lt};b.push(v)}}if(a){for(;b.length;)Gn({participant:b.pop(),tournamentRecord:n});ut({element:o,extension:{name:Vo,value:u}})}return{...P,lineUps:u,participantsToAdd:b}}function Sh(t){if(!t)return{error:nt};let e=X(t,[{dates:!1,[$e]:s=>Array.isArray(s)&&s.every(Me)},{uuids:!1,[$e]:s=>Array.isArray(s)&&s.every(wt)},{startTime:!1,endTime:!1,[$e]:ry},{idPrefix:!1,namePrefix:!1,[$e]:wt},{count:!0,[$e]:Le}]);if(e.error)return e;let{startDate:r,endDate:n}=t.tournamentRecord??{},o=t.dates??(r&&n?Ua(r,n):[]),i=Q(1,t.count+1).map(s=>et({courtId:t.uuids?.pop()??(t.idPrefix&&`${t.idPrefix}-${s}`)??it(),courtName:t.courtNames?.pop()??(t.namePrefix&&`${t.namePrefix} ${s}`),dateAvailability:o.map(a=>({startTime:t.startTime??"08:00",endTime:t.endTime??"20:00",date:a}))}));return{...P,courts:i}}var Yv={};Gt(Yv,{default:()=>I9,garman:()=>gG});function pa(t){let e=X(t,[{courtDate:!0,_ofType:qr}]);if(e.error)return e;let{includeBookingTypes:r=[],courtDate:n}=t,o=[],i=ve(n.startTime);(n.bookings??[]).filter(a=>!a.bookingType||!r.includes(a.bookingType)).sort((a,c)=>(II(a.startTime)||"").localeCompare(II(c.startTime)||"")).forEach(a=>{let c={startTime:$t(i.toISOString()),endTime:a.startTime};ve(a.startTime)>i&&o.push(c),ve(a.endTime)>i&&(i=ve(a.endTime))});let s={startTime:$t(i.toISOString()),endTime:n.endTime};return ve(n.endTime)>i&&o.push(s),{timeSlots:o}}function lG({averageMatchUpMinutes:t,includeBookingTypes:e,periodStartTime:r,periodEndTime:n}){let o=s=>{let{timeSlots:a}=pa({includeBookingTypes:e,courtDate:s});return!!a?.filter(i)?.length};function i(s){let a=ve(s.startTime),c=ve(s.endTime);return a>r||c<n?!1:ks(r,c)>=t}return{enoughTime:o}}function ZP(t){let e=X(t,[{periodStart:!0,date:!0},{courts:!0,_ofType:ke}]);if(e.error)return e;let{averageMatchUpMinutes:r,includeBookingTypes:n,periodStart:o,date:i}=t,s=t.courts,a=ve(o),c=hI(a,r),{enoughTime:u}=lG({averageMatchUpMinutes:r,includeBookingTypes:n,periodStartTime:a,periodEndTime:c});return{availableToScheduleCount:(s?.filter(m=>{if(!Array.isArray(m.dateAvailability))return!1;let d=Qo({date:i,court:m});return!!(d&&u(d))})??[]).length,...P}}function Gd(t){let{remainingScheduleTimes:e=[],clearScheduleDates:r,periodLength:n=30,scheduleDate:o,courts:i=[]}=t,{bookings:s=[]}=t;if(!Array.isArray(i)||!i.length)return{error:O,courts:i};if(!Array.isArray(s))return{error:il};if(!Me(o))return{error:ae};r&&(Array.isArray(r)?r.includes(o)&&(s=[]):s=[]);let{courtBookings:a,unassignedBookings:c}=s.reduce((l,f)=>{let{courtId:g}=f;return g?l.courtBookings[g]?l.courtBookings[g].push(f):l.courtBookings[g]=[f]:l.unassignedBookings.push(f),l},{courtBookings:{},unassignedBookings:[]}),u=i.map((l,f)=>{let{courtId:g,courtName:I}=l,S=a[g]??[],h=Qo({date:o,court:l})??{},{bookings:T=[],startTime:y,endTime:E,date:A}=h,D=[e[f]&&{startTime:y,endTime:e[f]},...q(T,!1,!0),...S].filter(Boolean);return{courtId:g,courtName:I,dateAvailability:{bookings:D,startTime:y,endTime:E,date:A}}});c.sort((l,f)=>jt(l.startTime)-jt(f.startTime));let p=()=>u.flatMap(l=>{let f=l.dateAvailability,{timeSlots:g=[]}=pa({courtDate:f});return{courtName:l.courtName,courtId:l.courtId,timeSlots:g}}),m=[];for(let l of c){let{startTime:f,endTime:g,averageMinutes:I,recoveryMinutes:S,matchUpId:h}=l,T=jt(f),y=jt(g),A=p().reduce((N,{courtId:D,courtName:R,timeSlots:U})=>{let b;return U.find(({startTime:_,endTime:v})=>{b=jt(_)-T;let w=T>=jt(_);return y<=jt(v)&&N.startDifference!==0&&((b===0||b+n>=0)&&(N.startDifference===void 0||b<N.startDifference)||w)})?{courtName:R,courtId:D,startDifference:b}:N},{});if(A.courtId){let N={averageMinutes:I,recoveryMinutes:S,matchUpId:h,startTime:f,endTime:g};m.push(N),u.find(({courtId:R})=>R===A.courtId)?.dateAvailability.bookings.push(N)}else console.log({unassignedBooking:l})}return{virtualCourts:u.map(({courtId:l,courtName:f,dateAvailability:g})=>({dateAvailability:[g],courtName:f,courtId:l})),assignedBookings:m}}function cm({averageMatchUpMinutes:t,periodLength:e=30,recoveryMinutes:r}){let n=(t||90)+(r||0);return e>n?n:e||30}function tN(t){let{startTime:e="8:00",endTime:r="20:30",count:n=10,date:o}=t??{};return Q(0,n).map(()=>({dateAvailability:[{date:o,startTime:e,endTime:r}]}))}function Vu({scheduleDate:t,startTime:e,endTime:r,courts:n}){let o=e&&"startTime"||r&&"endTime"||void 0;return n.reduce((i,s)=>{let a=Qo({date:t,court:s}),c=o&&(a?.[o]||s[o]);return c&&(!i||e&&jt(c)<jt(i)||r&&jt(c)>jt(i))?c:i},void 0)}function fG({averageMinutes:t,startTime:e,endTime:r,courts:n,date:o}){e=e||Vu({courts:n,scheduleDate:o,startTime:!0}),r=r||Vu({courts:n,scheduleDate:o,endTime:!0});let i;if(e&&r){let s=ve(e),a=ve(r);for(let c of n??[]){if(!Array.isArray(c.dateAvailability))continue;let u=Qo({court:c,date:o}),{timeSlots:p}=pa({courtDate:u});p?.forEach(m=>{let d=ve(m.startTime),l=ve(m.endTime);if(d>a||d<s||l<s)return!1;if(ks(d,l)>=t){let I=$t(d.toISOString());I&&(!i||I<i)&&(i=I)}})}}return{firstTimeSlotStartTime:i}}function eg(t){let e=X(t,[{courts:!0,_ofType:ke}]);if(e.error)return e;let{date:r=SI(),startTime:n="08:00",endTime:o="19:00",periodLength:i,courts:s}=t,{calculateStartTimeFromCourts:a=!0,remainingScheduleTimes:c,averageMatchUpMinutes:u,clearScheduleDates:p,courtsCount:m,bookings:d}=t;i=i||cm({averageMatchUpMinutes:u}),r=mt(r),n=$t(n),o=$t(o);let l=0,f=0,g=0,I=0,S=0;!s&&m&&(s=tN({startTime:n,endTime:o,count:m,date:r}));let{virtualCourts:h}=Gd({remainingScheduleTimes:c,clearScheduleDates:p,scheduleDate:r,periodLength:i,bookings:d,courts:s}),{firstTimeSlotStartTime:T}=fG({averageMinutes:u,courts:h,startTime:n,endTime:o,date:r});a&&T&&(n=T??n);let y=jt(n),A=jt(o)-y,N=Math.floor(A/i),R=Q(0,N+1).map(b=>{let C=y+b*i,_=Gw(C),v=ZP({courts:h??[],averageMatchUpMinutes:u,periodStart:_,date:r});if(v.error)return{error:v.error};let{availableToScheduleCount:w=0}=v,L=w>f?w-f:0;S+=b?w:0;let F=b?S/b:w,k=i*F/u,G=b?k*(b-1)+F:F,V=w?f&&G-l||L:0;l=G,f=w,g+=V;let B=st(g)-I;return I+=B,{periodStart:_,add:B,availableToScheduleCount:w,newCourts:L,totalMatchUps:I}});return{scheduleTimes:R.reduce((b,C)=>{let v=Q(0,C.add).map(()=>({scheduleTime:C.periodStart}));return b.concat(...v)},[]).flat(),timingProfile:R,totalMatchUps:I}}var gG={getCourtsAvailableAtPeriodStart:ZP,generateTimeSlots:pa,getScheduleTimes:eg,courtGenerator:tN},I9=gG;var eN={};Gt(eN,{isAggregateFormat:()=>Dd,isValid:()=>xr,isValidMatchUpFormat:()=>xr,parse:()=>oe,stringify:()=>mp});var mO={};Gt(mO,{allCompetitionMatchUps:()=>cn,allDrawMatchUps:()=>rr,allEventMatchUps:()=>vn,allTournamentMatchUps:()=>qt,analyzeMatchUp:()=>Ld,applyLineUps:()=>uO,assignMatchUpSideParticipant:()=>qv,assignTieMatchUpParticipantId:()=>og,bulkMatchUpStatusUpdate:()=>iO,calculateMatchUpMargin:()=>Id,calculateWinCriteria:()=>ua,checkInParticipant:()=>Th,checkMatchUpIsComplete:()=>Js,checkOutParticipant:()=>hh,competitionScheduleMatchUps:()=>am,disableTieAutoCalc:()=>nO,drawMatchUps:()=>FP,enableTieAutoCalc:()=>tO,eventMatchUps:()=>Qf,filterMatchUps:()=>zi,findMatchUp:()=>ch,getAllDrawMatchUps:()=>te,getAllStructureMatchUps:()=>ht,getCheckedInParticipantIds:()=>$s,getCompetitionFormat:()=>MP,getCompetitionMatchUps:()=>wd,getEventMatchUpFormatTiming:()=>UP,getHomeParticipantId:()=>_P,getMatchUpCompetitiveProfile:()=>js,getMatchUpContextIds:()=>OP,getMatchUpDailyLimits:()=>Jf,getMatchUpDailyLimitsUpdate:()=>CP,getMatchUpDependencies:()=>tn,getMatchUpFormat:()=>xP,getMatchUpFormatTiming:()=>Fp,getMatchUpFormatTimingUpdate:()=>NP,getMatchUpScheduleDetails:()=>Kl,getMatchUpType:()=>zl,getMatchUpsStats:()=>wP,getModifiedMatchUpFormatTiming:()=>Kf,getParticipantResults:()=>Vp,getPredictiveAccuracy:()=>vP,getRoundMatchUps:()=>Ue,getRounds:()=>LP,isValidMatchUpFormat:()=>xr,matchUpActions:()=>Af,mutate:()=>pO,participantScheduledMatchUps:()=>bP,predictMatchUpCompetitiveBands:()=>RP,query:()=>dv,removeDelegatedOutcome:()=>eO,removeMatchUpSideParticipant:()=>Eh,removeTieMatchUpParticipantId:()=>Kv,replaceTieMatchUpParticipantId:()=>yh,resetAdHocMatchUps:()=>aO,resetMatchUpLineUps:()=>Ph,resetScorecard:()=>Uh,resetTieFormat:()=>Dh,setDelegatedOutcome:()=>sO,setMatchUpFormat:()=>oO,setMatchUpState:()=>vi,setMatchUpStatus:()=>wc,setOrderOfFinish:()=>cO,substituteParticipant:()=>rO,tallyParticipantResults:()=>ea,toggleParticipantCheckInState:()=>rg,tournamentMatchUps:()=>Xf,updateTieMatchUpScore:()=>ho,validMatchUp:()=>rS,validMatchUps:()=>Rr});var pO={};Gt(pO,{applyLineUps:()=>uO,assignMatchUpSideParticipant:()=>qv,assignTieMatchUpParticipantId:()=>og,bulkMatchUpStatusUpdate:()=>iO,checkInParticipant:()=>Th,checkOutParticipant:()=>hh,disableTieAutoCalc:()=>nO,enableTieAutoCalc:()=>tO,findMatchUp:()=>ch,removeDelegatedOutcome:()=>eO,removeMatchUpSideParticipant:()=>Eh,removeTieMatchUpParticipantId:()=>Kv,replaceTieMatchUpParticipantId:()=>yh,resetAdHocMatchUps:()=>aO,resetMatchUpLineUps:()=>Ph,resetScorecard:()=>Uh,resetTieFormat:()=>Dh,setDelegatedOutcome:()=>sO,setMatchUpFormat:()=>oO,setMatchUpState:()=>vi,setMatchUpStatus:()=>wc,setOrderOfFinish:()=>cO,substituteParticipant:()=>rO,toggleParticipantCheckInState:()=>rg,updateTieMatchUpScore:()=>ho});function qv({tournamentRecord:t,drawDefinition:e,participantId:r,sideNumber:n,matchUpId:o,event:i}){if(r&&typeof r!="string")return{error:Hr};if(!e)return{error:$};if(!o)return{error:mr};let s=n===void 0;if(s&&(n=1),![1,2].includes(n))return M({result:{error:O,context:{sideNumber:n}}});let{matchUp:a,structure:c}=Wt({drawDefinition:e,matchUpId:o,event:i});if(!a)return{error:Be};if(!(!c?.structures&&!(e.drawType&&!yn(e.drawType))&&!c?.matchUps?.find(({roundPosition:p})=>!!p)))return{error:ol};if(!r&&(a?.score?.scoreStringSide1||Ot.includes(a?.matchUpstatus)||a?.matchUpStatus&&[Qt,ge].includes(a.matchUpStatus)))return{error:Om,info:"matchUp has completed status or score"};if(a){if(a.sides=[1,2].map(p=>{let m=a.sides?.find(d=>d.sideNumber===p)??{sideNumber:p};return n===p?{...m,participantId:r}:m}),s)for(let p of a.sides)p.sideNumber&&(p.sideNumber=3-p.sideNumber);It({tournamentId:t?.tournamentId,context:"assignSideParticipant",drawDefinition:e,matchUp:a})}return{...P,sidesSwapped:s}}function Kr({removePriorValues:t,tournamentRecord:e,duplicateValues:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:s,event:a}){let{matchUp:c}=Wt({drawDefinition:n,event:a,matchUpId:i});if(!c)return{error:Be};let u=oo({removePriorValues:t,element:c,duplicateValues:r,timeItem:s});return o||It({tournamentId:e?.tournamentId,eventId:a?.eventId,context:"addTimeItem",drawDefinition:n,matchUp:c}),u}function hh(t){let e=[{[rt]:!0},{[Kt]:!0},{[sr]:!0},{[wr]:!0}],r=X(t,e);if(r.error)return r;let n=ss(t,[{[Gi]:Rn,attr:{[hp]:!0}}]);if(n.error)return n;let{tournamentRecord:o,drawDefinition:i,participantId:s,matchUpId:a}=t,c=n?.matchUp?.matchUp,{matchUpStatus:u,score:p}=c??{};if(u&&Rl.includes(u)||u&&Ot.includes(u)||ue({score:p}))return{error:kD};let m=$s({matchUp:c});if(m?.error)return m;let{checkedInParticipantIds:d,allRelevantParticipantIds:l}=m??{};if(!l?.includes(s))return{error:Hr};if(!d?.includes(s))return{error:IU};let f=uE({matchUp:c});if(f?.error)return f;let{sideParticipantIds:g,nestedIndividualParticipantIds:I}=f??{},S=g?.indexOf(s);return S!==void 0&&[0,1].includes(S)&&(I?.[S]??[]).forEach(T=>{Kr({drawDefinition:i,matchUpId:a,timeItem:{itemType:Bl,itemValue:T}})}),Kr({tournamentRecord:o,drawDefinition:i,matchUpId:a,timeItem:{itemValue:s,itemType:Bl}}),{...P,checkedOut:!0}}function Th(t){let e=[{[rt]:!0},{[Kt]:!0},{[sr]:!0},{[wr]:!0}],r=X(t,e);if(r[jr])return r;let n=ss(t,[{[Gi]:Rn,attr:{[hp]:!0}}]);if(n[jr])return n;let{tournamentRecord:o,drawDefinition:i,participantId:s,matchUpId:a}=t,c=$s({matchUp:n?.matchUp?.matchUp});if(c?.error)return c;let{checkedInParticipantIds:u,allRelevantParticipantIds:p}=c??{};if(!p?.includes(s))return{[jr]:Hr};let m={...P,checkedIn:!0};return u?.includes(s)||Kr({tournamentRecord:o,drawDefinition:i,matchUpId:a,timeItem:{itemValue:s,itemType:Vl}}),m}function rg(t){let e=X(t,[{[sr]:!0,[Kt]:!0,[wr]:!0}]);if(e.error)return e;let r=t.tournamentId??t.activeTournamentId,n=t.tournamentRecord??(r&&t.tournamentRecords?.[r]);if(!n)return{error:j};let i=ss(t,[{[Gi]:Rn,attr:{[hp]:!0},[jr]:Be}]).matchUp?.matchUp;if(!i)return{error:Be};let{checkedInParticipantIds:s=[]}=$s({matchUp:i}),{participantId:a,matchUpId:c,drawDefinition:u}=t;return a&&s.includes(a)?hh({tournamentRecord:n,drawDefinition:u,participantId:a,matchUpId:c,matchUp:i}):Th({tournamentRecord:n,drawDefinition:u,participantId:a,matchUpId:c,matchUp:i})}function ng({tournamentRecord:t,drawDefinition:e,tieMatchUpId:r,event:n}){if(!t)return{error:j};if(!e)return{error:Nn};if(!n)return{error:Wr};let o=Ie({drawDefinition:e}),{matchUp:i}=Wt({matchUpId:r,drawDefinition:e,matchUpsMap:o});if(!i)return{error:Be};let{matchUp:s,structure:a}=Wt({tournamentParticipants:t.participants,matchUpId:r,inContext:!0,drawDefinition:e,matchUpsMap:o,event:n});if(!s)return{error:Be};let{collectionPosition:c,drawPositions:u,collectionId:p,matchUpTieId:m,matchUpType:d}=s;if(d&&!_s([Ct,Rt],d))return{error:cr};let{positionAssignments:l}=Pt({structure:a}),f=l?.filter(A=>u?.includes(A.drawPosition)),{matchUp:g}=Wt({matchUpId:m,drawDefinition:e,matchUpsMap:o}),I=g?.sides?.map(gt)??[],S=f?.map(gt)??[],h=[...I,...S],{participants:T}=bt({tournamentRecord:t,participantFilters:{participantTypes:[_t],participantIds:h}}),{matchUp:y}=Wt({matchUpId:m,inContext:!0,drawDefinition:e,matchUpsMap:o}),E=ze({matchUp:g,drawDefinition:e,structure:a,event:n})?.tieFormat;return{inContextDualMatchUp:y,inContextTieMatchUp:s,relevantAssignments:f,collectionPosition:c,teamParticipants:T,collectionId:p,matchUpType:d,dualMatchUp:g,tieMatchUp:i,tieFormat:E,structure:a,...P}}function yh(t){let e=ng(t);if(e.error)return e;let r="replaceTieMatchUpParticipantid",{existingParticipantId:n,tournamentRecord:o,newParticipantId:i,drawDefinition:s,substitution:a,event:c}=t;if(!n||!i)return M({result:{error:We},stack:r});if(n===i)return{...P};let{inContextDualMatchUp:u,inContextTieMatchUp:p,collectionPosition:m,collectionId:d,dualMatchUp:l,tieMatchUp:f,tieFormat:g}=e,I=p?.matchUpType,S=p?.sides?.find(L=>L.participant?.participantId===n||L.participant?.individualParticipantIds?.includes(n));if(!S)return{error:ee};let h=S9({existingParticipantId:n,inContextTieMatchUp:p,newParticipantId:i,tournamentRecord:o,drawDefinition:s,params:t,event:c,stack:r});if(h)return h;let{appliedPolicies:T}=ft({tournamentRecord:o,drawDefinition:s,event:c}),E=(t.policyDefinitions?.[He]??T?.[He]??Ns[He])?.processCodes?.substitution;Cc({tournamentId:o.tournamentId,eventId:c.eventId,inContextDualMatchUp:u,drawDefinition:s,dualMatchUp:l});let A=l?.sides?.find(({sideNumber:L})=>L===S.sideNumber);if(!A)return M({result:{sideNumber:S.sideNumber,existingParticipantId:n,error:fe},stack:r});if(p?.sides?.flatMap(L=>L.participant?.individualParticipantIds||(L.participant?.participantId??[]))?.includes(i))return M({result:{error:_m},stack:r});let D=u?.sides?.find(({sideNumber:L})=>L===S.sideNumber)?.participantId,R=A.lineUp,U=h9({existingParticipantId:n,collectionPosition:m,newParticipantId:i,substitution:a,collectionId:d,teamLineUp:R}),b=I===Rt,{assignedParticipantIds:C}=ad({lineUp:R,collectionPosition:m,collectionId:d}),{assignedParticipantIds:_}=ad({lineUp:U,collectionPosition:m,collectionId:d});if(A.lineUp=U,D&&g){let L=Us({participantId:D,lineUp:U,drawDefinition:s,tieFormat:g});if(L.error)return M({result:L,stack:r})}else console.log("team participantId not found");let{participantAdded:v,participantRemoved:w}=b?T9({existingIndividualParticipantIds:C,individualParticipantIds:_,tournamentRecord:o,stack:r}):{participantAdded:void 0,participantRemoved:void 0};return y9({substitutionProcessCodes:E,tournamentRecord:o,drawDefinition:s,substitution:a,tieMatchUp:f,stack:r,side:S}),l&&It({tournamentId:o?.tournamentId,matchUp:l,context:r,drawDefinition:s}),{...P,modifiedLineUp:U,participantRemoved:w,participantAdded:v}}function S9({existingParticipantId:t,inContextTieMatchUp:e,newParticipantId:r,tournamentRecord:n,drawDefinition:o,params:i,event:s,stack:a}){let c=bt({tournamentRecord:n,participantFilters:{participantIds:[t,r]}})?.participants??[];if(c.length!==2)return M({result:{error:We},stack:a});if(c[0].participantType!==c[1].participantType)return M({result:{error:Dn},stack:a});let{appliedPolicies:u}=ft({tournamentRecord:n,drawDefinition:o,event:s}),p=i.policyDefinitions?.[He]??u?.[He]??Ns[He],m=c.find(({participantId:l})=>l===r);if((i.enforceGender??p?.participants?.enforceGender)!==!1&&Un(e?.gender)&&Ar(e?.gender)!==Ar(m?.person?.sex))return{error:xi,info:"Gender mismatch"}}function h9({existingParticipantId:t,collectionPosition:e,newParticipantId:r,substitution:n,collectionId:o,teamLineUp:i}){let s=i?.find(({participantId:u})=>r===u),a=i?.reduce((u,p)=>p.substitutionOrder>u?p.substitutionOrder:u,0),c=i?.map(u=>{let p=q(u,!1,!0);if(![t,r].includes(p.participantId))return p;if(!n&&[t,r].includes(p.participantId)&&(p.collectionAssignments=p.collectionAssignments?.filter(m=>!(m.collectionPosition===e&&m.collectionId===o))),n&&t===p.participantId&&(p.collectionAssignments=p.collectionAssignments.map(m=>m.collectionPosition===e&&m.collectionId===o&&m.substitutionOrder===void 0?{...m,substitutionOrder:a}:m)),p.participantId===r){p.collectionAssignments??=[];let m={collectionId:o,collectionPosition:e};n&&(m.previousParticipantId=t,m.substitutionOrder=(a??0)+1),p.collectionAssignments.push(m)}return p})??[];if(!s){let u={collectionId:o,collectionPosition:e};n&&(u.substitutionOrder=(a??0)+1,u.previousParticipantId=t);let p={collectionAssignments:[u],participantId:r};c.push(p)}return c}function T9({existingIndividualParticipantIds:t,individualParticipantIds:e,tournamentRecord:r,stack:n}){let o,i,s=Tn({participantIds:e,tournamentRecord:r});if(!s.participant){let u=Gn({returnParticipant:!0,pairOverride:!0,tournamentRecord:r,participant:{participantRole:Ve,individualParticipantIds:e,participantType:lt}});if(u.error)return M({result:u,stack:n});o=u.participant?.participantId}s=Tn({participantIds:t,tournamentRecord:r});let a=s.participant?.participantId;return a&&Ds({participantIds:[a],tournamentRecord:r}).success&&(i=a),{participantAdded:o,participantRemoved:i}}function y9({substitutionProcessCodes:t,tournamentRecord:e,drawDefinition:r,substitution:n,tieMatchUp:o,stack:i,side:s}){if(n||s.substitutions?.length===1){if(n)t&&o&&(o.processCodes=pt([...o?.processCodes??[],...t]));else for(let a of t??[]){let c=o?.processCodes?.lastIndexOf(a);c!==void 0&&o?.processCodes?.splice(c,1)}o&&It({tournamentId:e?.tournamentId,matchUp:o,context:i,drawDefinition:r})}}function rN({collectionPosition:t,teamParticipantId:e,dualMatchUpSide:r,drawDefinition:n,participantIds:o,collectionId:i}){if(!i||!t||!Array.isArray(o))return{modifiedLineUp:r?.lineUp??[],error:O};let s=r?.lineUp||Xs({participantId:e,drawDefinition:n})?.lineUp,a=[],c=[];return{modifiedLineUp:s?.map(p=>{if(!o.includes(p.participantId))return p;let m=p.collectionAssignments?.filter(d=>{let l=d.collectionId===i&&d.collectionPosition===t;return l&&(d.previousParticipantId&&a.push(d.previousParticipantId),c.push({participantId:p.participantId,...d})),!l});return{participantId:p.participantId,collectionAssignments:m}}).filter(Boolean)??[],assignmentsRemoved:c,previousParticipantIds:a}}function IG({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:r}){let n=(r.events??[]).filter(i=>i?.eventType===Oe&&i?.entries?.some(s=>s.participantId===e)),o=i=>!t.includes(i.participantId);for(let i of n){i.entries=(i.entries??[]).filter(o);let{flightProfile:s}=Bt({event:i});s?.flights?.forEach(a=>{a.drawEntries=(a.drawEntries??[]).filter(o)}),i?.drawDefinitions?.forEach(a=>{a.entries=(a.entries??[]).filter(o)})}return{...P}}function Vd({individualParticipantIds:t,groupingParticipantId:e,removeFromOtherTeams:r,tournamentRecord:n}){let o="addIndividualParticipantIds";if(!n)return M({result:{error:j},stack:o});if(!e||!t)return M({result:{error:nt},stack:o});let i=n.participants??[],s=i.find(m=>m.participantId===e);if(!s)return M({result:{error:ee},stack:o});if(s?.participantType&&![_t,$r].includes(s.participantType))return M({context:{participantType:s.participantType},result:{error:Dn},stack:o});let a=t.filter(m=>i.find(l=>l.participantId===m)?.participantType!==St);if(a.length)return M({result:{error:_r,invalidParticipantIds:a},stack:o});s.individualParticipantIds??=[];let c=s.individualParticipantIds,u=t.filter(m=>!c.includes(m));u.length&&(r&&cd({individualParticipantIds:u,tournamentRecord:n}),s.individualParticipantIds=s.individualParticipantIds.concat(...u));let{topics:p}=vr();if(p.includes(tr)){let m=i.find(({participantId:d})=>d===e);at({topic:tr,payload:{participants:[m]}})}return IG({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:n}),{groupingParticipant:q(s,!1,!0),added:u.length,...P}}function Bd(t){let{updateParticipantName:e=!0,groupingParticipantId:r,removeFromOtherTeams:n,tournamentRecord:o,pairOverride:i,participant:s}=t,a=dt({tournamentRecord:o,participant:s},[rt,$m]);if(a.error)return a;if(!s.participantId)return Gn({tournamentRecord:o,participant:s});let{participant:c}=Do({participantId:s.participantId,tournamentRecord:o});if(!c)return Gn({tournamentRecord:o,participant:s});let{participantRoleResponsibilties:u,individualParticipantIds:p,participantOtherName:m,participantName:d,participantRole:l,participantType:f,onlineResources:g,contacts:I,person:S}=s;if(f&&c.participantType!==f)return{error:cU};let h={};if(I&&(h.contacts=I),g&&(h.onlineResources=g),m!==void 0&&(h.participantOtherName=m||void 0),d&&wt(d)&&(h.participantName=d),Array.isArray(p)&&E9({individualParticipantIds:p,updateParticipantName:e,existingParticipant:c,participantType:f,tournamentRecord:o,pairOverride:i,newValues:h}),Object.keys(ef).includes(l)&&(h.participantRole=l),Object.keys(Op).includes(f)&&(h.participantType=f),Array.isArray(u)&&(h.participantRoleResponsibilties=u),c.participantType===Op.INDIVIDUAL&&S){let T=P9({updateParticipantName:e,existingParticipant:c,newValues:h,person:S});if(T?.error)return T}return Object.assign(c,et(h)),r&&Vd({individualParticipantIds:[c.participantId],groupingParticipantId:r,removeFromOtherTeams:n,tournamentRecord:o}),at({topic:tr,payload:{tournamentId:o.tournamentId,participants:[c]}}),{participant:q(c),...P}}function E9({individualParticipantIds:t,updateParticipantName:e,existingParticipant:r,participantType:n,tournamentRecord:o,pairOverride:i,newValues:s}){let{participants:a}=bt({participantFilters:{participantTypes:[St]},tournamentRecord:o}),c=a?.map(gt);if(!c)return;let u=t.filter(p=>wt(p)&&c.includes(p));([$r,xt].includes(n||r.participantType)||n===lt&&(u.length===2||i))&&(s.individualParticipantIds=u),r.participantType===Op.PAIR&&e&&(s.participantName=A9({individualParticipants:a,newValues:s}))}function A9({individualParticipants:t,newValues:e}){let r=e.individualParticipantIds,n=t.filter(({participantId:o})=>r.includes(o)).map(o=>o.person?.standardFamilyName||o.participantOtherName||o.participantName||"").filter(Boolean).sort().join("/");return r.length===1&&(n+="/Unknown"),n}function P9({updateParticipantName:t,existingParticipant:e,newValues:r,person:n}){let o={},{standardFamilyName:i,standardGivenName:s,nationalityCode:a,personId:c,birthdate:u,tennisId:p,sex:m}=n;m&&Object.keys(pl).includes(m)&&(o.sex=m);let d;if(wt(c)&&(o.personId=c),a&&wt(a)&&(N9(a)||a==="")&&(o.nationalityCode=a),i&&typeof wt(i)&&i.length>1&&(o.standardFamilyName=i,d=!0),s&&typeof wt(s)&&s.length>1&&(o.standardGivenName=s,d=!0),d&&t){let l=o.standardGivenName||e.person?.standardGivenName,f=o.standardFamilyName||e.person?.standardFamilyName;if(l&&f)r.participantName=`${l} ${f}`;else{let g=[l,f].filter(Boolean).join(" ");r.participantName=g||e.participantOtherName||e.participantName}}if(u){if(!Me(u))return{error:ae};let l=new Date(u).getFullYear();if(new Date(u)>new Date||l<1900)return{error:ae,info:"birthdate must be a past date"};o.birthdate=u}p&&wt(p)&&(o.tennisId=p),Object.assign(e.person,o)}function N9(t){return Ui.flatMap(({iso:e,ioc:r})=>[e,r]).filter(Boolean).includes(t)}function og(t){let e=ng(t);if(e.error)return e;let r="assignTieMatchUpParticipantId",n=t.teamParticipantId,{tournamentRecord:o,drawDefinition:i,participantId:s,event:a}=t;if(!s)return M({result:{error:We},stack:r});let c=new Set([1,2]);if(t.sideNumber&&!c.has(t.sideNumber))return M({result:{error:rU},stack:r});let{inContextDualMatchUp:u,inContextTieMatchUp:p,relevantAssignments:m,collectionPosition:d,teamParticipants:l,collectionId:f,matchUpType:g,dualMatchUp:I,tieFormat:S}=e;if(D9(p,s))return M({result:{...P},stack:r});n=U9({teamParticipantId:n,inContextDualMatchUp:u,sideNumber:t.sideNumber});let T=bt({participantFilters:{participantIds:[s]},tournamentRecord:o})?.participants?.[0];if(!T)return M({result:{error:ee},stack:r});let y=R9({policyDefinitions:t.policyDefinitions,inContextTieMatchUp:p,participantToAssign:T,tournamentRecord:o,drawDefinition:i,enforceGender:t.enforceGender,event:a});if(y)return y;let{individualParticipantIds:E,participantType:A}=T;if(re(Ct)(g)&&A!==St)return{error:Dn};let N=A===St?[s]:E,D=n&&l?.find(({participantId:G})=>G===n)||l?.find(({individualParticipantIds:G})=>Re(N,G));if(!D)return{error:nI};if(n||(n=D.participantId),!n)return{error:ee};let R=b9({inContextTieMatchUp:p,teamParticipantId:n,relevantAssignments:m,participantTeam:D,dualMatchUp:I,sideNumber:t.sideNumber});if(!S)return{error:ya};if(!S.collectionDefinitions?.find(G=>G.collectionId===f))return{error:ZD};Cc({tournamentId:o.tournamentId,eventId:a.eventId,inContextDualMatchUp:u,drawDefinition:i,dualMatchUp:I});let b=I?.sides?.find(G=>G.sideNumber===R),C=p?.sides?.find(G=>G.sideNumber===R),w=(b?.lineUp??Xs({participantId:n,drawDefinition:i})?.lineUp)?.filter(G=>G.collectionAssignments?.find(V=>V.collectionPosition===d&&V.collectionId===f&&!V.previousParticipantId))?.map(G=>G?.participantId),L=w?.length>1&&w||(A===lt?T.individualParticipantIds:[s]),F=rN({collectionPosition:d,teamParticipantId:n,dualMatchUpSide:b,drawDefinition:i,participantIds:L,collectionId:f});if(F.error)return M({result:F,stack:r});let{modifiedLineUp:x}=F,k;if(g===Rt){let G=C9({collectionPosition:d,teamParticipantId:n,tournamentRecord:o,dualMatchUpSide:b,participantType:A,drawDefinition:i,tieMatchUpSide:C,modifiedLineUp:x,participantIds:L,participantId:s,dualMatchUp:I,collectionId:f,tieFormat:S,stack:r});if(G.error)return G;k=G.deletedParticipantId}else{let G=$v({collectionPosition:d,teamParticipantId:n,drawDefinition:i,modifiedLineUp:x,participantId:s,collectionId:f,tieFormat:S});if(G?.error)return G}if(b&&(b.lineUp=x),I&&It({tournamentId:o?.tournamentId,matchUp:I,context:r,drawDefinition:i}),k){let{error:G}=Ds({participantIds:[k],tournamentRecord:o});G&&console.log("cleanup")}return{...P,modifiedLineUp:x}}function D9(t,e){return t?.sides?.flatMap(n=>n.participant?.individualParticipantIds||(n.participant?.participantId??[]))?.includes(e)}function U9({teamParticipantId:t,inContextDualMatchUp:e,sideNumber:r}){if(t)return t;if(r)return e?.sides?.find(n=>n.sideNumber===r)?.participantId}function R9({policyDefinitions:t,inContextTieMatchUp:e,participantToAssign:r,tournamentRecord:n,drawDefinition:o,enforceGender:i,event:s}){let{appliedPolicies:a}=ft({tournamentRecord:n,drawDefinition:o,event:s}),c=t?.[He]??a?.[He]??Ns[He];if((i??c?.participants?.enforceGender)!==!1&&Un(e?.gender)&&Ar(e?.gender)!==Ar(r.person?.sex))return{error:xi,info:"Gender mismatch"}}function b9({inContextTieMatchUp:t,teamParticipantId:e,relevantAssignments:r,participantTeam:n,dualMatchUp:o,sideNumber:i}){let a=r?.find(p=>p.participantId===n?.participantId)?.drawPosition,c=o?.sides?.find(p=>p.participantId===e)?.sideNumber,u=t?.sides?.find(p=>a&&p.drawPosition===a)?.sideNumber;return c??u??i}function C9({collectionPosition:t,teamParticipantId:e,tournamentRecord:r,dualMatchUpSide:n,participantType:o,drawDefinition:i,tieMatchUpSide:s,modifiedLineUp:a,participantIds:c,participantId:u,dualMatchUp:p,collectionId:m,tieFormat:d,stack:l}){let f;if(o!==lt){let g=$v({collectionPosition:t,teamParticipantId:e,drawDefinition:i,modifiedLineUp:a,participantId:u,collectionId:m,tieFormat:d});if(g?.error)return M({result:g,stack:l});if(g=M9({side:s,tournamentRecord:r,participantId:u}),g.error)return g;f=g.deletedParticipantId,n&&(n.lineUp=a),p&&It({tournamentId:r?.tournamentId,matchUp:p,context:l,drawDefinition:i})}else for(let g of c)$v({collectionPosition:t,teamParticipantId:e,drawDefinition:i,modifiedLineUp:a,participantId:g,collectionId:m,tieFormat:d});return{...P,deletedParticipantId:f}}function M9({side:t,tournamentRecord:e,participantId:r}){let n;if(t.participant){let o=t.participant.individualParticipantIds??[];if(o.filter(Boolean).length===1){let{participant:s}=Tn({participantIds:o,tournamentRecord:e});o.push(r);let{participant:a}=Tn({participantIds:o,tournamentRecord:e});if(!a&&s){s.individualParticipantIds=o;let c=Bd({pairOverride:!0,tournamentRecord:e,participant:s});if(c.error)return c}else n=s?.participantId}}else{let i=Gn({participant:{individualParticipantIds:[r],participantRole:Ve,participantType:lt},pairOverride:!0,tournamentRecord:e});if(i.error)return i}return{...P,deletedParticipantId:n}}function $v({collectionPosition:t,teamParticipantId:e,drawDefinition:r,modifiedLineUp:n,participantId:o,collectionId:i,tieFormat:s}){let a=Xs({participantId:e,drawDefinition:r})?.lineUp,c=(n||a)?.find(p=>p?.participantId===o),u={collectionId:i,collectionPosition:t};if(c)c.collectionAssignments.push(u);else{let p={collectionAssignments:[u],participantId:o};n.push(p)}return Us({participantId:e,lineUp:n,drawDefinition:r,tieFormat:s})}function v9({substitutionProcessCodes:t,inContextTieMatchUp:e,tournamentRecord:r,drawDefinition:n,tieMatchUp:o,stack:i,side:s}){if(!e?.sides?.find(c=>c.sideNumber!==s.sideNumber)?.substitutions?.length&&o?.processCodes?.length){for(let c of t??[]){let u=o.processCodes.lastIndexOf(c);o.processCodes.splice(u,1)}It({tournamentId:r?.tournamentId,matchUp:o,context:i,drawDefinition:n})}}function O9({inContextTieMatchUp:t,previousParticipantIds:e,dualMatchUpSide:r,tournamentRecord:n,participantId:o,stack:i}){let s=t?.sides?.find(p=>p.sideNumber===r?.sideNumber),{participantId:a}=s??{},c=a&&bt({participantFilters:{participantIds:[a]},tournamentRecord:n,withDraws:!0})?.participants?.[0];if(!c)return M({result:{error:ee},stack:i});let u=c?.individualParticipantIds?.filter(p=>p!==o)??[];if(e&&u.push(...e),u.length>2)return M({result:{error:_r},stack:i});if(!c.draws?.length)return _9({individualParticipantIds:u,pairParticipantId:a,tournamentRecord:n,pairParticipant:c,stack:i});if(u.length===1)return x9({individualParticipantIds:u,tournamentRecord:n,stack:i})}function _9({individualParticipantIds:t,pairParticipantId:e,tournamentRecord:r,pairParticipant:n,stack:o}){if(t.length){n.individualParticipantIds=t;let i=Bd({participant:n,pairOverride:!0,tournamentRecord:r});if(i.error)return M({result:i,stack:o})}else{let i=Ds({participantIds:[e],tournamentRecord:r});i.error&&console.log("cleanup",{result:i})}}function x9({individualParticipantIds:t,tournamentRecord:e,stack:r}){let{participant:n}=Tn({participantIds:t,tournamentRecord:e});if(!n){let i=Gn({participant:{participantRole:Ve,individualParticipantIds:t,participantType:lt},pairOverride:!0,tournamentRecord:e});if(i.error)return M({result:i,stack:r})}}function Kv(t){let{tournamentRecord:e,drawDefinition:r,participantId:n,event:o}=t,i="removeTieMatchUpParticiapantId";if(!n)return M({result:{error:We},stack:i});let s=ng(t);if(s.error)return s;let{appliedPolicies:a}=ft({tournamentRecord:e,drawDefinition:r,event:o}),u=(t.policyDefinitions?.[He]??a?.[He]??Ns[He])?.processCodes?.substitution,{inContextDualMatchUp:p,inContextTieMatchUp:m,relevantAssignments:d,collectionPosition:l,teamParticipants:f,collectionId:g,matchUpType:I,dualMatchUp:S,tieMatchUp:h,tieFormat:T}=s;if(!S)return M({result:{error:Xe},stack:i});let y=m?.sides?.find(C=>C.participant?.participantId===n||C.participant?.individualParticipantIds?.includes(n));if(!y)return M({result:{error:ee},stack:i});let E=t.policyDefinitions?.[Qr]??a?.[Qr];if(!y.substitutions?.length&&(ue({score:m?.score})||m?.winningSide)&&E?.requireParticipantsForScoring!==!1)return M({result:{error:GU},stack:i});let A=p?.sides?.find(({sideNumber:C})=>C===y.sideNumber)?.participantId;if(!A)return M({result:{error:ee},stack:i});let N=bt({participantFilters:{participantIds:[n]},tournamentRecord:e})?.participants?.[0];if(!N)return M({result:{error:ee},stack:i});if(I===Ct&&N.participantType===lt)return M({result:{error:xi},stack:i});let D=N.participantType===St?[n]:N.individualParticipantIds;Cc({tournamentId:e.tournamentId,eventId:o.eventId,inContextDualMatchUp:p,drawDefinition:r,dualMatchUp:S});let R=S.sides?.find(({sideNumber:C})=>C===y.sideNumber);if(!R&&(S.sides?.filter(({lineUp:C})=>!C).length||0)<2){let C=f?.map(({participantId:_})=>({drawPosition:d?.find(v=>v.participantId===_)?.drawPosition,teamParticipantId:_}));R=S.sides?.find(_=>C?.find(({drawPosition:v})=>v===_.drawPosition)?.teamParticipantId===A)}if(!R)return M({result:{error:ee,context:{participantId:n}}});let{modifiedLineUp:U,previousParticipantIds:b}=rN({collectionPosition:l,teamParticipantId:A,dualMatchUpSide:R,participantIds:D,drawDefinition:r,collectionId:g});if(R.lineUp=U,A&&T&&Us({participantId:A,lineUp:U,drawDefinition:r,tieFormat:T}),I===Rt&&N.participantType===St){let C=O9({inContextTieMatchUp:m,previousParticipantIds:b,dualMatchUpSide:R,tournamentRecord:e,participantId:n,stack:i});if(C?.error)return C}return y.substitutions?.length===1&&v9({substitutionProcessCodes:u,inContextTieMatchUp:m,tournamentRecord:e,drawDefinition:r,tieMatchUp:h,stack:i,side:y}),It({tournamentId:e?.tournamentId,matchUp:S,context:i,drawDefinition:r}),{...P,modifiedLineUp:U}}function Eh(t){let e=X(t,[{[rt]:!0,[Kt]:!0,[wr]:!0}]);if(e.error)return e;let{drawDefinition:r,sideNumber:n,matchUpId:o,event:i}=t;if(n&&![1,2].includes(n))return{error:O,sideNumber:n};let{matchUp:s,structure:a}=Wt({drawDefinition:r,matchUpId:o,event:i});return s?Ae({structure:a})?(s.sides?.forEach(c=>{(!n||c.sideNumber===n)&&delete c.participantId}),It({tournamentId:t.tournamentRecord?.tournamentId,context:"assignSideParticipant",drawDefinition:r,matchUp:s}),{...P}):{error:ol}:{error:Be}}function SG({matchUpStatuses:t=["BYE",vt,Mt],drawPositionMatchUps:e,loserDrawPosition:r,sourceMatchUps:n}){let o=e?.reduce((p,m)=>!p||m.roundNumber>p.roundNumber?m:p,void 0),i=o?.drawPositions?.find(p=>p!==r),s=n.filter(p=>p?.drawPositions?.includes(i)).map(p=>p.matchUpStatus),a=n.filter(p=>p?.drawPositions?.includes(r)).map(p=>p.matchUpStatus),c=Re(s??[],t),u=Re(a??[],t);return{sourceMatchUp:o,winnerHadMatchUpStatus:c,winnerMatchUpStatuses:s,loserHadMatchUpStatus:u,loserMatchUpStatuses:a}}function hG({inContextDrawMatchUps:t,sourceMatchUpStatus:e,targetDrawPosition:r,tournamentRecord:n,sourceMatchUpId:o,drawDefinition:i,structureId:s,dualMatchUp:a,roundNumber:c,matchUpsMap:u,event:p}){let{structure:m}=tt({drawDefinition:i,structureId:s});if(m?.structureType===de)return{...P};u=u??Ie({drawDefinition:i});let l=(u?.mappedMatchUps??{})[s].matchUps,{initialRoundNumber:f}=Zs({drawPosition:r,matchUps:l}),g=l?.filter(S=>S.roundNumber>=c&&S.roundNumber!==f&&S.drawPositions?.includes(r)),{positionAssignments:I}=Pt({drawDefinition:i,structureId:s});for(let S of g??[])w9({inContextDrawMatchUps:t,sourceMatchUpStatus:e,positionAssignments:I,targetDrawPosition:r,tournamentRecord:n,sourceMatchUpId:o,drawDefinition:i,dualMatchUp:a,matchUpsMap:u,matchUp:S,event:p});return{...P}}function w9({inContextDrawMatchUps:t,positionAssignments:e,sourceMatchUpStatus:r,targetDrawPosition:n,tournamentRecord:o,sourceMatchUpId:i,drawDefinition:s,dualMatchUp:a,matchUpsMap:c,matchUp:u,event:p}){let m="removeSubsequentDrawPosition";if(a){let g=t.find(({matchUpId:S})=>u.matchUpId===S).sides?.find(S=>S.drawPosition===n)?.sideNumber,I=u.sides?.find(S=>S.sideNumber===g);I&&delete I.lineUp}u.drawPositions=(u.drawPositions??[]).map(f=>f===n?void 0:f).filter(Boolean);let l=e.filter(({drawPosition:f})=>u.drawPositions?.includes(f)).filter(f=>f.bye).length;return u.matchUpStatus=l&&"BYE"||Ye(u.matchUpStatus)&&u.matchUpStatus||zt,Ye(u.matchUpStatus)&&(u.winningSide=void 0),u.matchUpStatusCodes&&OE({inContextDrawMatchUps:t,sourceMatchUpStatus:r,sourceMatchUpId:i,matchUpsMap:c,matchUp:u}),It({tournamentId:o?.tournamentId,eventId:p?.eventId,context:`${m}-${n}`,drawDefinition:s,matchUp:u}),{...P}}function Bu(t){let{dualWinningSideChange:e,inContextDrawMatchUps:r,tournamentRecord:n,drawDefinition:o,matchUpStatus:i,matchUpsMap:s,dualMatchUp:a,targetData:c,matchUpId:u,structure:p,event:m}=t,d=!!t.matchUp.collectionId,l=Ae({structure:p}),{drawPositions:f,winningSide:g}=c.matchUp??{};if(!l&&!f)return{error:jc};let{targetLinks:{loserTargetLink:I,winnerTargetLink:S,byeTargetLink:h},targetMatchUps:{loserMatchUp:T,winnerMatchUp:y,byeMatchUp:E}}=c,A=Fn({...t,matchUpStatus:i||zt,removeWinningSide:!0});if(A.error)return A;let N;if(d){let{matchUpTieId:x,matchUpsMap:k}=t;if(N=ho({appliedPolicies:t.appliedPolicies,matchUpId:x,tournamentRecord:n,drawDefinition:o,matchUpsMap:k,event:m}),!e&&!N.removeWinningSide)return{...P}}if(l)return{...P};let{matchUps:D}=ht({afterRecoveryTimes:!1,inContext:!0,drawDefinition:o,matchUpsMap:s,structure:p}),{positionAssignments:R}=se({structure:p}),U=g-1,b=1-U,C=f[U],_=f[b],{winnerParticipantId:v,loserParticipantId:w}=R?.reduce((x,k)=>(k.drawPosition===_&&(x.loserParticipantId=k.participantId),k.drawPosition===C&&(x.winnerParticipantId=k.participantId),x),{winnerParticipantId:void 0,loserParticipantId:void 0})??{},L=D.filter(x=>x.drawPositions?.includes(_));if(y&&zv({sourceMatchUpStatus:i,sourceMatchUpId:u,inContextDrawMatchUps:r,winningDrawPosition:C,winnerParticipantId:v,tournamentRecord:n,winnerTargetLink:S,drawDefinition:o,winnerMatchUp:y,dualMatchUp:a,matchUpsMap:s}),T){let{winnerHadMatchUpStatus:x}=SG({drawPositionMatchUps:L,loserDrawPosition:_,sourceMatchUps:D}),G=I.linkCondition===Wn;if(x&&G){let B=Math.min(...T.drawPositions);nN({targetLink:I,inContextDrawMatchUps:r,drawDefinition:o,drawPosition:B,matchUpsMap:s,event:m})}let V=L9({sourceMatchUpStatus:i,sourceMatchUpId:u,loserParticipantId:w,tournamentRecord:n,loserTargetLink:I,drawDefinition:o,loserMatchUp:T,dualMatchUp:a,matchUpsMap:s,event:m});if(V.error)return V}if(E){let x=Math.min(...E.drawPositions);nN({sourceMatchUpId:u,targetLink:h,inContextDrawMatchUps:r,drawDefinition:o,drawPosition:x,matchUpsMap:s,event:m})}return{...P,...N&&{tieMatchUpResult:N}}}function zv({inContextDrawMatchUps:t,winningDrawPosition:e,sourceMatchUpStatus:r,winnerParticipantId:n,tournamentRecord:o,winnerTargetLink:i,sourceMatchUpId:s,drawDefinition:a,winnerMatchUp:c,matchUpsMap:u,dualMatchUp:p,event:m}){let{structureId:d,roundNumber:l}=c,f="removeDirectedWinner";if(i){let g=i.target.structureId,{structure:I}=tt({drawDefinition:a,structureId:g});if(!I)return{error:Nt};let{positionAssignments:S}=se({structure:I});I.seedAssignments=(I.seedAssignments??[]).filter(R=>R.participantId!==n);let T=S?.find(R=>R.participantId===n)?.drawPosition,{matchUps:y}=ht({drawDefinition:a,structure:I,event:m}),E=y.map(R=>R.drawPositions).flat(1/0).filter(Boolean),A=mn(E);if((T?A[T]:void 0)===1)S?.forEach(R=>{R.participantId===n&&delete R.participantId});else{let R=y.filter(({drawPositions:U})=>U.includes(T));console.log("not removing from position assignments since instances > 1",{drawPositionMatchUps:R,winnerTargetLink:i})}let D=u?.drawMatchUps?.find(({matchUpId:R})=>R===c.matchUpId);D&&It({tournamentId:o?.tournamentId,eventId:m?.eventId,matchUp:D,context:f,drawDefinition:a})}return l&&hG({targetDrawPosition:e,inContextDrawMatchUps:t,sourceMatchUpStatus:r,tournamentRecord:o,sourceMatchUpId:s,drawDefinition:a,dualMatchUp:p,matchUpsMap:u,roundNumber:l,structureId:d}),{...P}}function L9({sourceMatchUpStatus:t,loserParticipantId:e,tournamentRecord:r,loserTargetLink:n,sourceMatchUpId:o,drawDefinition:i,loserMatchUp:s,matchUpsMap:a,dualMatchUp:c,event:u}){let p="removeDirectedLoser",m=n.target.structureId,{structure:d}=tt({drawDefinition:i,structureId:m});if(!d)return{error:Nt};let{positionAssignments:l}=se({structure:d}),f=l?.find(g=>g.participantId===e)?.drawPosition;if(l?.forEach(g=>{g.participantId===e&&delete g.participantId}),o&&t){let g=a?.drawMatchUps?.find(({matchUpId:I})=>I===s.matchUpId);g.matchUpStatusCodes=t===Qt?["WO","WO"]:[]}if(d.seedAssignments=(d.seedAssignments??[]).filter(g=>g.participantId!==e),c){let g=s?.sides.reduce((h,T,y)=>T.drawPosition===f?y:h,void 0),I=a?.drawMatchUps?.find(({matchUpId:h})=>h===s.matchUpId),S=I?.sides?.[g];S&&(delete S.lineUp,It({tournamentId:r?.tournamentId,eventId:u?.eventId,matchUp:I,context:p,drawDefinition:i}))}return{...P}}function nN({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,matchUpsMap:o,targetLink:i,event:s}){let a=i.target.structureId,c="removeDirectedBye";Pe({color:"brightyellow",method:c,drawPosition:n});let u=Au({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,matchUpsMap:o,structureId:a,event:s});return M({result:u,stack:c})}function TG(t){let{matchUpFormat:e,score:r}=t,n=r?.sets?.length,o=e&&oe(e),{setFormat:i,finalSetFormat:s,bestOf:a}=o??{};return(a&&n===a&&s||i)?.timed||!1}function yG({tournamentRecord:t,drawDefinition:e,structure:r,matchUp:n}){let o="attemptToSetMatchUpStatusBYE";if(n?.winningSide)return M({result:{error:uc},context:{matchUpStatus:"BYE"},stack:o});let{positionAssignments:i}=se({structure:r}),s=i?.filter(c=>c.bye).map(c=>c.drawPosition);return n.drawPositions?.some(c=>s?.includes(c))?(n.matchUpStatus="BYE",n.matchUpStatusCodes=[],It({tournamentId:t?.tournamentId,context:o,drawDefinition:e,matchUp:n}),{...P}):M({result:{error:zD},info:"matchUp does not include BYE",stack:o})}function ma(t,e){Pe({method:t,...e})}function ig(t){let{tournamentRecord:e,appliedPolicies:r,drawDefinition:n,matchUpsMap:o,targetData:i,structure:s,event:a}=t,c="doubleExitAdvancement";if(s.structureType===de)return M({result:{...P},stack:c});let{matchUp:u,targetMatchUps:p,targetLinks:m}=i,{loserMatchUp:d,winnerMatchUp:l,loserTargetDrawPosition:f}=p,g=Ye(d?.matchUpStatus)&&!d.sides?.map(S=>S.participantId??S.participant).filter(Boolean).length,I=d?.matchUpStatus===Qt;if(ma(c,{newline:!0,color:"brightyellow",keyColors:{sourceMatchUpId:"brightcyan",loserMatchUpId:"brightmagenta",winnerMatchUpId:"brightgreen"},sourceMatchUpId:u?.matchUpId,sourceStatus:t.matchUpStatus,sourceDP:JSON.stringify(u?.drawPositions),loserMatchUpId:d?.matchUpId,loserStatus:d?.matchUpStatus,loserDP:JSON.stringify(d?.drawPositions),loserTargetDP:f,loserIsEmptyExit:g,loserIsDoubleExit:I,loserSides:JSON.stringify(d?.sides?.map(S=>({sn:S.sideNumber,pid:S.participantId?.slice(0,8),fed:S.participantFed}))),winnerMatchUpId:l?.matchUpId,winnerStatus:l?.matchUpStatus,winnerDP:JSON.stringify(l?.drawPositions)}),d&&d.matchUpStatus!=="BYE"){let S=F9({loserMatchUpIsEmptyExit:g,loserMatchUpIsDoubleExit:I,loserTargetDrawPosition:f,appliedPolicies:r,tournamentRecord:e,drawDefinition:n,sourceMatchUp:u,loserMatchUp:d,targetLinks:m,matchUpsMap:o,params:t,event:a,stack:c});if(S?.error)return M({result:S,stack:c})}if(l){ma(c,{color:"cyan",decision:"conditionallyAdvanceWinner",winnerMatchUpId:l.matchUpId});let S=EG({...t,matchUpId:l.matchUpId,targetMatchUp:l,tournamentRecord:e,sourceMatchUp:u});if(S.error)return M({result:S,stack:c})}return M({result:{...P},stack:c})}function F9({loserMatchUpIsEmptyExit:t,loserMatchUpIsDoubleExit:e,loserTargetDrawPosition:r,appliedPolicies:n,tournamentRecord:o,drawDefinition:i,sourceMatchUp:s,loserMatchUp:a,targetLinks:c,matchUpsMap:u,params:p,event:m,stack:d}){let{loserTargetLink:l}=c,f=n?.progression?.doubleExitPropagateBye,g=a.feedRound&&a.sides?.[0]?.participantFed;if(f||g)return ma(d,{color:"cyan",decision:"advanceByeToLoserMatchUp",propagateBye:f,targetFedIn:!!g}),AG({loserTargetDrawPosition:r,tournamentRecord:o,loserTargetLink:l,drawDefinition:i,loserMatchUp:a,matchUpsMap:u,event:m});if(t)return k9({loserMatchUp:a,matchUpsMap:u,params:p,stack:d});if(e)return ma(d,{color:"brightyellow",decision:"SKIP_loserMatchUp_already_doubleExit",loserMatchUpId:a.matchUpId}),{...P};let{feedRound:I,drawPositions:S,matchUpId:h}=a,T=I?2:2-S.indexOf(r);return ma(d,{color:"cyan",decision:"conditionallyAdvanceLoser",feedRound:I,walkoverWinningSide:T,loserMatchUpId:h}),EG({...p,targetMatchUp:a,walkoverWinningSide:T,tournamentRecord:o,sourceMatchUp:s,matchUpId:h})}function k9({loserMatchUp:t,matchUpsMap:e,params:r,stack:n}){let o=r.matchUpStatus===ge?ge:Qt,i=r.matchUpStatus===ge?Mt:vt,s=e.drawMatchUps.find(a=>a.matchUpId===t.matchUpId);if(ma(n,{color:"brightred",decision:"EMPTY_EXIT_converting_to_DOUBLE_EXIT",loserMatchUpId:t.matchUpId,currentStatus:t.matchUpStatus,newStatus:o}),s){let a=[{matchUpStatus:i,previousMatchUpStatus:o,sideNumber:1},{matchUpStatus:i,previousMatchUpStatus:r.matchUpStatus,sideNumber:2}].map(c=>et(c));return Fn({...r,matchUp:s,matchUpId:t.matchUpId,matchUpStatus:o,matchUpStatusCodes:a,winningSide:void 0,removeScore:!0,context:n})}return{...P}}function EG(t){let{inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,sourceMatchUp:o,targetMatchUp:i,matchUpsMap:s}=t,a=n.structures.find(({structureId:x})=>x===i.structureId),c=t.matchUpStatus===ge?ge:Qt,u=t.matchUpStatus===ge?Mt:vt,p="conditionallyAdvanceDrawPosition",m=s.drawMatchUps.find(x=>x.matchUpId===i.matchUpId);if(!m)return{error:Xe};let d=o?.drawPositions??[],l=m.drawPositions?.filter(Boolean),f=o?.structureId===i.structureId;if(ma(p,{newline:!0,color:"magenta",keyColors:{targetMatchUpId:"brightcyan",sourceMatchUpId:"brightyellow"},targetMatchUpId:i.matchUpId,targetStructureId:i.structureId?.slice(0,8),targetRound:[i.roundNumber,i.roundPosition],targetDP:JSON.stringify(m.drawPositions),targetStatus:m.matchUpStatus,targetFeedRound:i.feedRound,sourceMatchUpId:o?.matchUpId,sourceStructureId:o?.structureId?.slice(0,8),sourceRound:o?[o.roundNumber,o.roundPosition]:void 0,sourceDP:JSON.stringify(d),sameStructure:f,paramMatchUpStatus:t.matchUpStatus,EXIT:u,DOUBLE_EXIT:c}),f&&Re(d,l)&&(l=l.filter(x=>!d.includes(x))),f&&l.length>1)return M({result:{error:Yc},stack:p});let{pairedPreviousMatchUpIsDoubleExit:g,pairedPreviousMatchUp:I}=ME({...t,structure:a});ma(p,{color:"magenta",keyColors:{pairedMatchUpId:"brightcyan"},pairedMatchUpId:I?.matchUpId,pairedRound:I?[I.roundNumber,I.roundPosition]:void 0,pairedStatus:I?.matchUpStatus,pairedStructureId:I?.structureId?.slice(0,8),pairedIsDoubleExit:g});let S=er({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),{targetMatchUps:h,targetLinks:T}=S,{loserTargetDrawPosition:y,winnerMatchUp:E,loserMatchUp:A}=h;if(A){let{loserTargetLink:x}=T,k=AG({loserTargetDrawPosition:y,loserMatchUp:A,tournamentRecord:r,loserTargetLink:x,drawDefinition:n,matchUpsMap:s});if(k.error)return M({result:k,stack:p})}let N=m.drawPositions?.filter(Boolean)??[],D=N.length===1,R=t.walkoverWinningSide||D&&nf({drawPosition:N[0],matchUpId:i.matchUpId,inContextDrawMatchUps:e})||void 0,U=Ye(m.matchUpStatus)&&!N.length,b=U?c:u;ma(p,{color:"brightyellow",keyColors:{matchUpStatus:"brightgreen",existingExit:"brightred"},existingExit:U,matchUpStatus:b,targetCurrentStatus:m.matchUpStatus,targetDP:JSON.stringify(N),hasDrawPosition:D,walkoverWinningSide:R});let C=e.find(x=>x.matchUpId===I.matchUpId),_=G9({inContextPairedPreviousMatchUp:C,pairedPreviousMatchUp:I,walkoverWinningSide:R,sourceMatchUp:o,targetMatchUp:i,stack:p}),v=t.matchUpStatus,w=I?.matchUpStatus,L=V9({sourceMatchUpStatus:v,pairedMatchUpStatus:w,sourceSideNumber:_});ma(p,{color:"brightgreen",keyColors:{matchUpStatus:"brightcyan",winningSide:"brightyellow"},action:"modifyMatchUpScore",targetMatchUpId:m.matchUpId,matchUpStatus:b,winningSide:R,matchUpStatusCodes:JSON.stringify(L),sourceStatus:v,pairedStatus:w});let F=Fn({...t,winningSide:R,matchUp:m,matchUpStatusCodes:L,context:p,matchUpStatus:b});return F.error?M({result:F,stack:p}):B9({pairedPreviousMatchUpIsDoubleExit:g,targetMatchUpDrawPositions:l,noContextTargetMatchUp:m,inContextDrawMatchUps:e,walkoverWinningSide:R,nextWinnerMatchUp:E,drawDefinition:n,existingExit:U,matchUpStatus:b,targetMatchUp:i,matchUpsMap:s,targetData:S,DOUBLE_EXIT:c,structure:a,params:t,stack:p,EXIT:u})}function G9({inContextPairedPreviousMatchUp:t,pairedPreviousMatchUp:e,walkoverWinningSide:r,sourceMatchUp:n,targetMatchUp:o,stack:i}){if(!n)return;let s;return n?.structureId===t?.structureId?s=n.roundPosition<e?.roundPosition?1:2:o.feedRound?s=n.structureId===o.structureId?2:1:r&&(s=3-r),ma(i,{color:"cyan",keyColors:{sourceSideNumber:"brightgreen"},sourceSideNumber:s,sourceStructureId:n.structureId?.slice(0,8),pairedStructureId:t?.structureId?.slice(0,8),targetStructureId:o.structureId?.slice(0,8),sameStructureAsPaired:n?.structureId===t?.structureId,targetFeedRound:o.feedRound,sourceRP:n.roundPosition,pairedRP:e?.roundPosition}),s}function V9({sourceMatchUpStatus:t,pairedMatchUpStatus:e,sourceSideNumber:r}){let n=[];return r===1?n=[{matchUpStatus:oN(t),previousMatchUpStatus:t,sideNumber:1},{matchUpStatus:oN(e),previousMatchUpStatus:e,sideNumber:2}]:r===2&&(n=[{matchUpStatus:oN(e),previousMatchUpStatus:e,sideNumber:1},{matchUpStatus:oN(t),previousMatchUpStatus:t,sideNumber:2}]),n.length&&(n=n.map(o=>et(o))),n}function B9({pairedPreviousMatchUpIsDoubleExit:t,targetMatchUpDrawPositions:e,noContextTargetMatchUp:r,inContextDrawMatchUps:n,walkoverWinningSide:o,nextWinnerMatchUp:i,drawDefinition:s,existingExit:a,matchUpStatus:c,targetMatchUp:u,matchUpsMap:p,targetData:m,DOUBLE_EXIT:d,structure:l,params:f,stack:g,EXIT:I}){if(a)return ma(g,{color:"brightred",decision:"EXISTING_EXIT_triggers_recursive_doubleExitAdvancement",targetMatchUpId:r.matchUpId,matchUpStatus:c}),ig({...f,matchUpStatus:c,targetData:m});if(!i)return M({result:{...P},stack:g});let S=e.length===2?e[o-1]:e[0],{positionAssignments:h}=Pt({structure:l}),T=h?.find(N=>N.drawPosition===S),y=p.drawMatchUps.find(N=>N.matchUpId===i.matchUpId),E=y?.drawPositions?.filter(Boolean),A=E.length===1;if(S)return T?.bye?W9({nextWinnerMatchUpDrawPositions:E,nextWinnerMatchUpHasDrawPosition:A,noContextNextWinnerMatchUp:y,inContextDrawMatchUps:n,nextWinnerMatchUp:i,drawDefinition:s,matchUpStatus:c,matchUpsMap:p,params:f,stack:g,EXIT:I}):bc({matchUpId:i.matchUpId,drawPosition:S,inContextDrawMatchUps:n,drawDefinition:s});if(t){if(!y)return{error:Xe};if(A){let R=E[0],U=nf({matchUpId:u.matchUpId,inContextDrawMatchUps:n,drawPosition:R});console.log("existing drawPosition is winningSide",{walkoverWinningSide:U})}let N=Ye(y.matchUpStatus)?I:d,D=Fn({matchUpId:y.matchUpId,appliedPolicies:f.appliedPolicies,matchUp:y,matchUpStatus:N,matchUpStatusCodes:[],removeScore:!0,context:g,drawDefinition:s});if(D.error)return M({result:D,stack:g});if(N===d){let R=er({matchUpId:u.matchUpId,inContextDrawMatchUps:n,drawDefinition:s}),U=ig({...f,matchUpId:u.matchUpId,matchUpStatus:N,targetData:R});if(U.error)return U}}return M({result:{...P},stack:g})}function W9({nextWinnerMatchUpDrawPositions:t,nextWinnerMatchUpHasDrawPosition:e,noContextNextWinnerMatchUp:r,inContextDrawMatchUps:n,nextWinnerMatchUp:o,drawDefinition:i,matchUpStatus:s,matchUpsMap:a,params:c,stack:u,EXIT:p}){let m=er({matchUpId:r.matchUpId,inContextDrawMatchUps:n,drawDefinition:i});if(e){let d=t.find(Boolean),l=nf({drawPosition:d,matchUpId:r.matchUpId,inContextDrawMatchUps:n}),f=Fn({appliedPolicies:c.appliedPolicies,matchUpId:r.matchUpId,matchUp:r,matchUpStatus:p,matchUpStatusCodes:[],removeScore:!0,context:u,drawDefinition:i,winningSide:l});return f.error?M({result:f,stack:u}):EE({drawPositionToAdvance:d,matchUpId:r.matchUpId,inContextDrawMatchUps:n,drawDefinition:i,matchUpsMap:a})}else if(Ye(o.matchUpStatus)){let d=ig({...c,matchUpId:r.matchUpId,matchUpStatus:s,targetData:m});if(d.error)return M({result:d,stack:u})}return M({result:{...P},stack:u})}function AG(t){let{loserTargetDrawPosition:e,tournamentRecord:r,loserTargetLink:n,drawDefinition:o,matchUpsMap:i,event:s,loserMatchUp:a}=t,c=n?.target?.structureId,{structure:u}=tt({drawDefinition:o,structureId:c});return u?Or({drawPosition:e,tournamentRecord:r,drawDefinition:o,structureId:c,matchUpsMap:i,loserMatchUp:a,event:s}):{error:_i}}function oN(t){return t===Qt?vt:t===ge?Mt:t}function PG(t){let{tournamentRecord:e,drawDefinition:r,matchUpStatus:n,structure:o,matchUp:i}=t,s=!!(i.tieMatchUps&&!i.rondPosition&&t.inContextDrawMatchUps.find(h=>h.matchUpId===i.matchUpId).containerStructureId),a="attemptToSetMatchUpStatus",c=n==="BYE",u=i.winningSide,p=[Qt,ge].includes(n),m=Va({matchUpStatus:n}),d=cS({matchUpStatus:n}),l=!m&&!d,f=t.matchUpTieId||u&&m&&!p,g=u&&p;Pe({method:a,newline:!0,color:"brightyellow",keyColors:{matchUpStatus:"brightcyan",matchUpId:"brightmagenta"},matchUpId:i.matchUpId,matchUpStatus:n,existingStatus:i.matchUpStatus,existingWinningSide:u,isDoubleExit:p,isBYE:c,directing:m,nonDirecting:d,unrecognized:l,onlyModifyScore:f,changeCompletedToDoubleExit:g,propagateExitStatus:t.propagateExitStatus,teamRoundRobinContext:s});let I=()=>Fn({...t,removeScore:[to,vt].includes(n),matchUpStatus:n||zt}),S=l&&"unrecognized"||f&&"onlyModifyScore"||g&&"changeCompletedToDoubleExit"||u&&"existingWinningSide_removeDirected"||d&&"nonDirecting_clearScore"||c&&"isBYE"||!m&&"notDirecting_error"||p&&"isDoubleExit_modifyAndAdvance"||s&&"teamRoundRobinContext"||t.propagateExitStatus&&"propagateExitStatus"||"fallthrough_error";return Pe({method:a,color:"brightgreen",keyColors:{route:"brightcyan"},route:S,matchUpId:i.matchUpId}),l&&{error:VT}||f&&iN(t)||g&&H9(t)||u&&Bu(t)||d&&I()||c&&yG({tournamentRecord:e,drawDefinition:r,structure:o,matchUp:i})||!m&&{error:VT}||p&&Y9(t)||s&&iN(t)||t.propagateExitStatus&&iN(t)||M({result:{error:uc,info:"matchUpStatus: "+n},stack:a})}function H9(t){let e=Bu(t);return e.error?e:ig(t)}function Y9(t){let e=iN({...t,removeScore:!0});return e.error?e:ig(t)}function iN(t){let e="scoreModification";if(t.isCollectionMatchUp&&t.dualMatchUp?.winningSide&&!t.projectedWinningSide){let i=Bu(t);if(i.error)return M({result:i,stack:e})}let n=!!t.matchUp.collectionId,o=Fn({...t,context:e});if(n){let{matchUpTieId:i,drawDefinition:s,matchUpsMap:a}=t,c=ho({tournamentRecord:t.tournamentRecord,appliedPolicies:t.appliedPolicies,matchUpId:i,event:t.event,drawDefinition:s,matchUpsMap:a});if(c.error)return M({result:c,stack:e});Object.assign(o,{tieMatchUpResult:c})}return M({result:o,stack:e})}function NG({drawDefinition:t,structure:e,matchUp:r}){let{drawPositions:n}=r,{positionAssignments:o}=Pt({drawDefinition:t,structure:e}),s=o?.filter(({drawPosition:m})=>n?.includes(m))?.map(m=>{let{extension:d}=ot({element:m,name:Bo});return d?.value?.groupOrder}),{containerStructures:a}=ji({drawDefinition:t}),c=a[e.structureId];return{structureIds:ka({drawDefinition:t,structureId:c})?.links?.source?.filter(m=>Re(s,m.source?.finishingPositions??[])).map(m=>m.source.structureId)}}function sN({drawDefinition:t,structure:e,matchUp:r}){let n=[];if(e.finishingPosition===po&&Ro({drawDefinition:t,structure:e})){let{structureIds:i}=NG({drawDefinition:t,structure:e,matchUp:r});i?.length&&n.push(...i)}return{connectedStructureIds:n}}function DG(t){let e,{inContextDrawMatchUps:r,inContextMatchUp:n,drawDefinition:o,winningSide:i}=t,s=t.targetData.targetLinks?.winnerTargetLink;if(s.target.feedProfile===ln){let a=n.sides.find(({sideNumber:u})=>u!==i).participantId,c=r.find(u=>u.structureId===s.target.structureId&&u.roundNumber===s.target.roundNumber&&u.sides.some(({participantId:p})=>p===a));if(c?.matchUpStatus===zt){let u=er({matchUpId:c.matchUpId,inContextDrawMatchUps:r,drawDefinition:o});if(!es({inContextDrawMatchUps:r,drawDefinition:o,targetData:u})){let{structure:m}=tt({structureId:c.structureId,drawDefinition:o}),d=Pt({structure:m}).positionAssignments;for(let l of d??[])if(l.participantId===a){let f=n.sides.find(({sideNumber:g})=>g===i).participantId;if(l.participantId=f,m?.positionAssignments)m.positionAssignments=d;else if(m?.structures){let g=Object.assign({},...(d??[]).map(I=>({[I.drawPosition]:I.participantId})));for(let I of m.structures)I.positionAssignments?.forEach(S=>S.participantId=g[S.drawPosition])}hn({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:o,structure:m}),e=!0}}}}return{...P,qualifierReplaced:e}}function UG(t){let{inContextDrawMatchUps:e,inContextMatchUp:r,drawDefinition:n,winningSide:o,random:i}=t,s=t.targetData.targetLinks?.winnerTargetLink;if(s.target.feedProfile!==ln)return{...P,qualifierPlaced:void 0};let a=r.sides.find(({sideNumber:p})=>p===o)?.participantId,c=j9({inContextDrawMatchUps:e,winnerTargetLink:s,random:i});if(c?.matchUpStatus!==zt)return{...P,qualifierPlaced:void 0};let u=er({matchUpId:c.matchUpId,inContextDrawMatchUps:e,drawDefinition:n});return es({inContextDrawMatchUps:e,drawDefinition:n,targetData:u})?{...P,qualifierPlaced:void 0}:q9({mainDrawTargetMatchUp:c,winningQualifierId:a,drawDefinition:n,params:t})}function j9({inContextDrawMatchUps:t,winnerTargetLink:e,random:r}){let n=t.filter(o=>o.structureId===e.target.structureId&&o.roundNumber===e.target.roundNumber&&o.sides.some(({participantId:i,qualifier:s})=>s&&!i));return Pn(n,r)}function q9({mainDrawTargetMatchUp:t,winningQualifierId:e,drawDefinition:r,params:n}){let o=t.sides.find(c=>c.qualifier&&!c.participantId)?.drawPosition,{structure:i}=tt({structureId:t.structureId,drawDefinition:r});if(!i)return{error:Nt};let s=Pt({structure:i}).positionAssignments,a;for(let c of s??[])c.drawPosition===o&&!c.participantId&&(c.participantId=e,$9(i,s),hn({tournamentId:n.tournamentRecord?.tournamentId,event:n.event,drawDefinition:r,structure:i}),a=!0);return{...P,qualifierPlaced:a}}function $9(t,e){if(t.positionAssignments)t.positionAssignments=e;else if(t.structures){let r=Object.assign({},...(e??[]).map(n=>({[n.drawPosition]:n.participantId})));for(let n of t.structures)n.positionAssignments?.forEach(o=>o.participantId=r[o.drawPosition])}}function RG(t){let e="attemptToSetWinningSide",r,n={},{appliedPolicies:o,disableAutoCalc:i,drawDefinition:s,dualMatchUp:a,winningSide:c,structure:u,matchUp:p}=t;if(a?._disableAutoCalc&&i!==!1)return If(t);if(p.winningSide&&p.winningSide!==c){let{connectedStructureIds:f}=sN({drawDefinition:s,structure:u,matchUp:p});f.length&&(r=!0);let g=Bu(t);if(g.error)return g}let m=nA(t);if(m.context?.progressExitStatus&&Object.assign(n,m.context),m.error)return M({result:m,stack:e});let d,l;return t.qualifierChanging&&o?.[Ap]?.autoReplaceQualifiers&&(d=DG(t).qualifierReplaced),t.qualifierAdvancing&&o?.[Ap]?.autoPlaceQualifiers&&(l=UG(t).qualifierPlaced),M({result:et({...P,...m,connectedStructures:r,qualifierReplaced:d,qualifierPlaced:l,context:n}),stack:e})}var aN={drawPositionToRemove:"green",iteration:"brightred",winner:"green",loser:"brightred"};function Qv(t){let{inContextDrawMatchUps:e,appliedPolicies:r,drawDefinition:n,matchUpsMap:o,targetData:i,matchUp:s}=t,{matchUpId:a}=s,{iteration:c=0}=t;c+=1;let u="removeDoubleExit";Pe({color:"brightyellow",method:u,matchUpId:a,iteration:c,keyColors:aN});let{targetMatchUps:{loserMatchUp:p,winnerMatchUp:m,loserTargetDrawPosition:d},targetLinks:{loserTargetLink:l}}=i;if(m&&m.matchUpStatus!=="BYE"){let{stage:I,roundNumber:S,roundPosition:h,structureName:T}=m;Pe({winner:"winner",roundPosition:h,structureName:T,roundNumber:S,keyColors:aN,stage:I}),bG({...t,targetMatchUp:m,sourceMatchUp:s,iteration:c})}let f=p?.matchUpStatus==="BYE"&&(p?.feedRound||p?.roundNumber===1),g=i?.targetLinks?.loserTargetLink?.linkCondition===Wn;if(f&&g){let I=e.filter(({roundNumber:E,structureId:A})=>A===s.structureId&&E===1),S=I.map(({roundPosition:E})=>E),h=he(S.sort((E,A)=>E-A),2).find(E=>E.includes(s.roundPosition));if((I.filter(({roundPosition:E})=>h.includes(E))?.map(({matchUpStatus:E})=>E)).every(E=>[ge,Qt].includes(E)))return M({result:{...P},stack:u})}if(p&&(p.matchUpStatus!=="BYE"||f)){let I=e.find(({matchUpId:N})=>N===p.matchUpId),{structure:S}=tt({drawDefinition:n,structureId:I.structureId}),{stage:h,roundNumber:T,roundPosition:y,feedRound:E,structureName:A}=p;if(Pe({loser:"loser",roundPosition:y,structureName:A,roundNumber:T,keyColors:aN,feedRound:E,stage:h}),r?.progression?.doubleExitPropagateBye||f)nN({drawPosition:d,targetLink:l,inContextDrawMatchUps:e,drawDefinition:n,matchUpsMap:o});else{let N=bG({...t,targetMatchUp:p,structure:S,iteration:c});if(N.error)return M({result:N,stack:u})}}return M({result:{...P},stack:u})}function bG(t){let{inContextDrawMatchUps:e,appliedPolicies:r,drawDefinition:n,sourceMatchUp:o,targetMatchUp:i,matchUpsMap:s,structure:a,iteration:c}=t,u="conditionallyRemoveDrawPosition";Pe({method:u,structureName:a?.structureName,iteration:c});let p=er({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),{targetMatchUps:{winnerMatchUp:m}}=p,d=s?.drawMatchUps.find(T=>T.matchUpId===i.matchUpId),l,f,g;if(i.feedRound)g=m?.drawPositions?.filter(Boolean)?.find(y=>i.drawPositions.includes(y));else if(o==null)g=Yt(i?.drawPositions??[],m?.drawPositions??[])?.[0];else{f=vE({structureId:a.structureId,matchUp:o,matchUpsMap:s})?.pairedPreviousMatchUp,l=[Qt,ge].includes(f?.matchUpStatus);let T=f?.drawPositions?.filter(Boolean)??[];if([...Ot,"BYE"].includes(f?.matchUpStatus)||f?.winningSide){let E=o.drawPositions??[],A=i.drawPositions?.filter(Boolean);Re(E,A)&&(A=A?.filter(D=>!E.includes(D))),g=E.concat(T).find(D=>A?.includes(D))}}if(m&&g){let{stage:T,roundNumber:y,roundPosition:E,structureName:A}=m;Pe({method:"removeDirectedWinner",drawPositionToRemove:g,color:"brightgreen",roundPosition:E,structureName:A,roundNumber:y,keyColors:aN,stage:T}),zv({winningDrawPosition:g,winnerMatchUp:m,inContextDrawMatchUps:e,drawDefinition:n,matchUpsMap:s})}let I=Qv({targetData:p,matchUp:i,inContextDrawMatchUps:e,appliedPolicies:r,drawDefinition:n,matchUpsMap:s,structure:a,iteration:c});if(I.error)return M({result:I,stack:u});let S=K9({pairedPreviousDoubleExit:l,noContextTargetMatchUp:d}),h=!l;return I=Fn({...t,matchUpId:i.matchUpId,matchUp:d,removeWinningSide:!0,matchUpStatusCodes:[],context:u,matchUpStatus:S,removeScore:h,score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0}}),I.error?M({result:I,stack:u}):{...P}}function K9({pairedPreviousDoubleExit:t,noContextTargetMatchUp:e}){return e.matchUpStatus==="BYE"?"BYE":t?[ge,Mt].includes(e?.matchUpStatus)?Mt:vt:zt}function CG(t){let e,{inContextDrawMatchUps:r,inContextMatchUp:n,drawDefinition:o}=t,i=t.targetData.targetLinks?.winnerTargetLink;if(i.target.feedProfile===ln){let s=n.sides?.find(({sideNumber:c})=>c===n.winningSide)?.participantId,a=r.find(c=>c.structureId===i.target.structureId&&c.roundNumber===i.target.roundNumber&&c.sides?.some(({participantId:u})=>u===s));if(a&&a.matchUpStatus===zt){let c=er({matchUpId:a.matchUpId,inContextDrawMatchUps:r,drawDefinition:o});if(!es({inContextDrawMatchUps:r,drawDefinition:o,targetData:c})){let{structure:p}=tt({structureId:a.structureId,drawDefinition:o}),m=Pt({structure:p}).positionAssignments;for(let d of m??[])if(d.participantId===s){if(d.participantId=void 0,p?.positionAssignments)p.positionAssignments=m;else if(p?.structures){let l=Object.assign({},...(m??[]).map(f=>({[f.drawPosition]:f.participantId})));for(let f of p?.structures??[])f.positionAssignments?.forEach(g=>g.participantId=l[g.drawPosition])}hn({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:o,structure:p}),e=!0}}}}return{qualifierRemoved:e}}function vG(t){let{matchUp:e,matchUpStatus:r,score:n,winningSide:o}=t,i="noDownStreamDependencies";if([Qt,ge].includes(e?.matchUpStatus)&&![Qt,ge].includes(r)){let h=Qv(t);if(h.error)return M({result:h,stack:i})}let a=r===Qt,c=[Cn,Wi,to,Fr,Xr],u=ue({score:n})&&!a&&!c.includes(r)&&(t.isCollectionMatchUp&&!t.projectedWinningSide||!o),p=t?.inContextMatchUp?.collectionId&&TG(t.inContextMatchUp),m=t.removeScore||!p&&![Xr,Fr].includes(r||Xr),d=t.isCollectionMatchUp&&t.dualMatchUp.winningSide&&!t.projectedWinningSide||e.winningSide&&!o&&!ue({score:n}),l=h=>{let T,{structure:y,drawDefinition:E,dualMatchUp:A,disableAutoCalc:N}=t;if(A?._disableAutoCalc&&N!==!1)return If({...t,removeWinningSide:d});let{connectedStructureIds:D}=sN({drawDefinition:E,structure:y,matchUp:e});D.length&&(T=!0),Object.assign(t,{removeScore:h});let R=Bu(t);if(R.error)return R;if(t.removingQualifier&&t.appliedPolicies?.[Ap]?.autoRemoveQualifiers){let U=CG(t);return{...P,connectedStructures:T,...U}}return{...P,connectedStructures:T}};if(d&&o&&t.isCollectionMatchUp)return MG(t);let f=[to,Fr].includes(r)&&t.dualWinningSideChange,g=r&&r!==zt,I=t.propagateExitStatus&&Ye(r),S=(o||f||I)&&RG(t)||u&&l(m)||g&&PG(t)||d&&l(m)||e&&MG({...t,removeScore:!0})||{...P};return M({result:S,stack:i})}function MG(t){let e="ndd:scoreModification";if(t.isCollectionMatchUp&&t.dualMatchUp?.winningSide&&!t.projectedWinningSide&&!t.autoCalcDisabled){let o=Bu(t);if(o.error)return o}let n=Fn({...t,context:e});if(t.isCollectionMatchUp){let{matchUpTieId:o,drawDefinition:i,event:s,matchUpsMap:a}=t,{removeWinningSide:c}=ho({tournamentRecord:t.tournamentRecord,appliedPolicies:t.appliedPolicies,matchUpId:o,drawDefinition:i,matchUpsMap:a,event:s});c&&console.log("REMOVE WINNING SIDE")}return M({result:n,stack:e})}function Ah(t){let e=X(t,[{[rt]:!0,[Kt]:!0,[wr]:!0},{homeParticipantId:!0,[jr]:We}]);if(e.error)return e;let r=ss(t,[{[Gi]:Rn,attr:{[hp]:!0}}]);if(r.error)return r;let n=r?.matchUp?.matchUp?.sides?.map(m=>m?.participantId);if(t.homeParticipantId&&!n?.includes(t.homeParticipantId))return{error:Hr};let{disableNotice:o,homeParticipantId:i,removePriorValues:s,tournamentRecord:a,drawDefinition:c,matchUpId:u}=t;return Kr({duplicateValues:!1,removePriorValues:s,tournamentRecord:a,drawDefinition:c,disableNotice:o,matchUpId:u,timeItem:{itemType:Wl,itemValue:i}})}function Xv({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Ii({timeItems:r?.timeItems??[],itemType:rd});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{timeModifiers:n}:e}function yi(t){let e="addMatchUpScheduledTime",r=t.matchUp,{removePriorValues:n,tournamentRecord:o,drawDefinition:i,disableNotice:s,scheduledTime:a,matchUpId:c}=t;if(!c)return M({result:{error:mr},stack:e});if(!Bm(a))return M({result:{error:ws},stack:e});if(!r){let I=Wt({drawDefinition:i,matchUpId:c});if(I.error)return M({result:I,stack:e});r=I.matchUp}let u=mt(a),p=Qs({matchUp:r}).scheduledDate,m=u&&!p;if((Xv({matchUp:r}).timeModifiers??[])?.length){let I=Jv({disableNotice:!0,removePriorValues:n,tournamentRecord:o,timeModifiers:[],drawDefinition:i,matchUpId:c,matchUp:r});if(I?.error)return M({result:I,stack:e})}let f=dp(a,!0,m);return Kr({duplicateValues:!1,removePriorValues:n,tournamentRecord:o,drawDefinition:i,disableNotice:s,matchUpId:c,timeItem:{itemType:Es,itemValue:f}})}function Jv({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,timeModifiers:o,matchUpId:i,matchUp:s}){let a="addMatchUpTimeModifiers";if(!i)return M({result:{error:mr},stack:a});if(o!==void 0&&!Array.isArray(o))return M({info:Ri("timeModifiers"),result:{error:O},stack:a});if(!s){let l=Wt({drawDefinition:r,matchUpId:i});if(l.error)return M({result:l,stack:a});s=l.matchUp}let c=Xv({matchUp:s}).timeModifiers??[],u=o.filter(l=>!c.includes(l));if(o.length&&!u.length)return{...P};if(u.some(l=>pE.includes(l))){c=c.filter(f=>!pE.includes(f));let l=yi({disableNotice:!0,removePriorValues:t,scheduledTime:"",tournamentRecord:e,drawDefinition:r,matchUpId:i});if(l.error)return M({result:l,stack:a})}let m=o?.length?[...u,...c]:void 0;return Kr({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:i,timeItem:{itemType:rd,itemValue:m}})}function Wu({scheduledDate:t,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i}){let s="addMatchUpScheduledDate";if(!i)return{error:mr};let a=t&&_o.test(t);if(t&&!a)return{error:ae};let c=mt(t);if(c&&r?.startDate&&r?.endDate){let p=new Date(c).getTime(),m=new Date(mt(r.startDate)).getTime(),d=new Date(mt(r.endDate)).getTime();if(p<m||p>d)return M({result:{error:ae},info:"scheduledDate must be within tournament start and end dates",stack:s})}return Kr({duplicateValues:!1,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:{itemValue:c,itemType:ys}})}function Wd({removePriorValues:t,tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,courtDayDate:i,matchUpId:s,courtIds:a}){if(!r&&!e)return{error:j};if(!s)return{error:mr};let c=Wt({drawDefinition:n,matchUpId:s});if(c.error)return c;if(c?.matchUp?.matchUpType!==Ir)return{error:cr};if(!(a===void 0||Array.isArray(a)&&a.length&&a.every(d=>typeof d=="string")))return{error:O,context:{courtIds:a}};let p;if(a){let d=e||r&&{[r.tournamentId]:r},l=kn({tournamentRecords:d});if(l.error)return l;let f=l.courts?.filter(g=>a.includes(g.courtId));if(f?.length!==a.length)return{error:O,context:{courtIds:a}};p=f?.map(g=>({venueId:g.venueId,courtId:g.courtId}))}return Kr({duplicateValues:!1,removePriorValues:t,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:s,timeItem:{itemType:Io,itemDate:i,itemValue:p}})}function nc({removePriorValues:t,tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,venueId:s}){if(!r)return{error:j};if(!i)return{error:mr};if(s){let c=Ln({tournamentRecords:e,tournamentRecord:r,venueId:s});if(c.error)return c}return Kr({duplicateValues:!1,removePriorValues:t,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:{itemType:Ts,itemValue:s}})}function Ms({removePriorValues:t,tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,courtDayDate:i,matchUpId:s,courtId:a}){if(!r&&!e)return{error:j};if(!s)return{error:mr};if(a){let u=Si({tournamentRecords:e,tournamentRecord:r,courtId:a});if(u.error)return u;let p=u.venue?.venueId;nc({tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:s,venueId:p})}return Kr({duplicateValues:!1,removePriorValues:t,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:s,timeItem:{itemType:li,itemDate:i,itemValue:a}})}function um(t,e){let r=ZT.test(t)?t:$t(t),n=mt(t)||mt(e)||Qn(new Date);return new Date(`${n}T${r}`).getTime()}function z9({removePriorValues:t,tournamentRecord:e,drawDefinition:r,scheduledDate:n,scheduledTime:o,startTime:i,stopTime:s,resumeTime:a,endTime:c,matchUpId:u,matchUp:p,event:m,stack:d}){if(n!==void 0){let l=Wu({disableNotice:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:r,scheduledDate:n,matchUpId:u});if(l?.error)return M({result:l,stack:d,context:{scheduledDate:n}})}if(o!==void 0){let l=yi({disableNotice:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:r,scheduledTime:o,matchUpId:u,matchUp:p});if(l?.error)return M({result:l,stack:d,context:{scheduledTime:o}})}if(i!==void 0){let l=uN({disableNotice:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:r,matchUpId:u,startTime:i,event:m});if(l?.error)return M({result:l,stack:d,context:{startTime:i}})}if(s!==void 0){let l=mN({disableNotice:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:r,matchUpId:u,stopTime:s,event:m});if(l?.error)return M({result:l,stack:d,context:{stopTime:s}})}if(a!==void 0){let l=dN({disableNotice:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:r,resumeTime:a,matchUpId:u,event:m});if(l?.error)return M({result:l,stack:d,context:{resumeTime:a}})}if(c!==void 0){let l=pN({disableNotice:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:r,matchUpId:u,endTime:c,event:m});if(l?.error)return M({result:l,stack:d,context:{endTime:c}})}}function Q9({proConflictDetection:t,removePriorValues:e,tournamentRecords:r,tournamentRecord:n,drawDefinition:o,homeParticipantId:i,timeModifiers:s,courtAnnotation:a,scheduledDate:c,courtOrder:u,courtIds:p,courtId:m,venueId:d,matchUpId:l,matchUp:f,stack:g}){if(p!==void 0){let S=Wd({disableNotice:!0,removePriorValues:e,tournamentRecord:n,drawDefinition:o,matchUpId:l,courtIds:p});if(S?.error)return M({result:S,stack:g,context:{courtIds:p}})}let I=X9({proConflictDetection:t,tournamentRecord:n,scheduledDate:c,courtOrder:u,matchUpId:l,courtId:m,stack:g});if(I)return I;if(m!==void 0&&c!==void 0){let S=Ms({courtDayDate:c,disableNotice:!0,removePriorValues:e,tournamentRecords:r,tournamentRecord:n,drawDefinition:o,matchUpId:l,courtId:m});if(S?.error)return M({result:S,stack:g,context:{courtId:m}})}if(d!==void 0){let S=nc({disableNotice:!0,removePriorValues:e,tournamentRecords:r,tournamentRecord:n,drawDefinition:o,matchUpId:l,venueId:d});if(S?.error)return M({result:S,stack:g,context:{venueId:d}})}if(u!==void 0){let S=cN({disableNotice:!0,removePriorValues:e,tournamentRecord:n,drawDefinition:o,courtOrder:u,matchUpId:l});if(S?.error)return M({result:S,stack:g,context:{courtOrder:u}})}if(a!==void 0){let S=J9({disableNotice:!0,removePriorValues:e,tournamentRecord:n,drawDefinition:o,courtAnnotation:a,matchUpId:l});if(S?.error)return M({result:S,stack:g,context:{courtAnnotation:a}})}if(s!==void 0){let S=Jv({disableNotice:!0,removePriorValues:e,tournamentRecord:n,drawDefinition:o,timeModifiers:s,matchUpId:l,matchUp:f});if(S?.error)return M({result:S,stack:g,context:{timeModifiers:s}})}wt(i)&&Ah({disableNotice:!0,homeParticipantId:i,removePriorValues:e,tournamentRecord:n,drawDefinition:o,matchUpId:l})}function Hd(t){let e="addMatchUpScheduleItems",r=X(t,[{drawDefinition:!0,matchUpId:!0},{schedule:!0,[Ge]:qr}],e);if(r.error)return r;let{matchUpDependencies:n,inContextMatchUps:o}=t,{proConflictDetection:i=!1,errorOnAnachronism:s=!1,checkChronology:a=!0,removePriorValues:c,tournamentRecords:u,tournamentRecord:p,drawDefinition:m,disableNotice:d,drawMatchUps:l,matchUpId:f,schedule:g,event:I}=t,S,h;if(l)S=l.find(k=>k.matchUpId===f);else{let k=Wt({drawDefinition:m,event:I,matchUpId:f});if(k.error)return k;S=k.matchUp}let{endTime:T,courtId:y,courtIds:E,courtAnnotation:A,courtOrder:N,resumeTime:D,homeParticipantId:R,scheduledDate:U,scheduledTime:b,startTime:C,stopTime:_,timeModifiers:v,venueId:w}=g;a&&(!n||!o)&&({matchUpDependencies:n,matchUps:o}=tn({drawDefinition:m}));let L=n?.[f]?.matchUpIds;if(g.scheduledDate&&a&&L){let k=o?.filter(G=>(G.schedule?.scheduledDate||mt(G.schedule?.scheduledTime))&&L.includes(G.matchUpId)).map(({schedule:G})=>{let V=ll(G);return new Date(V??"").getTime()});if(k?.length){let G=ll(g),V=new Date(G??"").getTime();if(Math.max(...k)>=V){if(s)return M({result:{error:FT},stack:e});h=FT}}}let F=z9({removePriorValues:c,tournamentRecord:p,drawDefinition:m,scheduledDate:U,scheduledTime:b,startTime:C,stopTime:_,resumeTime:D,endTime:T,matchUpId:f,matchUp:S,event:I,stack:e});if(F?.error)return F;let x=Q9({proConflictDetection:i,removePriorValues:c,tournamentRecords:u,tournamentRecord:p,drawDefinition:m,homeParticipantId:R,timeModifiers:v,courtAnnotation:A,scheduledDate:U,courtOrder:N,courtIds:E,courtId:y,venueId:w,matchUpId:f,matchUp:S,stack:e});return x?.error?x:(d||It({tournamentId:p?.tournamentId,eventId:I?.eventId,context:e,drawDefinition:m,matchUp:S}),h?{...P,warnings:[h]}:{...P})}function X9({proConflictDetection:t,tournamentRecord:e,scheduledDate:r,courtOrder:n,matchUpId:o,courtId:i,stack:s}){if(!t||i===void 0||r===void 0||n===void 0||!yt(n))return;let a=st(n),u=(qt({tournamentRecord:e})?.matchUps??[]).find(p=>{if(p.matchUpId===o)return!1;let m=p.schedule?.courtOrder?st(p.schedule.courtOrder):void 0;return p.schedule?.courtId===i&&m===a&&p.schedule?.scheduledDate===r});if(u)return M({result:{error:vD,info:`Court slot already occupied by matchUp ${u.matchUpId}`},stack:s,context:{courtId:i,courtOrder:n,scheduledDate:r}})}function cN({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,courtOrder:o,matchUpId:i}){if(!i)return{error:mr};if(o&&!yt(o))return{error:O,info:"courtOrder must be numeric"};let s=o&&st(o);return Kr({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:i,timeItem:{itemType:hu,itemValue:s}})}function J9({removePriorValues:t,tournamentRecord:e,drawDefinition:r,courtAnnotation:n,disableNotice:o,matchUpId:i}){return i?Kr({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:o,matchUpId:i,timeItem:{itemType:Tu,itemValue:n||void 0}}):{error:mr}}function Zv({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,participantId:o,officialType:i,matchUpId:s}){if(!s)return{error:mr};if(!o)return{error:We};if(e){let c=bt({tournamentRecord:e,participantFilters:{participantTypes:[St],participantRoles:[dS]}}).participants??[];if(!ui({tournamentParticipants:c,participantId:o}))return{error:ee}}let a={itemType:"SCHEDULE.ASSIGNMENT.OFFICIAL",itemValue:o};return i&&(a.itemSubTypes=[i]),Kr({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:s,timeItem:a})}function uN({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,startTime:i,event:s}){if(!o)return{error:mr};if(!Bm(i))return{error:ws};let{matchUp:a}=Wt({drawDefinition:r,event:s,matchUpId:o}),{scheduledDate:c}=Qs({matchUp:a}),p=(a?.timeItems??[]).filter(m=>[Fa,qs,As].includes(m?.itemType)).map(m=>um(m.itemValue,c)).reduce((m,d)=>!m||d<m?d:m,void 0);if(!p||um(i,c)<p){a?.timeItems&&(a.timeItems=a.timeItems.filter(l=>l.itemType!==fi));let m=dp(i,!0,!0);return Kr({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,timeItem:{itemType:fi,itemValue:m}})}else return{error:MU}}function pN({validateTimeSeries:t=!0,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,endTime:s,event:a}){if(!i)return{error:mr};if(!Bm(s))return{error:ws};let{matchUp:c}=Wt({drawDefinition:n,event:a,matchUpId:i}),{scheduledDate:u}=Qs({matchUp:c}),m=(c?.timeItems??[]).filter(d=>[fi,qs,Fa].includes(d?.itemType)).map(d=>um(d.itemValue,u)).reduce((d,l)=>!d||l>d?l:d,void 0);if(!t||!m||um(s,u)>m){c?.timeItems&&(c.timeItems=c.timeItems.filter(f=>f.itemType!==As));let d=dp(s,!0,!0);return Kr({duplicateValues:!1,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:{itemType:As,itemValue:d}})}else return{error:RU}}function OG({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,invalidError:o,matchUpId:i,itemType:s,timeValue:a,event:c}){if(!i)return{error:mr};if(!Bm(a))return{error:ws};let{matchUp:u}=Wt({drawDefinition:r,event:c,matchUpId:i}),{scheduledDate:p}=Qs({matchUp:u}),m=u?.timeItems??[];if(m.reduce((S,h)=>h.itemType===As||S,void 0))return{error:bU};let l=m.filter(S=>[fi,qs,Fa].includes(S?.itemType)).sort((S,h)=>um(S.itemValue,p)-um(h.itemValue,p)),f=l.at(-1),g=f?.itemType===s,I=l.filter(S=>!g||S!==f).map(S=>um(S.itemValue,p)).reduce((S,h)=>!S||h>S?h:S,void 0);if(um(a,p)>I){u?.timeItems&&g&&(u.timeItems=u.timeItems.filter(T=>T!==f));let h={itemValue:dp(a,!0,!0),itemType:s};return Kr({duplicateValues:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:i,timeItem:h})}else return{error:o}}function mN({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,stopTime:i,event:s}){return OG({invalidError:CU,timeValue:i,itemType:Fa,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,event:s})}function dN({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,resumeTime:o,matchUpId:i,event:s}){return OG({invalidError:Ew,timeValue:o,itemType:qs,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:i,event:s})}function _G(t){let{targetData:e,matchUpsMap:r}=t,{targetMatchUps:{loserMatchUp:n}}=e,o=Ye(n?.matchUpStatus),i=!!r?.drawMatchUps.find(s=>s.loserMatchUpId===n?.matchUpId&&Ye(s.matchUpStatus));return i&&n?.matchUpStatus===Qt||i&&o}function xG({drawDefinition:t,matchUpStatus:e,matchUpsMap:r,winningSide:n,dualMatchUp:o,tieFormat:i,structure:s,matchUp:a,event:c,score:u}){let p=q(o,void 0,!0);for(let d of p?.tieMatchUps??[])d.matchUpId===a.matchUpId&&(d.winningSide=n,d.score=u,!ue({score:u})&&!e?Object.assign(d,{...qa}):e&&(d.matchUpStatus=e));i=i??ze({matchUp:a,structure:s,drawDefinition:t,event:c})?.tieFormat;let{winningSide:m}=_u({matchUp:p,drawDefinition:t,matchUpsMap:r,structure:s,tieFormat:i,event:c});return{projectedWinningSide:m}}function wG(t){let{tournamentRecord:e,inContextMatchUp:r,structure:n,drawDefinition:o}=t,i=r.roundNumber,s=r.sides.find(A=>A.sideNumber===r.winningSide),a=r.sides.find(A=>A.sideNumber!==r.winningSide),{drawPosition:c,participantId:u}=s,{drawPosition:p,participantId:m}=a,d="swapWinnerLoser",{matchUps:l}=ht(t),f=l.filter(({drawPositions:A,roundNumber:N})=>A?.includes(c)&&N>i);je({changeWinner:!0})&&console.log({existingWinnerSubsequentMatchUps:f}),f.forEach(A=>{A.drawPositions=A.drawPositions?.map(N=>N===c?p:N)??[],It({tournamentId:e?.tournamentId,eventId:t.event?.eventId,context:d,drawDefinition:o,matchUp:A})});let{stage:g,stageSequence:I}=n,S=o.structures.filter(({stage:A,stageSequence:N})=>A===g&&N>I).map(({structureId:A})=>A),{targetLinks:{loserTargetLink:h,winnerTargetLink:T}}=t.targetData,y=[h?.target.structureId,T?.target?.structureId].filter(Boolean);return o.structures.filter(({stage:A,structureId:N})=>A!==g&&y.includes(N)).forEach(({stage:A,stageSequence:N,structureId:D})=>{S.includes(D)||S.push(D),o.structures.filter(({stage:R,stageSequence:U})=>R===A&&U>N).forEach(({structureId:R})=>{S.includes(R)||S.push(R)})}),o.structures.filter(({structureId:A})=>S.includes(A)).forEach(A=>{let{positionAssignments:N}=Pt({structure:A}),D=N?.find(({participantId:U})=>U===u),R=N?.find(({participantId:U})=>U===m);D&&(D.participantId=m),R&&(R.participantId=u)}),Fn({...t,context:d})}function vi(t){let e="setMatchUpStatus";t.matchUpStatus&&[vt,Qt].includes(t.matchUpStatus)&&(t.score=void 0);let{disableScoreValidation:r,propagateExitStatus:n,tournamentRecord:o,disableAutoCalc:i,enableAutoCalc:s,drawDefinition:a,matchUpStatus:c,winningSide:u,matchUpId:p,event:m,score:d}=t,l=Z9({drawDefinition:a,matchUpStatus:c,winningSide:u});if(l)return l;let f=tX({tournamentRecord:o,drawDefinition:a,matchUpId:p,event:m,matchUpStatus:c,winningSide:u});if(f.error)return f;let{matchUp:g,inContextMatchUp:I,inContextDrawMatchUps:S,matchUpsMap:h,structure:T,isTeam:y,assignedDrawPositions:E,matchUpTieId:A}=f,N=er({matchUpId:A||p,inContextDrawMatchUps:S,drawDefinition:a});Object.assign(t,{inContextDrawMatchUps:S,inContextMatchUp:I,matchUpTieId:A,matchUpsMap:h,targetData:N,structure:T,matchUp:g});let D=c===zt&&d?.scoreStringSide1===""&&d?.scoreStringSide2===""&&!u;if(_G(t)&&D)return{error:Iw};let U=es(t),b;if(y){let x=nX({tournamentRecord:o,inContextMatchUp:I,activeDownstream:U,disableAutoCalc:i,enableAutoCalc:s,drawDefinition:a,winningSide:u,matchUpsMap:h,structure:T,matchUp:g,params:t,event:m});if(x?.error)return x;x?.dualWinningSideChange!==void 0&&(b=x.dualWinningSideChange)}if(y&&c&&[lu].includes(c))return{info:"Not supported for matchUpType: TEAM",error:O};if(d&&!y&&!r){let x=g.matchUpFormat??T?.matchUpFormat??a?.matchUpFormat??m?.matchUpFormat,k=eh({existingMatchUpStatus:g.matchUpStatus,matchUpFormat:x,matchUpStatus:c,winningSide:u,score:d});if(k.error)return k}let C=ft({policyTypes:[Ap,Qr],tournamentRecord:o,drawDefinition:a,event:m})?.appliedPolicies??{};Tt(t.policyDefinitions)&&Object.assign(C,t.policyDefinitions);let _=aX({assignedDrawPositions:E,propagateExitStatus:n,inContextMatchUp:I,appliedPolicies:C,drawDefinition:a,matchUpStatus:c,structure:T,matchUp:g});if(_?.error)return _;let{qualifierAdvancing:v,qualifierChanging:w,removingQualifier:L}=oX({inContextMatchUp:I,winningSide:u,matchUp:g,params:t});if(Object.assign(t,{qualifierAdvancing:v,qualifierChanging:w,removingQualifier:L,appliedPolicies:C}),A){let x=iX({drawDefinition:a,matchUpStatus:c,matchUpTieId:A,matchUpsMap:h,winningSide:u,structure:T,matchUp:g,event:m,score:d});x&&(b=x.dualWinningSideChange,Object.assign(t,x))}let F=eX({matchUpTieId:A,activeDownstream:U,matchUpStatus:c,winningSide:u,matchUp:g});return F||rX({params:t,isTeam:y,dualWinningSideChange:b,activeDownstream:U,stack:e})}function Z9({drawDefinition:t,matchUpStatus:e,winningSide:r}){if(!t)return{error:$};if(e&&[to,Xr,Fr,zt].includes(e)&&r)return{error:O,winningSide:r,matchUpStatus:e};if(![void 0,...ky].includes(e))return M({result:{error:uc},info:"matchUpStatus does not exist",stack:"setMatchUpStatus"})}function tX({tournamentRecord:t,drawDefinition:e,matchUpId:r,event:n,matchUpStatus:o,winningSide:i}){let s=Ie({drawDefinition:e}),{matchUps:a}=te({nextMatchUps:!0,tournamentRecord:t,inContext:!0,drawDefinition:e,matchUpsMap:s,event:n}),c=s.drawMatchUps.find(g=>g.matchUpId===r),u=a?.find(g=>g.matchUpId===r);if(!c||!a)return{error:Be};if((c.winningSide||i)&&o==="BYE")return{context:"Cannot have Bye with winningSide",error:Hg,matchUpStatus:o};let p=u?.structureId,{structure:m}=tt({drawDefinition:e,structureId:p}),d=re(xt)(c.matchUpType),l=u?.drawPositions?.filter(Boolean),f=u?.matchUpTieId;return{inContextDrawMatchUps:a,assignedDrawPositions:l,inContextMatchUp:u,matchUpTieId:f,matchUpsMap:s,structure:m,matchUp:c,isTeam:d}}function eX({matchUpTieId:t,activeDownstream:e,matchUpStatus:r,winningSide:n,matchUp:o}){let i=Va({matchUpStatus:r});if(!t){if(e&&!n&&(r&&cS({matchUpStatus:r})||r&&[Qt,ge].includes(r)))return{error:Hg,activeDownstream:e,winningSide:n};if(n&&n===o.winningSide&&r&&!i)return{context:"winningSide must include directing matchUpStatus",error:Hg,directingMatchUpStatus:i,matchUpStatus:r}}}function rX({params:t,isTeam:e,dualWinningSideChange:r,activeDownstream:n,stack:o}){let{allowChangePropagation:i,tournamentRecords:s,tournamentRecord:a,drawDefinition:c,winningSide:u,matchUpId:p,matchUpTieId:m,matchUp:d}=t,{schedule:l}=t;if(l){let h=Hd({disableNotice:!0,tournamentRecords:s,tournamentRecord:a,drawDefinition:c,matchUpId:p,schedule:l});if(h.error)return h}let f=!e&&!r&&u&&d.winningSide&&d.winningSide!==u;if(i&&f&&d.roundPosition)return wG(t);let g=u&&!m||t.projectedWinningSide,I=Va({matchUpStatus:t.matchUpStatus});Pe({activeDownstream:n,matchUpWinner:g,method:o,winningSide:u});let S;return n?g?S=sX(t):I||t.autoCalcDisabled?S=LG(t):S={error:FU}:S=vG(t),M({result:S,stack:o})}function nX({tournamentRecord:t,inContextMatchUp:e,activeDownstream:r,disableAutoCalc:n,enableAutoCalc:o,drawDefinition:i,winningSide:s,matchUpsMap:a,structure:c,matchUp:u,params:p,event:m}){let d;if(n)ut({extension:{name:gc,value:!0},element:u});else if(o){let l=u.winningSide,{winningSide:f,scoreStringSide1:g,scoreStringSide2:I,set:S}=_u({drawDefinition:i,matchUpsMap:a,structure:c,matchUp:u,event:m}),h={scoreStringSide1:g,scoreStringSide2:I,sets:S?[S]:[]};if(d=f!==l,r&&d)return M({stack:"winningSideWithDownstreamDependencies",result:{error:al},context:{winningSide:s,matchUp:u}});dr({name:gc,element:u}),Object.assign(p,{winningSide:f,dualWinningSideChange:d,projectedWinningSide:f,score:h})}return Cc({tournamentId:t?.tournamentId,inContextDualMatchUp:e,eventId:m?.eventId,dualMatchUp:u,drawDefinition:i}),{dualWinningSideChange:d}}function oX({inContextMatchUp:t,winningSide:e,matchUp:r,params:n}){let o=t?.stage===Z&&t.finishingRound===1,i=o&&e,s=o&&r.winningSide&&!e&&(!n.matchUpStatus||n.matchUpStatus&&cS({matchUpStatus:n.matchUpStatus}))&&(!n.outcome||!ue({outcome:n.outcome})),a=i&&e!==r.winningSide&&r.winningSide;return{qualifierAdvancing:i,qualifierChanging:a,removingQualifier:s}}function iX({drawDefinition:t,matchUpStatus:e,matchUpTieId:r,matchUpsMap:n,winningSide:o,structure:i,matchUp:s,event:a,score:c}){let{matchUp:u}=Wt({matchUpId:r,inContext:!0,drawDefinition:t,matchUpsMap:n,event:a});if(!u)return;let p=ze({matchUp:u,drawDefinition:t,structure:i,event:a})?.tieFormat,{projectedWinningSide:m}=xG({drawDefinition:t,matchUpStatus:e,dualMatchUp:u,matchUpsMap:n,winningSide:o,tieFormat:p,structure:i,matchUp:s,event:a,score:c}),d=u.winningSide,l=m!==d,f=u._disableAutoCalc;return{isCollectionMatchUp:!0,dualWinningSideChange:l,projectedWinningSide:m,autoCalcDisabled:f,matchUpTieId:r,dualMatchUp:u,tieFormat:p}}function sX(t){let{matchUp:e,winningSide:r,matchUpTieId:n,dualWinningSideChange:o}=t;return r===e.winningSide||n&&!o?LG(t):M({stack:"winningSideWithDownstreamDependencies",result:{error:al},context:{winningSide:r,matchUp:e}})}function LG(t){let{tournamentRecord:e,matchUp:r,event:n}=t,o=t.isCollectionMatchUp&&r.winningSide&&!t.winningSide&&!ue({score:t.score}),i=t.isCollectionMatchUp?t.matchUpStatus||o&&zt||t.winningSide&&ie||Xr:t.matchUpStatus||ie,s=t.removeScore||[to,vt].includes(i)&&![Xr,Fr].includes(i),a=Fn({...t,matchUpStatus:i,removeWinningSide:o,context:"sms",removeScore:s});if(a.error)return a;if(t.isCollectionMatchUp){let{matchUpTieId:c,drawDefinition:u,matchUpsMap:p}=t,m=ho({appliedPolicies:t.appliedPolicies,matchUpId:c,tournamentRecord:e,drawDefinition:u,matchUpsMap:p,event:n});if(m.error)return m;Object.assign(a,{tieMatchUpResult:m})}return a}function aX({assignedDrawPositions:t,propagateExitStatus:e,inContextMatchUp:r,appliedPolicies:n,drawDefinition:o,matchUpStatus:i,structure:s,matchUp:a}){if(n?.[Qr]?.requireParticipantsForScoring===!1)return{...P};let c=r?.sides?.map(m=>m.participantId).filter(Boolean).length,u=a?.sides?[]:Pt({structureId:s?.structureId,drawDefinition:o}).positionAssignments,p=c&&c===2||a.collectionId&&Ae({structure:s})&&c&&c>=1||t?.length===2&&u?.filter(m=>t.includes(m.drawPosition)).every(m=>m.participantId);return i&&[vt,Mt,Qt].includes(i)&&c===1&&e?{...P}:i&&Fy.includes(i)&&!p?M({info:"matchUpStatus requires assigned participants",context:{matchUpStatus:i,requiredParticipants:p},result:{error:uc}}):{...P}}function tO({tournamentRecord:t,drawDefinition:e,matchUpId:r,event:n}){if(!e)return{error:$};let{matchUp:o}=Wt({drawDefinition:e,matchUpId:r,event:n});return o?.matchUpType!==Ir?{error:cr}:vi({enableAutoCalc:!0,tournamentRecord:t,drawDefinition:e,matchUpId:r,event:n})}function eO({drawDefinition:t,event:e,matchUpId:r}){let n=dt({drawDefinition:t,matchUpId:r},[Kt,wr]);if(n.error)return n;let{matchUp:o}=Wt({drawDefinition:t,event:e,matchUpId:r});return o?dr({name:Al,element:o}):{error:Be}}function FG({substituteParticipantId:t,existingParticipantId:e,tournamentRecord:r,drawDefinition:n,sideNumber:o,matchUpId:i,event:s}){let a="substituteParticipant";if(!n)return{error:$};if(!i)return{error:mr};if(!e||!t)return M({result:{error:We},stack:a});let{matchUp:c}=Wt({drawDefinition:n,matchUpId:i,event:s});if(!c)return{error:Be};if(!c.collectionId)return M({result:{error:cr},stack:a});let u=Ie({drawDefinition:n}),{matchUps:p}=te({tournamentParticipants:r?.participants,inContext:!0,drawDefinition:n,matchUpsMap:u}),m=p?.find(g=>g.matchUpId===i),l=p?.find(g=>g.matchUpId===m?.matchUpTieId)?.sides?.find(g=>g.participant.individualParticipants.some(({participantId:I})=>I===e));return!l||o&&l.sideNumber!==o?{error:Hr}:l.participant?.individualParticipants?.map(gt).filter(g=>g!==e)?.includes(t)?yh({newParticipantId:t,tieMatchUpId:i,existingParticipantId:e,substitution:!0,tournamentRecord:r,drawDefinition:n,event:s}):M({result:{error:Hr},stack:a})}function rO(t){return FG(t)}function nO({drawDefinition:t,matchUpId:e,event:r}){if(!t)return{error:$};let{matchUp:n}=Wt({drawDefinition:t,matchUpId:e,event:r});return ut({extension:{name:gc,value:!0},element:n})}function oO(t){let e="setMatchUpFormat",r=X(t,[{tournamentRecord:!0},{[$e]:E=>xr({matchUpFormat:E}),[Lr]:Kc,matchUpFormat:!0}]);if(r.error)return M({result:r,stack:e});let{tournamentRecord:n,drawDefinition:o,scheduledDates:i,stageSequences:s,matchUpFormat:a,structureId:c,eventType:u,matchUpId:p,eventId:m,stages:d,drawId:l,event:f,force:g}=t;if(i&&!Array.isArray(i))return M({result:{error:O,scheduledDates:i},stack:e});if(u&&!_s([Dt,Lt],u))return M({result:{error:zn},stack:e});let I=0,S=t.structureIds??(c?[c]:[]),h=t.eventIds??(m?[m]:[]),T=t.drawIds??(l?[l]:[]);if((c||S?.length)&&!o)return M({result:{error:$},stack:e});if(l&&p&&o){let E=Ff({tournamentRecord:n,drawDefinition:o,matchUpFormat:a,structureIds:S,structureId:c,matchUpId:p});if(E.error)return E;I+=1}return I+=cX({tournamentRecord:n,processStructures:E=>uX({drawDefinition:E,tournamentRecord:n,stageSequences:s,scheduledDates:i,matchUpFormat:a,structureIds:S,stack:e,force:g,event:f,stages:d}),stageSequences:s,matchUpFormat:a,structureIds:S,eventType:u,eventIds:h,drawIds:T,stages:d}),I?{...P,modificationsCount:I}:{...P,info:Na}}function cX({tournamentRecord:t,processStructures:e,stageSequences:r,matchUpFormat:n,structureIds:o,eventType:i,eventIds:s,drawIds:a,stages:c}){let u=0;for(let p of t?.events??[])if(!(s?.length&&!s.includes(p.eventId)||i&&i!==p.eventType||i===Oe))if(Array.isArray(r)||Array.isArray(c)||o?.length||a?.length)for(let m of p.drawDefinitions??[]){if(Array.isArray(a)&&!a.includes(m.drawId))continue;let d=e(m);u+=d.modificationsCount,Ft({structureIds:d.modifiedStructureIds,drawDefinition:m})}else p.matchUpFormat!==n&&(p.matchUpFormat=n,u+=1);return u}function uX({drawDefinition:t,tournamentRecord:e,stageSequences:r,scheduledDates:n,matchUpFormat:o,structureIds:i,stack:s,force:a,event:c,stages:u}){let p=[],m=0;for(let d of t.structures??[]){if(Array.isArray(u)&&!u.includes(d.stage)||Array.isArray(r)&&!r.includes(d.stageSequence)||i?.length&&!i.includes(d.structureId))continue;i?.length&&d.matchUpFormat!==o&&(d.matchUpFormat=o,p.push(d.structureId),m+=1);let l=((a||n)&&ht({matchUpFilters:{matchUpStatuses:[zt]},structure:d}).matchUps)??[],f=(n&&ht({matchUpFilters:{matchUpStatuses:[zt]},contextFilters:{scheduledDates:n},afterRecoveryTimes:!1,inContext:!0,structure:d}).matchUps)??[];if(l?.length){let g=f?f.map(Te):l.map(Te);for(let I of l)g.includes(I.matchUpId)&&(I.matchUpFormat=n?.length?o:void 0,It({tournamentId:e?.tournamentId,eventId:c?.eventId,context:s,drawDefinition:t,matchUp:I}))}}return!p.length&&t.matchUpFormat!==o&&(t.matchUpFormat=o,m+=1),{modifiedStructureIds:p,modificationsCount:m}}function Ph({inheritance:t=!0,tournamentRecord:e,drawDefinition:r,matchUpId:n,event:o}){if(!r)return{error:$};let i=Wt({drawDefinition:r,matchUpId:n})?.matchUp;if(!i?.tieMatchUps)return{error:cr};let s=Wt({inContext:!0,drawDefinition:r,matchUpId:n,event:o})?.matchUp,a=0;return(i?.sides??[]).forEach(c=>{c.lineUp&&delete c.lineUp}),(s?.sides??[]).forEach(c=>{if(a+=1,t===!1){let u=s?.tieFormat,p=c.participantId;u&&p&&Us({drawDefinition:r,participantId:p,lineUp:[],tieFormat:u})}It({tournamentId:e?.tournamentId,context:"resetMatchUpLineUps",eventId:o?.eventId,drawDefinition:r,matchUp:i})}),{...P,modificationsCount:a}}function lN(t){let{matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o,setTBlast:i}=t;if(!o)return{sets:[]};let s=o.sets??[],a=Ci({winnerFirst:!1,matchUpFormat:e,matchUpStatus:r,setTBlast:i,sets:s}),c=Ci({winnerFirst:!1,reversed:!0,matchUpFormat:e,matchUpStatus:r,setTBlast:i,sets:s}),u=Ci({matchUpFormat:e,matchUpStatus:r,winningSide:n,setTBlast:i,sets:s}),p=a===u?c:a;return n&&(a=n===1?u:p,c=n===2?u:p),{score:{sets:s,scoreStringSide1:a,scoreStringSide2:c}}}function kG({sourceMatchUpStatusCodes:t,propagateExitStatus:e,sourceMatchUpStatus:r,loserParticipantId:n,tournamentRecord:o,drawDefinition:i,loserMatchUp:s,matchUpsMap:a,event:c}){let u="progressExitStatus";Pe({method:u,newline:!0,color:"magenta",keyColors:{loserMatchUpId:"brightcyan",sourceMatchUpStatus:"brightyellow"},loserMatchUpId:s?.matchUpId,loserMatchUpStatus:s?.matchUpStatus,sourceMatchUpStatus:r,sourceMatchUpStatusCodes:JSON.stringify(t),loserParticipantId:n?.slice(0,8),propagateExitStatus:e});let p=Ye(r)&&r!==De&&r||vt,m=te({inContext:!0,drawDefinition:i,matchUpsMap:a})?.matchUps,d=p,l=m?.find(f=>f.matchUpId===s?.matchUpId);if(Pe({method:u,color:"magenta",carryOverMatchUpStatus:p,updatedLoserMatchUpId:l?.matchUpId,updatedLoserStatus:l?.matchUpStatus,updatedLoserSides:JSON.stringify(l?.sides?.map(f=>({sn:f.sideNumber,pid:f.participantId?.slice(0,8),bye:f.bye}))),updatedLoserDP:JSON.stringify(l?.drawPositions),existingStatusCodes:JSON.stringify(l?.matchUpStatusCodes)}),l?.matchUpId&&d){let f,g=l.matchUpStatusCodes?.map(h=>typeof h=="string"?h:"WO")??[],I=l.sides?.find(h=>h.participantId===n);if(I?.sideNumber){let h=l?.sides?.reduce((T,y)=>y?.participantId?T+1:T,0);if(Pe({method:u,color:"brightyellow",keyColors:{decision:"brightgreen"},loserSideNumber:I.sideNumber,participantsCount:h,statusCodesLength:g.length,existingStatusCodes:JSON.stringify(g),loserMatchUpIsExit:Ye(s.matchUpStatus),loserMatchUpOriginalStatus:s.matchUpStatus}),h===1&&g.length===0)f=I.sideNumber===1?2:1,g[0]=t[0],Pe({method:u,color:"brightgreen",decision:"SINGLE_PARTICIPANT_no_existing_codes",winningSide:f,statusCodes:JSON.stringify(g)});else if(!Ye(s.matchUpStatus))f=I.sideNumber===1?2:1,g[0]=t[0],Pe({method:u,color:"brightgreen",decision:"TWO_PARTICIPANTS_not_exit",winningSide:f,statusCodes:JSON.stringify(g)});else{let T=g[0];g[I.sideNumber-1]=t[0];let y=I.sideNumber===1?2:1;g[y-1]=T,d=Qt,f=void 0,Pe({method:u,color:"brightred",decision:"BOTH_EXITS_converting_to_DOUBLE_WALKOVER",loserMatchUpStatus:d,winningSide:f,statusCodes:JSON.stringify(g)})}}else Pe({method:u,color:"brightyellow",decision:"NO_LOSER_PARTICIPANT_SIDE_FOUND",loserParticipantId:n?.slice(0,8),availableSides:JSON.stringify(l.sides?.map(h=>({sn:h.sideNumber,pid:h.participantId?.slice(0,8)})))});Pe({method:u,color:"brightmagenta",keyColors:{finalStatus:"brightgreen",finalWinningSide:"brightyellow"},action:"calling_setMatchUpState",loserMatchUpId:s.matchUpId,finalStatus:d,finalWinningSide:f,finalStatusCodes:JSON.stringify(g)});let S=vi({matchUpStatus:d,matchUpId:s.matchUpId,matchUpStatusCodes:g,allowChangePropagation:!0,propagateExitStatus:e,tournamentRecord:o,drawDefinition:i,winningSide:f,event:c});return M({result:S,stack:u,context:{progressExitStatus:!0}})}return M({result:{error:Xe},stack:u})}function wc(t){let e=X(t,[{[wr]:!0,[Kt]:!0}]);if(e.error)return e;let r="setMatchUpStatus",n=Dr(t);if(!t.drawDefinition){let E=t.tournamentRecord??(t.tournamentId&&n[t.tournamentId]);t.tournamentRecord??=E;let A=_e({eventId:t.eventId,drawId:t.drawId,tournamentRecord:E});if(A.error)return A;A.drawDefinition&&(t.drawDefinition=A.drawDefinition),t.event=A.event}let{disableScoreValidation:o,propagateExitStatus:i,policyDefinitions:s,tournamentRecord:a,disableAutoCalc:c,enableAutoCalc:u,drawDefinition:p,matchUpId:m,schedule:d,event:l,notes:f}=t,g=t.matchUpFormat||t.outcome?.matchUpFormat,{policy:I}=go({policyType:Qr,tournamentRecord:a,event:l}),S=t.allowChangePropagation!==void 0&&t.allowChangePropagation||I?.allowChangePropagation!==void 0&&I.allowChangePropagation||void 0,{outcome:h,setTBlast:T}=t;if(h?.winningSide&&![1,2].includes(h.winningSide))return{error:sl};if(g){let E=Ff({tournamentRecord:a,drawDefinition:p,matchUpFormat:g,matchUpId:m,event:l});if(E.error)return E}if(h?.score?.sets&&!h.score.scoreStringSide1){let{score:E}=lN({...h,setTBlast:T});h.score=E,h.score.sets=h.score.sets.filter(A=>A.side1Score||A.side2Score||A.side1TiebreakScore||A.side2TiebreakScore||A.side1PointScore||A.side2PointScore)}let y=vi({matchUpStatusCodes:h?.matchUpStatusCodes,matchUpStatus:h?.matchUpStatus,winningSide:h?.winningSide,allowChangePropagation:S,disableScoreValidation:o,score:h?.score,propagateExitStatus:i,tournamentRecords:n,policyDefinitions:s,tournamentRecord:a,disableAutoCalc:c,enableAutoCalc:u,drawDefinition:p,matchUpFormat:g,matchUpId:m,schedule:d,event:l,notes:f});if(y.context?.progressExitStatus){let E=!0,A=0;for(;E&&A<10;){E=!1,A+=1;let N=kG({sourceMatchUpStatusCodes:y.context.sourceMatchUpStatusCodes,sourceMatchUpStatus:y.context.sourceMatchUpStatus,loserParticipantId:y.context.loserParticipantId,propagateExitStatus:t.propagateExitStatus,tournamentRecord:t.tournamentRecord,loserMatchUp:y.context.loserMatchUp,matchUpsMap:y.context.matchUpsMap,drawDefinition:t.drawDefinition,event:t.event});N.context?.loserMatchUp&&(Object.assign(y.context,N.context),E=!0)}}return M({result:y,stack:r})}function iO(t){if(!t?.outcomes)return{error:nt};if(!Array.isArray(t.outcomes))return{error:nt,info:{outcomes:t.outcomes}};let e=t.tournamentRecords||t.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord}||{},r=t.outcomes??[],n=r.reduce((o,i)=>o.includes(i.tournamentId)?o:o.concat(i.tournamentId),[]);for(let o of n){let i=e[o];if(!i)return{error:j};let s=r.filter(a=>a.tournamentId===o);if(s.length){let a=pX({outcomes:s,tournamentRecord:i});if(a.error)return a}}return{...P}}function pX(t){let{tournamentRecords:e,tournamentRecord:r,outcomes:n,policyDefinitions:o}=t,i={};n.forEach(s=>{let{eventId:a}=s;i[a]||(i[a]=[]),i[a].push(s)});for(let s of Object.keys(i)){let{event:a}=_e({tournamentRecord:r,eventId:s});for(let c of i[s]){let{drawId:u}=c,p=a?.drawDefinitions?.find(m=>m.drawId===u);if(p&&u){let{matchUpFormat:m,matchUpId:d}=c,l=wc({schedule:c?.schedule,tournamentRecords:e,policyDefinitions:o,tournamentRecord:r,drawDefinition:p,matchUpFormat:m,matchUpId:d,outcome:c,drawId:u,event:a});if(l.error)return l}}}return{...P}}function GG({drawDefinition:t,matchUpId:e,outcome:r,matchUp:n}){if(!n&&!t)return{error:$};if(!r)return{error:nt,info:"missing outcome"};if(!n&&!e)return{error:Xe};if(!n){let i=Wt({drawDefinition:t,matchUpId:e});if(i.error)return i;n=i.matchUp}return typeof r!="object"||!r.score?.scoreStringSide1||!r.score?.scoreStringSide2?{error:O}:ut({element:n,extension:{name:Al,value:r}})}function sO(t){return GG(t)}function En({target:t,tieFormat:e,event:r}){if(t){if(t.tieFormatId&&r?.tieFormats?.length){let n=t.tieFormatId;if(mX({event:r,tieFormatId:n})<=1){let s=r.tieFormats.findIndex(a=>a.tieFormatId===n);if(s>=0){let a=q(e,void 0,!0);a.tieFormatId=n,r.tieFormats[s]=a;return}}let i=q(e,void 0,!0);i.tieFormatId=it(),r.tieFormats.push(i),t.tieFormatId=i.tieFormatId,delete t.tieFormat;return}t.tieFormat=e}}function mX({event:t,tieFormatId:e}){let r=0;t.tieFormatId===e&&r++;for(let o of t.drawDefinitions??[]){o.tieFormatId===e&&r++;for(let i of o.structures??[])i.tieFormatId===e&&r++}let n=vn({matchUpFilters:{matchUpTypes:[Ir]},event:t});for(let o of n.matchUps??[])o.tieFormatId===e&&r++;return r}function Nh({event:t}){if(!t?.tieFormats?.length)return;let e=new Set;t.tieFormatId&&e.add(t.tieFormatId);for(let n of t.drawDefinitions??[]){n.tieFormatId&&e.add(n.tieFormatId);for(let o of n.structures??[])o.tieFormatId&&e.add(o.tieFormatId)}let r=vn({matchUpFilters:{matchUpTypes:[Ir]},event:t});for(let n of r.matchUps??[])n.tieFormatId&&e.add(n.tieFormatId);t.tieFormats=t.tieFormats.filter(n=>n.tieFormatId&&e.has(n.tieFormatId)),t.tieFormats.length||delete t.tieFormats}function Dh(t){let e="resetTieFormat",{drawDefinition:r,event:n,uuids:o}=t,i=X(t,[{[rt]:!0,[wr]:!0}],e);if(i.error)return i;let s=ss(t,[{[Gi]:Rn}]);if(s[jr])return s;let a=t.tournamentRecord?.tournamentId,{matchUp:c,structure:u}=s?.matchUp??{};if(!c?.tieMatchUps)return M({result:{error:cr},info:"Must be a TEAM matchUp",stack:e});if(!c.tieFormat&&!c.tieFormatId)return{...P};let p=ze({structure:u,drawDefinition:r,event:n})?.tieFormat;if(!p)return M({result:{error:fe},info:"No inherited tieFormat",stack:e});let m=[],d=[],l=[],f=[];for(let g of p.collectionDefinitions){let{matchUpCount:I,collectionId:S}=g;d.push(S);let h=(c.tieMatchUps??[]).filter(T=>T.collectionId===S);if(h.length>I)h.sort((T,y)=>(T.matchUpStatus===zt?1:0)-(y.matchUpStatus===zt?1:0)),l.push(...h.slice(0,I)),m.push(...h.slice(3).map(Te));else if(l.push(...h),h.length<I){let T=I-h.length,y=Qp({collectionDefinition:g,matchUpsLimit:T,matchUp:c,uuids:o});f.push(...y)}}for(let g of c?.tieMatchUps??[])g.collectionId&&!d.includes(g.collectionId)&&m.push(g.matchUpId);return f.length&&(l.push(...f),Ho({eventId:n?.eventId,matchUps:f,drawDefinition:r,tournamentId:a})),m.length&&wn({matchUpIds:m,eventId:n?.eventId,drawDefinition:r,tournamentId:a}),c&&(c.tieMatchUps=l,c.tieFormatId=void 0,c.tieFormat=void 0,n&&Nh({event:n}),It({structureId:u?.structureId,eventId:n?.eventId,context:e,drawDefinition:r,tournamentId:a,matchUp:c})),{...P,newMatchUps:f,deletedMatchUpIds:m}}function Uh(t){let{tournamentRecord:e,drawDefinition:r,matchUpId:n,event:o}=t,i="resetScorecard";if(!r)return M({result:{error:$},stack:i});if(!n)return M({result:{error:mr},stack:i});if(!wt(n))return M({result:{error:O,matchUpId:n},stack:i});let s=Ie({drawDefinition:r}),{matchUps:a}=te({nextMatchUps:!0,inContext:!0,drawDefinition:r,matchUpsMap:s}),c=s.drawMatchUps.find(I=>I.matchUpId===n),u=a?.find(I=>I.matchUpId===n);if(!c||!a)return{error:Be};if(c.matchUpType!==Ze)return{error:cr};let p=er({inContextDrawMatchUps:a,drawDefinition:r,matchUpId:n}),m=u?.structureId,{structure:d}=tt({drawDefinition:r,structureId:m});if(Object.assign(t,{inContextDrawMatchUps:a,inContextMatchUp:u,matchUpsMap:s,targetData:p,structure:d,matchUp:c}),es(t))return{error:al};if(c.tieMatchUps?.length)for(let I of c.tieMatchUps){let S=vi({matchUpId:I.matchUpId,matchUpTieId:n,winningSide:void 0,removeScore:!0,tournamentRecord:e,drawDefinition:r,event:o});if(S.error)return M({result:S,stack:i})}let f=ft({tournamentRecord:e,drawDefinition:r,event:o})?.appliedPolicies,g=ho({event:t.event,removeScore:!0,tournamentRecord:e,appliedPolicies:f,drawDefinition:r,matchUpsMap:s,matchUpId:n});if(g.error)return M({result:g,stack:i});if(t.tiebreakReset&&!g.tieFormatRemoved){let I=ze({drawDefinition:r,structure:d,event:o})?.tieFormat;if(c.tieFormat&&I){let{matchUpCountDifference:S,descendantDifferences:h,ancestorDifferences:T,valueDifference:y}=Ti({descendant:c.tieFormat,ancestor:I});if(h.collectionIds.length===1&&!T.collectionIds.length&&!T.groupsCount&&S===1&&y===1){let E=Dh({tournamentRecord:e,drawDefinition:r,matchUpId:n,event:o});if(E.error)return E}}}return{...P}}function aO(t){let e=X(t,[{[Kt]:!0,[ce]:!0},{[_a]:{[cu]:!1,roundNumbers:!1},[Oy]:"At least one must be provided",[Ge]:ke}]);if(e.error)return e;let r=oA(t);if(r.error)return r;let{matchUpIds:n}=r,o=re(Ze)(t.event.eventType),{tournamentRecord:i,drawDefinition:s,event:a}=t;for(let c of n){if(o){let p=Uh({tiebreakReset:!0,tournamentRecord:i,drawDefinition:s,matchUpId:c,event:a});if(p.error)return p;if(t.removeAssignments){let m=Ph({inheritance:!1,drawDefinition:s,matchUpId:c});if(m.error)return m}}let u=vi({winningSide:void 0,removeScore:!0,tournamentRecord:i,drawDefinition:s,matchUpId:c,event:a});if(u.error)return u;if(t.removeAssignments){let p=Eh({...t,matchUpId:c});if(p.error)return p}}return{...P}}function VG({tournamentRecord:t,drawDefinition:e,finishingOrder:r}){if(!e)return{error:$};let n="setOrderOfFinish";if(!Array.isArray(r))return M({info:Ri("finishingOrder"),result:{error:O},stack:n});let{completedMatchUps:o,matchUpsMap:i}=Ga({inContext:!0,drawDefinition:e}),s=o?.map(Te)??[],a=r.map(Te),{matchUpTypes:c,roundNumbers:u,structureIds:p,matchUpTieIds:m}=(o??[]).filter(({matchUpId:T})=>a.includes(T)).reduce((T,y)=>{let{matchUpTieId:E,matchUpType:A,roundNumber:N,structureId:D}=y;return T.matchUpTypes.includes(A)||T.matchUpTypes.push(A),T.roundNumbers.includes(N)||T.roundNumbers.push(N),T.structureIds.includes(D)||T.structureIds.push(D),T.matchUpTieIds.includes(E)||T.matchUpTieIds.push(E),T},{matchUpTypes:[],roundNumbers:[],structureIds:[],matchUpTieIds:[]});if(c.length>1||m.length>1||u.length>1||p.length>1)return M({info:"matchUpType, structureId and roundNumber must be equivalent",result:{error:O},stack:n});let d,l,f={},g=[],I=[];if(!r.every(({orderOfFinish:T,matchUpId:y})=>(g.push(y),T&&I.push(T),f[y]=T,d=s.includes(y),l=T===void 0||yt(T)&&Math.floor(T)>0,d&&l)))return M({result:{error:d?O:uc},info:!d&&"matchUps must be completed"||!l&&"orderOfFinish must be integer > 0 or undefined"||void 0,stack:n});let h=o?.filter(T=>T.structureId===p[0]&&T.roundNumber===u[0]&&T.matchUpType===c[0]&&T.matchUpTieId===m[0]&&!g.includes(T.matchUpId));for(let T of h??[]){let{orderOfFinish:y}=T??{};if(y){if(!yt(y))return M({context:{orderOfFinish:y,matchUp:T},result:{error:O},stack:n});I.push(y)}}if(_T(I).length!==I.length||Math.max(...I)>I.length)return M({info:"Values not unique or greater than expected number of values",result:{error:O},stack:n});if(p.length){let T=Gp({matchUpFilters:{matchUpIds:a},structureId:p[0],drawDefinition:e,matchUpsMap:i});if(T.error)return M({result:T,stack:n});T.completedMatchUps?.forEach(y=>{y.orderOfFinish=f[y.matchUpId],It({tournamentId:t.tournamentId,context:"setOrderOfFinish",drawDefinition:e,matchUp:y})})}return{...P}}function cO(t){return VG(t)}function uO(t){let{tournamentRecord:e,drawDefinition:r,matchUpId:n,lineUps:o,event:i}=t,s="applyLineUps",a=X(t,[{[rt]:!0,[Kt]:!0,[wr]:!0},{lineUps:!0,[Ge]:ke}],s);if(a.error)return a;let c=e.participants??[],u=Wt({tournamentParticipants:c,inContext:!0,drawDefinition:r,matchUpId:n});if(u.error)return u;if(!u.matchUp)return{error:Be};let{matchUp:p,structure:m}=u,{drawPositions:d,matchUpType:l}=p;if(l!==xt)return{error:cr};if(!d?.length)return{error:jc};let f=ze({matchUp:p,drawDefinition:r,structure:m,event:i})?.tieFormat,g={};for(let S of o){if(!Array.isArray(S))return{error:O,lineUp:S};let h=dX({tournamentParticipants:c,inContextMatchUp:p,tieFormat:f,lineUp:S});if(h.error)return h;let{collectionParticipantIds:T,sideNumbers:y}=h,E=lX({collectionParticipantIds:T,tournamentParticipants:c,tournamentRecord:e});if(E?.error)return E;let A=fX(y),N=Object.keys(g).map(D=>Number.parseInt(D));A&&!N.includes(A)&&(g[A]=S)}if(!Object.keys(g).length)return{error:oI};if(u=Wt({drawDefinition:r,matchUpId:n}),u.error)return u;if(!u.matchUp)return{error:Be};let{matchUp:I}=u;I.sides??=[];for(let S of[1,2]){let h=I.sides.find(y=>y.sideNumber===S),T=g[S];if(T)h?h.lineUp=T:I.sides.push({lineUp:T,sideNumber:S});else continue}return It({tournamentId:e?.tournamentId,context:s,drawDefinition:r,matchUp:I}),{...P}}function dX({tournamentParticipants:t,inContextMatchUp:e,tieFormat:r,lineUp:n}){let o={},i=[];for(let s of n){if(typeof s!="object")return{error:O,lineUpAssignment:s};let{participantId:a,collectionAssignments:c=[]}=s;if(!Array.isArray(c))return{error:O,collectionAssignments:c};let u=t.find(m=>m.participantId===a);if(!u)return{error:ee};if(u.participantType!==St)return{error:Dn};let p=e.sides?.find(m=>m.participant?.individualParticipantIds?.includes(a))?.sideNumber;p&&i.push(p);for(let m of c){if(typeof m!="object")return{error:O,collectionAssignment:m};let{collectionId:d,collectionPosition:l}=m,f=r?.collectionDefinitions?.find(S=>S.collectionId===d);if(!f)return{error:O,collectionId:d};let g=`${d}-${l}`;o[g]||(o[g]=[]);let I=o[g].length;if(re(Ct)(f.matchUpType)&&I||f.matchUpType===Rt&&I>1)return{info:"Excessive collectionPosition assignments",error:O};o[g].push(a)}}return{collectionParticipantIds:o,sideNumbers:i}}function lX({collectionParticipantIds:t,tournamentParticipants:e,tournamentRecord:r}){let n=Object.values(t);for(let o of n)if(o.length===2){let{participant:i}=Tn({tournamentParticipants:e,participantIds:o});if(!i){let a=Gn({participant:{participantType:lt,participantRole:Ve,individualParticipantIds:o},pairOverride:!0,tournamentRecord:r});if(a.error)return a}}}function fX(t){let e=mn(t);return(e[1]||0)>(e[2]||0)&&1||(e[2]||0)>(e[1]||0)&&2||void 0}var xh={};Gt(xh,{anonymizeTournamentRecord:()=>hO,completeDrawMatchUps:()=>$u,generate:()=>SO,generateEventWithDraw:()=>zd,generateOutcome:()=>vh,generateOutcomeFromScoreString:()=>Rh,generateParticipants:()=>oc,generateTournamentRecord:()=>IO,modifyTournamentRecord:()=>yO,mutate:()=>EO,removeMatchUpOutcome:()=>TO});var SO={};Gt(SO,{generateEventWithDraw:()=>zd,generateOutcome:()=>vh,generateOutcomeFromScoreString:()=>Rh,generateParticipants:()=>oc,generateTournamentRecord:()=>IO});function gX(t){let e=t.reduce((n,o)=>((o.side1Score!==void 0||o.side2Score!==void 0)&&(n.side1+=o.side1Score??0,n.side2+=o.side2Score??0),n),{side1:0,side2:0});return e.side1>e.side2?1:e.side2>e.side1?2:t.find(n=>n.side1TiebreakScore!==void 0||n.side2TiebreakScore!==void 0)?.winningSide}function IX(t){let e={side1:0,side2:0};if(t.forEach(r=>{r.winningSide===1?e.side1++:r.winningSide===2&&e.side2++}),e.side1>e.side2)return 1;if(e.side2>e.side1)return 2}function SX(t,e,r){if(t||!e||!r)return t;let n=oe(e);return Dd(n)?gX(r):IX(r)}function hX(t,e,r){let n=Rd({scoreString:t,matchUpFormat:e});return{sets:n,scoreStringSide1:Ci({sets:n,matchUpFormat:e,setTBlast:r}),scoreStringSide2:Ci({sets:n,reversed:!0,matchUpFormat:e,setTBlast:r})}}function TX(t,e,r,n){let o=Ci({sets:t,matchUpFormat:r,setTBlast:n}),i=Ci({sets:t,reversed:!0,matchUpFormat:r,setTBlast:n});if(typeof o!="string")return o;if(typeof i!="string")return i;let s=e===2?i:o,a=e===2?o:i;return{sets:Rd({scoreString:s,matchUpFormat:r}),scoreStringSide1:s,scoreStringSide2:a}}function Rh(t){let{matchUpFormat:e,matchUpStatus:r,winningSide:n,scoreString:o,setTBlast:i,preserveSideOrder:s=!1}=t;if(!o)return{outcome:{...qa,winningSide:n,matchUpStatus:r}};if(n&&![1,2,void 0].includes(n))return{error:O,winningSide:n};let a=o&&Rd({scoreString:o,matchUpFormat:e}),c=o?.trim().startsWith("["),u=SX(n,e,a),p=oe(e),m=s||c||Dd(p)?hX(o,e,i):TX(a,u,e,i);return et({outcome:{matchUpStatus:r,winningSide:u,score:m}})}function sg({matchUpScheduleTimes:t,matchUpDependencies:e,allDateMatchUpIds:r,matchUp:n}){let i=(e?.[n.matchUpId]?.matchUpIds??[]).filter(a=>r.includes(a)).filter(a=>!t[a]);return{dependenciesScheduled:!i?.length,remainingDependencies:i}}function Lc({individualParticipantProfiles:t,participantId:e}){t[e]||(t[e]={typeChangeTimeAfterRecovery:void 0,timeAfterRecovery:void 0,priorMatchUpType:void 0,potentialRecovery:{},potentialCounted:{},potentialBookings:{},bookings:[],counters:{}})}function BG({individualParticipantProfiles:t,recoveryValue:e,participantId:r,scheduleTime:n,drawId:o}){t[r].potentialRecovery[o]||(t[r].potentialRecovery[o]=[]),t[r].potentialRecovery[o].push(e),t[r].potentialBookings[o]||(t[r].potentialBookings[o]=[]),t[r].potentialBookings[o].push({timeAfterRecovery:e,scheduleTime:n})}function Hu({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,typeChangeRecoveryMinutes:r,averageMatchUpMinutes:n=0,matchUpNotBeforeTimes:o,matchUpDependencies:i,recoveryMinutes:s=0,scheduleTime:a,matchUp:c}){let u=$t(c?.schedule?.endTime),p=u?Yr(u,st(s)):Yr(a,st(n)+st(s)),m=r&&(u?Yr($t(u),r):Yr(a,st(n)+st(r))),d=i?.[c.matchUpId]?.participantIds??[],l=(c.roundPosition&&t[c.matchUpId]||[]).flat();d.forEach(f=>{Lc({individualParticipantProfiles:e,participantId:f});let I=e[f].priorMatchUpType!==c.matchUpType&&m||p;l.includes(f)?BG({individualParticipantProfiles:e,drawId:c.drawId,recoveryValue:I,participantId:f,scheduleTime:a}):(e[f].timeAfterRecovery=I,e[f].bookings.push({scheduleTime:a,timeAfterRecovery:I}))}),Za({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:o,timeAfterRecovery:p,matchUp:c})}function fN({matchUpScheduleTimes:t,matchUpDependencies:e,scheduleTime:r,matchUpId:n,details:o}){let i,s=o.minutesMap?.[n]?.recoveryMinutes,c=(o.minutesMap?.[n]?.averageMinutes||0)+(s||0),u=Yr(r,c),p=e?.[n]?.dependentMatchUpIds??[];if(p.length){let m=p.reduce((d,l)=>{let f=t[l];if(!f)return d;let g={scheduleTime:f,matchUpId:l};return f&&!d.matchUpId||jt(f)<jt(d.scheduleTime)?g:d},{});m.scheduleTime&&jt(u)>jt(m.scheduleTime)&&(i=m)}return{scheduledDependent:i}}function WG(t){let{sides:e,matchUpType:r}=t??{};return(e??[]).map(n=>r===Rt&&(n?.participant?.individualParticipants??[])||n?.participant&&[n.participant]||[]).flat()}var Yu="DO_NOT_SCHEDULE",HG={DO_NOT_SCHEDULE:Yu};function ag({averageMatchUpMinutes:t=90,requestConflicts:e={},potentials:r=!0,personRequests:n,scheduleTime:o,scheduleDate:i,matchUp:s}){let a=WG(s).map(({person:l})=>l?.personId);if(r){let l=(s?.potentialParticipants??[]).flat().map(({person:f})=>f?.personId);a.push(...l)}let c=a.map(l=>n[l]?.map(f=>({...f,personId:l}))).filter(Boolean).flat().filter(l=>l.requestType===Yu&&Xn(i,l.date)),u=[],p=s?.matchUpId,m=ve($t(o),mt(i)),d=$t(hI(m,t).toISOString());for(let l of c){let{requestId:f,startTime:g,endTime:I}=l;(o>g&&o<I||d&&d>g&&d<I)&&(u.push({matchUpId:p,request:l,scheduleTime:o}),e[f]?(e[f].scheduleTimes.includes(o)||e[f].scheduleTimes.push(o),e[f].matchUpIds.includes(p)||e[f].matchUpIds.push(p)):e[f]={request:l,scheduleTimes:[o],matchUpIds:[p]})}return{conflicts:u}}function bh({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,matchUp:r,value:n}){let{matchUpType:o}=r,{individualParticipantIds:i}=Mp(r),a=(t[r.matchUpId]??[]).filter(u=>!Re(u,i)).flat();[...i,...a].forEach(u=>{if(Lc({individualParticipantProfiles:e,participantId:u}),!e[u].potentialCounted[r.drawId]){let p=e[u].counters;p[o]?p[o]+=n:n>0&&(p[o]=n),p[So]?p[So]+=n:n>0&&(p[So]=n),a.includes(u)&&(e[u].potentialCounted[r.drawId]=!0)}})}function YG({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,dateScheduledMatchUpIds:r,greatestAverageMinutes:n,dateScheduledMatchUps:o,matchUpNotBeforeTimes:i,matchUpScheduleTimes:s,matchUpDependencies:a,clearScheduleDates:c,scheduleDate:u,minutesMap:p,matchUps:m}){let d=[];r||(o=m?.filter(g=>{let I=g.schedule??{},S=g.matchUpStatus==="BYE";return S&&d.push({tournamentId:g.tournamentId,matchUpId:g.matchUpId}),!S&&_c({schedule:I})&&(!u||g.schedule.scheduledDate===u)}),r=o.map(Te));let l=Array.isArray(c)?c.includes(u):c,f=l?[]:m.filter(({matchUpId:g})=>r.includes(g));for(let g of f){bh({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,value:1,matchUp:g});let I=g.schedule?.scheduledTime;if(I){s[g.matchUpId]=I;let S=p?.[g.matchUpId]?.recoveryMinutes;Hu({individualParticipantProfiles:e,matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:i,matchUpDependencies:a,averageMatchUpMinutes:n,recoveryMinutes:S,scheduleTime:I,matchUp:g})}}return{dateScheduledMatchUpIds:r,byeScheduledMatchUpDetails:d,dateScheduledMatchUps:o,clearDate:l}}function Yd({defaultRecoveryMinutes:t=0,averageMatchUpMinutes:e=90,dateScheduledMatchUps:r,tournamentRecords:n,venueIds:o=[],periodLength:i,scheduleDate:s,matchUps:a}){if(typeof n!="object")return{error:kt};if(!Rr(a)&&!Array.isArray(r))return{error:Bn};i=i??cm({recoveryMinutes:t,averageMatchUpMinutes:e});let c=Object.assign({},...Object.values(n).flatMap(d=>(d.events??[]).map(l=>{let{scheduleTiming:f}=Ac({tournamentRecord:d,event:l});return{[l.eventId]:{event:l,scheduleTiming:f}}}))),u={averageTimes:[{minutes:{default:e}}],recoveryTimes:[{minutes:{default:t}}]};r??=a?.filter(d=>{let l=d.schedule;return _c({schedule:l})&&(!s||d.schedule.scheduledDate===s)});let p=r?.filter(d=>(!o.length||o.includes(d.schedule.venueId))&&d.matchUpStatus!=="BYE");return{bookings:p?.map(({eventId:d,schedule:l,matchUpFormat:f})=>{let{event:g,scheduleTiming:I}=c[d],S=g?.eventType,h={...I,defaultTiming:u,matchUpFormat:f},{averageMinutes:T,recoveryMinutes:y}=id({timingDetails:h,eventType:S}),{courtId:E,venueId:A}=l,N=$t(l.scheduledTime),D=Yr(N,T);return{recoveryMinutes:y,averageMinutes:T,periodLength:i,startTime:N,courtId:E,endTime:D,venueId:A}}).filter(Boolean),relevantMatchUps:p,dateScheduledMatchUps:r}}function jG({calculateStartTimeFromCourts:t=!0,remainingScheduleTimes:e,defaultRecoveryMinutes:r,averageMatchUpMinutes:n,clearScheduleDates:o,tournamentRecords:i,tournamentRecord:s,periodLength:a,scheduleDate:c,startTime:u,venueIds:p,matchUps:m,endTime:d}){if(s&&!i&&(i={[s.tournamentId]:s}),typeof i!="object"||!Object.keys(i).length)return{error:kt};a=a??cm({recoveryMinutes:r,averageMatchUpMinutes:n});let{courts:l,venues:f}=kn({dates:[c],ignoreDisabled:!0,tournamentRecords:i}),g=l?.filter(A=>!p||p.includes(A.venueId))??[];u=u??Vu({courts:g,scheduleDate:c,startTime:!0}),d=d??Vu({courts:g,scheduleDate:c,endTime:!0});let{bookings:I,dateScheduledMatchUps:S}=Yd({defaultRecoveryMinutes:r,averageMatchUpMinutes:n,tournamentRecords:i,scheduleDate:c,periodLength:a,venueIds:p,matchUps:m}),h={calculateStartTimeFromCourts:t,remainingScheduleTimes:e,averageMatchUpMinutes:n,clearScheduleDates:o,date:c,periodLength:a,startTime:u,bookings:I,endTime:d,courts:g},{scheduleTimes:T}=eg(h),y=p?.length===1&&p[0]||f?.length===1&&f[0].venueId||void 0;return{dateScheduledMatchUpIds:S?.map(Vr("matchUpId")),dateScheduledMatchUps:S,scheduleTimes:T,venueId:y}}function qG({scheduledRoundsDetails:t,greatestAverageMinutes:e,garmanSinglePass:r}){let n=[],o=[],i,s,a,c;for(let u of t.filter(Boolean))c||(c=u.hash),(u.hash===c||r)&&(o=o.concat(u.matchUpIds)),u.hash!==c&&!r&&(c=u.hash,n.push({averageMinutes:a,recoveryMinutes:s,roundPeriodLength:i,matchUpIds:o}),o=u.matchUpIds),a=r?e:u.averageMinutes,s=u.recoveryMinutes,i=u.roundPeriodLength;return o.length&&n.push({matchUpIds:o,roundPeriodLength:i,recoveryMinutes:s,averageMinutes:a}),{groupedRounds:n}}function gN({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,scheduleCompletedMatchUps:r,containedStructureIds:n,matchUpNotBeforeTimes:o,matchUpScheduleTimes:i,matchUpDependencies:s,clearScheduleDates:a,tournamentRecords:c,periodLength:u,scheduleDate:p,useGarman:m,matchUps:d,courts:l,venues:f}){let g={},I=[],S=[],h=[];for(let T of f){let{rounds:y=[],venueId:E}=T,{scheduledRoundsDetails:A,greatestAverageMinutes:N,orderedMatchUpIds:D,minutesMap:R}=sm({scheduleCompletedMatchUps:r,containedStructureIds:n,tournamentRecords:c,periodLength:u,matchUps:d,rounds:y});h.push(...D??[]);let{groupedRounds:U}=qG({scheduledRoundsDetails:A,greatestAverageMinutes:N,garmanSinglePass:!0}),b,C=[];m&&({scheduleTimes:C,dateScheduledMatchUpIds:b}=jG({averageMatchUpMinutes:U[0]?.averageMinutes,scheduleDate:mt(p),venueIds:[T.venueId],clearScheduleDates:a,tournamentRecords:c,periodLength:u,matchUps:d}));let _=YG({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,dateScheduledMatchUpIds:b,greatestAverageMinutes:N,matchUpNotBeforeTimes:o,matchUpScheduleTimes:i,matchUpDependencies:s,clearScheduleDates:a,scheduleDate:p,minutesMap:R,matchUps:d});({dateScheduledMatchUpIds:b}=_);let v=_,{byeScheduledMatchUpDetails:w,clearDate:L}=_;w?.length&&S.push(...w);let{matchUpsToSchedule:F,matchUpMap:x}=Yf({matchUpPotentialParticipantIds:t,scheduleCompletedMatchUps:r,dateScheduledMatchUpIds:b,matchUpNotBeforeTimes:o,matchUpScheduleTimes:i,orderedMatchUpIds:D,clearDate:L,matchUps:d}),k=l.filter(G=>G.venueId===E);g[E]={previousRemainingScheduleTimes:[],courtsCount:k.length,greatestAverageMinutes:N,scheduledRoundsDetails:A,dateScheduledMatchUps:v,matchUpsToSchedule:F,scheduleTimes:C,groupedRounds:U,venueCourts:k,minutesMap:R,matchUpMap:x},a||I.push(...b)}return{allDateScheduledByeMatchUpDetails:S,allDateScheduledMatchUpIds:I,venueScheduledRoundDetails:g,allDateMatchUpIds:h}}function $G(t,e){let r=jt(t.scheduleTime),n=jt(t.timeAfterRecovery),o=jt(e.scheduleTime),i=jt(e.timeAfterRecovery),s=r===o||n===i,a=r>o&&r<i,c=o>r&&o<n,u=n>o&&n<i,p=i>r&&i<n;return et({hasOverlap:s||a||u||c||p,startAisContained:a,endAisContained:u,startBisContained:c,endBisContained:p},!0)}function cg({individualParticipantProfiles:t,matchUpNotBeforeTimes:e,matchUpDependencies:r,scheduleTime:n,matchUp:o,details:i}){let s=(r?.[o.matchUpId]?.participantIds??[]).flat(),a=i?.minutesMap?.[o.matchUpId]?.averageMinutes||0,c=i?.minutesMap?.[o.matchUpId]?.recoveryMinutes||0,u=s.every(f=>{Lc({individualParticipantProfiles:t,participantId:f});let g=t[f];if(!g.timeAfterRecovery)return!0;let I=$t(o?.schedule?.endTime),S=I?Yr(I,st(c)):Yr(n,st(a)+st(c));return!!![...Object.keys(g.potentialBookings).filter(E=>E!==o.drawId).map(E=>g.potentialBookings[E]).flat(),...g.bookings].find(E=>$G({scheduleTime:n,timeAfterRecovery:S},E).hasOverlap)}),p=e[o.matchUpId],d=(p?ks(ve(p),ve(n),!1):0)>=0;return{enoughTime:u&&d}}function IN({autoSchedulingAudit:t,tournamentRecords:e}){at({topic:Yi,payload:t});let r=s=>s?Object.values(s).reduce((c,u)=>c+u.length||0,0):0,n=(t?.schedulingProfile??[]).reduce((s,a)=>s+a.venues.reduce((c,u)=>c+u.rounds.length,0),0),o={scheduledDatesCount:t.scheduledDates?.length,noTimeMatchUpIdsCount:r(t?.noTimeMatchUpIds),scheduledMatchUpIdsCount:r(t?.scheduledMatchUpIds),overLimitMatchUpIdsCount:r(t?.overLimitMatchUpIds),requestConflictsCount:r(t?.requestConflicts),profileRoundsCount:n},i={itemType:qP,itemValue:o};for(let s of Object.values(e)){let a=s.tournamentId;tu(Yi)?at({payload:{type:qP,tournamentId:a,detail:o},topic:Yi}):vu({tournamentRecord:s,timeItem:i})}}function ug({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,matchUpDailyLimits:r={},matchUp:n}){let{enteredIndividualParticipantIds:o}=Mp(n),{matchUpId:i,matchUpType:s}=n,a=((n.roundPosition&&t[i])??[]).flat(),c=pt(o.concat(...a));return c.forEach(p=>{Lc({individualParticipantProfiles:e,participantId:p})}),{participantIdsAtLimit:c.filter(p=>{let m=e[p];if(m)return[s,So].find(d=>{let l=m.counters?.[d]||0,f=r[d]||0;return l&&f&&l>=f})}),relevantParticipantIds:c}}function pm({scheduleCompletedMatchUps:t=!1,scheduleByeMatchUps:e=!1,errorOnAnachronism:r=!1,checkChronology:n=!0,matchUpDependencies:o,removePriorValues:i,tournamentRecords:s,tournamentRecord:a,matchUpDetails:c,matchUpIds:u,schedule:p}){if(!a)return{error:j};if(!c&&(!u||!Array.isArray(u)))return{error:xs};if(!c&&(!p||typeof p!="object"))return{error:OU};let m,d=[],l=0;if(n&&!o){let I=tn({tournamentRecords:s,tournamentRecord:a});o=I.matchUpDependencies,m=I.matchUps}m||(m=qt({tournamentRecord:a})?.matchUps??[]);let f=m.reduce((I,S)=>{let{matchUpId:h,drawId:T,matchUpStatus:y}=S;return(e||y!=="BYE")&&(t||!Ot.includes(y))&&(I[T]?I[T].push(h):I[T]=[h]),I},{}),g=c?.map(I=>I.matchUpId);for(let I of Object.keys(f)){let{drawDefinition:S}=zo({tournamentRecord:a,drawId:I});if(!S)continue;let h=f[I].filter(y=>u?.includes(y)??g?.includes(y)),T=rr({inContext:!1,drawDefinition:S}).matchUps;for(let y of h){let E=c?.find(N=>N.matchUpId===y)?.schedule||p,A=Hd({schedule:E,matchUpDependencies:o,errorOnAnachronism:r,removePriorValues:i,inContextMatchUps:m,tournamentRecords:s,tournamentRecord:a,checkChronology:n,drawDefinition:S,drawMatchUps:T,matchUpId:y});if(A?.warnings?.length&&d.push(...A.warnings),A?.success&&(l+=1),A.error)return A}}return d.length?{...P,scheduled:l,warnings:d}:{...P,scheduled:l}}function ju(t){let{scheduleCompletedMatchUps:e=!1,scheduleByeMatchUps:r=!1,errorOnAnachronism:n,matchUpContextIds:o,removePriorValues:i,tournamentRecords:s,checkChronology:a,matchUpDetails:c,schedule:u}=t;if(t.matchUpIds&&!o)return pm(t);let p=X(t,[{[Ee]:!0},{[_a]:{matchUpContextIds:!1,matchUpDetails:!1},[Lr]:O,[Ge]:ke}]);if(p.error)return p;if((!c||o)&&!u)return{error:nt,info:"schedule is required"};let m=[],d=0,{matchUpDependencies:l}=tn({tournamentRecords:s});for(let f of Object.values(s)){let{tournamentId:g}=f,I=o?.filter(h=>h.tournamentId===g).map(Te),S=c?.filter(h=>h?.tournamentId===g);if(I?.length||S?.length){let h=pm({matchUpDetails:S,scheduleCompletedMatchUps:e,scheduleByeMatchUps:r,matchUpDependencies:l,errorOnAnachronism:n,removePriorValues:i,tournamentRecords:s,tournamentRecord:f,checkChronology:a,matchUpIds:I,schedule:u});if(h.warnings?.length&&m.push(...h.warnings),h.scheduled&&(d+=h.scheduled),h.error)return h}}return m.length?{...P,scheduled:d,warnings:m}:{...P,scheduled:d}}function KG({schedulingProfileModifications:t,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:r,schedulingProfileIssues:n,dateSchedulingProfiles:o,containedStructureIds:i,matchUpDependencies:s,matchUpDailyLimits:a,clearScheduleDates:c,tournamentRecords:u,schedulingProfile:p,personRequests:m,periodLength:d,matchUps:l,courts:f,dryRun:g}){let I={},S={},h={},T={},y={},E={},A={},N={},D={},R={};for(let C of o){let _=mt(C?.scheduleDate),v=C?.venues??[],w={},L={};yX({recoveryTimeDeferredMatchUpIds:h,dependencyDeferredMatchUpIds:T,scheduleTimesRemaining:I,skippedScheduleTimes:S,scheduledMatchUpIds:A,overLimitMatchUpIds:N,noTimeMatchUpIds:D,requestConflicts:R,scheduleDate:_});let F={};l.forEach(V=>{V.schedule?.scheduledDate&&Xn(_,mt(V.schedule.scheduledDate))&&Za({matchUpPotentialParticipantIds:w,matchUpNotBeforeTimes:F,matchUp:V})});let{allDateScheduledByeMatchUpDetails:x,venueScheduledRoundDetails:k,allDateMatchUpIds:G}=gN({matchUpPotentialParticipantIds:w,individualParticipantProfiles:L,scheduleCompletedMatchUps:r,containedStructureIds:i,matchUpNotBeforeTimes:F,matchUpScheduleTimes:E,matchUpDependencies:s,clearScheduleDates:c,tournamentRecords:u,useGarman:!0,periodLength:d,scheduleDate:_,matchUps:l,courts:f,venues:v});PX({checkPotentialRequestConflicts:e,recoveryTimeDeferredMatchUpIds:h,dependencyDeferredMatchUpIds:T,individualParticipantProfiles:L,matchUpPotentialParticipantIds:w,scheduleDateRequestConflicts:y,venueScheduledRoundDetails:k,matchUpScheduleTimes:E,matchUpNotBeforeTimes:F,overLimitMatchUpIds:N,skippedScheduleTimes:S,matchUpDependencies:s,matchUpDailyLimits:a,allDateMatchUpIds:G,requestConflicts:R,personRequests:m,scheduleDate:_,venues:v}),NX({venueScheduledRoundDetails:k,scheduleTimesRemaining:I,matchUpScheduleTimes:E,scheduledMatchUpIds:A,tournamentRecords:u,noTimeMatchUpIds:D,scheduleDate:_,venues:v,dryRun:g}),UX({allDateScheduledByeMatchUpDetails:x,tournamentRecords:u,dryRun:g}),RX({scheduledMatchUpIds:A,dateSchedulingProfile:C,scheduleDate:_})}let U=o.map(({scheduleDate:C})=>C),b={timeStamp:Date.now(),overLimitMatchUpIds:N,scheduledMatchUpIds:A,schedulingProfile:p,noTimeMatchUpIds:D,requestConflicts:R,scheduledDates:U};return IN({tournamentRecords:u,autoSchedulingAudit:b}),{...P,schedulingProfileModifications:t,schedulingProfileIssues:n,scheduleTimesRemaining:I,dateSchedulingProfiles:o,skippedScheduleTimes:S,recoveryTimeDeferredMatchUpIds:h,dependencyDeferredMatchUpIds:T,matchUpScheduleTimes:E,overLimitMatchUpIds:N,scheduledMatchUpIds:A,noTimeMatchUpIds:D,requestConflicts:R,scheduledDates:U}}function yX({recoveryTimeDeferredMatchUpIds:t,dependencyDeferredMatchUpIds:e,scheduleTimesRemaining:r,skippedScheduleTimes:n,scheduledMatchUpIds:o,overLimitMatchUpIds:i,noTimeMatchUpIds:s,requestConflicts:a,scheduleDate:c}){t[c]={},e[c]={},r[c]={},n[c]={},o[c]=[],i[c]=[],s[c]=[],a[c]=[]}function EX(t,e,r){t.forEach(n=>{let o=r[n].counters;o[e]?o[e]+=1:o[e]=1,o[So]?o[So]+=1:o[So]=1})}function AX({checkPotentialRequestConflicts:t,recoveryTimeDeferredMatchUpIds:e,dependencyDeferredMatchUpIds:r,individualParticipantProfiles:n,matchUpPotentialParticipantIds:o,scheduleDateRequestConflicts:i,matchUpScheduleTimes:s,matchUpNotBeforeTimes:a,overLimitMatchUpIds:c,matchUpDependencies:u,matchUpDailyLimits:p,allDateMatchUpIds:m,requestConflicts:d,personRequests:l,scheduleTime:f,scheduleDate:g,details:I,matchUp:S}){let{matchUpId:h,matchUpType:T}=S,{participantIdsAtLimit:y,relevantParticipantIds:E}=ug({matchUpPotentialParticipantIds:o,individualParticipantProfiles:n,matchUpDailyLimits:p,matchUp:S});if(y.length)return c[g].includes(h)||c[g].push(h),!1;let{scheduledDependent:A}=fN({matchUpScheduleTimes:s,matchUpDependencies:u,scheduleTime:f,matchUpId:h,details:I});if(A)return!1;let{dependenciesScheduled:N,remainingDependencies:D}=sg({matchUpScheduleTimes:s,matchUpDependencies:u,allDateMatchUpIds:m,matchUp:S});if(!N)return r[g][h]||(r[g][h]=[]),r[g][h].push({scheduleTime:f,remainingDependencies:D}),!1;let{enoughTime:R}=cg({individualParticipantProfiles:n,matchUpNotBeforeTimes:a,matchUpDependencies:u,scheduleTime:f,details:I,matchUp:S});if(!R)return e[g][h]||(e[g][h]=[]),e[g][h].push({scheduleTime:f}),!1;let U=I.greatestAverageMinutes,{conflicts:b}=ag({potentials:t,averageMatchUpMinutes:U,requestConflicts:d,personRequests:l,scheduleTime:f,scheduleDate:g,matchUp:S});if(b?.length)return i[g]||(i[g]=[]),i[g].push(...b),!1;EX(E,T,n);let C=I.minutesMap?.[h]?.recoveryMinutes;return Hu({matchUpPotentialParticipantIds:o,individualParticipantProfiles:n,matchUpNotBeforeTimes:a,averageMatchUpMinutes:U,matchUpDependencies:u,recoveryMinutes:C,scheduleTime:f,matchUp:S}),s[h]=f,!0}function PX({checkPotentialRequestConflicts:t,recoveryTimeDeferredMatchUpIds:e,dependencyDeferredMatchUpIds:r,individualParticipantProfiles:n,matchUpPotentialParticipantIds:o,scheduleDateRequestConflicts:i,venueScheduledRoundDetails:s,matchUpScheduleTimes:a,matchUpNotBeforeTimes:c,overLimitMatchUpIds:u,skippedScheduleTimes:p,matchUpDependencies:m,matchUpDailyLimits:d,allDateMatchUpIds:l,requestConflicts:f,personRequests:g,scheduleDate:I,venues:S}){let T=0,y,E=10;for(;!y;){for(let{venueId:A}of S){let N=0,D=s[A];for(;D.courtsCount&&D.scheduleTimes?.length&&D.matchUpsToSchedule?.length&&N<=D.courtsCount;){let{scheduleTime:R,attempts:U=0}=D.scheduleTimes.shift(),b=D.matchUpsToSchedule.find(C=>AX({checkPotentialRequestConflicts:t,recoveryTimeDeferredMatchUpIds:e,dependencyDeferredMatchUpIds:r,individualParticipantProfiles:n,matchUpPotentialParticipantIds:o,scheduleDateRequestConflicts:i,matchUpScheduleTimes:a,matchUpNotBeforeTimes:c,overLimitMatchUpIds:u,matchUpDependencies:m,matchUpDailyLimits:d,allDateMatchUpIds:l,requestConflicts:f,personRequests:g,scheduleTime:R,scheduleDate:I,details:D,matchUp:C}));D.matchUpsToSchedule=D.matchUpsToSchedule.filter(({matchUpId:C})=>C!==b?.matchUpId),b?N+=1:(p[I][A]||(p[I][A]=[]),p[I][A].push({scheduleTime:R,attempts:U+1}))}D.matchUpsToSchedule?.length&&(p[I][A]=p[I][A]?.filter(R=>{let U=R.attempts<10;return U&&D.scheduleTimes.push(R),!U})),(!D.scheduleTimes?.length||!D.matchUpsToSchedule?.length)&&(D.complete=!0)}T+=1,y=S.every(({venueId:A})=>s[A].complete)||T===E}}function NX({venueScheduledRoundDetails:t,scheduleTimesRemaining:e,matchUpScheduleTimes:r,scheduledMatchUpIds:n,tournamentRecords:o,noTimeMatchUpIds:i,scheduleDate:s,venues:a,dryRun:c}){for(let{venueId:u}of a){let p=t[u].matchUpMap;Object.keys(p).forEach(m=>{let d=o[m];d&&Object.keys(p[m]).forEach(l=>{let{drawDefinition:f}=zo({tournamentRecord:d,drawId:l});if(!f)return;p[m][l].forEach(({matchUpId:I})=>{DX({scheduledMatchUpIds:n,drawDefinition:f,matchUpScheduleTimes:r,tournamentRecord:d,scheduleDate:s,matchUpId:I,venueId:u,dryRun:c})})})}),i[s]=t[u].matchUpsToSchedule.map(Te),e[s][u]=t[u].scheduleTimes.sort((m,d)=>jt(m.scheduleTime)-jt(d.scheduleTime))}}function DX({scheduledMatchUpIds:t,drawDefinition:e,matchUpScheduleTimes:r,tournamentRecord:n,scheduleDate:o,matchUpId:i,venueId:s,dryRun:a}){let c=r[i];if(!c)return;let u=c.split(":").map(co).join(":"),p=mt(o);if(a){t[o].push(i);return}Wu({tournamentRecord:n,drawDefinition:e,scheduledDate:p,matchUpId:i}),yi({drawDefinition:e,scheduledTime:u,matchUpId:i}).success&&t[o].push(i),s&&nc({tournamentRecord:n,drawDefinition:e,matchUpId:i,venueId:s})}function UX({allDateScheduledByeMatchUpDetails:t,tournamentRecords:e,dryRun:r}){r||!t?.length||ju({matchUpDetails:t,scheduleByeMatchUps:!0,removePriorValues:!0,tournamentRecords:e,schedule:{scheduledDate:"",scheduledTime:"",courtOrder:"",courtId:"",venueId:""}})}function RX({scheduledMatchUpIds:t,dateSchedulingProfile:e,scheduleDate:r}){for(let n of e.venues)for(let o of n.rounds){let s=(o.matchUps?.map(({matchUpId:c})=>c)??[]).filter(c=>t[r].includes(c));o.canScheduledMatchUpIds=s;let a=Math.round(s.length/o.matchUpsCount*1e4)/100;(a===1/0||Number.isNaN(a))&&(a=0),o.possibleToSchedulePct=a,o.matchUpsCount===s.length&&(o.possibleToSchedule=!0)}}function dO({averageMinutes:t,startTime:e,endTime:r,court:n,date:o}){if(!Array.isArray(n.dateAvailability))return{error:nt,stack:"getEarliestCourtTime"};let i=Vu({scheduleDate:o,courts:[n],startTime:!0}),s=Vu({scheduleDate:o,courts:[n],endTime:!0});e=e||i,r=r||s;let a=Qo({court:n,date:o}),{timeSlots:c}=pa({courtDate:a}),u=ve(e),p=ve(r);return{earliestCourtTime:c?.reduce((d,l)=>{let f=ve(l.startTime),g=ve(l.endTime);if(f>p||g<u)return d;let I=u>f?u:f;if(ks(I,g)>=t){let T=$t(I.toISOString());T&&(!d||T<d)&&(d=T)}return d},void 0),courtStartTime:i,courtEndTime:s}}function bX({recoveryTimeDeferredMatchUpIds:t,checkPotentialRequestConflicts:e,matchUpPotentialParticipantIds:r,individualParticipantProfiles:n,matchUpNotBeforeTimes:o,venueEarliestCourtTime:i,schedulingConflicts:s,matchUpScheduleTimes:a,matchUpDependencies:c,relevantParticipantIds:u,requestConflicts:p,personRequests:m,scheduleDate:d,bumpLimits:l,matchUpType:f,matchUpId:g,courtTime:I,matchUp:S,details:h,court:T}){let{earliestCourtTime:y}=dO({averageMinutes:h.greatestAverageMinutes,startTime:i,date:d,court:T});if(I.scheduleTime&&jt(y)>=jt(I.scheduleTime))return I;let{scheduledDependent:E}=fN({matchUpScheduleTimes:a,matchUpDependencies:c,scheduleTime:y,matchUpId:g,details:h});if(E)return I;let{enoughTime:A}=cg({individualParticipantProfiles:n,matchUpNotBeforeTimes:o,matchUpDependencies:c,scheduleTime:y,details:h,matchUp:S});if(!A)return t[d][g]||(t[d][g]=[]),t[d][g].includes(y)||t[d][g].push(y),I;let N=h.minutesMap?.[g]?.averageMinutes||h.greatestAverageMinutes,{conflicts:D}=ag({potentials:e,averageMatchUpMinutes:N,requestConflicts:p,personRequests:m,scheduleTime:y,scheduleDate:d,matchUp:S});if(D?.length)return s.push(...D),!1;l(u,f);let R=h.minutesMap?.[g]?.recoveryMinutes;return Hu({matchUpPotentialParticipantIds:r,individualParticipantProfiles:n,matchUpNotBeforeTimes:o,averageMatchUpMinutes:N,matchUpDependencies:c,recoveryMinutes:R,scheduleTime:y,matchUp:S}),(!I.scheduleTime||jt(y)<jt(I.scheduleTime))&&(I.averageMatchUpMinutes=N,I.recoveryMinutes=R,I.scheduleTime=y,I.courtName=T.courtName,I.courtId=T.courtId),I}function CX({recoveryTimeDeferredMatchUpIds:t,checkPotentialRequestConflicts:e,matchUpPotentialParticipantIds:r,individualParticipantProfiles:n,matchUpNotBeforeTimes:o,venueEarliestCourtTime:i,schedulingConflicts:s,matchUpScheduleTimes:a,matchUpDependencies:c,relevantParticipantIds:u,courtIdsScheduled:p,requestConflicts:m,personRequests:d,scheduleDate:l,bumpLimits:f,matchUpType:g,dateCourts:I,matchUpId:S,matchUp:h,details:T}){return I?.reduce((y,E)=>p.includes(E.courtId)?y:bX({recoveryTimeDeferredMatchUpIds:t,checkPotentialRequestConflicts:e,matchUpPotentialParticipantIds:r,individualParticipantProfiles:n,matchUpNotBeforeTimes:o,venueEarliestCourtTime:i,schedulingConflicts:s,matchUpScheduleTimes:a,matchUpDependencies:c,relevantParticipantIds:u,requestConflicts:m,personRequests:d,scheduleDate:l,bumpLimits:f,matchUpType:g,matchUpId:S,courtTime:y,matchUp:h,details:T,court:E}),{})}function MX({recoveryTimeDeferredMatchUpIds:t,checkPotentialRequestConflicts:e,dependencyDeferredMatchUpIds:r,matchUpPotentialParticipantIds:n,individualParticipantProfiles:o,scheduleDateRequestConflicts:i,matchUpNotBeforeTimes:s,venueEarliestCourtTime:a,matchUpScheduleCourtIds:c,overLimitMatchUpIds:u,matchUpScheduleTimes:p,matchUpDependencies:m,matchUpDailyLimits:d,courtIdsScheduled:l,requestConflicts:f,allDateMatchUpIds:g,personRequests:I,periodLength:S,scheduleDate:h,bumpLimits:T,dateCourts:y,matchUp:E,details:A,venueId:N}){let{matchUpId:D,matchUpType:R}=E,{participantIdsAtLimit:U,relevantParticipantIds:b}=ug({matchUpPotentialParticipantIds:n,individualParticipantProfiles:o,matchUpDailyLimits:d,matchUp:E});if(U.length)return u[h].includes(D)||u[h].push(D),{skipped:"overLimit"};let{dependenciesScheduled:C,remainingDependencies:_}=sg({matchUpScheduleTimes:p,matchUpDependencies:m,allDateMatchUpIds:g,matchUp:E});if(!C)return r[h][D]||(r[h][D]=[]),r[h][D].push({remainingDependencies:_}),{skipped:"dependencyDeferred"};let v=[],w=CX({recoveryTimeDeferredMatchUpIds:t,checkPotentialRequestConflicts:e,matchUpPotentialParticipantIds:n,individualParticipantProfiles:o,matchUpNotBeforeTimes:s,venueEarliestCourtTime:a,schedulingConflicts:v,matchUpScheduleTimes:p,matchUpDependencies:m,relevantParticipantIds:b,courtIdsScheduled:l,requestConflicts:f,personRequests:I,scheduleDate:h,bumpLimits:T,matchUpType:R,dateCourts:y,matchUpId:D,matchUp:E,details:A});if(w.scheduleTime){let{averageMatchUpMinutes:L,recoveryMinutes:F,scheduleTime:x,courtId:k}=w;p[D]=x,c[D]=k;let G=x,V=Yr(G,L);return{scheduled:!0,matchUpId:D,courtId:k,booking:{averageMatchUpMinutes:L,recoveryMinutes:F,periodLength:S,matchUpId:D,startTime:G,courtId:k,endTime:V,venueId:N}}}else v?.length&&(i[h]||(i[h]=[]),i[h].push(...v));return{scheduled:!1}}function vX({venueScheduledRoundDetails:t,matchUpScheduleCourtIds:e,scheduledMatchUpIds:r,matchUpScheduleTimes:n,noTimeMatchUpIds:o,tournamentRecords:i,scheduleDate:s,venues:a,dryRun:c}){for(let{venueId:u}of a){let p=t[u].matchUpMap;Object.keys(p).forEach(m=>{let d=i[m];d&&Object.keys(p[m]).forEach(l=>{let{drawDefinition:f}=zo({tournamentRecord:d,drawId:l});f&&p[m][l].forEach(({matchUpId:I})=>{let S=n[I],h=e[I];if(S){let T=S.split(":").map(co).join(":"),y=`${mt(s)}T${T}`;c||(yi({drawDefinition:f,scheduledTime:y,matchUpId:I}),Ms({courtDayDate:s,tournamentRecords:i,tournamentRecord:d,drawDefinition:f,matchUpId:I,courtId:h})),r[s].push(I)}})})}),o[s]=t[u].matchUpsToSchedule.map(Te)}}function OX({recoveryTimeDeferredMatchUpIds:t,checkPotentialRequestConflicts:e,dependencyDeferredMatchUpIds:r,matchUpPotentialParticipantIds:n,individualParticipantProfiles:o,scheduleDateRequestConflicts:i,matchUpNotBeforeTimes:s,venueEarliestCourtTime:a,matchUpScheduleCourtIds:c,addDateCourtBooking:u,overLimitMatchUpIds:p,matchUpScheduleTimes:m,matchUpDependencies:d,matchUpDailyLimits:l,requestConflicts:f,allDateMatchUpIds:g,personRequests:I,periodLength:S,scheduleDate:h,bumpLimits:T,dateCourts:y,details:E,venueId:A}){let N=E.matchUpsToSchedule.length,D=[],R=[],U,b=0;for(;!U;){for(let C of E.matchUpsToSchedule){if(R.length===E.courtsCount||D.length===E.courtsCount){U=!0;break}let _=MX({recoveryTimeDeferredMatchUpIds:t,checkPotentialRequestConflicts:e,dependencyDeferredMatchUpIds:r,matchUpPotentialParticipantIds:n,individualParticipantProfiles:o,scheduleDateRequestConflicts:i,matchUpNotBeforeTimes:s,venueEarliestCourtTime:a,matchUpScheduleCourtIds:c,overLimitMatchUpIds:p,matchUpScheduleTimes:m,matchUpDependencies:d,matchUpDailyLimits:l,courtIdsScheduled:R,requestConflicts:f,allDateMatchUpIds:g,personRequests:I,periodLength:S,scheduleDate:h,bumpLimits:T,dateCourts:y,matchUp:C,details:E,venueId:A});if(!_.skipped&&_.scheduled){let{matchUpId:v,courtId:w,booking:L}=_;D.push(v),R.push(w),u({courtId:w,booking:L}),E.matchUpsToSchedule=E.matchUpsToSchedule.filter(F=>F.matchUpId!==v)}}(R.length===E.courtsCount||D.length===E.courtsCount||!E.matchUpsToSchedule.length)&&(U=!0),b+=1,!U&&b>=N&&(U=!0)}return{matchUpIdsScheduled:D}}function _X({recoveryTimeDeferredMatchUpIds:t,checkPotentialRequestConflicts:e,dependencyDeferredMatchUpIds:r,matchUpPotentialParticipantIds:n,individualParticipantProfiles:o,scheduleDateRequestConflicts:i,venueScheduledRoundDetails:s,matchUpNotBeforeTimes:a,venueEarliestCourtTime:c,matchUpScheduleCourtIds:u,addDateCourtBooking:p,overLimitMatchUpIds:m,matchUpScheduleTimes:d,matchUpDependencies:l,matchUpDailyLimits:f,venueTimeBoundaries:g,requestConflicts:I,allDateMatchUpIds:S,personRequests:h,periodLength:T,scheduleDate:y,bumpLimits:E,dateCourts:A,venues:N}){let R=0,U;for(;!U;){for(let{venueId:b}of N){let C=s[b],{matchUpIdsScheduled:_}=OX({recoveryTimeDeferredMatchUpIds:t,checkPotentialRequestConflicts:e,dependencyDeferredMatchUpIds:r,matchUpPotentialParticipantIds:n,individualParticipantProfiles:o,scheduleDateRequestConflicts:i,matchUpNotBeforeTimes:a,venueEarliestCourtTime:c,matchUpScheduleCourtIds:u,addDateCourtBooking:p,overLimitMatchUpIds:m,matchUpScheduleTimes:d,matchUpDependencies:l,matchUpDailyLimits:f,requestConflicts:I,allDateMatchUpIds:S,personRequests:h,periodLength:T,scheduleDate:y,bumpLimits:E,dateCourts:A,details:C,venueId:b});C.matchUpsToSchedule.length&&_<C.courtsCount&&(ve(c)<ve(g.endTime)?c=Yr(c,T):C.complete=!0),C.matchUpsToSchedule?.length||(C.complete=!0)}R+=1,U=N.every(({venueId:b})=>s[b].complete)||R===10}return c}function xX({dateSchedulingProfile:t,scheduledMatchUpIds:e,scheduleDate:r}){for(let n of t.venues)for(let o of n.rounds){let s=(o.matchUps??[]).map(({matchUpId:c})=>c)?.filter(c=>e[r].includes(c));o.canScheduledMatchUpIds=s;let a=Math.round((s?.length||0)/o.matchUpsCount*1e4)/100;(a===1/0||isNaN(a))&&(a=void 0),o.possibleToSchedulePct=a,o.matchUpsCount===s?.length&&(o.possibleToSchedule=!0)}}function zG({schedulingProfileModifications:t,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:r,schedulingProfileIssues:n,dateSchedulingProfiles:o,containedStructureIds:i,matchUpDependencies:s,matchUpDailyLimits:a,clearScheduleDates:c,tournamentRecords:u,periodLength:p=30,schedulingProfile:m,personRequests:d,matchUps:l=[],courts:f,dryRun:g}){let I={},S={},h={},T={},y={},E={},A={},N={},D={};for(let b of o??[]){let C=mt(b?.scheduleDate),_=b?.venues??[],v={},w={},L=(ct,Et)=>{ct.forEach(Ht=>{let Ut=w[Ht].counters;Ut[Et]?Ut[Et]+=1:Ut[Et]=1,Ut[So]?Ut[So]+=1:Ut[So]=1})};I[C]={},S[C]={},E[C]=[],A[C]=[],N[C]=[],D[C]=[];let F={};l?.forEach(ct=>{ct.schedule?.scheduledDate&&Xn(C,mt(ct.schedule.scheduledDate))&&Za({matchUpPotentialParticipantIds:v,matchUpNotBeforeTimes:F,matchUp:ct})});let{allDateScheduledByeMatchUpDetails:x,allDateScheduledMatchUpIds:k,venueScheduledRoundDetails:G,allDateMatchUpIds:V}=gN({matchUpPotentialParticipantIds:v,individualParticipantProfiles:w,scheduleCompletedMatchUps:r,containedStructureIds:i,matchUpNotBeforeTimes:F,matchUpScheduleTimes:y,matchUpDependencies:s,clearScheduleDates:c,tournamentRecords:u,periodLength:p,scheduleDate:C,matchUps:l,courts:f,venues:_}),B=l?.filter(({matchUpId:ct})=>k.includes(ct)),{bookings:z}=Yd({dateScheduledMatchUps:B,tournamentRecords:u,scheduleDate:C,periodLength:p}),{virtualCourts:H}=Gd({scheduleDate:C,periodLength:p,bookings:z,courts:f}),K=H?.reduce((ct,Et)=>{let{earliestCourtTime:Ht,courtEndTime:Ut}=dO({date:C,averageMinutes:0,court:Et});return(!ct.startTime||ve(Ht)<ve(ct.startTime))&&(ct.startTime=Ht),(!ct.endTime||ve(Ut)>ve(ct.endTime))&&(ct.endTime=Ut),ct},{}),Y=K.startTime;_X({recoveryTimeDeferredMatchUpIds:I,checkPotentialRequestConflicts:e,dependencyDeferredMatchUpIds:S,matchUpPotentialParticipantIds:v,individualParticipantProfiles:w,scheduleDateRequestConflicts:h,venueScheduledRoundDetails:G,matchUpNotBeforeTimes:F,venueEarliestCourtTime:Y,matchUpScheduleCourtIds:T,addDateCourtBooking:({courtId:ct,booking:Et})=>H?.find(Ht=>Ht.courtId===ct)?.dateAvailability[0].bookings.push(Et),overLimitMatchUpIds:A,matchUpScheduleTimes:y,matchUpDependencies:s,matchUpDailyLimits:a,venueTimeBoundaries:K,requestConflicts:D,allDateMatchUpIds:V,personRequests:d,periodLength:p,scheduleDate:C,bumpLimits:L,dateCourts:H,venues:_}),vX({venueScheduledRoundDetails:G,matchUpScheduleCourtIds:T,scheduledMatchUpIds:E,matchUpScheduleTimes:y,noTimeMatchUpIds:N,tournamentRecords:u,scheduleDate:C,venues:_,dryRun:g}),!g&&x?.length&&ju({matchUpDetails:x,scheduleByeMatchUps:!0,removePriorValues:!0,tournamentRecords:u,schedule:{scheduledDate:"",scheduledTime:"",courtOrder:"",courtId:"",venueId:""}}),xX({dateSchedulingProfile:b,scheduledMatchUpIds:E,scheduleDate:C})}let R=(o??[]).map(({scheduleDate:b})=>b),U={timeStamp:Date.now(),overLimitMatchUpIds:A,scheduledMatchUpIds:E,schedulingProfile:m,noTimeMatchUpIds:N,requestConflicts:D,scheduledDates:R};return IN({tournamentRecords:u,autoSchedulingAudit:U}),{...P,schedulingProfileModifications:t,schedulingProfileIssues:n,dateSchedulingProfiles:o,recoveryTimeDeferredMatchUpIds:I,dependencyDeferredMatchUpIds:S,matchUpScheduleTimes:y,overLimitMatchUpIds:A,scheduledMatchUpIds:E,noTimeMatchUpIds:N,requestConflicts:D,scheduledDates:R}}function qu(t){let{scheduleAttributes:e=["scheduledDate","scheduledTime","courtOrder"],ignoreMatchUpStatuses:r=Ot,scheduledDates:n,venueIds:o}=t,i=Dr(t),s=Tt(i)?Object.values(i).map(({tournamentId:c})=>c).filter(Boolean):[];if(!s?.length)return{error:kt};let a=0;for(let c of s){let u=i[c],p=wX({ignoreMatchUpStatuses:r,scheduleAttributes:e,tournamentRecord:u,scheduledDates:n,venueIds:o});if(p.error)return p;a+=p.clearedScheduleCount??0}return{...P,clearedScheduleCount:a}}function wX({scheduleAttributes:t=["scheduledDate","scheduledTime","courtOrder"],ignoreMatchUpStatuses:e=Ot,tournamentRecord:r,scheduledDates:n,venueIds:o=[]}){if(typeof r!="object")return{error:j};if(!Array.isArray(e)||!Array.isArray(o))return{error:O};o.length&&t.push("venueId");let i=qt({matchUpFilters:{scheduledDates:n},tournamentRecord:r}).matchUps??[],s={};i.forEach(({matchUpStatus:u,schedule:p,drawId:m,matchUpId:d})=>{(!u||!e.includes(u))&&_c({schedule:p,scheduleAttributes:t})&&(!o?.length||o.includes(p.venueId))&&(s[m]||(s[m]=[]),s[m].push(d))});let a=r.tournamentId,c=0;for(let u in s){let{event:p,drawDefinition:m}=_e({tournamentRecord:r,drawId:u}),d=rr({drawDefinition:m,matchUpFilters:{matchUpIds:s[u]}}).matchUps??[];for(let l of d){let f=!1;l.timeItems=(l.timeItems??[]).filter(g=>{let I=g?.itemType&&![Io,li,Ts,Tu,hu,ys,Es].includes(g?.itemType);return I||(f=!0),I}),f&&(It({context:"clear schedules",eventId:p?.eventId,drawDefinition:m,tournamentId:a,matchUp:l}),c+=1)}}return{...P,clearedScheduleCount:c}}function jd(t){let{checkPotentialRequestConflicts:e=!0,scheduleCompletedMatchUps:r,clearScheduleDates:n,scheduleDates:o=[],tournamentRecords:i,periodLength:s,useGarman:a,courtIds:c,dryRun:u,pro:p}=t,m=X(t,[{[Ee]:!0},{[$e]:b=>!b||Array.isArray(b)&&b.every(Me),[hl]:!1,[Ge]:ke}]);if(m.error)return m;let d=bo({tournamentRecords:i});if(d.error)return d;if(!d.schedulingProfile.length)return{...P};let{modifications:l,issues:f=[],schedulingProfile:g=[]}=d,I=Object.assign({},...Object.values(i).map(b=>ji({tournamentRecord:b}).containedStructures)),S=new Set(o.map(b=>{if(Me(b))return mt(b)}).filter(Boolean)),h=g.map(b=>b.scheduleDate).map(b=>Me(b)&&mt(b)).filter(b=>b&&(!o.length||S.has(b)));if(!h.length)return{error:qg};if(n&&!u){let b=Array.isArray(n)?n:[];qu({tournamentRecords:i,scheduledDates:b})}let T=kn({ignoreDisabled:!1,tournamentRecords:i}).courts,y=Array.isArray(c)?T.filter(b=>c.includes(b.courtId)):T,{matchUps:E}=cn({matchUpFilters:{matchUpTypes:[Ct,Rt]},afterRecoveryTimes:!0,nextMatchUps:!0,tournamentRecords:i}),{matchUpDependencies:A}=tn({includeParticipantDependencies:!0,tournamentRecords:i,matchUps:E}),{matchUpDailyLimits:N}=Jf({tournamentRecords:i}),{personRequests:D}=is({requestType:Yu,tournamentRecords:i}),R=g.filter(b=>{let C=mt(b?.scheduleDate);return h.includes(C)}).sort((b,C)=>new Date(b.scheduleDate).getTime()-new Date(C.scheduleDate).getTime()),U={schedulingProfileModifications:l,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:r,schedulingProfileIssues:f,dateSchedulingProfiles:R,containedStructureIds:I,matchUpDependencies:A,matchUpDailyLimits:N,clearScheduleDates:n,tournamentRecords:i,schedulingProfile:g,personRequests:D,periodLength:s,useGarman:a,matchUps:E,dryRun:u,courts:y};return p?zG(U):KG(U)}function Ch(t){if(!t||typeof t!="string")return!1;try{return Intl.DateTimeFormat(void 0,{timeZone:t}),!0}catch{return!1}}function lO(t,e){let r=e??new Date,s=new Intl.DateTimeFormat("en-US",{timeZone:t,timeZoneName:"longOffset"}).formatToParts(r).find(m=>m.type==="timeZoneName")?.value??"";if(s==="GMT")return 0;let a=s.match(/GMT([+-])(\d{2}):(\d{2})/);if(!a)return 0;let c=a[1]==="+"?1:-1,u=Number.parseInt(a[2],10),p=Number.parseInt(a[3],10);return c*(u*60+p)}function QG(t,e,r){if(!Ch(r))return{error:op};let[n,o]=e.split(":").map(Number),[i,s,a]=t.split("-").map(Number),c=new Date(Date.UTC(i,s-1,a,n,o,0,0)),u=lO(r,c),p=c.getTime()-u*60*1e3,m=new Date(p),d=lO(r,m);if(d!==u){let l=c.getTime()-d*60*1e3;return new Date(l).toISOString()}return m.toISOString()}function LX(t,e){if(!Ch(e))return{error:op};let r=new Date(t),o=new Intl.DateTimeFormat("en-CA",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(r),i=u=>o.find(p=>p.type===u)?.value??"",s=`${i("year")}-${i("month")}-${i("day")}`,c=`${i("hour")==="24"?"00":i("hour")}:${i("minute")}`;return{date:s,time:c}}function FX(t,e,r){let n=QG(t,e,r);return typeof n!="string"||Ra(n)?n:{error:op}}var XG={isValidIANATimeZone:Ch,getTimeZoneOffsetMinutes:lO,wallClockToUTC:QG,utcToWallClock:LX,toEmbargoUTC:FX};function qd(t){let{tournamentRecord:e,tournamentRecords:r,activeTournamentId:n,...o}=t??{};if(o.tournamentId??=it(),o.startDate&&!fs(o.startDate)&&!Vm.test(o.startDate))return{error:ae};if(o.endDate&&!fs(o.endDate)&&!Vm.test(o.endDate))return{error:ae};if(o.activeDates){let i=o.activeDates.filter(Boolean);if(!i.every(s=>fs(s)||Vm.test(s)))return{error:ae};if(i.length){let s=[...i].sort();o.startDate??=s[0],o.endDate??=s[s.length-1];let a=i.every(u=>new Date(u)>=new Date(o.startDate)),c=i.every(u=>new Date(u)<=new Date(o.endDate));if(!a||!c)return{error:ae}}o.activeDates=i}return o.localTimeZone&&!Ch(o.localTimeZone)?{error:op}:(o.extensions&&(o.extensions=o.extensions.filter(Yn)),{...o})}function Mh({addParticipants:t=!0,participantAttribute:e,tournamentRecord:r,personAttribute:n,teamNames:o,accessor:i,uuids:s}){if(!r)return{error:j};let a={},c=(r.participants??[]).filter(({participantType:f,participantRole:g})=>f===St&&g===Ve),u=0;for(let f of c){let I=i&&Bi({element:f,accessor:i})?.value||n&&f.person?.[n]||e&&f[e];if(I){if(!Object.keys(a).includes(I)){a[I]={participantName:o?.[u]??I,participantId:s?.pop()??it(),individualParticipantIds:[],participantRole:Ve,participantType:_t};let S={value:n??e,name:xy};ut({element:a[I],extension:S}),u+=1}a[I].individualParticipantIds.push(f.participantId)}}let p=Object.keys(a),m=(r.participants??[]).map(f=>{if(f.participantType!==_t||f.participantRole!==Ve)return;let{extension:g}=ot({name:xy,element:f}),I=g?.value;if(p.includes(I))return f.participantId}).filter(Boolean),d=0,l=[];return Object.keys(a).forEach(f=>{let g=a[f],{participantId:I}=g;m.includes(I)||(r.participants??=[],t&&r.participants.push(g),l.push(g),d++)}),t&&d?(at({payload:{tournamentId:r.tournamentId,participants:l},topic:Di}),{...P,participantsAdded:d}):l.length?{...P,newParticipants:l}:{error:hw}}var JG=[{AA:"Annexia"},{BA:"Bacteria"},{BO:"Borduria"},{BM:"Bensalem"},{BS:"Basenji"},{BI:"Balnibarbi"},{BV:"Bartovia"},{BZ:"Berzerkistan"},{CA:"Caldonia"},{CC:"Concordia"},{CH:"Chula"},{DA:"Deltora"},{DW:"Discworld"},{EA:"Eastasia"},{EP:"Ecotopia"},{ER:"Erewhon"},{FA:"Freedonia"},{FN:"Florin"},{FG:"Fogg"},{FK:"Fourecks"},{GA:"Genovia"},{GL:"Gilead"},{GD:"Gilead"},{GL:"Gondal"},{GO:"Gondor"},{GR:"Gruzinia"},{GT:"Goritania"},{GU:"Guilder"},{HA:"Heldscalla"},{HO:"Hidalgo"},{IL:"Illyria"},{KA:"Kinakuta"},{KG:"Kangan"},{KN:"Kreplachistan"},{KS:"Kallipolis"},{LH:"Lugash"},{LI:"Listenbourg"},{LT:"Lilliput"},{LU:"Luggnagg"},{LV:"Lichtenslava"},{MR:"Moher"},{NA:"Narnia"},{NV:"Novaria"},{OA:"Oceania"},{OS:"Orsinia"},{OV:"Octavia"},{PA:"Palombia"},{PG:"Penguina"},{QA:"Qasha"},{PM:"Panem"},{SA:"Solymbria"},{SD:"Syldavia"},{SG:"San Glucose"},{SL:"San Lorenzo"},{SR:"Sontar"},{SY:"Sylvania"},{TF:"Tralfamadore"},{TH:"Themyscira"},{UA:"Utopia"},{VA:"Vespugia"},{WA:"Wakanda"},{WX:"Wessex"},{ZA:"Zamunda"},{ZK:"Zubrowka"}];var ZG=["Amber","Ansul","Atlantis","Braavos","Busytown","Castle Rock","Centralia","Coober Pedy","Chefchaouen","Chronopolis","Damanhur","Diaspar","Dictionopolis","Diomira","El Dorado","Elista","Ephesus","Gotham","Hadleyburg","Hallstatt","Hierusalem","Ilium","Inverness","Kowloon","Laputa","Longyearbyen","Lys","Matmata","Maycomb","Metropolis","Miyake-jima","Monowi","Nagoro","Navarre","New New York","Nimbin","Pemberley","Pseudopolis","Rivendell","Roswell","Shangri-La","Springfield","Supilinn","Thneedville","Trantor","Wobegon","Yonwood","Xanadu","Xylar","Zion"];function SN({count:t=1,participantsCount:e=32,random:r}={}){let n=ar(ZG,r),o=n.slice(0,t);return{cities:Q(0,e).map(s=>s<Math.min(t,n.length)?o[s]:Pn(o,r))}}function hN({count:t=1,participantsCount:e=32,random:r}={}){let n=ar(JG,r),o=n.slice(0,t).flatMap(s=>Object.keys(s));return{states:Q(0,e).map(s=>s<Math.min(t,n.length)?o[s]:Pn(o,r))}}function TN({count:t=1,participantsCount:e=32,random:r}={}){let n=Q(0,t).map(()=>Q(0,5).map(()=>pn(0,9,r)).join(""));return{postalCodes:Q(0,e).map(i=>i<t?n[i]:Pn(n,r))}}function $d({idPrefix:t,participantType:e,index:r,uuids:n,random:o}){let i=wt(e)?e[0]:"X";return t?`${t}-${i}-${r}`:n?.pop()||it(void 0,o)}function yN(t){let{cities:e,states:r,postalCodes:n,nationalityCode:o,participantIndex:i}=t;return{postalCode:n?.[i],state:r?.[i],city:e?.[i],countryCode:o}}var tV={lastNames:["Abbey","Ahern","Ampleforth","Ananiadis","Andelic","Assange","Atreides","Austen","Bach","Banks","Barrington","Batty","Bauers","Beals","Beer","Bennett","Berry","Bonaparte","Brewer","Brockovich","Bukowski","Cassidy","Catton","Calvino","Carlin","Carson","Chip","Constant","Crane","Crowne","Cummings","Curie","Dallas","Diamond","Deckard","Drazic","Dunbar","Earhart","Eisenstein","Eldritch","Elliot","Ellul","Escher","Eyre","Faulkner","Fulcher","Fukuoka","Godel","Goldstein","Greer","Hedges","Herbert","Holmgren","Humperdinck","Huxley","Illich","Jeffers","Jensen","Jevons","Johnson","Johnstone","Jovovich","Kingsnorth","Langer","Fernwright","Fuller","Le Guin","Lem","Lovelace","Mander","McLuhan","Midgely","Mond","Montoya","Moore","Murry","Nagle","Nearing","Ogden","Ophuls","Parks","Paz","Peet","Perfect","Pendejo","Pevensie","Postman","Ripley","Rodda","Rumfoord","Runciter","Rugen","Sale","Schumacher","Shaftoe","Shelley","Shepard","Smith","Stratton","Stewart","Swift","Tillich","Turing","Tyrell","Twain","Yeats","Veblen","Yates","Vonnegut","Waterhouse","Watson","Wolin","Wirt","Waschuk","Wormwood","Zecic"],firstFemale:["Ada","Amelia","Amelie","America","Anne","Antonia","Aravis","Astrid","Beatrice","Brienne","Buttercup","Caitlin","Cimorene","Cordelia","Desdemona","Ellen","Elizabeth","Emily","Emmie","Erin","Eva","Evelyn","Heather","Helen","Hermia","Hypatia","Imogen","Jane","Jasmine","Juliana","Juliet","Katniss","Leeloo","Lenina","Lilith","Linda","Lizzie","Louise","Lucy","Marie","Mary","Martha","Matilda","Milla","Miranda","Meg","Melba","Nicole","Ola","Portia","Pris","Rachael","Rachel","Rebecca","River","Rosa","Rosalind","Scout","Sharn","Susanne","Titania","Uhura","Ursula","Valentina","Viola","Virginia","Xena","Zoe"],firstMale:["Alan","Aldous","August","Axel","Barda","Barry","Bill","Bruce","Charles","Chris","Constantine","Darwin","David","Derrick","Edward","Emmanuel","Ernst","Estlin","Fezzik","Filby","Frank","Frito","George","Glen","Helmholtz","Inigo","Italo","Ivan","Jacques","James","Jared","Jerry","Joe","Johann","Julian","John Michael","Jonathan","Korben","Kirkpatrick","Kurt","Lief","Malachi","Mark","Marhsall","Masanobu","Maurits","Michael","Miro","Mustapha","Neil","Nikola","Octavio","Palmer","Paul","Pierre","Robinson","Rick","Rincewind","Roy","Shannon","Sheldon","Stafford","Stanislaw","Stanley","Syme","Thorstein","Thomas","Tyrone","Vizzini","Walton","Walker","Warren","Wendell","Westley","William","Winston","Zoran"]};function EN(t){let{count:e=100,random:r,sex:n}=t??{};if(!e||n&&!Un(n))return{personData:[],error:O};let o=Math.ceil(e*1.3),{lastNames:i,firstFemale:s,firstMale:a}=tV,c=Ui.map(({iso:S})=>S).filter(Boolean),u=Math.ceil(o/i.length),p=Math.ceil(o/s.length),m=Math.ceil(o/a.length),d=Q(0,u).flatMap(()=>{let S=q(i,!1,!0);return Q(0,i.length).map(()=>Sr(S,r))}),l=Q(0,p).flatMap(()=>{let S=q(s,!1,!0);return Q(0,s.length).map(()=>Sr(S,r))}),f=Q(0,m).flatMap(()=>{let S=q(a,!1,!0);return Q(0,a.length).map(()=>Sr(S,r))}),g={};for(let S=0;S<o;S++){let h=d.pop(),T=n||Pn([Ce,Je],r),y=T===Ce?f.pop():l.pop(),E=Pn(c,r);g[`${y}${h}`]={nationalityCode:E,sex:T,firstName:y,lastName:h}}return{personData:Object.values(g).slice(0,e)}}function AN(t){let e=t?.count||1,{personExtensions:r,consideredDate:n,isMock:o=!0,gendersCount:i,personData:s,random:a,category:c,sex:u}=t??{};if(Number.isNaN(Number(e)))return{error:O};let p=i?.[Ce]||Da(u)&&e||0,m=i?.[Je]||ls(u)&&e||0;e=Math.max(e,p+m);let d=e-(p+m),l=p&&EN({count:p,sex:Ce,random:a}).personData||[],f=m&&EN({count:m,sex:Je,random:a}).personData||[],g=[...l,...f,...d&&EN({count:d,random:a}).personData||[]],I=g.filter(R=>!u||p&&m||R.sex===u),S=[];if(Array.isArray(s)){let R=s.filter(U=>typeof U.firstName!="string"||typeof U.lastName!="string"||U.sex&&![Ce,Je].includes(U.sex)||U.nationalityCode&&(typeof U.nationalityCode!="string"||U.nationalityCode.length>3||!Ui.some(({iso:b,ioc:C})=>[b,C].includes(U.nationalityCode)))?!1:(U.nationalityCode&&S.push(U.nationalityCode),!0));if(R.length)I=R;else return{error:O}}let h=s?I:ar(I,a);if(h.length<e){let{maleFirstNames:R,maleLastNames:U,femaleFirstNames:b,femaleLastNames:C,nationalityCodes:_}=g.reduce((v,w)=>{let{firstName:L,lastName:F,nationalityCode:x}=w;return w.sex===Ce?(v.maleFirstNames.includes(L)||v.maleFirstNames.push(L),v.maleLastNames.includes(F)||v.maleLastNames.push(F)):(v.femaleFirstNames.includes(L)||v.femaleFirstNames.push(L),v.femaleLastNames.includes(F)||v.femaleLastNames.push(F)),v.nationalityCodes.includes(x)||v.nationalityCodes.push(x),v},{maleFirstNames:[],maleLastNames:[],femaleFirstNames:[],femaleLastNames:[],nationalityCodes:[]});Q(0,e-h.length).forEach(()=>{let v=u||Pn([Ce,Je],a),w=Pn(_,a),L=v===Ce?Pn(R,a):Pn(b,a),F=v===Ce?Pn(U,a):Pn(C,a),x={firstName:L,lastName:F,sex:v,nationalityCode:w};h.push(x)})}let{ageMinDate:T,ageMaxDate:y}=gs({consideredDate:n,category:c}),E=st(T?.slice(0,4)||0)||st(y?.slice(0,4)||0)-3,A=st(y?.slice(0,4)||0)||st(T?.slice(0,4)||0)+3,N=(T||y)&&[E,A],D=h.slice(0,e).map((R,U)=>{let[b,C]=N??[],_=N&&Sr(Q(b,C),a),v=Sr(Q(0,365),a),w=_&&Vw(_,v);return Object.assign(et({extensions:r||[{name:"regionCode",value:U+1}],birthDate:w,isMock:o}),R)});return{persons:D.length&&D||h[0],nationalityCodes:S}}var eV=["Ace Academy","Avengers","Ball Bouncers","Baseliners","Captivators","Civil Disobedients","Continentals","Court Royal","Court Sharks","Diamond Dogs","Danger Zone","Doubles Dominators","Double Faults","Tricksters","Eliminators","Court Crusaders","Fuzz Busters","Game Changers","Goal Gurus","Good Volley","Green Machine","Hawk Eyes","Inside Outers","Killer Instinct","Line Toers","Masters of Mayhem","Matter Catchers","Cheap Shot","Mean Machines","Mindspace Invaders","Net Centric","Net Positive","Smash Mullet","Over Your Head","Spin Meisters","Aggressors","Racket Machine","Slice Happy","Refs Nightmare","Sandeaters","Sun Seekers","Slicer Dicers","Stacked Deck","Cross Stringers","The Emergence","Total Demolition","Touch and Go","Unreturnables","Upside Downers","Vertically Challenged","Visual Spectacle"];function Kd({nameRoot:t="TEAM",count:e=1,random:r}={}){let o=ar(eV,r).slice(0,e);return o.length<e&&Q(0,e-o.length).forEach(i=>o.push(`${t} ${i+1}`)),{names:o}}function oc(t){let{scaledParticipantsCount:e,rankingRange:r}=t,{ratingsParameters:n=Ke,valuesInstanceLimit:o,ratingsValues:i=[],consideredDate:s,categories:a,category:c,nationalityCodesCount:u,nationalityCodeType:p,nationalityCodes:m,participantsCount:d=32,participantType:l,teamSize:f=8,personIds:g,idPrefix:I,uuids:S,personExtensions:h,addressProps:T,gendersCount:y,matchUpType:E,personData:A,sex:N,participantRole:D,inContext:R,withISO2:U,withIOC:b,scaleAllParticipants:C,random:_}=t,v=D||Ve,w=l===lt||E===ei,L=l===_t||E===_t;r&&(!Array.isArray(r)||!r.every(we=>Le(we))||r.length!==2)&&(r=void 0),e=C?d:e;let F=1e3,x=e&&e>F?e:F;r=r||[1,x],r[1]+=1;let k=d*(w&&2||L&&(f??8)||1),G=AN({count:k,personExtensions:h,consideredDate:s,gendersCount:y,personData:A,category:c,random:_,sex:N});if(G.error)return G;let{nationalityCodes:V,persons:B}=G,z={},H={},K={},Y={},J=we=>{Object.assign(z,we.doublesRankings),Object.assign(H,we.singlesRankings),Object.assign(Y,we.doublesRatings),Object.assign(K,we.singlesRatings)};if(Tt(c)){let we=rV({scaledParticipantsCount:e,ratingsParameters:n,participantType:l,ratingsValues:i,rankingRange:r,category:c,random:_});J(we)}Array.isArray(a)&&a.forEach(we=>{let Ai=rV({scaledParticipantsCount:e,ratingsParameters:n,participantType:l,ratingsValues:i,rankingRange:r,category:we,random:_});J(Ai)});let ct=Ui.filter(we=>p==="IOC"&&we.ioc||we.iso);function Et(we){let Ai=Math.ceil(k/we);return o&&Ai>o?Math.ceil(k/o):we}let{postalCodesProfile:Ht,postalCodesCount:Ut,statesProfile:pe,citiesProfile:ye,citiesCount:Jt,statesCount:pr}=T??{},Kn=we=>Object.keys(we).flatMap(Ai=>Q(0,pe[Ai]).map(()=>Ai)),zr=ye&&Kn(ye)||T?.cities||SN({count:Jt||k,participantsCount:k}).cities,so=pe&&Kn(pe)||T?.states||hN({count:pr||k,participantsCount:k}).states,Zo=Ht&&Kn(Ht)||T?.postalCodes||TN({count:Ut||k,participantsCount:k}).postalCodes,ti={cities:zr,states:so,postalCodes:Zo},la=Et(u),fa=la?ar(ct,_).slice(0,u):m&&ct.filter(we=>m.includes(we.iso))||ct,ga=ar(Q(0,Math.ceil(k/(la||1))).map(()=>fa).flat(1/0),_),bm=Kd({count:d,random:_}).names;return{participants:Q(0,d).flatMap(we=>{let Ai=w&&2||L&&(f??8)||1,as=Q(0,Ai).map(Ia=>{let Vn=we*Ai+Ia;return Cm(Vn)}),ic=as.map(Ia=>Ia.participantId),An=as.map(Ia=>Ia.person.standardFamilyName).join("/"),Vc=w?lt:_t,tp={participantId:$d({participantType:Vc,index:we,idPrefix:I,random:_,uuids:S}),participantName:w?An:bm[we],participantRole:v,individualParticipantIds:ic,participantType:Vc};return R&&(tp.individualParticipants=as),w||L?[tp,...as]:as}),...P};function Cm(we){let Ai=B[we],{nationalityCode:as,participantExtensions:ic,participantTimeItems:An,extensions:Vc,firstName:tp,birthDate:Ia,lastName:Vn,personId:UT,sex:TD}=Ai??{},RT=tp||"GivenName",_g=Vn||"FamilyName",yD=`${RT} ${_g}`,Bc=ga[we],sc=V?.length&&as||Bc&&(p==="IOC"?Bc.ioc||Bc.iso:Bc.iso||Bc.ioc)||as;ga?.length&&!sc&&!as&&console.log("%c Invalid Nationality Code",{participantIndex:we,country:Bc});let ED=yN({...ti,participantIndex:we,nationalityCode:sc}),Sa=et({participantId:$d({participantType:St,index:we,idPrefix:I,random:_,uuids:S}),extensions:ic,timeItems:An,participantRole:v,participantType:St,participantName:yD,person:{personId:UT||g?.length&&g[we]||it(void 0,_),birthDate:Me(Ia)?Ia:void 0,addresses:[ED],standardFamilyName:_g,standardGivenName:RT,nationalityCode:sc,extensions:Vc,sex:TD}});if(b&&sc){let ao=Ui.find(({iso:ep})=>ep===sc);ao?.ioc&&(Sa.person.iocNationalityCode=ao.ioc),ao?.label&&(Sa.person.countryName=ao.label)}if(U&&sc){let ao=Ui.find(({iso:ep})=>ep===sc);ao?.iso2&&(Sa.person.iso2NationalityCode=ao.iso2),ao?.label&&(Sa.person.countryName=ao.label)}let bT=ao=>{let ep=ao.categoryName||ao.ratingType||ao.ageCategoryCode,CW=H[ep]?.[we],MW=z[ep]?.[we];PN({scaleValue:CW,eventType:ba,scaleType:Jn,participant:Sa,category:ao}),PN({scaleValue:MW,eventType:si,scaleType:Jn,participant:Sa,category:ao});let vW=K[ep]?.[we],OW=Y[ep]?.[we];PN({scaleValue:vW,eventType:ba,scaleType:Lo,participant:Sa,category:ao}),PN({scaleValue:OW,eventType:si,scaleType:Lo,participant:Sa,category:ao})};return Array.isArray(a)?a.forEach(ao=>bT(ao)):c&&bT(c),Sa}}function PN({scaleValue:t,participant:e,eventType:r,scaleType:n,category:o}){let i=o.categoryName||o.ratingType||o.ageCategoryCode,s=[ci,n,r,i].join("."),a={itemValue:t,itemType:s};i&&t&&(e.timeItems??=[],e.timeItems.push(a))}function rV(t){let{category:e,scaledParticipantsCount:r,ratingsParameters:n,participantType:o,random:i,ratingsValues:s=[]}=t,a=e.rankingRange||t.rankingRange||[1,1e3],c={},u={},p={},m={},{categoryName:d,ageCategoryCode:l,ratingType:f}=e,g=e.categoryName||e.ratingType||e.ageCategoryCode;if((d||l)&&!f){let[I,S]=a??[];if(u[g]=ar(Q(I,S),i).slice(0,r||pn(20,30,i)),[lt,_t].includes(o)){let[h,T]=a??[];c[g]=ar(Q(h,T),i).slice(0,r||pn(20,30,i))}}if(f&&n[f]){let{ratingMax:I,ratingMin:S,ratingAttributes:h}=e,T={...n[f],...h??{}},{attributes:y={},decimalsCount:E,accessors:A,range:N,step:D}=T,R=L=>{let F={},x=Object.keys(L??{});for(let k of x){let G=L[k];if(typeof G=="object"&&G.generator){let{range:V}=G,[B,z]=V.slice().sort((H,K)=>H-K);F[k]=pn(B,z,i)}else F[k]=G}return F},b=N[0]>N[1]?2:.7,[C,_]=N.slice().sort((L,F)=>L-F),w=Q(0,2e3).map(()=>PD(C,_,b,D,E,i)).filter(F=>(!I||F<=I)&&(!S||F>=S)).slice(0,r||pn(20,30,i)).map(F=>A?Object.assign({},...A.map(x=>({[x]:F})),R(y)):F);p[g]=[...s,...w],[lt,_t].includes(o)&&(m[g]=[...s,...w])}return{singlesRankings:u,doublesRankings:c,singlesRatings:p,doublesRatings:m}}function pg(t){let{alternatesCount:e=0,tieFormatName:r,drawSize:n}=t,o=0,i=0,s=0,a=0,c={},u={[Ce]:0,[Je]:0,[ds]:0,[ii]:0,ANY:0};(Tt(t.tieFormat)?t.tieFormat:uo({namedFormat:r}))?.collectionDefinitions?.filter(Boolean).forEach(f=>{let{category:g,collectionId:I,matchUpType:S,matchUpCount:h,gender:T}=f;if(Un(T)){let y=Ar(T),E=h*(S===Rt?2:1);y&&u[y]<E&&(u[y]=E)}else nn(T)&&(u[Ce]<h&&(u[Ce]=h),u[Je]<h&&(u[Je]=h));if(g){let y=JSON.stringify(g);c[y]=g}if(I||(f.collectionId=it(void 0,t.random)),re(Rt)(S)){let y=h;a+=h,o=Math.max(o,y)}if(re(Ct)(S)){let y=h;s+=h,i=Math.max(i,y)}});let m=Object.keys(c).length?Math.max(s,a*2):Math.max(i,o*2),d=o*(n+e),l=i*(n+e);return{maxDoublesDraw:d,maxSinglesDraw:l,teamSize:m,genders:u}}function nV({participantsProfile:t,eventProfiles:e,drawProfiles:r}){let{participantsCount:n,participantType:o=St}=t??{},i=n||0,s={[Je]:0,[ds]:0,[ii]:0,[Ce]:0,ANY:0},a=0,c=0,u=0,p=0,m=0,d=({alternatesCount:f=0,uniqueParticipants:g,tieFormatName:I,drawSize:S=0,eventType:h,tieFormat:T,category:y,gender:E,stage:A})=>{let N=h===Lt,D=h===Oe,R=!!(g||A===Z||y||E);if(D){p=Math.max(p,S+f),T=typeof T=="object"?T:uo({namedFormat:I});let{teamSize:U,maxDoublesDraw:b,maxSinglesDraw:C,genders:_}=pg({alternatesCount:f,tieFormatName:I,tieFormat:T,drawSize:S});u=Math.max(u,U),c=Math.max(c,C),R||(a=Math.max(a,b)),Object.keys(_).forEach(v=>s[v]+=_[v])}else if(N)if(R){let U=(S+f)*2;m+=U,E&&(s[E]+=U)}else S+f&&S+f>a&&(a=S+f);else if(R){let U=S+f;E&&(s[E]+=U),m+=U}else S&&S>c&&(c=S+f)};if(e?.forEach(f=>{let{tieFormatName:g,tieFormat:I,drawProfiles:S,eventType:h,category:T,gender:y}=f;if(S)for(let E of S){let{tieFormatName:A,tieFormat:N}=E;d({...E,tieFormatName:A||g,tieFormat:N||I,eventType:h,category:T,gender:y})}}),Array.isArray(r))for(let f of r)d(f);let l=Math.max(p*u,a*2,c);return a&&(o=lt),(n||i)<l&&(n=l),n&&a&&[lt,Oe].includes(o)&&(c&&Math.floor(c/2)>a?n=Math.floor(c/2):(!c||a*2>=c)&&(n=Math.ceil(n/2))),n===void 0&&(n=!e?.length&&!r?.length?32:0),n<i&&(n=i),{uniqueParticipantsCount:m,participantsCount:n,largestTeamDraw:p,largestTeamSize:u,participantType:o,gendersCount:s}}function NN({participantsProfile:t,tournamentRecord:e,eventProfiles:r,drawProfiles:n,startDate:o,random:i,uuids:s}){if(t?.participantsCount===0)return{addedCount:0,...P};let{participantsCount:a,participantType:c,largestTeamDraw:u,largestTeamSize:p,gendersCount:m}=nV({participantsProfile:t,eventProfiles:r,drawProfiles:n}),d=t?.teamKey,l=oc({consideredDate:o,...t,participantsCount:a,participantType:c,gendersCount:m,random:i,uuids:s}).participants,f=0,g=un({tournamentRecord:e,participants:l});if(g.error)return g;if(f+=g.addedCount,d){let T=Mh({tournamentRecord:e,...d});if(T.error)return T}let I=l.filter(({participantType:T})=>T===St).map(gt),S=t?.idPrefix?`${_t}-${t.idPrefix}`:void 0,h=Q(0,u).map(T=>{let y=I.slice(T*p,(T+1)*p),E=$d({index:T,participantType:c,idPrefix:S,random:i,uuids:s});return{participantName:`Team ${T+1}`,participantRole:Ve,individualParticipantIds:y,participantType:_t,participantId:E}});return g=un({participants:h,tournamentRecord:e}),g.error?g:(f+=g.addedCount,{addedCount:f,...P})}function DN({drawProfiles:t,category:e,gender:r}){let n={},o=t?.reduce((s,a)=>{let{qualifyingPositions:c=0,participantsCount:u=0,uniqueParticipants:p,stage:m=W,drawSize:d=0}=a??{};Object.keys(s).includes(m)||(s[m]=0);let l=(u||d)-c;return p||r||e||m===Z?(Object.keys(n).includes(m)||(n[m]=0),n[m]+=l):s[m]=Math.max(s[m],l),s},{}),i=Object.keys(n);return i.forEach(s=>o[s]+=n[s]),{stageParticipantsCount:o,uniqueParticipantsCount:n,uniqueParticipantStages:i}}function UN({allUniqueParticipantIds:t,stageParticipantsCount:e,eventParticipantType:r,targetParticipants:n}){let o=e[W]||0,i=e[Z]||0;return{stageParticipants:{QUALIFYING:n?.filter(({participantType:a})=>a===r).filter(({participantId:a})=>!t.includes(a)).slice(0,i),MAIN:n?.filter(({participantType:a})=>a===r).filter(({participantId:a})=>!t.includes(a)).slice(i,i+o)}}}var WX={[vt]:2,[Qt]:1,[ge]:1,[De]:1,[Mt]:4},HX=new Set([De,Mt,Xr,Wi]),YX=new Set([Qt,ge]),jX=new Set(Object.keys(Wy));function qX({matchUpStatusProfile:t,defaultWithScorePercent:e,pointsPerMinute:r,sideWeight:n,matchUpFormat:o}){if(!xr({matchUpFormat:o}))return{error:XD};if(typeof t!="object")return{error:O};if(Number.isNaN(Number(e))||Number.isNaN(Number(r))||Number.isNaN(Number(n)))return{error:O}}function $X({matchUpStatusProfile:t,random:e}){let r=Object.keys(t).filter(a=>jX.has(a)&&a!==ie);if(Object.keys(r).reduce((a,c)=>a+t[c],0)>100)return{error:O,matchUpStatusProfile:t};let o=r.reduce((a,c)=>(a.pointer=a.pointer+t[c],a.valueMap.push([a.pointer,c]),a),{pointer:0,valueMap:[]}),i=pn(1,100,e);return{matchUpStatus:(o.valueMap.find(a=>i<=a[0])??[100,ie])[1]}}function KX({parsedFormat:t,winningSide:e,adjustSet:r,random:n,sets:o}){let i=o.reduce((c,u)=>c+(u.side1Score??0),0),s=o.reduce((c,u)=>c+(u.side2Score??0),0),a=t?.setFormat?.outs?t.setFormat.outs*3:void 0;if(e)return(e===1&&i<=s||e===2&&s<=i)&&zX({sets:o,winningSide:e,side1Total:i,side2Total:s,maxSetScore:a,adjustSet:r,random:n}),e;if(i===s){let c=pn(1,2,n);return iV(o,c,1,a,r),c}return i>s?1:2}function zX({maxSetScore:t,side1Total:e,side2Total:r,winningSide:n,adjustSet:o,random:i,sets:s}){if(t){if(e!==r)for(let u of s)[u.side1Score,u.side2Score]=[u.side2Score,u.side1Score],u.winningSide&&(u.winningSide=u.winningSide===1?2:1);let a=s.reduce((u,p)=>u+(p.side1Score??0),0),c=s.reduce((u,p)=>u+(p.side2Score??0),0);a===c&&iV(s,n,1,t,o)}else{let a=Math.abs(e-r)+pn(1,3,i);n===1?s[o].side1Score+=a:s[o].side2Score+=a}}function vh(t){let{winningSide:e,defaultWithScorePercent:r=2}=t,{matchUpStatusProfile:n=WX,matchUpFormat:o=xn,pointsPerMinute:i=2.5,sideWeight:s=4,random:a}=t,c=Math.min(r,100),u=qX({defaultWithScorePercent:c,matchUpStatusProfile:n,pointsPerMinute:i,matchUpFormat:o,sideWeight:s});if(u?.error)return u;let p=$X({matchUpStatusProfile:n,random:a});if(p.error)return p;let{matchUpStatus:m}=p,d=QX({defaultWithScorePercent:c,winningSide:e,matchUpStatus:m,random:a});if(d)return d;let l=Ye(m)?e||pn(1,2,a):e;return XX({pointsPerMinute:i,matchUpFormat:o,matchUpStatus:m,winningSide:l,sideWeight:s,random:a})}function QX({matchUpStatus:t,winningSide:e,defaultWithScorePercent:r,random:n}){let o={sets:[],scoreStringSide1:"",side2ScoreString:""};if(Ye(t)){let i=e||pn(1,2,n),s={score:o,matchUpStatus:t,winningSide:i};if(!(t===Mt&&pn(1,100,n)>100-r))return{outcome:s}}else if(YX.has(t))return{outcome:{score:o,matchUpStatus:t}}}function XX({pointsPerMinute:t,matchUpFormat:e,matchUpStatus:r,winningSide:n,sideWeight:o,random:i}){let s=oe(e),{bestOf:a=1,exactly:c,setFormat:u,finalSetFormat:p}=s??{},m=[],d=pn(0,1,i),l=n?[n-1]:[...Q(0,o).map(()=>d),1-d],g=HX.has(r)&&(Sr(Q(1,c||a),i)||1),I,S=Q(1,(c??a)+1);for(let E of S){let A=E===(c??a),{set:N,incomplete:D,winningSideNumber:R}=ZX({setFormat:A&&p||u,incomplete:g===E,pointsPerMinute:t,matchUpStatus:r,weightedRange:l,setNumber:E,random:i});if(m.push(N),D){I=R;break}if(Ld({matchUp:{score:{sets:m},matchUpFormat:e}}).calculatedWinningSide&&!s?.aggregate)break}let h=JX({weightedWinningSide:I,matchUpFormat:e,parsedFormat:s,winningSide:n,random:i,sets:m}),{score:T}=lN({winningSide:h,score:{sets:m},matchUpStatus:r});return{outcome:{winningSide:h,matchUpStatus:r,score:T}}}function JX({weightedWinningSide:t,matchUpFormat:e,parsedFormat:r,winningSide:n,random:o,sets:i}){if(t)return n||t;if(r?.aggregate&&i.length>0){let a=pn(0,i.length-1,o);return KX({parsedFormat:r,winningSide:n,adjustSet:a,random:o,sets:i})}return Ld({matchUp:{score:{sets:i},matchUpFormat:e,winningSide:n}}).calculatedWinningSide}function ZX({weightedRange:t=[0,1],pointsPerMinute:e,matchUpStatus:r,incomplete:n,setFormat:o,setNumber:i,random:s}){let a={setNumber:i},{setTo:c,tiebreakFormat:u,tiebreakAt:p,tiebreakSet:m,timed:d,minutes:l,outs:f}=o,g=pn(0,t.length-1,s),I=t[g];return d?tJ({set:a,minutes:l,pointsPerMinute:e,reverseScores:I,weightedRange:t,weightIndex:g,incomplete:n,matchUpStatus:r,random:s}):f?eJ({set:a,outs:f,reverseScores:I,weightedRange:t,weightIndex:g,incomplete:n,matchUpStatus:r,random:s}):n?rJ({set:a,tiebreakAt:p,weightedRange:t,weightIndex:g,matchUpStatus:r,random:s}):nJ({tiebreakFormat:u,reverseScores:I,weightedRange:t,weightIndex:g,tiebreakSet:m,tiebreakAt:p,setFormat:o,random:s,setTo:c,set:a})}function tJ({pointsPerMinute:t,reverseScores:e,weightedRange:r,matchUpStatus:n,weightIndex:o,incomplete:i,minutes:s,random:a,set:c}){let u=s*t,p=Math.round(u*.2),m=u+Sr([1,-1],a)*p,d=aw(m,2,void 0,a),l=[d,m-d];e&&l.reverse();let f=r[o]+1;if(i){let[T,y]=l;return Object.assign(c,{side1Score:T,side2Score:y}),Ot.includes(n)?{set:c,incomplete:i,winningSideNumber:f}:{set:c,incomplete:i}}l[0]>l[1]||l[1]>l[0]||(l[pn(0,1,a)]+=1),(l[0]>l[1]?1:2)!==f&&l.reverse();let[S,h]=l;return Object.assign(c,{side1Score:S,side2Score:h,winningSide:f}),{set:c}}function eJ({reverseScores:t,weightedRange:e,matchUpStatus:r,weightIndex:n,incomplete:o,random:i,outs:s,set:a}){let c=s*3,u=[pn(0,c,i),pn(0,c,i)],p=e[n]+1;if(t&&u.reverse(),o){let[l,f]=u;return Object.assign(a,{side1Score:l,side2Score:f}),Ot.includes(r)?{set:a,incomplete:o,winningSideNumber:p}:{set:a,incomplete:o}}let[m,d]=u;return Object.assign(a,{side1Score:m,side2Score:d}),m!==d&&(a.winningSide=m>d?1:2),{set:a}}function rJ({matchUpStatus:t,weightedRange:e,tiebreakAt:r,weightIndex:n,random:o,set:i}){i.side1Score=pn(0,r,o),i.side2Score=pn(0,r,o);let s;return Ot.includes(t)&&(s=e[n]+1),{set:i,incomplete:!0,winningSideNumber:s}}function nJ({tiebreakFormat:t,reverseScores:e,weightedRange:r,weightIndex:n,tiebreakSet:o,tiebreakAt:i,setFormat:s,random:a,setTo:c,set:u}){let p=Q(1,c+1).flatMap(S=>Q(0,c+2-S).map(()=>S)),m=p[pn(0,p.length-1,a)],d=c&&rh({isSide1:!0,tiebreakAt:i,lowValue:m,setTo:c}),l=!d,f=r.length===1&&r[n]+1;if(d){oV({scores:d,specifiedWinningSide:f,reverseScores:e});let[S,h]=d;Object.assign(u,{side1Score:S,side2Score:h})}let g=om({matchUpScoringFormat:{setFormat:s},setObject:u}),I;return(g.hasTiebreakCondition||l)&&(I=oJ({specifiedWinningSide:f,tiebreakFormat:t,reverseScores:e,isTiebreakSet:l,tiebreakSet:o,setAnalysis:g,random:a,set:u})),u.winningSide=g.winningSide||g.leadingSide||f||I,{set:u}}function oV({scores:t,specifiedWinningSide:e,reverseScores:r}){e?(t[0]>t[1]?1:2)!==e&&t.reverse():r&&t.reverse()}function oJ({specifiedWinningSide:t,tiebreakFormat:e,reverseScores:r,isTiebreakSet:n,tiebreakSet:o,setAnalysis:i,random:s,set:a}){let{NoAD:c,tiebreakTo:u}=e||(o??{}),p=Q(1,u+1).flatMap(l=>Q(0,u+2-l).map(()=>l)),m=p[pn(0,p.length-1,s)],d=Ud({isSide1:!0,tiebreakNoAd:c,tiebreakTo:u,lowValue:m});if(d){if(n)return oV({scores:d,specifiedWinningSide:t,reverseScores:r}),[a.side1TiebreakScore,a.side2TiebreakScore]=d,d[0]>d[1]&&1||d[1]>d[0]&&2||void 0;i.leadingSide===2?[a.side1TiebreakScore,a.side2TiebreakScore]=d:[a.side2TiebreakScore,a.side1TiebreakScore]=d}}function iV(t,e,r,n,o){let i=e===1?"side1Score":"side2Score",s=e===1?"side2Score":"side1Score";if(!n){t[o][i]+=r;return}let a=r;for(let c=0;a>0&&c<t.length;c++){let u=(o+c)%t.length,p=t[u][s]??0;if(p>0){let m=Math.min(a,p);t[u][s]-=m,a-=m}}for(let c=0;a>0&&c<t.length;c++){let u=(o+c)%t.length,p=n-(t[u][i]??0);if(p>0){let m=Math.min(a,p);t[u][i]+=m,a-=m}}}function sJ({firstRoundDualMatchUps:t,event:e,tournamentRecord:r,drawDefinition:n}){let o=e?.category?.ageCategoryCode||e?.category?.categoryName;if(o){let d=JP({singlesOnly:!0,tournamentRecord:r,drawDefinition:n,scaleAccessor:{scaleName:o,sortOrder:"ASC",scaleType:Jn},event:e});if(d.error)return d;let{lineUps:l,participantsToAdd:f}=d;un({tournamentRecord:r,participants:f}),ut({element:n,extension:{name:Vo,value:l}});return}let i=t[0]?.structureId,{positionAssignments:s}=Pt({drawDefinition:n,structureId:i});if(!s?.length)return;let{participants:a}=bt({participantFilters:{participantTypes:[xt]},tournamentRecord:r});function c(m){return a?.find(d=>{let{participantId:l}=d;return s.find(g=>g.participantId===l)?.drawPosition===m})}function u(m,d,l){m.sides.forEach(f=>{let{drawPosition:g}=f,I=c(g);if(I){let S=I.individualParticipantIds?.[d];S&&og({teamParticipantId:I.participantId,participantId:S,tournamentRecord:r,drawDefinition:n,tieMatchUpId:l,event:e});return}})}function p(m,d,l){m.sides.forEach(f=>{let{drawPosition:g}=f,I=c(g);I&&I.individualParticipantIds?.slice(d*2,d*2+2)?.forEach(h=>{og({teamParticipantId:I.participantId,participantId:h,tournamentRecord:r,drawDefinition:n,tieMatchUpId:l,event:e})})})}t.forEach(m=>{let d=m.tieMatchUps.filter(re(Ct)),l=m.tieMatchUps.filter(re(Rt));d.forEach((f,g)=>{let I=f.matchUpId;u(f,g,I)}),l.forEach((f,g)=>{let I=f.matchUpId;p(f,g,I)})})}function aJ({structure:t,matchUpsMap:e,drawDefinition:r,tournamentRecord:n,event:o,matchUpStatusProfile:i,matchUpFormat:s,matchUpStatus:a,scoreString:c,randomWinningSide:u,completionGoal:p,completedCount:m,roundNumber:d,random:l}){let g=ht({contextFilters:{matchUpTypes:[Rt,Ct]},afterRecoveryTimes:!1,tournamentRecord:n,inContext:!0,drawDefinition:r,matchUpsMap:e,structure:t,event:o}).matchUps.filter(({winningSide:I,roundNumber:S})=>!I&&(!d||S===d)).sort(Qi).map(Te);for(let I of g){if(!Number.isNaN(Number(p))&&m.value>=p)break;let{matchUps:S}=ht({matchUpFilters:{matchUpTypes:[Rt,Ct]},afterRecoveryTimes:!1,tournamentRecord:n,inContext:!0,drawDefinition:r,matchUpsMap:e,structure:t,event:o}),h=S.find(y=>y.matchUpId===I),T=[Qt,ge].includes(h.matchUpStatus);if(h?.readyToScore&&!T){let E=cJ({matchUpStatusProfile:i,tournamentRecord:n,drawDefinition:r,targetMatchUp:h,matchUpFormat:s,matchUpStatus:a,scoreString:c,winningSide:!u&&1,random:l,event:o});if(E?.error)return E;m.value+=1}}}function $u(t){let{matchUpStatusProfile:e,completeAllMatchUps:r,randomWinningSide:n,tournamentRecord:o,completionGoal:i,drawDefinition:s,roundNumber:a,stageSequence:c,random:u,stage:p,event:m}=t;if(!s)return{error:$};let d=t.matchUpFormat||s.matchUpFormat||m?.matchUpFormat,l=s.structures.slice().sort(Hi),f={value:0},{matchUps:g}=te({matchUpFilters:{matchUpTypes:[xt],roundNumbers:[1]},contextFilters:{stages:[W,Z]},inContext:!0,drawDefinition:s});if(g?.length){let N=sJ({firstRoundDualMatchUps:g,event:m,tournamentRecord:o,drawDefinition:s});if(N?.error)return N}let I=typeof r=="string"&&r,S=I&&ie,h=l.length===2&&l[0].finishingPosition===po&&Yt(l.map(({stage:N})=>N),[W,Vt]).length===2,T=l.map(({structureId:N})=>N),y=10,E=0,A=-1;for(;f.value>A&&(i===void 0||f.value<i)&&E<y;){E++,A=f.value;let{matchUpsMap:N}=te({matchUpFilters:{matchUpTypes:[xt],roundNumbers:[1]},contextFilters:{stages:[W,Z]},inContext:!0,drawDefinition:s});for(let D of T){if(f.value>=i)break;let R=s.structures.find(b=>b.structureId===D);if(p&&R.stage!==p||c&&R.stageSequence!==c)continue;let U=aJ({structure:R,matchUpsMap:N,drawDefinition:s,tournamentRecord:o,event:m,matchUpStatusProfile:e,matchUpFormat:d,matchUpStatus:S,scoreString:I,randomWinningSide:n,completionGoal:i,completedCount:f,roundNumber:a,random:u});if(U?.error)return U;h&&R.finishingPosition===po&&t.completeRoundRobinPlayoffs&&Ha({structureId:R.structureId,applyPositioning:!0,drawDefinition:s})}}return{...P,completedCount:f.value}}function fO(t){let{matchUpStatusCodes:e,policyDefinitions:r,tournamentRecord:n,drawDefinition:o,targetMatchUp:i,matchUpStatus:s,matchUpFormat:a,scoreString:c,winningSide:u,event:p}=t;if(!i||i.matchUpStatus==="BYE")return;let{matchUpId:m}=i??{},{outcome:d}=Rh({matchUpFormat:a,matchUpStatus:s,scoreString:c,winningSide:u});return e&&(d.matchUpStatusCodes=e),wc({tournamentRecord:n,policyDefinitions:r,drawDefinition:o,matchUpFormat:a,matchUpId:m,outcome:d,event:p})}function cJ(t){let{matchUpStatusProfile:e={},tournamentRecord:r,policyDefinitions:n,drawDefinition:o,matchUpStatus:i,matchUpFormat:s,targetMatchUp:a,scoreString:c,winningSide:u,random:p,event:m}=t,d=a?.matchUpFormat||s;if(c||i)return fO({...t,matchUpFormat:d});let{matchUpId:l}=a??{},f=vh({matchUpStatusProfile:e,matchUpFormat:d,winningSide:u,random:p}),{outcome:g}=f;return wc({policyDefinitions:n,tournamentRecord:r,drawDefinition:o,matchUpFormat:d,matchUpId:l,outcome:g,event:m})}function RN({matchUpStatusProfile:t,completeAllMatchUps:e,randomWinningSide:r,tournamentRecord:n,drawProfiles:o,random:i,isMock:s,event:a}){let c=Bt({event:a}).flightProfile,{eventName:u,eventType:p,category:m}=a,{startDate:d}=n,l=[],f=m?.categoryName||m?.ageCategoryCode||m?.ratingType,g=a.drawDefinitions?.map(({drawId:S})=>S),I=new Set(g??[]);if(!Array.isArray(c?.flights))return{...P,drawIds:l};for(let[S,h]of c.flights.entries()){let{drawId:T,stage:y,drawName:E,drawEntries:A}=h;l.push(h.drawId);let N=o[S],{seedsCount:D,generate:R=!0}=N??{};if(!R)continue;let U=f||u;if(uJ({drawParticipantIds:A.filter(Vr(sr)).map(Vr(sr)),seedingScaleName:U,tournamentRecord:n,seedsCount:D,startDate:d,eventType:p}),I.has(T))break;let b=pJ({drawProfile:o[S],seedingScaleName:U,tournamentRecord:n,drawEntries:A,eventType:p,drawName:E,drawId:T,isMock:s,random:i,event:a,stage:y});if(b.error)return{error:b.error,drawIds:[]};let{drawDefinition:C}=b,_=o[S]?.automated===!1,v=o[S]?.completionGoal;if(!_&&(e||v)){let w=mJ({matchUpFormat:o[S]?.matchUpFormat,drawType:o[S]?.drawType,matchUpStatusProfile:t,completeAllMatchUps:e,randomWinningSide:r,tournamentRecord:n,drawDefinition:C,completionGoal:v,random:i,event:a});if(w?.error)return{error:w.error,drawIds:[]}}}return{...P,drawIds:l}}function uJ({drawParticipantIds:t,seedingScaleName:e,tournamentRecord:r,seedsCount:n,startDate:o,eventType:i}){if(!r||!n||n>t.length)return;Q(1,n+1).forEach((a,c)=>{let u={scaleValue:a,scaleName:e,scaleType:Eo,eventType:i,scaleDate:o},p=t[c];$a({tournamentRecord:r,participantId:p,scaleItem:u})})}function pJ({seedingScaleName:t,tournamentRecord:e,drawProfile:r,drawEntries:n,eventType:o,drawName:i,drawId:s,isMock:a,random:c,event:u,stage:p}){let m=xc({...r,matchUpType:o,seedingScaleName:t,tournamentRecord:e,drawEntries:n,drawName:i,drawId:s,isMock:a,random:c,event:u,stage:p});if(m.error)return{error:m.error};let{drawDefinition:d}=m;if(!d)return{error:Mr};let l=r?.drawExtensions;return Array.isArray(l)&&l.filter(Yn).forEach(f=>ut({element:d,extension:f})),m=Gu({suppressNotifications:!0,tournamentRecord:e,drawDefinition:d,event:u}),m.error?{error:m.error}:{drawDefinition:d}}function mJ({matchUpStatusProfile:t,completeAllMatchUps:e,randomWinningSide:r,tournamentRecord:n,drawDefinition:o,completionGoal:i,matchUpFormat:s,drawType:a,random:c,event:u}){let p=$u({completeAllMatchUps:!i&&e,matchUpStatusProfile:t,randomWinningSide:r,tournamentRecord:n,completionGoal:i,drawDefinition:o,matchUpFormat:s,random:c,event:u});if(p.error)return p;if(a!==Tr)return;let m=o.structures?.find(I=>I.stage===W);if(!m)return{error:Nt};let d=Ha({structureId:m.structureId,tournamentRecord:n,drawDefinition:o,event:u});if(d.error)return d;let l=p.completedCount,f=i?i-(l??0):void 0,g=$u({completeAllMatchUps:!i&&e,completionGoal:i?f:void 0,matchUpStatusProfile:t,randomWinningSide:r,tournamentRecord:n,drawDefinition:o,matchUpFormat:s,random:c,event:u});if(g.error)return g}function bN(t){let{participantsProfile:e={},uniqueParticipantsCount:r,ratingsParameters:n,tournamentRecord:o,eventProfile:i,eventIndex:s,event:a,uuids:c}=t,{category:u,gender:p,eventType:m}=a,d=re(Dt)(m)&&St||re(Lt)(m)&<||m,l=r[W]||0,f=r[Z]||0,g=i.drawProfiles?.length?l+f:i.participantsProfile?.participantsCount??0,I=Un(p)?p:void 0,S=e?.idPrefix?`E-${s}-${e?.idPrefix}`:void 0,{participants:h}=oc({uuids:i.uuids||c,...e,scaledParticipantsCount:i.scaledParticipantsCount,consideredDate:o?.startDate,rankingRange:i.rankingRange,participantType:d,participantsCount:g,ratingsParameters:n,category:u,idPrefix:S,sex:I}),y=un({tournamentRecord:o,participants:h});if(y.error)return y;let E=h?.filter(({participantType:N})=>N===d),A=h?.map(gt);return{uniqueDrawParticipants:E,uniqueParticipantIds:A}}function sV({autoEntryPositions:t,tournamentRecord:e,drawParticipants:r,drawProfile:n,event:o}){let{drawType:i=Nr,qualifyingPositions:s=0,stage:a=W,drawSize:c=0,drawName:u,drawId:p}=n,m=c-s,d=r.slice(0,m).map(gt);if(d.length){let g=jn({participantIds:d,autoEntryPositions:t,entryStage:a,tournamentRecord:e,event:o});if(g.error)return g}let l=d.map(g=>({entryStatus:kr,entryStage:a,participantId:g})),f=kd({drawName:u||i,qualifyingPositions:s,drawEntries:l,drawId:p,event:o,stage:a});return f.error?f:{...P}}function CN({uniqueDrawParticipants:t,autoEntryPositions:e,stageParticipants:r,tournamentRecord:n,drawProfiles:o,category:i,gender:s,event:a}){let c=0;for(let u of o){let{qualifyingPositions:p=0,uniqueParticipants:m,stage:d=W,drawSize:l=0}=u,f=l-p,g=m||s||i||d===Z,I=g?t.slice(c,c+f):r[d||W]??[];g&&(c+=f);let S=sV({autoEntryPositions:e,drawParticipants:I,tournamentRecord:n,drawProfile:u,event:a});if(S.error)return S}return{...P}}function MN(t){let{allUniqueParticipantIds:e,matchUpStatusProfile:r,participantsProfile:n,completeAllMatchUps:o,autoEntryPositions:i,hydrateCollections:s,randomWinningSide:a,ratingsParameters:c,tournamentRecord:u,eventProfile:p,eventIndex:m,publish:d,random:l,isMock:f,uuids:g}=t,I=p.gender,S=p.eventName,{eventType:h=Dt,policyDefinitions:T,drawProfiles:y=[],eventExtensions:E,surfaceCategory:A,tieFormatName:N,processCodes:D,discipline:R,eventLevel:U,timeItems:b,ballType:C,category:_}=p,v=p.eventId||it(void 0,l),w=p.tieFormat||(h===Oe?uo({namedFormat:N,event:{eventId:v,category:_,gender:I},hydrateCollections:s,isMock:f}):void 0),L=u.participants;for(let Et of y)!I&&Et.gender&&(I=Et?.gender);let{stageParticipantsCount:F,uniqueParticipantsCount:x,uniqueParticipantStages:k}=DN({drawProfiles:y,category:_,gender:I}),G=re(Dt)(h)&&St||re(Lt)(h)&<||h,{uniqueDrawParticipants:V=[],uniqueParticipantIds:B=[]}=k?bN({event:{eventType:h,category:_,gender:I},uniqueParticipantsCount:x,participantsProfile:n,ratingsParameters:c,tournamentRecord:u,eventProfile:p,eventIndex:m,uuids:g}):{},z=_?.categoryName||_?.ageCategoryCode||_?.ratingType;S=S||z||"Generated Event";let H=dJ({eventProfile:p,surfaceCategory:A,processCodes:D,discipline:R,eventLevel:U,eventExtensions:E,policyDefinitions:T,timeItems:b,eventName:S,eventType:h,tieFormat:w,ballType:C,category:_,eventId:v,gender:I,categoryName:z}),K,Y=tc({suppressNotifications:!1,internalUse:!0,tournamentRecord:u,event:H});if(Y.error)return Y;let J=Y?.event,{stageParticipants:ct}=UN({allUniqueParticipantIds:e,stageParticipantsCount:F,eventParticipantType:G,targetParticipants:L});if(y?.length){let Et=CN({uniqueDrawParticipants:V,autoEntryPositions:i,stageParticipants:ct,tournamentRecord:u,drawProfiles:y,category:_,gender:I,event:J});if(Et.error)return Et;let Ht=RN({matchUpStatusProfile:r,completeAllMatchUps:o,randomWinningSide:a,tournamentRecord:u,drawProfiles:y,random:l,isMock:f,event:J});if(Ht.error)return Ht;K=Ht.drawIds}else if(p?.participantsProfile?.participantsCount){let Et=V.map(gt);if(Et.length){let Ht=jn({participantIds:Et,autoEntryPositions:i,tournamentRecord:u,entryStage:W,event:J});if(Ht.error)return Ht}}return d&&rc({tournamentRecord:u,event:J}),{drawIds:K,eventId:v,uniqueParticipantIds:B}}function dJ({eventProfile:t,surfaceCategory:e,processCodes:r,discipline:n,eventLevel:o,eventExtensions:i,policyDefinitions:s,timeItems:a,eventName:c,eventType:u,tieFormat:p,ballType:m,category:d,eventId:l,gender:f,categoryName:g}){let{eventAttributes:I}=t;typeof I!="object"&&(I={});let S={...I,surfaceCategory:e,processCodes:r,discipline:n,eventLevel:o,eventName:c,eventType:u,tieFormat:p,ballType:m,category:d,eventId:l,gender:f};if(i?.length&&Array.isArray(i)){let h=i.filter(Yn);h?.length&&Object.assign(S,{extensions:h})}if(Array.isArray(a)&&a.forEach(h=>Rs({event:S,timeItem:h})),typeof s=="object")for(let h of Object.keys(s))bs({policyDefinitions:{[h]:s[h]},event:S});return S.category&&(S.category.categoryName=g),S}function Oh({tournamentRecords:t,scheduleDate:e,venueId:r,round:n}){if(!Me(e))return{error:ae};let o="addSchedulingProfileRound",{extension:i}=ot({name:hc,tournamentRecords:t,discover:!0}),s=i?.value??[],a=s.find(l=>Xn(e,l.scheduleDate));if(!a){let{startDate:l,endDate:f}=Vf({tournamentRecords:t}),g=new Date(e);if(l&&g<new Date(l)||f&&g>new Date(f))return{error:ae};a={scheduleDate:e,venues:[]},s.push(a)}let c=a.venues.find(l=>l.venueId===r);c||(c={venueId:r,rounds:[]},a.venues.push(c));let u=["notBeforeTime"],p=l=>Object.keys(l).filter(f=>!u.includes(f)).sort().map(f=>Tt(l[f])?p(l[f]):l[f]).flat().join("|");if(c.rounds.find(l=>p(l)===p(n)))return M({result:{error:WD},stack:o});c.rounds.push(n);let d=Fu({tournamentRecords:t,schedulingProfile:s});return d.error?d:{...P}}function aV({schedulingProfile:t,tournamentRecord:e}){if(typeof t!="object")return{error:O};let r=ji({tournamentRecord:e}).containedStructures,n=qt({tournamentRecord:e}).matchUps??[],{tournamentId:o}=e,i=[];for(let s of t){let{scheduleDate:a,venues:c=[]}=s;for(let u of c){let{rounds:p,venueId:m}=u;for(let d of p){let{drawId:l,winnerFinishingPositionRange:f,roundSegment:g}=d,S=n.filter(h=>{let T=f?.indexOf("-")>0&&f.split("-").map(E=>+E),y=h.finishingPositionRange?.winner;return h.drawId===l&&(!d.roundNumber||h.roundNumber===d.roundNumber)&&(!y||!T||Yt(y,T).length===2||pt(y).length===pt(T).length&&Yt(y,T).length===pt(y).length)})[0];if(S){let{eventId:h,roundNumber:T,drawName:y,structureName:E,roundName:A}=S,N=S.structureId;T&&!f&&(N=Object.keys(r).find(U=>r[U].includes(N))??N);let D={tournamentId:o,structureId:N,roundNumber:T,roundSegment:g,eventId:h,drawId:l},R=Oh({tournamentRecords:{[o]:e},round:D,scheduleDate:a,venueId:m});if(R.error)return R;i.push({structureName:E,roundName:A,drawName:y,...D})}}}}return{scheduledRounds:i}}function lJ({qualifyingParticipantsCount:t,participantsProfile:e,drawParticipantsCount:r,ratingsParameters:n,tournamentRecord:o,drawProfileCopy:i,participantType:s,categoryName:a,drawProfile:c,buildTeams:u,eventType:p,drawSize:m,isHybrid:d,drawIndex:l,category:f,gender:g,random:I,event:S,uuids:h}){let T=r,y={[Ce]:0,[Je]:0},E,A;if(d){let C=Math.floor(r/2);T=r-C+C*2}if(p===_t){({teamSize:E,genders:A}=pg({tieFormatName:i.tieFormatName,tieFormat:i.tieFormat,alternatesCount:i.alternatesCount||0,drawSize:m,random:I}));let C=i.teamGenders;if(C){for(let v of Object.keys(C))A[v]!==void 0&&C[v]>A[v]&&(A[v]=C[v]);let _=(A[Ce]||0)+(A[Je]||0);_>E&&(E=_)}Object.keys(A).forEach(_=>{let v=Ar(_);v&&Un(_)&&A[v]&&(y[v]=m*A[v])}),T=E*((m||0)+t)}let N=e?.idPrefix?`D-${l}-${e?.idPrefix}`:void 0,R=oc({...e,scaledParticipantsCount:c.scaledParticipantsCount||e.scaledParticipantsCount,participantsCount:T,consideredDate:o?.startDate,sex:g||e?.sex,rankingRange:c.rankingRange,uuids:c.uuids||h,ratingsParameters:n,participantType:s,gendersCount:y,idPrefix:N,category:f,random:I}).participants;if(S.category&&(S.category.categoryName=a),o){let C=un({participants:R,tournamentRecord:o});if(C.error)return C}let U=[];R.forEach(({participantId:C})=>U.push(C));let b=R;if(p===_t){let C=fJ({drawParticipantsCount:r,tournamentRecord:o,drawProfileCopy:i,buildTeams:u,genders:A,teamSize:E,unique:R,random:I});if(C.error)return C;b=C.teamParticipants}if(d){let C=gJ({drawParticipantsCount:r,tournamentRecord:o,unique:R,random:I});if(C.error)return C;b=C.targetParticipants}return{uniqueParticipantIds:U,targetParticipants:b}}function fJ({drawParticipantsCount:t,tournamentRecord:e,drawProfileCopy:r,buildTeams:n,genders:o,teamSize:i,unique:s,random:a}){let c=o[Ce]?s.filter(({participantType:y,person:E})=>y===St&&E?.sex===Ce).map(gt):[],u=o[Je]?s.filter(({participantType:y,person:E})=>y===St&&ls(E?.sex)).map(gt):[],p=new Set(c),m=new Set(u),d=s.filter(({participantType:y})=>y===St).map(gt).filter(y=>!p.has(y)&&!m.has(y)),l=[...r.teamNames??[],...Kd({count:t,random:a}).names],f=i-(o[Ce]+o[Je]),g=0,I=0,S=0,h=Q(0,t).map(y=>{let E=u.slice(g,g+o[Je]),A=c.slice(I,I+o[Ce]),N=d.slice(S,S+f);g+=o[Je],I+=o[Ce],S+=f;let D=n!==!1?[...E,...A,...N]:[],R=l[y]||`Team ${y+1}`,U=it(void 0,a);if(n!==!1){let b=1;for(let C of D){let _=s.find(v=>v.participantId===C);_?.person&&(_.person.biographicalInformation||(_.person.biographicalInformation={}),_.person.biographicalInformation.teamAttributes||(_.person.biographicalInformation.teamAttributes=[]),_.person.biographicalInformation.teamAttributes.push({jerseyName:_.person.standardFamilyName?.toUpperCase(),jerseyNumber:String(b),teamName:R,teamId:U}),b+=1)}}return{participantOtherName:`TM${y+1}`,participantName:R,participantId:U,participantRole:Ve,individualParticipantIds:D,participantType:_t,useOtherName:!1}}),T=un({participants:h,tournamentRecord:e});return T.success?{teamParticipants:h}:T}function gJ({drawParticipantsCount:t,tournamentRecord:e,unique:r,random:n}){let o=r.filter(({participantType:c})=>c===St),i=t-Math.floor(t/2),s=o.slice(i),a=[];for(let c=0;c+1<s.length;c+=2){let u=s[c],p=s[c+1];a.push({participantName:`${u.person?.standardGivenName??"A"} / ${p.person?.standardGivenName??"B"}`,individualParticipantIds:[u.participantId,p.participantId],participantRole:Ve,participantType:lt,participantId:it(void 0,n)})}if(a.length&&e){let c=un({participants:a,tournamentRecord:e});if(!c.success)return c}return{targetParticipants:[...o.slice(0,i),...a]}}function IJ({qualifyingParticipantIds:t,autoEntryPositions:e,qualifyingProfiles:r,tournamentRecord:n,event:o}){let i=0,s=1,a=(u,p)=>u.stageSequence-p.stageSequence,c=(u,p)=>u.roundTarget-p.roundTarget;for(let u of r.sort(c)){s=u.roundTarget||s;let p=1,m;for(let d of u.structureProfiles.sort(a)){let f=(d.drawSize||el(d.participantsCount))-(m||0),g=t.slice(i,i+f),I=jn({entryStage:Z,entryStageSequence:p,autoEntryPositions:e,tournamentRecord:n,participantIds:g,roundTarget:s,event:o});if(I.error)return I;m=d.qualifyingPositions,i+=f,p+=1}s+=1}}function SJ({matchUpStatusProfile:t,completeAllMatchUps:e,randomWinningSide:r,tournamentRecord:n,drawDefinition:o,completionGoal:i,matchUpFormat:s,drawProfile:a,drawType:c,random:u,event:p}){let m=d=>{let l=$u({completeAllMatchUps:d.completeAllMatchUps,completionGoal:d.completionGoal,matchUpStatusProfile:t,randomWinningSide:r,tournamentRecord:n,drawDefinition:o,matchUpFormat:s,random:u,event:p});if(l.error)return l;if(c===Tr){let f=hJ({completedCount:l.completedCount,matchUpStatusProfile:t,completeAllMatchUps:e,randomWinningSide:r,tournamentRecord:n,drawDefinition:o,completionGoal:i,matchUpFormat:s,random:u,event:p});if(f?.error)return f}};if(i&&m({completionGoal:i}),a.outcomes){let d=TJ({outcomes:a.outcomes,tournamentRecord:n,drawDefinition:o,event:p});if(d?.error)return d}return e&&m({completeAllMatchUps:e}),{goComplete:m}}function hJ({matchUpStatusProfile:t,completeAllMatchUps:e,randomWinningSide:r,tournamentRecord:n,drawDefinition:o,completedCount:i,completionGoal:s,matchUpFormat:a,random:c,event:u}){let p=o.structures?.find(l=>l.stage===W);if(!p)return{error:Nt};Ha({structureId:p.structureId,tournamentRecord:n,drawDefinition:o,event:u});let m=s?s-(i??0):void 0,d=$u({completionGoal:s?m:void 0,matchUpStatusProfile:t,completeAllMatchUps:e,randomWinningSide:r,tournamentRecord:n,drawDefinition:o,matchUpFormat:a,random:c,event:u});if(d.error)return d}function TJ({tournamentRecord:t,drawDefinition:e,outcomes:r,event:n}){let{matchUps:o}=rr({inContext:!0,drawDefinition:e,event:n}),i=yJ(o);for(let s of r){let{matchUpStatus:a=ie,matchUpStatusCodes:c,stageSequence:u=1,matchUpIndex:p=0,structureOrder:m,matchUpFormat:d,drawPositions:l,roundPosition:f,stage:g=W,roundNumber:I,winningSide:S,scoreString:h}=s,y=o?.filter(A=>(!g||A.stage===g)&&(!u||A.stageSequence===u)&&(!I||A.roundNumber===I)&&(!f||A.roundPosition===f)&&(!m||i[A.structureId]===m)&&(!l||Yt(l,A.drawPositions).length===2))?.[p],E=fO({matchUpStatusCodes:c,tournamentRecord:t,drawDefinition:e,targetMatchUp:y,matchUpFormat:d,matchUpStatus:a,scoreString:h,winningSide:S});if(E?.error)return E}}function yJ(t){let e=t?.reduce((r,n)=>{let{structureId:o,matchUpId:i}=n;return r[o]?r[o].push(i):r[o]=[i],r},{})??[];return Object.assign({},...Object.keys(e).map((r,n)=>({[r]:n+1})))}function EJ({tournamentRecord:t,drawDefinition:e,drawProfileCopy:r,drawProfile:n,goComplete:o,category:i,isMock:s,event:a}){let c=r.roundsCount,u=n.drawMatic?.scaleName??n.scaleName??i?.ratingType;for(let p=2;p<=c;p++){let m=im({eventType:n.drawMatic?.eventType??n.matchUpType,updateParticipantRatings:!!u,dynamicRatings:!!u,generateMatchUps:!0,tournamentRecord:t,drawDefinition:e,roundsCount:1,scaleName:u,isMock:s,event:a});if(m.error)return m;if(m.matchUps?.length){let l=Jp({matchUps:m.matchUps,suppressNotifications:!0,tournamentRecord:t,drawDefinition:e,event:a});if(l.error)return l}let d=o({completeAllMatchUps:!0});if(d?.error)return d}}function AJ({qualifyingParticipantsCount:t,consideredParticipants:e,isEventParticipantType:r,excessParticipantAlternates:n,tournamentAlternates:o,autoEntryPositions:i,qualifyingProfiles:s,participantsCount:a,alternatesCount:c,tournamentRecord:u,participantIds:p,isEventGender:m,drawSize:d,isMock:l,event:f,stage:g}){if(l&&p?.length){let T=jn({autoEntryPositions:i,entryStage:g,tournamentRecord:u,participantIds:p,event:f});if(T.error)return T}let I=t?e.slice(a,a+t).map(T=>T.participantId):0;if(l&&I?.length){let T=IJ({qualifyingParticipantIds:I,autoEntryPositions:i,qualifyingProfiles:s,tournamentRecord:u,event:f});if(T?.error)return T}let S=new Set(p),h=n&&u?.participants?.filter(({participantId:T})=>!S.has(T)).filter(r).filter(m).slice(0,c||d-a||o).map(T=>T.participantId);if(l&&h?.length){let T=jn({participantIds:h,autoEntryPositions:!1,entryStatus:Zr,tournamentRecord:u,event:f});if(T.error)return T.error}}function PJ({tournamentRecord:t,participantIds:e,seedingScaleName:r,seedsCount:n,startDate:o,eventType:i}){t&&n&&n<=e.length&&Q(1,n+1).forEach((a,c)=>{let u={scaleName:r,scaleDate:o,scaleType:sS,scaleValue:a,eventType:i},p=e[c];$a({tournamentRecord:t,participantId:p,scaleItem:u})})}function NJ({matchUpStatusProfile:t,completeAllMatchUps:e,randomWinningSide:r,tournamentRecord:n,drawProfileCopy:o,seedingScaleName:i,drawExtensions:s,iterativeAdHoc:a,completionGoal:c,matchUpFormat:u,drawProfile:p,drawType:m,category:d,generate:l,drawName:f,isMock:g,random:I,eventId:S,publish:h,event:T,qualifyingPositions:y,stage:E}){let A=a?{...q(p,!1,!0),roundsCount:1}:q(p,!1,!0),N=xc({...A,tournamentRecord:n,seedingScaleName:i,matchUpFormat:u,eventId:S,isMock:g,random:I,event:T});if(N.error)return N;if(!N.drawDefinition)return{error:Mr};let{drawDefinition:D}=N,R=D.drawId;if(Array.isArray(s)&&s.filter(Yn).forEach(U=>ut({element:D,extension:U})),l){Gu({drawDefinition:D,event:T,suppressNotifications:!0});let U=p.automated===!1;if(g&&!U){let b=SJ({matchUpStatusProfile:t,completeAllMatchUps:e,randomWinningSide:r,tournamentRecord:n,drawDefinition:D,completionGoal:c,matchUpFormat:u,drawProfile:p,drawType:m,random:I,event:T});if(b?.error)return b;if(a){let C=EJ({goComplete:b.goComplete,tournamentRecord:n,drawDefinition:D,drawProfileCopy:o,drawProfile:p,category:d,isMock:g,event:T});if(C?.error)return C}}h&&rc({tournamentRecord:n,event:T})}else{let U=kd({drawEntries:D.entries,drawName:f||m,qualifyingPositions:y,drawId:R,event:T,stage:E});if(U.error)return U}return{drawDefinition:D,drawId:R}}function zd(t){let e=X(t,[{drawProfile:!0,_ofType:qr}]);if(e.error)return e;let{allUniqueParticipantIds:r=[],participantsProfile:n={},matchUpStatusProfile:o,completeAllMatchUps:i,autoEntryPositions:s,hydrateCollections:a,randomWinningSide:c,ratingsParameters:u,tournamentRecord:p,isMock:m=!0,drawProfile:d,startDate:l,drawIndex:f,random:g,uuids:I}=t,S=q(d,!1,!0),{excessParticipantAlternates:h=!0,matchUpFormat:T=xn,drawType:y=Nr,tournamentAlternates:E=0,alternatesCount:A=0,qualifyingPositions:N,qualifyingProfiles:D,generate:R=!0,eventExtensions:U,drawExtensions:b,completionGoal:C,tieFormatName:_,buildTeams:v,seedsCount:w,timeItems:L,drawName:F,category:x,publish:k,gender:G,stage:V}=S,B=S.drawSize||(S.ignoreDefaults?void 0:32),z=S.eventId||it(void 0,g),H=d.eventType||d.matchUpType||Dt,K=H===Ip,Y=H===Lt?lt:St,J=RJ({drawProfile:d,tournamentRecord:p,eventId:z,eventType:H,category:x,gender:G,tieFormatName:_,hydrateCollections:a,isMock:m}),ct=x?.categoryName||x?.ageCategoryCode||x?.ratingType,Et=d.eventName||ct||`Generated ${H}`,Ht=p?.participants??[],Ut=DJ({qualifyingProfiles:D,participantType:Y}),pe=(!d.participantsCount||d.participantsCount>B?B:d.participantsCount)||0,ye=UJ({eventName:Et,eventType:H,tieFormat:J,category:x,eventId:z,gender:G,timeItems:L,drawProfile:d,eventExtensions:U}),Jt=[];if(n?.participantsCount===0||d.uniqueParticipants||Ut||!p||G||x||K){let bm=(pe||0)+A+Ut,Gc=lJ({qualifyingParticipantsCount:Ut,participantsProfile:n,drawParticipantsCount:bm,ratingsParameters:u,tournamentRecord:p,drawProfileCopy:S,participantType:Y,categoryName:ct,drawProfile:d,buildTeams:v,eventType:H,drawSize:B,isHybrid:K,drawIndex:f,category:x,gender:G,random:g,event:ye,uuids:I});if(Gc.error)return Gc;Gc.uniqueParticipantIds.forEach(Cm=>Jt.push(Cm)),Ht=Gc.targetParticipants}let{consideredParticipants:Kn,participantIds:zr,isEventParticipantType:so,isEventGender:Zo}=bJ({allUniqueParticipantIds:r,targetParticipants:Ht,participantsCount:pe,drawProfile:d,eventType:H,isHybrid:K}),ti=AJ({qualifyingParticipantsCount:Ut,consideredParticipants:Kn,isEventParticipantType:so,excessParticipantAlternates:h,tournamentAlternates:E,autoEntryPositions:s,qualifyingProfiles:D,participantsCount:pe,alternatesCount:A,tournamentRecord:p,participantIds:zr,isEventGender:Zo,drawSize:B,isMock:m,event:ye,stage:V});if(ti?.error)return ti;let la=ct||Et;PJ({tournamentRecord:p,participantIds:zr,seedingScaleName:la,seedsCount:w,startDate:l,eventType:H});let fa=yn(y)&&i&&d.automated!==!1&&(S.roundsCount??1)>1,ga=NJ({matchUpStatusProfile:o,completeAllMatchUps:i,randomWinningSide:c,tournamentRecord:p,drawProfileCopy:S,seedingScaleName:la,drawExtensions:b,iterativeAdHoc:fa,completionGoal:C,matchUpFormat:T,drawProfile:d,drawType:y,category:x,generate:R,drawName:F,isMock:m,random:g,eventId:z,publish:k,event:ye,qualifyingPositions:N,stage:V});return ga.error?ga:{...P,event:et(ye),drawDefinition:ga.drawDefinition,uniqueParticipantIds:Jt,targetParticipants:Ht,eventId:z,drawId:ga.drawId}}function DJ({qualifyingProfiles:t,participantType:e}){return(t?.flatMap(n=>n.structureProfiles??[]).reduce((n,o)=>{let i=!o.participantsCount||o.participantsCount>o.drawSize?o.drawSize:o.participantsCount||0;return n+i},0)||0)*(e===lt?2:1)}function UJ({eventName:t,eventType:e,tieFormat:r,category:n,eventId:o,gender:i,timeItems:s,drawProfile:a,eventExtensions:c}){let u={eventName:t,eventType:e,tieFormat:r,category:n,eventId:o,gender:i};Array.isArray(s)&&s.forEach(m=>Rs({event:u,timeItem:m}));let{eventAttributes:p}=a;if(typeof p!="object"&&(p={}),Object.assign(u,p),c?.length&&Array.isArray(c)){let m=c.filter(Yn);m?.length&&Object.assign(u,{extensions:m})}return u}function RJ({drawProfile:t,tournamentRecord:e,eventId:r,eventType:n,category:o,gender:i,tieFormatName:s,hydrateCollections:a,isMock:c}){if(Tt(t.tieFormat))return t.tieFormat;if(t.tieFormatId){let u=e?.events?.find(p=>p.eventId===r)?.tieFormats?.find(p=>p.tieFormatId===t.tieFormatId);if(u)return u}if(n===_t)return uo({event:{eventId:r,category:o,gender:i},namedFormat:s,hydrateCollections:a,isMock:c})}function bJ({allUniqueParticipantIds:t,targetParticipants:e,participantsCount:r,drawProfile:n,eventType:o,isHybrid:i}){let s=m=>{let{participantType:d}=m;return i&&(d===St||d===lt)||re(Dt)(o)&&d===St||re(Lt)(o)&&d===lt?!0:o===_t&&d===_t},a=m=>!n.gender||m.person?.sex===n.gender?!0:m.individualParticipantIds?.some(d=>{let l=e.find(f=>f.participantId===d);return l&&a(l)}),c=new Set(t),u=e.filter(s).filter(a).filter(({participantId:m})=>!c.has(m)),p=u.slice(0,r).map(m=>m.participantId);return{consideredParticipants:u,participantIds:p,isEventParticipantType:s,isEventGender:a}}var gO=()=>({altitude:void 0,courtId:void 0,courtName:"",courtDimensions:void 0,latitude:void 0,longitude:void 0,surfaceCategory:void 0,surfaceType:void 0,surfacedDate:void 0,indoorOutdoor:void 0,floodlit:void 0,dateAvailability:[],onlineResources:[],pace:void 0,notes:void 0}),cV=gO;function mg({tournamentRecord:t,disableNotice:e,venueId:r,courtId:n,court:o}){let{venue:i}=Ln({tournamentRecord:t,venueId:r});if(!i)return{error:wi};i.courts??=[];let s={...gO(),venueId:r,courtId:n};if(s.courtId||(s.courtId=it()),i.courts.some(c=>c.courtId===s.courtId))return{error:PU};{let c=(o?.dateAvailability??[]).map(m=>({...m,date:mt(m.date),startTime:$t(m.startTime),endTime:$t(m.endTime),bookings:m.bookings?.map(({startTime:d,endTime:l,bookingType:f})=>({startTime:$t(d),endTime:$t(l),bookingType:f}))})),u=Object.keys(s);for(let m of u)if(o?.[m])if(m==="dateAvailability"){let d=kp({dateAvailability:c});if(!d.valid&&d.error)return d;s.dateAvailability=c}else s[m]=o[m];let p=s;return i.courts.push(p),e||at({payload:{venue:i,tournamentId:t.tournamentId},topic:No,key:i.venueId}),{...P,court:q(s),venueId:r}}}function _h(t){let{tournamentRecord:e,venueId:r}=t;if(typeof r!="string"||!r)return{error:Ls};let n=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},o=[],i;for(let s of Object.values(n)){let{venue:a}=Ln({tournamentRecord:s,venueId:r});if(a){let c=CJ({...t,tournamentRecord:s});for(let u of c?.courts??[])o.push(u?.courtId);if(c.error)return c;i=!0}}return i?{...P,courtIds:o}:{error:wi}}function CJ({courtNameRoot:t="Court",dateAvailability:e=[],venueAbbreviationRoot:r,tournamentRecord:n,courtNames:o=[],courtTimings:i,courtsCount:s,startTime:a,courtIds:c,endTime:u,idPrefix:p,venueId:m,dates:d}){if(!m)return{error:Ls};let l=Ln({tournamentRecord:n,venueId:m});if(l.error)return l;let{venue:f}=l;if(!Le(s)||!o)return{error:AU};s=s??o.length;let S=Q(0,s).map(h=>{let T=i?.[h],y=T?d.map(E=>({date:Qn(E),startTime:a,endTime:u,...T})):e;return T&&a&&u&&y.push({startTime:a,endTime:u}),{courtName:o[h]||r&&f?.venueAbbreviation&&`${f?.venueAbbreviation} ${h+1}`||`${t} ${h+1}`,dateAvailability:y}}).map((h,T)=>{let y=c?.pop()||p&&`${p}-${T+1}`;return mg({disableNotice:!0,tournamentRecord:n,courtId:y,venueId:m,court:h})}).map(h=>h.court).filter(Boolean);return S.length!==s?M({info:"not all courts could be generated",result:{error:O}}):(f&&at({payload:{venue:f,tournamentId:n.tournamentId},topic:No,key:f.venueId}),{...P,courts:q(S)})}function dg({tournamentRecord:t,ignoreExistingVenues:e,venueProfiles:r,uuids:n}){let{startDate:o,endDate:i}=t,s=[];for(let[a,c]of r.entries()){let{venueAbbreviation:u,venueId:p=n?.pop()??it(),dateAvailability:m,venueDateAvailability:d,defaultStartTime:l,defaultEndTime:f,startTime:g="07:00",endTime:I="19:00",courtTimings:S,courtsCount:h,courtNames:T,venueName:y,idPrefix:E,courtIds:A}=c,N={venueName:y||`Venue ${a+1}`,venueAbbreviation:u,venueId:p};l&&(N.defaultStartTime=l),f&&(N.defaultEndTime=f),c.isPrimary&&(N.isPrimary=!0),d&&(N.dateAvailability=d);let D=yu({tournamentRecord:t,venue:N});if(D.error){if(e)continue;return D}s.push(p);let R=Ua(o,i),U=!Array.isArray(m)&&[{startTime:g,endTime:I}].concat(R.map(b=>({date:Qn(b),startTime:g,endTime:I})));if(h||T){let b=_h({dateAvailability:m||U,tournamentRecord:t,courtTimings:S,courtsCount:h,courtNames:T,startTime:g,idPrefix:E,courtIds:A,endTime:I,venueId:p,dates:R});if(b.error)return b}}return s}function uV(t){let{tournamentRecord:e,leagueProfiles:r,eventIds:n,venueIds:o,drawIds:i,allUniqueParticipantIds:s,random:a,uuids:c}=t,u=0;for(let m of r){let d=[],{tieFormatName:l=yI,teamProfiles:f=[],teamsCount:g=0,category:I,idPrefix:S,gender:h}=m,T=m.leagueName??m.eventName??`League ${u+1}`,y=m.leagueId??m.eventId??c?.pop()??it(void 0,a);n.push(y);let E=Tt(m.tieFormat)&&m.tieFormat||uo({event:{eventId:y,category:I,gender:h},namedFormat:l,isMock:t.isMock})||void 0;if(!E)return{error:ya};let A=Math.max(g,f.length),N=Q(0,A),{genders:D,teamSize:R}=pg({tieFormat:E,drawSize:A,random:a}),U={[Je]:0,[ds]:0,[ii]:0,[Ce]:0,ANY:0};Object.keys(D).forEach(_=>U[_]+=D[_]);for(let _ of N){let v=f?.[_]?.teamName??`Team ${_+1}`,w=f?.[_]?.teamId||c?.pop()||it(void 0,a),L=m.startDate??t.startDate,F=oc({...m?.participantsProfile,participantsCount:R,consideredDate:L,gendersCount:U,category:I,gender:h,random:a,uuids:c}).participants,x=F.map(H=>H.participantId),k=_t,G=w??$d({participantType:k,idPrefix:S,random:a,index:_,uuids:c});d.push({participantId:G,entryStatus:kr,entryStage:W});let V=f?.[_]?.venueIds??[],B={participantId:G,participantRole:Ve,participantName:v,individualParticipantIds:x,participantType:k,homeVenueIds:V};V.forEach(H=>!o.includes(H)&&o.push(H)),s.push(...x,G);let z=un({participants:[B,...F],tournamentRecord:e});if(z.error)return z}let C={eventName:T,entries:d,eventType:_t,tieFormat:E,category:I,eventId:y,gender:h};if(e.events??=[],e.events.push(C),d.length){let _=(Le(m.roundsCount)&&m.roundsCount)??m.roundsCount===Uy?(A-1)*2:A-1,v=xc({automated:m.automated,tournamentRecord:e,drawType:Ni,roundsCount:_,drawSize:A,event:C});if(v.error)return v;let{drawDefinition:w}=v;if(w){let L=w?.drawId;Gu({drawDefinition:w,event:C,suppressNotifications:!0}),i.push(L)}}u++}let p=o.map(m=>({venueId:m}));dg({tournamentRecord:e,ignoreExistingVenues:!0,venueProfiles:p,uuids:c})}var MJ=["Generated Tournament","CourtHive Challenge","Replication Crisis","Open Competition","Factory Follies","Mock Tournament","Atomic Culture","Racket Rally","Stats Fail"];function IO(t){let{startDate:e,endDate:r}=t??{},{tournamentName:n=Sr(MJ,t?.random),ratingsParameters:o=Ke,tournamentExtensions:i,policyDefinitions:s,schedulingProfile:a,venueProfiles:c,uuids:u}=t??{},p=t?.isMock===!1?void 0:!0;if(e&&!Me(e)||r&&!Me(r))return{error:ae};if(!xJ(t))return{error:O};({startDate:e,endDate:r}=wJ(e,r));let m=qd({...t.tournamentAttributes,tournamentName:n,startDate:e,endDate:r,isMock:p}),d=c?.length?dg({tournamentRecord:m,venueProfiles:c,uuids:u}):[];if(i?.length&&Array.isArray(i)){let y=i.filter(E=>Yn({extension:E}));y?.length&&Object.assign(m,{extensions:y,isMock:p})}if(typeof s=="object")for(let y of Object.keys(s))bs({policyDefinitions:{[y]:s[y]},tournamentRecord:m});if(!t?.leagueProfiles?.length||t.eventProfiles?.length||t.drawProfiles?.length||t.participantsProfile){let y=NN({tournamentRecord:m,...t});if(!y.success)return y}let f=[],g=[],I=[],S=LJ({allUniqueParticipantIds:f,ratingsParameters:o,tournamentRecord:m,params:t,eventIds:g,venueIds:d,drawIds:I});if(S?.error)return S;let{scheduledRounds:h=void 0,schedulerResult:T={}}=a?_J({...t,tournamentRecord:m}):{};return pI(),et({...P,tournamentRecord:m,scheduledRounds:h,schedulerResult:T,eventIds:g,venueIds:d,drawIds:I})}function vJ(t){let{tournamentRecord:e,drawProfiles:r,allUniqueParticipantIds:n,eventIds:o,drawIds:i}=t,s=0;for(let a of r){let c=zd({allUniqueParticipantIds:n,tournamentRecord:e,drawProfile:a,drawIndex:s,...t});if(c.error)return c;let{drawId:u,eventId:p,event:m,uniqueParticipantIds:d}=c;if(a?.addEvent!==!1){if(c=tc({suppressNotifications:!1,internalUse:!0,tournamentRecord:e,event:m}),c.error)return c;u&&i.push(u),o.push(p)}d?.length&&n.push(...d),s+=1}}function OJ(t){let{eventProfiles:e,allUniqueParticipantIds:r,eventIds:n,drawIds:o}=t,i=0;for(let s of e){let a=MN({...t,eventIndex:i,eventProfile:s});if(a.error)return a;let{eventId:c,drawIds:u,uniqueParticipantIds:p}=a;u&&o.push(...u),n.push(c),p?.length&&r.push(...p),i+=1}}function _J(t){let{schedulingProfile:e,tournamentRecord:r,autoSchedule:n,periodLength:o,scheduleCompletedMatchUps:i}=t,s=aV({schedulingProfile:e,tournamentRecord:r});if(s.error)return s;let a=s.scheduledRounds;if(n){let{tournamentId:c}=r,u={[c]:r};return{schedulerResult:jd({scheduleCompletedMatchUps:i,tournamentRecords:u,periodLength:o}),scheduledRounds:a}}return{scheduledRounds:a}}function xJ(t){return!(t.leagueProfiles&&!Array.isArray(t.leagueProfiles)||t.eventProfiles&&!Array.isArray(t.eventProfiles)||t.drawProfiles&&!Array.isArray(t.drawProfiles))}function wJ(t,e){let r=t,n=e;if(!r){let o=new Date;r=Qn(n??o),n=Qn(o.setDate(o.getDate()+7))}if(!n){let o=new Date(r);n=Qn(o.setDate(o.getDate()+7))}return{startDate:r,endDate:n}}function LJ({allUniqueParticipantIds:t,ratingsParameters:e,tournamentRecord:r,params:n,eventIds:o,venueIds:i,drawIds:s}){if(n.leagueProfiles){let a=uV({allUniqueParticipantIds:t,tournamentRecord:r,...n,eventIds:o,venueIds:i,drawIds:s});if(a?.error)return a}if(n.drawProfiles){let a=vJ({allUniqueParticipantIds:t,ratingsParameters:e,tournamentRecord:r,...n,eventIds:o,drawIds:s});if(a?.error)return a}if(n.eventProfiles){let a=OJ({allUniqueParticipantIds:t,ratingsParameters:e,tournamentRecord:r,...n,eventIds:o,drawIds:s});if(a?.error)return a}}var EO={};Gt(EO,{anonymizeTournamentRecord:()=>hO,completeDrawMatchUps:()=>$u,modifyTournamentRecord:()=>yO,removeMatchUpOutcome:()=>TO});function hO({keepExtensions:t=[],anonymizeParticipantNames:e=!0,tournamentRecord:r,tournamentName:n,personIds:o=[],tournamentId:i}){if(!r)return{error:j};let s=Array.isArray(t)?LR.concat(...t):LR,a=u=>Array.isArray(t)?u?.extensions?.filter(p=>s.includes(p.name)):u?.extensions,c={};return FJ({tournamentRecord:r,filterExtensions:a,idMap:c,tournamentId:i,tournamentName:n}),kJ({tournamentRecord:r,filterExtensions:a,idMap:c}),GJ({tournamentRecord:r,filterExtensions:a,idMap:c}),BJ({tournamentRecord:r,filterExtensions:a,idMap:c}),WJ({anonymizeParticipantNames:e,tournamentRecord:r,filterExtensions:a,personIds:o,idMap:c}),jJ({tournamentRecord:r}),qJ({tournamentRecord:r,idMap:c}),{...P}}function FJ({tournamentRecord:t,filterExtensions:e,idMap:r,tournamentId:n,tournamentName:o}){t.extensions=e(t);let i=n||it();r[t.tournamentId]=i,t.tournamentId=i,t.createdAt=new Date().toISOString(),t.tournamentName=o||`Anonymized: ${Qn(new Date)}`,t.isMock=!0,delete t.parentOrganisation}function kJ({tournamentRecord:t,filterExtensions:e,idMap:r}){for(let n of t.participants??[]){n.extensions=e(n),n.onlineResources=[];let o=it();r[n.participantId]=o,n.participantId=o}for(let n of t.participants??[])Array.isArray(n.individualParticipantIds)&&(n.individualParticipantIds=n.individualParticipantIds.map(o=>r[o]))}function GJ({tournamentRecord:t,filterExtensions:e,idMap:r}){let n=0;for(let o of t.venues??[]){o.venueAbbreviation=`V${n}`,o.extensions=e(o),o.venueName=`Venue #${n}`,o.onlineResources=[],o.addresses=[];let i=it();r[o.venueId]=i,o.isMock=!0,n+=1;let s=0;for(let a of o.courts??[])a.courtName=`V${n}C${s}`,a.extensions=e(a),a.onlineResources=[],a.isMock=!0,s+=1}}function VJ({drawDefinition:t,filterExtensions:e,idMap:r}){t.extensions=e(t);let n=it();if(r[t.drawId]=n,t.drawId=n,t.isMock=!0,Array.isArray(t.entries))for(let i of t.entries)i.participantId=r[i.participantId];let o=i=>{i.extensions=e(i);let s=it();r[i.structureId]=s,i.structureId=s;for(let a of i.positionAssignments??[])a.participantId&&(a.participantId=r[a.participantId]);for(let a of i.seedAssignments??[])a.participantId&&(a.participantId=r[a.participantId]);for(let a of i.matchUps??[]){a.isMock=!0;for(let c of a.sides??[])c.lineUp&&(c.lineUp=c.lineUp.map(({participantId:u,collectionAssignments:p})=>({participantId:r[u],collectionAssignments:p})))}};for(let i of t.structures??[])if(o(i),Array.isArray(i.structures))for(let s of i.structures)o(s);for(let i of t.links??[])i.source.structureId=r[i.source.structureId],i.target.structureId=r[i.target.structureId]}function BJ({tournamentRecord:t,filterExtensions:e,idMap:r}){let n=1;for(let o of t.events??[]){o.extensions=e(o),o.onlineResources=[],o.isMock=!0;let i=it();r[o.eventId]=i,o.eventId=i;let s=o.category?.categoryName||o.category?.ageCategoryCode||o.category?.ratingType||o.gender;if(o.eventName=`Event ${n} ${s}`,Array.isArray(o.entries))for(let c of o.entries)c.participantId=r[c.participantId];for(let c of o.drawDefinitions??[])VJ({drawDefinition:c,filterExtensions:e,idMap:r});let{extension:a}=ot({name:on,element:o});Array.isArray(a?.value?.flights)&&a?.value.flights?.forEach(c=>{if(c.drawId=r[c.drawId],Array.isArray(c.drawEntries))for(let u of c.drawEntries)u.participantId=r[u.participantId]}),n+=1}}function WJ({anonymizeParticipantNames:t,tournamentRecord:e,filterExtensions:r,personIds:n,idMap:o}){let i=e.startDate||Qn(new Date),s=(e.participants??[]).filter(({participantType:d})=>d===St),a=s.reduce((d,l)=>{let f=l.person?.sex,g=Ar(f);return g&&Un(f)?d[g]+=1:d[ii]+=1,d},{[Ce]:0,[Je]:0,[ii]:0}),c=Object.assign({},...Object.keys(a).map(d=>({[d]:AN({category:{ageCategoryCode:"O18"},count:a[d],addressProps:{citiesCount:10},personExtensions:[],consideredDate:i,sex:d})?.persons??[]}))),u={[Ce]:0,[Je]:0,[ii]:0},p=s.length,m=HJ(s,p);s.forEach((d,l)=>{YJ({anonymizeParticipantNames:t,individualParticipant:d,filterExtensions:r,participantIndex:l,genderedPersons:c,genderedIndices:u,addressValues:m,personIds:n,idMap:o})})}function HJ(t,e){let r=t.reduce((u,p)=>{let m=p.person?.addresses?.[0]??{},{city:d,state:l,postalCode:f}=m;return u.cities.includes(d)||u.cities.push(d),u.states.includes(l)||u.states.push(l),u.postalCodes.includes(f)||u.postalCodes.push(f),u},{cities:[],postalCodes:[],states:[]}),n=r.postalCodes.length,o=r.cities.length,i=r.states.length,{cities:s}=SN({count:o||e,participantsCount:e}),{states:a}=hN({count:i||e,participantsCount:e}),{postalCodes:c}=TN({count:n||e,participantsCount:e});return{cities:s,states:a,postalCodes:c}}function YJ({anonymizeParticipantNames:t,individualParticipant:e,filterExtensions:r,participantIndex:n,genderedPersons:o,genderedIndices:i,addressValues:s,personIds:a,idMap:c}){let u=e?.person,p=u?.sex||ii,m=mt(u?.birthDate)?.split("-")[0],d=i[p],l=o[p][d];if(i[p]+=1,m){let[,f,g]=l?.birthDate?.split("-")??[],I=[m,f,g].join("-");l.birthDate=I}if(u?.addresses){let f=yN({...s,participantIndex:n,nationalityCode:l.nationalityCode});l.addresses=[f]}l.personId=a?.[n]||it(),t?(l.standardFamilyName=l.lastName,l.standardGivenName=l.firstName,e.participantName=`${l.standardGivenName} ${l.standardFamilyName}`):(l.standardFamilyName=u?.standardFamilyName,l.standardGivenName=u?.standardGivenName),delete l.firstName,delete l.lastName,l.extensions=r(u),e.person=l,c[u?.personId]=l.personId}function jJ({tournamentRecord:t}){let e=(t.participants??[]).filter(({participantType:a})=>a===St);(t.participants??[]).filter(({participantType:a})=>a===lt).forEach(a=>{let{individualParticipantIds:c}=a;a.participantName=$J({individualParticipantIds:c,individualParticipants:e})});let n=(t.participants??[]).filter(({participantType:a})=>a===_t),o=Kd({count:n.length}).names;n.forEach((a,c)=>{a.participantName=o[c]});let i=(t.participants??[]).filter(({participantType:a})=>a===$r),s=Kd({count:i.length,nameRoot:"Group"}).names;i.forEach((a,c)=>{a.participantName=s[c]})}function qJ({tournamentRecord:t,idMap:e}){let{extension:r}=ot({element:t,name:hc});Array.isArray(r?.value)&&r?.value.forEach(o=>{o.tournamentId=e[o.tournamentId],o.structureId=e[o.structureId],o.eventId=e[o.eventId],o.drawId=e[o.drawId]});let{extension:n}=ot({element:t,name:Sc});Array.isArray(n?.value)&&n?.value.forEach(o=>{o.personId=e[o.personId]})}function $J({individualParticipantIds:t,individualParticipants:e}){let r=e.filter(({participantId:n})=>t.includes(n)).map(n=>n.person?.standardFamilyName||n.participantOtherName||n.participantName||"").filter(Boolean).sort().join("/");return t.length===1&&(r+="/Unknown"),r}function TO({tournamentRecord:t,drawId:e,matchUpId:r,event:n,drawDefinition:o}){if(!o&&e&&t){let i=_e({tournamentRecord:t,drawId:e});if(i.error)return i;o=i.drawDefinition,n||(n=i.event)}return wc({outcome:qa,tournamentRecord:t,drawDefinition:o,matchUpId:r,event:n})}function KJ({event:t,eventProfile:e,tournamentRecord:r,allUniqueParticipantIds:n,drawIds:o}){let{gender:i,category:s,eventType:a}=t,{drawProfiles:c,publish:u}=e,p=re(Dt)(a)&&St||re(Lt)(a)&<||a;if(c){let{stageParticipantsCount:m,uniqueParticipantsCount:d,uniqueParticipantStages:l}=DN({drawProfiles:c,category:s,gender:i}),{uniqueDrawParticipants:f=[],uniqueParticipantIds:g=[]}=l?bN({event:{eventType:a,category:s,gender:i},uniqueParticipantsCount:d,participantsProfile:e.participantsProfile,ratingsParameters:e.ratingsParameters,tournamentRecord:r,eventProfile:e,uuids:e.uuids}):{};n.push(...g);let{stageParticipants:I}=UN({targetParticipants:r.participants??[],allUniqueParticipantIds:n,stageParticipantsCount:m,eventParticipantType:p}),S=CN({uniqueDrawParticipants:f,autoEntryPositions:e.autoEntryPositions,stageParticipants:I,tournamentRecord:r,drawProfiles:c,category:s,gender:i,event:t});if(S.error||(S=RN({matchUpStatusProfile:e.matchUpStatusProfile,completeAllMatchUps:e.completeAllMatchUps,randomWinningSide:e.randomWinningSide,tournamentRecord:r,drawProfiles:c,isMock:e.isMock,event:t}),S.error))return S;o.push(...S.drawIds)}return u&&rc({tournamentRecord:r,event:t}),P}function pV(t,e){return t?.find((r,n)=>e.eventIndex!==void 0&&n===e.eventIndex||e.eventName&&r.eventName===e.eventName||e.eventId&&r.eventId===e.eventId)}function zJ({event:t,eventProfile:e,tournamentRecord:r,allUniqueParticipantIds:n,drawIds:o,params:i}){return KJ({event:t,eventProfile:{...e,...i},tournamentRecord:r,allUniqueParticipantIds:n,drawIds:o})}function QJ({eventProfile:t,tournamentRecord:e,allUniqueParticipantIds:r,eventIds:n,drawIds:o,params:i,eventIndex:s}){let a=MN({startDate:e.startDate,allUniqueParticipantIds:r,matchUpStatusProfile:i.matchUpStatusProfile,participantsProfile:i.participantsProfile,completeAllMatchUps:i.completeAllMatchUps,autoEntryPositions:i.autoEntryPositions,randomWinningSide:i.randomWinningSide,ratingsParameters:t.ratingsParameters,tournamentRecord:e,eventProfile:t,eventIndex:s,uuids:i.uuids});if(a.error)return a;let{eventId:c,drawIds:u,uniqueParticipantIds:p}=a;return u&&o.push(...u),n.push(c),p?.length&&r.push(...p),{eventIndexIncrement:1}}function XJ({eventProfiles:t,tournamentRecord:e,allUniqueParticipantIds:r,eventIds:n,drawIds:o,params:i}){let s=e.events?.length||0;for(let a of t){let c=pV(e.events,a);if(c){let u=zJ({event:c,eventProfile:a,tournamentRecord:e,allUniqueParticipantIds:r,drawIds:o,params:i});if(u?.error)return u}else{let u=QJ({eventProfile:a,tournamentRecord:e,allUniqueParticipantIds:r,eventIds:n,drawIds:o,params:i,eventIndex:s});if(u?.error)return u;s+=u?.eventIndexIncrement||1}}return P}function JJ({drawProfiles:t,tournamentRecord:e,allUniqueParticipantIds:r,eventIds:n,drawIds:o,params:i}){let s=(e.events??[]).flatMap(a=>a.drawDefinitions?.map(()=>1)??[]).reduce((a,c)=>a+c,0);for(let a of t){let c=zd({startDate:e.startDate,allUniqueParticipantIds:r,matchUpStatusProfile:i.matchUpStatusProfile,participantsProfile:i.participantsProfile,completeAllMatchUps:i.completeAllMatchUps,autoEntryPositions:i.autoEntryPositions,hydrateCollections:i.hydrateCollections,randomWinningSide:i.randomWinningSide,ratingsParameters:i.ratingsParameters,tournamentRecord:e,drawProfile:a,drawIndex:s,uuids:i.uuids});if(c.error)return c;let{drawId:u,eventId:p,event:m,uniqueParticipantIds:d}=c;if(c=tc({tournamentRecord:e,event:m,internalUse:!0}),c.error)return c;u&&o.push(u),n.push(p),d?.length&&r.push(...d),s+=1}return P}function ZJ({schedulingProfile:t,autoSchedule:e,periodLength:r,tournamentRecord:n}){let o=[],i={};if(t?.length){let s={[n.tournamentId]:n},a=Fu({tournamentRecords:s,schedulingProfile:t});if(a.error)return a;if(e){let{tournamentId:c}=n,u={[c]:n};i=jd({tournamentRecords:u,periodLength:r})}}return{scheduledRounds:o,schedulerResult:i}}function yO(t){let{participantsProfile:e={},schedulingProfile:r,tournamentRecord:n,autoSchedule:o,eventProfiles:i,periodLength:s,venueProfiles:a,drawProfiles:c,uuids:u}=t;if(!n)return{error:j};let p=[],m=[],d=[];i?.forEach(y=>{let E=pV(n.events,y);E?.gender&&(y.gender=E.gender)});let l=n.participants?.length||void 0;l&&e?.idPrefix&&(e.idPrefix=`${e.idPrefix}-${l}`);let f=NN({startDate:n.startDate,participantsProfile:e,tournamentRecord:n,eventProfiles:i,drawProfiles:c,uuids:u});if(!f.success)return f;if(i){let y=XJ({eventProfiles:i,tournamentRecord:n,allUniqueParticipantIds:p,eventIds:m,drawIds:d,params:t});if(y.error)return y}if(c){let y=JJ({drawProfiles:c,tournamentRecord:n,allUniqueParticipantIds:p,eventIds:m,drawIds:d,params:t});if(y.error)return y}let g=a?.length?dg({tournamentRecord:n,venueProfiles:a}):[],I=ZJ({tournamentRecord:n,schedulingProfile:r,autoSchedule:o,periodLength:s});if(I.error)return I;let{scheduledRounds:S,schedulerResult:h}=I;return{totalParticipantsCount:n.participants.length,scheduledRounds:S,schedulerResult:h,...P,eventIds:m,venueIds:g,drawIds:d}}var WO={};Gt(WO,{addDynamicRatings:()=>HS,addIndividualParticipantIds:()=>Vd,addParticipant:()=>Gn,addParticipants:()=>un,addPenalty:()=>GO,addPersonRequests:()=>NO,addPersons:()=>VO,createGroupParticipant:()=>vO,createTeamsFromParticipantAttributes:()=>Mh,deleteParticipants:()=>Ds,filterParticipants:()=>Hp,findParticipant:()=>MO,getCompetitionParticipants:()=>eP,getPairedParticipant:()=>Tn,getParticipantEventDetails:()=>rP,getParticipantMembership:()=>nP,getParticipantScaleItem:()=>Zi,getParticipantSchedules:()=>oP,getParticipantSignInStatus:()=>iP,getParticipantTimeItem:()=>tE,getParticipants:()=>bt,getScaleValues:()=>lc,mergeParticipants:()=>kO,modifyIndividualParticipantIds:()=>DO,modifyParticipant:()=>Bd,modifyParticipantName:()=>OO,modifyParticipantOtherName:()=>RO,modifyParticipantsSignInStatus:()=>UO,modifyPenalty:()=>LO,modifyPersonRequests:()=>AO,mutate:()=>BO,participantScaleItem:()=>Po,query:()=>KM,regenerateParticipantNames:()=>CO,removeIndividualParticipantIds:()=>lS,removeParticipantIdsFromAllTeams:()=>cd,removePenalty:()=>wO,removePersonRequests:()=>PO,removeRatings:()=>xO,scaledTeamAssignment:()=>_O,setParticipantScaleItem:()=>$a,setParticipantScaleItems:()=>oM,validateLineUp:()=>sf});var BO={};Gt(BO,{addDynamicRatings:()=>HS,addIndividualParticipantIds:()=>Vd,addParticipant:()=>Gn,addParticipants:()=>un,addPenalty:()=>GO,addPersonRequests:()=>NO,addPersons:()=>VO,createGroupParticipant:()=>vO,createTeamsFromParticipantAttributes:()=>Mh,deleteParticipants:()=>Ds,findParticipant:()=>MO,mergeParticipants:()=>kO,modifyIndividualParticipantIds:()=>DO,modifyParticipant:()=>Bd,modifyParticipantName:()=>OO,modifyParticipantOtherName:()=>RO,modifyParticipantsSignInStatus:()=>UO,modifyPenalty:()=>LO,modifyPersonRequests:()=>AO,regenerateParticipantNames:()=>CO,removeIndividualParticipantIds:()=>lS,removeParticipantIdsFromAllTeams:()=>cd,removePenalty:()=>wO,removePersonRequests:()=>PO,removeRatings:()=>xO,scaledTeamAssignment:()=>_O,setParticipantScaleItem:()=>$a,setParticipantScaleItems:()=>oM});function vN(t=0){(typeof t!="number"||isNaN(t))&&(t=0);let e=new Date;return e.setHours(e.getHours()+t),e.getTime().toString(36).slice(-6).toUpperCase()}function ON({personRequests:t,personId:e,requests:r}){t[e]||(t[e]=[]);let n=r.filter(({requestType:o})=>o).map(o=>{let{date:i,startTime:s,endTime:a}=o;return o.requestType===Yu&&(i=mt(i),s=$t(s),a=$t(a),i&&s&&a)?{date:i,startTime:s,endTime:a,requestType:o.requestType}:o}).filter(Boolean);for(let o of n)o.requestId=vN(),t[e].push(o);return{mergeCount:n.length}}function lg(t){let{tournamentRecords:e,personRequests:r}=t,n=X(t,[{[Ee]:!0}]);if(n.error)return n;if(!r)return{...P};let o=Object.values(e);for(let i of o){let s=i.participants??[],a=[];for(let c of Object.keys(r))if(ui({tournamentParticipants:s,personId:c})){let u=r[c];u.length&&a.push({personId:c,requests:u})}Object.keys(a).length&&ut({element:i,extension:{value:a,name:Sc}})}return{...P}}function AO(t){let{tournamentRecords:e,requests:r,personId:n}=t,o=X(t,[{[Ee]:!0},{requests:!0,[Ge]:ke,[Lr]:O}]);if(o.error)return o;let i=r.map(({requestId:u})=>u).filter(Boolean),{personRequests:s}=is({tournamentRecords:e}),a=u=>{s&&(s[u]=s[u].map(p=>{if(!i.includes(p.requestId))return p;let m=r.find(d=>d.requestId===p.requestId);if(m.requestType)return Object.assign(p,m)}).filter(Boolean))};if(n&&s?.[n])a(n);else if(s)for(let u of Object.keys(s))a(u);let c=r.filter(u=>!u.requestId);return c.length&&ON({personRequests:s,personId:n,requests:c}),lg({tournamentRecords:e,personRequests:s})}function PO(t){let{tournamentRecords:e,requestType:r,requestId:n,personId:o,date:i}=t,s=X(t,[{[Ee]:!0}]);if(s.error)return s;let{personRequests:a}=is({tournamentRecords:e}),c=p=>{a&&(a[p]=a[p].filter(m=>(!r||m.requestType!==r)&&(!n||m.requestId!==n)&&(!i||m.date!==i)),a?.[p]?.length||delete a[p])},u=!r&&!n&&!o&&!i;if(!u){if(o&&a?.[o])c(o);else if(a)for(let p of Object.keys(a))c(p)}return u||!a||!Object.keys(a).length?dr({name:Sc,tournamentRecords:e,discover:!0}):lg({tournamentRecords:e,personRequests:a})}function NO(t){let{tournamentRecords:e,personId:r,requests:n}=t,o=X(t,[{[Ee]:!0,[tL]:!0},{requests:!0,[Ge]:ke,[Lr]:O}]);if(o.error)return o;let{personRequests:i}=is({tournamentRecords:e}),{mergeCount:s}=ON({personRequests:i,personId:r,requests:n});return s&&i?lg({tournamentRecords:e,personRequests:i}):{error:O}}function DO({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:r}){let n="modifyIndividualParticipantIds";if(!r)return M({result:{error:j},stack:n});if(!e||!t)return M({result:{error:nt},stack:n});let o=r.participants??[],i=o.find(l=>l.participantId===e);if(!i)return M({result:{error:ee},stack:n});if(![_t,$r].includes(i.participantType))return M({result:{error:Dn},context:{participantType:i.participantType},stack:n});let s=t.filter(l=>o.find(g=>g.participantId===l)?.participantType!==St);if(s.length)return M({result:{error:_r,invalidParticipantIds:s},stack:n});let a=i.individualParticipantIds??[],c=t.filter(l=>!a.includes(l)),u=a.filter(l=>!t.includes(l)),p=Vd({individualParticipantIds:c,groupingParticipantId:e,tournamentRecord:r});if(p.error)return M({result:p,stack:n});let m=lS({individualParticipantIds:u,groupingParticipantId:e,tournamentRecord:r});if(m.error)return M({result:m,stack:n});let{topics:d}=vr();if(d.includes(tr)){let l=o.find(({participantId:f})=>f===e);at({topic:tr,payload:{tournamentId:r.tournamentId,participants:[l]}})}return{...p,...m}}function UO({tournamentRecord:t,participantIds:e,signInState:r}){let n=dt({tournamentRecord:t},[rt]);if(n.error)return n;if(!Array.isArray(e))return{error:nt};if(![vp,fb].includes(r))return{error:O,signInState:r};let i=t.participants??[];if(!i.length)return{error:zc};let s=i.map(gt),a=e.filter(m=>!s.includes(m));if(a.length)return{error:O,context:{invalidParticipantIds:a}};let c=[],u=new Date().toISOString();for(let m of i){let{participantId:d}=m;if(e.includes(d)){let f=ES({duplicateValues:!1,tournamentRecord:t,participantId:d,timeItem:{itemType:fu,itemValue:r,createdAt:u}});if(f.error)return f;c.push(m)}}let{topics:p}=vr();return c.length&&p.includes(tr)&&at({topic:tr,payload:{tournamentId:t.tournamentId,participants:c}}),{...P}}function RO({tournamentRecord:t,participantId:e,participantOtherName:r}){let n=dt({tournamentRecord:t,participantId:e},[rt,sr]);if(n.error)return n;let{participant:o}=Do({tournamentRecord:t,participantId:e});if(!o)return{error:ee};o.participantOtherName=r;let{topics:i}=vr();return i.includes(tr)&&at({topic:tr,payload:{tournamentId:t.tournamentId,participants:[o]}}),{...P}}function bO({personFormat:t,person:e}){let r=g=>g.replace(/\W/g,""),n=g=>/^[a-z]*$/.test(r(g)),o=g=>/^[A-Z]*$/.test(r(g)),i=g=>/^[LAST]{4}/.test(r(g)),s=g=>g.toLowerCase().indexOf("l")<g.toLowerCase().indexOf("f"),a=g=>g.indexOf(",")>=0,c=g=>g.toLowerCase().indexOf("f.")>=0,u=g=>g.toLowerCase().indexOf("f")<0,p=g=>g.indexOf(" ")>0;if(!e)return;let m=p(t)?" ":"",d=RE(e?.standardGivenName??""),l=RE(e?.standardFamilyName??"");if(!t)return`${d}${m}${l}`;c(t)&&!a(t)&&!s(t)&&(d=`${d[0]}.`),n(t)?(d=d.toLowerCase(),l=l.toLowerCase()):o(t)?(d=d.toUpperCase(),l=l.toUpperCase()):i(t)&&(l=l.toUpperCase());let f=`${d}${m}${l}`;return u(t)?f=l:s(t)&&(a(t)?f=`${l},${m}${d}`:f=`${l}${m}${d}`),f}function mV({participantMap:t,participant:e,formats:r}){let{participantType:n,individualParticipantIds:o,person:i}=e,s=n&&r[n];if(n!==ur&&s){let{personFormat:a,doublesJoiner:c}=s;n===St&&(i?.standardGivenName||i?.standardFamilyName)&&(e.participantName=bO({person:i,personFormat:a})),n===lt&&(e.participantName=o?.map(u=>{let p=t[u],m=p?.person;return m?.standardGivenName||m?.standardFamilyName?bO({person:m,personFormat:a}):p?.participantOtherName||p?.participantName||""}).filter(Boolean).join(c??"/"))}}function CO({tournamentRecord:t,formats:e}){if(!t)return{error:j};if(!Tt(e))return{error:nt};let r=t.participants??[],n=vT(r,"participantId");for(let o of r)mV({participant:o,participantMap:n,formats:e});return{...P}}function MO(t){let{tournamentRecord:e,policyDefinitions:r,contextProfile:n,participantId:o,personId:i}=t,s=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(typeof o!="string"&&typeof i!="string")return{error:nt,stack:"publicFindParticipant"};let a,c;for(let u of Object.values(s)){c=u.tournamentId;let p=u.participants??[];if(a=ui({tournamentParticipants:p,internalUse:!0,policyDefinitions:r,contextProfile:n,participantId:o,personId:i}),a)break}return{participant:a,tournamentId:c,...P}}function vO({individualParticipantIds:t=[],participantRoleResponsibilities:e,participantRole:r=Qb,tournamentRecord:n,participantId:o,groupName:i}){let s=dt({tournamentRecord:n},[rt]);if(s.error)return s;if(!i)return{error:nt,info:"Missing groupName"};if(!Array.isArray(t))return{info:"Invalid individualParticipantIds",error:O};let c=(bt({participantFilters:{participantTypes:[St]},tournamentRecord:n}).participants??[]).map(d=>d.participantId);for(let d of t)if(!c.includes(d))return{error:Dn,participantId:d};let u=et({participantId:o||it(),participantRoleResponsibilities:e,participantName:i,individualParticipantIds:t,participantType:$r,participantRole:r}),p=Gn({participant:u,tournamentRecord:n});if(p.error)return p;let{topics:m}=vr();return m.includes(Di)&&at({topic:Di,payload:{tournamentId:n.tournamentId,participants:[u]}}),{...P,participant:q(u)}}function OO({tournamentRecord:t,participantName:e,participantId:r}){let n=dt({tournamentRecord:t,participantId:r},[rt,sr]);if(n.error)return n;if(!e)return{error:nt,info:"Missing participantName"};let{participant:o}=Do({tournamentRecord:t,participantId:r});if(!o)return{error:ee};o.participantName=e;let{topics:i}=vr();return i.includes(tr)&&at({topic:tr,payload:{tournamentId:t.tournamentId,participants:[o]}}),{...P}}function tZ({teamParticipantIds:t,teamsCount:e,eventId:r,initialTeamIndex:n,scaledParticipants:o,scaleAttributes:i,individualParticipantIds:s}){if(!Array.isArray(t)&&!yt(e)&&!r||!yt(n)||o&&!Array.isArray(o)||i&&(typeof i!="object"||!Object.keys(i).length))return{error:O};if(!i&&!o.length||!o&&!(s&&i))return{error:nt,info:"Missing scaling details"}}function eZ({eventId:t,event:e,teamParticipantIds:r}){return t&&!r?e?.eventType!==Ze?{error:zn}:{teamParticipantIds:e?.entries?.filter(({entryStatus:n})=>n===kr).map(gt)}:{teamParticipantIds:r}}function rZ({tournamentRecord:t,orderedTeamParticipantIds:e}){let r=[];for(let n of t.participants??[]){let{participantId:o,participantType:i}=n;if(e.includes(o)){if(i!==ur)return{error:Dn,participant:n};r.push(n)}}return{relevantTeams:r}}function nZ({teamsCount:t,relevantTeams:e,teamNameBase:r,tournamentRecord:n}){if(t&&e.length<t){let o=t-(e?.length||0),i=r??"Team",s=Q(0,o).map(p=>({participantName:`${i} ${p+1}`,participantType:ur,participantRole:Ve})),{participants:a=[]}=un({participants:s,returnParticipants:!0,tournamentRecord:n}),c=new Set(a.map(gt)),u=n.participants?.filter(({participantId:p})=>c.has(p))??[];e.push(...u)}}function oZ({tournamentRecord:t,participantIdsToAssign:e,scaleAttributes:r,scaledParticipants:n}){for(let o of t.participants??[]){let{participantId:i,participantType:s}=o;if(!e.includes(i))continue;if(s!==St)return{error:Dn,participant:o};let a=Po({scaleAttributes:r,participant:o})?.scaleItem,c=r?.accessor?a?.scaleValue?.[r?.accessor]:a?.scaleValue;n.push({participantId:i,scaleValue:c})}if(!n.length)return{error:ee}}function iZ({scaledParticipants:t,relevantTeams:e}){let r=0;for(;r<t.length;){for(let n of e){if(r+1>t.length)break;let o=t[r];n.individualParticipantIds.push(o.participantId),r++}e.reverse()}}function sZ({tournamentRecord:t,relevantTeams:e}){let r=new Set(e.map(gt));for(let n of t.events??[]){if(n.eventType!==Ze)continue;let o=(n.entries??[]).filter(i=>r.has(i.participantId));for(let i of o){let a=e.find(u=>u.participantId===i.participantId)?.individualParticipantIds;n.entries=(n.entries??[]).filter(u=>!a.includes(u.participantId)),(n.drawDefinitions??[]).forEach(u=>{u.entries=(u.entries??[]).filter(p=>!a.includes(p.participantId))});let{flightProfile:c}=Bt({event:n});(c?.flights??[]).forEach(u=>{u.drawEntries=(u.drawEntries??[]).filter(p=>!a.includes(p.participantId))})}}}function _O({clearExistingAssignments:t=!0,individualParticipantIds:e,reverseAssignmentOrder:r,initialTeamIndex:n=0,scaledParticipants:o=[],teamParticipantIds:i,tournamentRecord:s,scaleAttributes:a,teamNameBase:c,teamsCount:u,eventId:p,event:m}){if(!s)return{error:j};let d=tZ({teamParticipantIds:i,teamsCount:u,eventId:p,initialTeamIndex:n,scaledParticipants:o,scaleAttributes:a,individualParticipantIds:e});if(d)return d;let l=eZ({eventId:p,event:m,teamParticipantIds:i});if(l.error)return l;if(i=l.teamParticipantIds,!i?.length&&!u)return{info:"Missing teamParticipantIds or teamsCount",error:nt};let f=e??o.map(({participantId:h})=>h);r&&(i?.reverse(),n+=1),n>(i?.length||0)-1&&(n=0);let g=i?.slice(n).concat(...i.slice(0,n))??[],I=rZ({tournamentRecord:s,orderedTeamParticipantIds:g});if(I.error)return I;let{relevantTeams:S}=I;if(nZ({teamsCount:u,relevantTeams:S,teamNameBase:c,tournamentRecord:s}),!S.length)return{error:nI};if(t)for(let h of S)h.individualParticipantIds=[];else{let h=new Set(S.flat());e?.length?f=f.filter(T=>!h.has(T)):o=o?.filter(({participantId:T})=>!h.has(T))}if(!e?.length&&!o?.length)return{error:xm,info:"Nothing to be done"};if(!o.length){let h=oZ({tournamentRecord:s,participantIdsToAssign:f,scaleAttributes:a,scaledParticipants:o});if(h)return h}o.sort((h,T)=>a?.sortOrder?(T?.scaleValue||0)-(h?.scaleValue||0):(h?.scaleValue||1/0)-(T?.scaleValue||1/0));for(let h of o)if(!h.participantId)return{error:O,scaledParticipant:h};return iZ({scaledParticipants:o,relevantTeams:S}),sZ({tournamentRecord:s,relevantTeams:S}),{...P,scaledParticipants:o}}function xO(t){let e=X(t,[{[rt]:!0,[bI]:!0},{ratingType:!1,[$e]:s=>Ke[s]}]);if(e.error)return e;let r=`${t.ratingType}.${Ep}`,n=t.asDynamic?r:t.ratingType,o=[ci,Lo,t.eventType,n].join("."),i=t.tournamentRecord.participants??[];for(let s of i)s.timeItems&&(s.timeItems=s.timeItems.filter(a=>a.itemType!==o));return{...P}}function wO(t){let{tournamentRecords:e}=t;if(typeof e!="object"||!Object.keys(e).length)return{error:kt};for(let r of Object.values(e)){let n=aZ({...t,tournamentRecord:r});if(n.error&&n.error!==sp)return n}return{...P}}function aZ({tournamentRecord:t,penaltyId:e}){let r=dt({tournamentRecord:t,penaltyId:e},[rt,yl]);if(r.error)return r;let n=t?.participants??[],o=[],i=!1,s;return n.forEach(a=>{let c=!1;a.penalties=(a.penalties??[]).filter(u=>(u.penaltyId===e&&(c=!0,i||(s=u,i=!0)),c&&o.push(a),u.penaltyId!==e))}),s&&at({topic:tr,payload:{tournamentId:t.tournamentId,participants:o}}),s?{...P,penalty:s}:{error:sp}}var cZ=({penaltyId:t=it()}={})=>({refereeParticipantId:void 0,penaltyCode:void 0,penaltyType:void 0,extensions:void 0,matchUpId:void 0,createdAt:void 0,issuedAt:void 0,notes:void 0,penaltyId:t}),_N=cZ;function LO(t){let{tournamentRecords:e}=t;if(typeof e!="object"||!Object.keys(e).length)return{error:kt};for(let r of Object.values(e)){let n=uZ({...t,tournamentRecord:r});if(n.error&&n.error!==sp||n.success)return n}return{error:sp}}function uZ({tournamentRecord:t,modifications:e,penaltyId:r}){let n=dt({tournamentRecord:t,penaltyId:r},[rt,yl]);if(n.error)return n;if(!e)return{error:O,modifications:e};let o=t?.participants??[],i=Object.keys(_N()).filter(u=>u!=="penaltyId"),s=Object.keys(e).filter(u=>i.includes(u));if(!s.length)return{error:Xc};let a,c=[];return o.forEach(u=>{let p=!1;u.penalties=(u.penalties??[]).map(m=>(m.penaltyId===r&&(p=!0,s.forEach(d=>Object.assign(m,{[d]:e[d]})),a??=m),m)),p&&c.push(u)}),a&&at({topic:tr,payload:{tournamentId:t.tournamentId,participants:c}}),a?{...P,penalty:a}:{error:sp}}function FO(t,e,r){return!t&&e?e:t&&!e||typeof t!="object"||typeof e!="object"?t:pt(Object.keys(t).concat(Object.keys(e))).reduce((o,i)=>{if(!e[i])o[i]=t[i];else if(!t[i])o[i]=e[i];else if(typeof t[i]!=typeof e[i])o[i]=e[i];else if(Array.isArray(t[i]))if(r===!0||Array.isArray(r)&&r.includes(i)){let s=pt(t[i].map(a=>JSON.stringify(a)).concat(e[i].map(a=>JSON.stringify(a)))).map(a=>JSON.parse(a));o[i]=s}else o[i]=e[i];else typeof t[i]=="object"?o[i]=FO(t[i],e[i],r):o[i]=e[i];return o},{})}function kO({participants:t=[],tournamentRecord:e,arraysToMerge:r}){if(!e)return{error:j};e.participants??=[];let n=t.filter(Vr(sr)).map(u=>({[u.participantId]:u})),o=Object.assign({},...n),i=[];e.participants=e.participants.map(u=>{if(o[u.participantId]){let p=FO(u,o[u.participantId],r);return i.push(p),p}return u});let s=e.participants.map(Vr(sr))??[],a=t.filter(({participantId:u})=>!s.includes(u)),{topics:c}=vr();return a.length&&(e.participants=e.participants.concat(...a),c.includes(Di)&&at({topic:Di,payload:{participants:a}})),i.length&&c.includes(tr)&&at({topic:tr,payload:{tournamentId:e.tournamentId,participants:i}}),{modifiedParticipantsCount:i.length,newParticipantsCount:a.length,...P}}function GO(t){let{tournamentRecord:e,participantIds:r}=t,n=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},o;for(let i of Object.values(n)){let a=(bt({tournamentRecord:i}).participants??[])?.map(gt).filter(c=>r.includes(c));a.length&&(o=pZ({...t,penaltyId:t.penaltyId??o,tournamentRecord:i,participantIds:a}).penaltyId)}return o?{...P,penaltyId:o}:{error:ee}}function pZ({refereeParticipantId:t,tournamentRecord:e,participantIds:r,penaltyCode:n,penaltyType:o,extensions:i,penaltyId:s,matchUpId:a,issuedAt:c,notes:u}){let p=dt({tournamentRecord:e,penaltyType:o},[rt,vy]);if(p.error)return p;if(!r)return{error:We};let d=(e?.participants??[]).filter(g=>r.includes(g.participantId));if(!d.length)return{error:ee};let l=new Date().toISOString(),f=Object.assign(_N({penaltyId:s}),{refereeParticipantId:t,penaltyCode:n,penaltyType:o,matchUpId:a,createdAt:l,issuedAt:c,notes:u});return Array.isArray(i)&&i.forEach(g=>ut({element:f,extension:g})),d.forEach(g=>{g.penalties??=[],g.penalties.push(f)}),at({topic:tr,payload:{tournamentId:e.tournamentId,participants:d}}),{...P,penaltyId:f.penaltyId}}function VO({participantRole:t=Ve,tournamentRecord:e,persons:r}){if(!e)return{error:j};if(!Array.isArray(r))return{error:O};if(!Object.keys(ef).includes(t))return{error:pU};let n=new Set((e.participants??[]).map(({person:f})=>f?.personId).filter(Boolean)),o=[],i=r.filter(f=>f&&(!f.personId||!n.has(f.personId))).map(f=>(f.personId??=it(),o.push(f.personId),f)),s=(f,g)=>Object.assign({},...Object.keys(f).filter(I=>!g.includes(I)).map(I=>({[I]:f[I]}))),a=i.map(f=>et({extensions:f.participantExtensions,timeItems:f.participantTimeItems,participantType:St,participantRole:t,person:s(f,["participantExtensions","participantTimeItems","pairedPersons"])})),c=0,u,p=un({participants:a,tournamentRecord:e});if(p.error)return p;u=p.addedCount||0;let m=[],d=bt({participantFilters:{participantTypes:[St]},tournamentRecord:e})?.participants??[];if(t===Ve&&r.filter(({pairedPersons:f})=>f).forEach(({personId:f,pairedPersons:g})=>{Array.isArray(g)&&g.forEach(I=>{let S=[f,I.personId].map(h=>ui({tournamentParticipants:d,personId:h})).filter(Boolean);if(S.length===2){let h=S.map(gt);m.push(et({extensions:I.participantExtensions,timeItems:I.timeItems,participantRole:Ve,individualParticipantIds:h,participantType:lt}))}})}),m.length){if(p=un({participants:m,tournamentRecord:e}),p.error)return p;c=p.addedCount||0}let l=u+c;return{...P,addedCount:l,newPersonIds:o}}var XO={};Gt(XO,{bulkUpdatePublishedEventIds:()=>hP,getAllEventData:()=>yP,getCourtInfo:()=>$l,getDrawData:()=>yf,getEventData:()=>tm,getEventPublishStatus:()=>Cr,getPublishState:()=>ra,getRoundVisibilityState:()=>TP,getTournamentPublishStatus:()=>Uc,getVenueData:()=>Eu,isEmbargoed:()=>Uo,isVisiblyPublished:()=>ro,mutate:()=>QO,publishEvent:()=>rc,publishEventSeeding:()=>HO,publishOrderOfPlay:()=>KO,publishParticipants:()=>$O,query:()=>nv,setEventDisplay:()=>tg,unPublishEvent:()=>zO,unPublishEventSeeding:()=>YO,unPublishOrderOfPlay:()=>qO,unPublishParticipants:()=>jO});var QO={};Gt(QO,{publishEvent:()=>rc,publishEventSeeding:()=>HO,publishOrderOfPlay:()=>KO,publishParticipants:()=>$O,setEventDisplay:()=>tg,unPublishEvent:()=>zO,unPublishEventSeeding:()=>YO,unPublishOrderOfPlay:()=>qO,unPublishParticipants:()=>jO});function HO({removePriorValues:t=!0,stageSeedingScaleNames:e,seedingScaleNames:r,tournamentRecord:n,status:o=br,drawIds:i=[],event:s}){let a=dt({tournamentRecord:n,event:s},[rt,ce]);if(a.error)return a;let c=Cr({event:s,status:o}),u=(c?.seeding?.seedingScaleNames||r)&&{...c?.seeding?.seedingScaleNames,...r},p=(c?.seeding?.stageSeedingScaleNames||e)&&{...c?.seeding?.stageSeedingScaleNames,...e},m=et({stageSeedingScaleNames:p,seedingScaleNames:u,published:!0,drawIds:i});return ec({statusObject:{seeding:m},removePriorValues:t,status:o,event:s}),at({topic:ub,payload:{tournamentId:n.tournamentId,eventId:s.eventId,drawIds:i}}),{...P}}function YO({removePriorValues:t=!0,seedingScaleNames:e,tournamentRecord:r,status:n=br,drawIds:o,stages:i,event:s}){let a=dt({tournamentRecord:r,event:s},[rt,ce]);if(a.error)return a;let c=Cr({event:s});if(c){let u=c.seeding;if(Array.isArray(i)&&u.stageSeedingScaleNames)for(let p of i)u.stageSeedingScaleNames[p]&&delete u.stageSeedingScaleNames[p];Array.isArray(e)&&u?.seedingScaleNames&&(u.seedingScaleNames=u.seedingScaleNames.filter(p=>!e.includes(p))),Array.isArray(o)&&u?.drawIds&&(u.drawIds=u.drawIds.filter(p=>!o.includes(p))),(!Object.values(u.stageSeedingScaleNames??{}).length&&!u.seedingScaleNames?.length&&!u.drawIds?.length||!i&&!e&&!o?.length)&&(delete u.stageSeedingScaleNames,delete u.seedingScaleNames,delete u.drawIds,u.published=!1),ec({statusObject:{seeding:u},removePriorValues:t,status:n,event:s})}return at({topic:zI,payload:{tournamentId:r.tournamentId,eventId:s.eventId}}),{...P}}function fg({tournamentRecord:t}){if(!tu(Ml))return;let e=Uc({tournamentRecord:t});if(!(e?.orderOfPlay?.published||e?.participants?.published)){for(let r of t.events??[]){let o=Cr({event:r})?.drawDetails??{};for(let i of r.drawDefinitions?.map(Tc)??[])if(Bp({drawDetails:o,drawId:i,ignoreEmbargo:!0}))return}at({topic:Ml,payload:{tournamentId:t.tournamentId}})}}function jO(t){let e=Dr(t);if(!Object.keys(e).length)return{error:kt};for(let r of Object.values(e)){let n=mZ({tournamentRecord:r,...t});if(n.error)return n}return{...P}}function mZ({removePriorValues:t=!0,tournamentRecord:e,status:r=br}){if(!e)return{error:j};let n=`${qo}.${$o}`,{timeItem:o}=Jr({element:e,itemType:n}),i=o?.itemValue||{[r]:{}};return i[r]&&delete i[r].participants,oo({timeItem:{itemValue:i,itemType:n},element:e,removePriorValues:t}),at({payload:{tournamentId:e.tournamentId},topic:db}),fg({tournamentRecord:e}),{...P}}function qO(t){let e=Dr(t);if(!Object.keys(e).length)return{error:kt};for(let r of Object.values(e)){let n=dZ({tournamentRecord:r,...t});if(n.error)return n}return{...P}}function dZ({removePriorValues:t=!0,tournamentRecord:e,status:r=br}){if(!e)return{error:j};let n=`${qo}.${$o}`,{timeItem:o}=Jr({element:e,itemType:n}),i=o?.itemValue||{[r]:{}};return i[r]&&delete i[r].orderOfPlay,oo({timeItem:{itemValue:i,itemType:n},element:e,removePriorValues:t}),at({topic:QI,payload:{tournamentId:e.tournamentId}}),fg({tournamentRecord:e}),{...P}}function $O(t){let e=Dr(t);if(!Object.keys(e).length)return{error:kt};for(let r of Object.values(e)){let n=lZ({tournamentRecord:r,...t});if(n.error)return n}return{...P}}function lZ({removePriorValues:t,tournamentRecord:e,status:r=br,embargo:n,columns:o,language:i}){if(!e)return{error:j};let s=`${qo}.${$o}`,{timeItem:a}=Jr({element:e,itemType:s}),c=a?.itemValue||{[r]:{}},u={published:!0};return n&&!Ra(n)?{error:ip}:(n&&(u.embargo=n),o&&(u.columns=o),c[r].participants=u,i&&(c[r].language=i),oo({timeItem:{itemValue:c,itemType:s},element:e,removePriorValues:t}),at({payload:{tournamentId:e.tournamentId},topic:mb}),{...P})}function KO(t){let e=Dr(t);if(!Object.keys(e).length)return{error:kt};for(let r of Object.values(e)){let n=fZ({tournamentRecord:r,...t});if(n.error)return n}return{...P}}function fZ({scheduledDates:t,removePriorValues:e,tournamentRecord:r,status:n=br,eventIds:o,embargo:i,language:s}){if(!r)return{error:j};let a=`${qo}.${$o}`,{timeItem:c}=Jr({element:r,itemType:a}),u=c?.itemValue||{[n]:{}},p={published:!0};return t!==void 0&&(p.scheduledDates=t),o!==void 0&&(p.eventIds=o),i&&!Ra(i)?{error:ip}:(i&&(p.embargo=i),u[n].orderOfPlay=p,s&&(u[n].language=s),oo({timeItem:{itemValue:u,itemType:a},element:r,removePriorValues:e}),at({topic:pb,payload:{tournamentId:r.tournamentId,scheduledDates:t,eventIds:o}}),{...P})}function zO({removePriorValues:t=!0,tournamentRecord:e,status:r=br,event:n}){let o=dt({tournamentRecord:e,event:n},[rt,ce]);if(o.error)return o;let i=`${qo}.${$o}`,{timeItem:s}=xp({itemType:i,event:n}),a=s?.itemValue||{[r]:{}};return delete a[r].structureIds,delete a[r].drawDetails,delete a[r].drawIds,Rs({event:n,timeItem:{itemValue:a,itemType:i},removePriorValues:t}),ec({statusObject:{structureIds:void 0,drawIds:void 0,seeding:void 0},removePriorValues:t,status:r,event:n}),at({topic:KI,payload:{tournamentId:e.tournamentId,eventId:n.eventId}}),fg({tournamentRecord:e}),{eventId:n.eventId,...P}}var wh={};Gt(wh,{applyTournamentRankingPoints:()=>e_,generateRankingList:()=>JO,getApplicableAwardProfileLevels:()=>vd,getAwardPoints:()=>Bf,getAwardProfile:()=>Md,getEventRankingPoints:()=>Od,getParticipantPoints:()=>ZO,getQualityWinPoints:()=>ih,getTournamentPoints:()=>Ja,mutate:()=>r_,query:()=>t_});var t_={};Gt(t_,{generateRankingList:()=>JO,getApplicableAwardProfileLevels:()=>vd,getAwardPoints:()=>Bf,getAwardProfile:()=>Md,getEventRankingPoints:()=>Od,getParticipantPoints:()=>ZO,getQualityWinPoints:()=>ih,getTournamentPoints:()=>Ja});function gg({awards:t,pointComponents:e,bestOfCount:r,maxResultsPerLevel:n,mandatoryRules:o}){let i=t.map(m=>{let d=0;for(let l of e)d+=typeof m[l]=="number"?m[l]:0;return{award:m,value:d}});i.sort((m,d)=>d.value-m.value);let s=i,a=[];if(n){let m={};s=[];for(let d of i){let l=d.award.level;l===void 0||!n[l]?s.push(d):(m[l]=(m[l]||0)+1,m[l]<=n[l]?s.push(d):a.push(d))}}if(o?.length)return gZ(s,a,r,o);let c=r>0?s.slice(0,r):s,u=[...r>0?s.slice(r):[],...a],p=c.reduce((m,d)=>m+d.value,0);return{counting:c,dropped:u,bucketTotal:p}}function gZ(t,e,r,n){let o=new Set;for(let d of n){let l=new Set(d.levels),f=[];for(let I=0;I<t.length;I++){let S=t[I].award.level;S!==void 0&&l.has(S)&&f.push(I)}let g=d.bestOfCount?f.slice(0,d.bestOfCount):f;for(let I of g)o.add(I)}let i=[],s=[];for(let d=0;d<t.length;d++)o.has(d)?i.push(t[d]):s.push(t[d]);let a,c;if(r>0){let d=Math.max(0,r-i.length);a=s.slice(0,d),c=s.slice(d)}else a=s,c=[];let u=[...i,...a],p=[...c,...e],m=u.reduce((d,l)=>d+l.value,0);return{counting:u,dropped:p,bucketTotal:m}}function JO({pointAwards:t,aggregationRules:e={},categoryFilter:r,asOfDate:n}){let{rollingPeriodDays:o,countingBuckets:i,tiebreakCriteria:s=[],minCountableResults:a=0,maxResultsPerLevel:c,bestOfCount:u}=e,p=IZ(t,r,o,n),m=SZ(p),d=[];for(let[l,f]of Object.entries(m)){let g=hZ({countingBuckets:i,minCountableResults:a,maxResultsPerLevel:c,bestOfCount:u,personId:l,awards:f});d.push(g)}return TZ(d,s),d}function IZ(t,e,r,n){let o=t;if(e&&(o=o.filter(i=>{if(e.ageCategoryCodes?.length){let s=i.category?.ageCategoryCode;if(!s||!e.ageCategoryCodes.includes(s))return!1}if(e.genders?.length){let s=i.category?.gender||i.gender;if(!s||!e.genders.includes(s))return!1}return!(e.eventTypes?.length&&(!i.eventType||!e.eventTypes.includes(i.eventType)))})),r&&n){let i=new Date(n);i.setDate(i.getDate()-r);let s=i.getTime();o=o.filter(a=>!a.endDate||new Date(a.endDate).getTime()>=s)}return o}function SZ(t){let e={};for(let r of t){let n=r.personId;n&&(e[n]||(e[n]=[]),e[n].push(r))}return e}function hZ({countingBuckets:t,minCountableResults:e,maxResultsPerLevel:r,bestOfCount:n,personId:o,awards:i}){let s=0,a=[],c=[],u;if(t?.length){u=[];for(let m of t){let{bucketName:d,eventTypes:l,pointComponents:f,bestOfCount:g,maxResultsPerLevel:I,mandatoryRules:S}=m,h=i;l?.length&&(h=h.filter(A=>A.eventType&&l.includes(A.eventType)));let{counting:T,dropped:y,bucketTotal:E}=gg({awards:h,pointComponents:f,bestOfCount:g,maxResultsPerLevel:I,mandatoryRules:S});s+=E,a.push(...T.map(A=>A.award)),c.push(...y.map(A=>A.award)),u.push({bucketName:d,countingResults:T.map(A=>A.award),droppedResults:y.map(A=>A.award),bucketTotal:E})}}else{let{counting:m,dropped:d,bucketTotal:l}=gg({awards:i,pointComponents:["points","qualityWinPoints"],bestOfCount:n||0,maxResultsPerLevel:r});s=l,a=m.map(f=>f.award),c=d.map(f=>f.award)}let p={personId:o,totalPoints:s,rank:0,meetsMinimum:a.length>=e,countingResults:a,droppedResults:c};return u&&(p.bucketBreakdown=u),p}function TZ(t,e){t.sort((n,o)=>o.totalPoints-n.totalPoints),e.length&&t.sort((n,o)=>{if(n.totalPoints!==o.totalPoints)return o.totalPoints-n.totalPoints;for(let i of e){let s=dV(i,n,o);if(s!==0)return s}return 0});let r=1;for(let n=0;n<t.length;n++){if(n>0&&t[n].totalPoints===t[n-1].totalPoints){let o=e.some(i=>dV(i,t[n-1],t[n])!==0);t[n].rank=o?r:t[n-1].rank}else t[n].rank=r;r=n+2}}function dV(t,e,r){switch(t){case"highestSingleResult":{let n=Math.max(0,...e.countingResults.map(i=>i.points||0));return Math.max(0,...r.countingResults.map(i=>i.points||0))-n}case"mostCountingResults":return r.countingResults.length-e.countingResults.length;case"mostWins":{let n=e.countingResults.reduce((i,s)=>i+(s.winCount||0),0);return r.countingResults.reduce((i,s)=>i+(s.winCount||0),0)-n}default:return 0}}function ZO({pointAwards:t,personId:e,aggregationRules:r={}}){let{countingBuckets:n,maxResultsPerLevel:o,bestOfCount:i}=r,s=t.filter(p=>p.personId===e);if(n?.length){let p=[],m=0;for(let d of n){let{bucketName:l,eventTypes:f,pointComponents:g,bestOfCount:I,maxResultsPerLevel:S,mandatoryRules:h}=d,T=s;f?.length&&(T=T.filter(N=>N.eventType&&f.includes(N.eventType)));let{counting:y,dropped:E,bucketTotal:A}=gg({awards:T,pointComponents:g,bestOfCount:I,maxResultsPerLevel:S,mandatoryRules:h});m+=A,p.push({bucketName:l,countingResults:y.map(N=>N.award),droppedResults:E.map(N=>N.award),bucketTotal:A})}return{buckets:p,totalPoints:m}}let{counting:a,dropped:c,bucketTotal:u}=gg({awards:s,pointComponents:["points","qualityWinPoints"],bestOfCount:i||0,maxResultsPerLevel:o});return{buckets:[{bucketName:"All",countingResults:a.map(p=>p.award),droppedResults:c.map(p=>p.award),bucketTotal:u}],totalPoints:u}}var r_={};Gt(r_,{applyTournamentRankingPoints:()=>e_});function e_({tournamentRecord:t,policyDefinitions:e,participantFilters:r,scaleName:n="RANKING_POINTS",level:o,removePriorValues:i}){if(!t)return{error:j};let s=Ja({tournamentRecord:t,policyDefinitions:e,participantFilters:r,level:o});if(s.error)return s;let{personPoints:a,pairPoints:c,teamPoints:u}=s,p={};for(let l of t.participants??[])l.person?.personId&&(p[l.person.personId]=l.participantId);let m=t.endDate,d=0;for(let[l,f]of Object.entries(a)){let g=p[l];if(!g)continue;let I={};for(let S of f){let h=S.eventType||"SINGLES";I[h]||(I[h]=[]),I[h].push(S)}for(let[S,h]of Object.entries(I)){let T=h.reduce((A,N)=>A+(N.points||0)+(N.qualityWinPoints||0)+(N.linePoints||0),0),E=$a({tournamentRecord:t,participantId:g,scaleItem:{scaleType:Jn,scaleName:n,eventType:S,scaleDate:m,scaleValue:{points:T,awards:h}},removePriorValues:i});if(E.error)return E;d++}}return{...P,personPoints:a,pairPoints:c,teamPoints:u,modificationsApplied:d}}var o_={};Gt(o_,{buildReportContext:()=>gV,generateReport:()=>RV,getAvailableReports:()=>fV,getEntryStatusReports:()=>VN,getParticipantStats:()=>wN,getStructureReports:()=>BN,getVenuesReport:()=>WN});function wN({withCompetitiveProfiles:t,opponentParticipantId:e,withIndividualStats:r,teamParticipantId:n,tournamentRecord:o,withScaleValues:i,tallyPolicy:s,matchUps:a}){if(!o)return{error:j};if(a&&!Array.isArray(a))return{error:cr};if(a=a??qt({tournamentRecord:o,participantsProfile:i?{withScaleValues:i}:void 0}).matchUps,!a?.length)return{error:Bn};let u=[];e&&u.push(e),n&&u.push(n);let p=u.length?{participantIds:u}:{participantTypes:[ur]},m=bt({participantFilters:p,tournamentRecord:o}).participants??[];if(!m.every(({participantType:y})=>y===ur))return{error:_r};u.length||u.push(...m.map(gt));let d=new Map,l=new Map,f=new Map,g=new Map,I=(y,E="")=>l.get(y)||l.set(y,{participantName:E,participantId:y,competitorIds:[],competitiveness:{},matchUpStatuses:{},tiebreaks:[0,0],matchUps:[0,0],points:[0,0],games:[0,0],sets:[0,0]})&&l.get(y);for(let y of m){let{participantId:E,individualParticipantIds:A}=y;g.set(E,A??[]),I(E,y.participantName)}if(n&&!g.get(n))return M({result:{error:ee},context:{teamParticipantId:n}});if(e&&!g.get(e))return M({result:{error:ee},context:{opponentParticipantId:e}});let S=[];for(let y of a){if(!Tt(y))return{error:cr};let{matchUpStatus:E,matchUpFormat:A,matchUpType:N,winningSide:D,score:R,sides:U}=y;if(!U||!R||N===Ir||E==="BYE")continue;let b=yZ({sides:U,participantDetails:d,participantStats:l,teamMap:g,withIndividualStats:r,teamParticipantId:n,opponentParticipantId:e});if(!b.filter(Boolean).length)continue;let C=t&&D&&js({matchUp:y})?.competitiveness;S.push(y);let _=pS({matchUpStatus:E,matchUpFormat:A,tallyPolicy:s,winningSide:D,score:R}),v=PE({matchUpStatus:E,matchUpFormat:A,tallyPolicy:s,winningSide:D,score:R}),{pointsTally:w,tiebreaksTally:L}=NE({matchUpFormat:A,score:R});PZ({tallies:{setsTally:_,gamesTally:v,pointsTally:w,tiebreaksTally:L},sideParticipantIds:b,participantDetails:d,competitiveness:C,matchUpStatus:E,winningSide:D,initStats:I})}let h=bZ(l,f);n||CZ(l,h);let T={relevantMatchUps:S,...P};return n?(T.teamStats=l.get(n),e&&(T.opponentStats=l.get(e))):T.participatingTeamsCount=f.size,T.allParticipantStats=[...l.values()],T}function xN({side:t,individualParticipantIds:e}){return t.participantId&&(!e?.length||e.includes(t.participantId))&&[t.participantId]||t.participant?.individualParticipantIds?.length&&(!e?.length||Yt(e,t.participant?.individualParticipantIds).length===t.participant?.individualParticipantIds?.length)&&t.participant.individualParticipantIds}function yZ({sides:t,participantDetails:e,participantStats:r,teamMap:n,withIndividualStats:o,teamParticipantId:i,opponentParticipantId:s}){let a=[[],[]];for(let c of t){let u=c.participant;if(u?.participantName){e.set(u.participantId,{participantName:u.participantName,ratings:u.ratings});let p=r.get(u.participantId);p&&(p.participantName=u.participantName)}}if(n.size)EZ({sides:t,sideParticipantIds:a,participantStats:r,teamMap:n,withIndividualStats:o,teamParticipantId:i,opponentParticipantId:s});else if(o)for(let c of t){if(!c.participant)continue;let u=xN({individualParticipantIds:[],side:c}),p=c.sideNumber;p&&(a[p-1]=u)}return a}function EZ({sides:t,sideParticipantIds:e,participantStats:r,teamMap:n,withIndividualStats:o,teamParticipantId:i,opponentParticipantId:s}){let a=(c,u)=>{for(let p of t){if(!p.participant)continue;let m=xN({individualParticipantIds:u,side:p});if(m?.length){let d=p.sideNumber;if(!d)continue;let l=[c];o&&l.push(...m),e[d-1]=l;let f=r.get(c);for(let g of m.filter(Boolean))f&&!f.competitorIds.includes(g)&&f.competitorIds.push(g)}}};if(i)(!s||t.every(u=>u.participant&&(xN({individualParticipantIds:n.get(i),side:u})||xN({individualParticipantIds:n.get(s),side:u}))))&&a(i,n.get(i));else for(let[c,u]of n)a(c,u)}var lV=["tiebreaks","matchUps","points","games","sets"],AZ=["competitive","routine","decisive"];function PZ({tallies:t,sideParticipantIds:e,participantDetails:r,competitiveness:n,matchUpStatus:o,winningSide:i,initStats:s}){e.forEach((a,c)=>{for(let u of a){let p=r.get(u)?.participantName,m=s(u,p);m&&(NZ({stats:m,tallies:t,index:c}),DZ({stats:m,winningSide:i,index:c}),UZ({stats:m,competitiveness:n,index:c}),RZ({stats:m,matchUpStatus:o}))}})}function NZ({stats:t,tallies:e,index:r}){let{setsTally:n,gamesTally:o,pointsTally:i,tiebreaksTally:s}=e,a=(c,u)=>u.forEach((p,m)=>t[c][m]+=p);a("tiebreaks",r?[...s].reverse():s),a("points",r?[...i].reverse():i),a("games",r?[...o].reverse():o),a("sets",r?[...n].reverse():n)}function DZ({stats:t,winningSide:e,index:r}){if(e){let n=e-1===r?0:1;t.matchUps[n]+=1}}function UZ({stats:t,competitiveness:e,index:r}){if(e){let n=e.toLowerCase();t.competitiveness[n]||(t.competitiveness[n]=[0,0]),t.competitiveness[n][r]+=1}}function RZ({stats:t,matchUpStatus:e}){if(e){let r=e.toLowerCase();t.matchUpStatuses[r]||(t.matchUpStatuses[r]=0),t.matchUpStatuses[r]+=1}}function bZ(t,e){let r=new Map,n=(o,i)=>(o??0)+(i??0);for(let[o,i]of t.entries()){for(let s of lV){let a=i[s].reduce(n);if(a){let c=i[s][0]/a,u=`${s}Ratio`,p=parseFloat(c.toFixed(2));i[u]=p,e.set(o,!0),r.has(u)||r.set(u,[]),r.get(u)?.push(p)}}for(let s of AZ){let a=i.competitiveness?.[s]?.reduce(n);if(a){let c=i.competitiveness[s][0]/a,u=`${s}Ratio`,p=parseFloat(c.toFixed(2));i[u]=p}}}return r}function CZ(t,e){let r=(n,o)=>o-n;for(let n of t.values())for(let o of lV){let i=`${o}Ratio`;if(typeof n[i]=="number"){let s=e.get(i)?.sort(r).indexOf(n[i]);if(typeof s=="number"&&s>=0){let a=`${o}Rank`;n[a]=s+1}}}}var n_={};Gt(n_,{COMPETITIVENESS_REPORT:()=>Tm,DRAW_REVISIONS_REPORT:()=>LN,ENTRY_STATUS_REPORT:()=>mm,MATCHUP_STATUS_REPORT:()=>Sm,MATCH_RESULTS_REPORT:()=>Im,MUTATION_LOG_REPORT:()=>kN,PARTICIPANT_RESULTS_REPORT:()=>fm,PARTICIPANT_STATS_REPORT:()=>lm,POSITION_CHANGES_REPORT:()=>GN,REPORT_CATEGORIES:()=>Oi,REPORT_SOURCE:()=>Ig,SCHEDULING_CHURN_REPORT:()=>FN,SEEDING_PERFORMANCE_REPORT:()=>hm,STRUCTURE_REPORT:()=>dm,VENUE_UTILIZATION_REPORT:()=>gm});var mm="entries.entryStatus",dm="structure.drawReport",lm="participant.teamStats",fm="participant.results",gm="venue.utilization",Im="matchUp.results",Sm="matchUp.statusSummary",hm="participant.seedingPerformance",Tm="matchUp.competitiveness",LN="audit.drawRevisions",FN="audit.schedulingChurn",kN="audit.mutationLog",GN="audit.positionChanges",Oi={ENTRIES:"Entries",DRAWS:"Draws",MATCHUPS:"MatchUps",PARTICIPANTS:"Participants",SCHEDULING:"Scheduling",AUDIT:"Audit"},Ig={FACTORY:"factory",SERVER:"server"};var MZ=[{reportId:mm,name:"Entry Status Report",description:"Entry statuses and participant details across all events and draws",category:Oi.ENTRIES},{reportId:dm,name:"Draw Structure Report",description:"Draw structures with size, matchUp counts, winners, and seeding basis",category:Oi.DRAWS},{reportId:Im,name:"Match Results",description:"All completed match results by round with scores",category:Oi.MATCHUPS},{reportId:Sm,name:"MatchUp Status Summary",description:"Completed, walkovers, defaults, and retirements aggregated by event",category:Oi.MATCHUPS},{reportId:Tm,name:"Match Competitiveness",description:"Competitive profile of each match \u2014 decisive, routine, or competitive",category:Oi.MATCHUPS},{reportId:fm,name:"Participant Results",description:"Per-participant wins, losses, sets, and games across all events",category:Oi.PARTICIPANTS},{reportId:hm,name:"Seeding Performance",description:"Seeded participants \u2014 expected vs actual finishing position",category:Oi.PARTICIPANTS},{reportId:lm,name:"Team Statistics",description:"Team participant win/loss statistics across matchUps, sets, games, and tiebreaks",category:Oi.PARTICIPANTS},{reportId:gm,name:"Venue Utilization",description:"Court availability and scheduling utilization by venue and date",category:Oi.SCHEDULING},{reportId:kN,name:"Mutation Log",description:"Chronological log of all server mutations with user attribution",category:Oi.AUDIT,source:Ig.SERVER},{reportId:LN,name:"Draw Revision History",description:"Timeline of draw changes \u2014 position assignments, seeding, generation",category:Oi.AUDIT,source:Ig.SERVER},{reportId:FN,name:"Scheduling Churn",description:"Scheduling changes \u2014 bulk schedules, reschedules, clears",category:Oi.AUDIT,source:Ig.SERVER},{reportId:GN,name:"Position Changes",description:"Draw position assignment changes over time",category:Oi.AUDIT,source:Ig.SERVER}];function fV({tournamentRecord:t}){if(!t)return{error:j};let e=(t.events?.length??0)>0,r=(t.venues?.length??0)>0,n=(t.events??[]).some(c=>(c.drawDefinitions??[]).some(u=>(u.structures??[]).some(p=>(p.positionAssignments??[]).length>0))),o=(t.events??[]).some(c=>(c.drawDefinitions??[]).some(u=>(u.structures??[]).some(p=>(p.seedAssignments??[]).length>0))),i=(t.participants??[]).some(c=>c.participantType===ur),s={[mm]:e,[dm]:e,[Im]:n,[Sm]:n,[Tm]:n,[fm]:n,[hm]:o,[lm]:i,[gm]:r,[kN]:!0,[LN]:!0,[FN]:!0,[GN]:!0};return{availableReports:MZ.map(c=>({...c,computableNow:s[c.reportId]??!1}))}}function Qd({participant:t,eventType:e}){let r=t?.person?.personId,n=t?.person?.personOtherIds?.[0],o=t?.person?.tennisId,i=t?.ratings?.[e]?.find(({scaleName:u})=>u==="WTN"),s=i?.scaleValue,{wtnRating:a,confidence:c}=s??{};return{timeStamp:i?.scaleDate,personOtherId:n,confidence:c,wtnRating:a,personId:r,tennisId:o}}function VN({tournamentRecord:t}){if(!t)return{error:j};let e=t.tournamentId,{participantMap:r}=bt({withScaleValues:!0,withEvents:!0,withSeeding:!0,tournamentRecord:t,withDraws:!0}),o=(qt({matchUpFilters:{matchUpTypes:[Os,ei]},tournamentRecord:t}).matchUps??[]).flatMap(({sides:f,matchUpType:g})=>f?.flatMap(I=>g===ei?I?.participant?.individualParticipantIds:I?.participant?.participantId||I.participantId).filter(Boolean)).filter(Boolean),i=[],s={},a={},c={},u=0,p=({id:f,entry:g,eventId:I,eventType:S})=>{let{qualifyingSeeding:h,mainSeeding:T,entryStatus:y,entryStage:E,drawId:A}=g;s[f]||(s[f]=[]);let{participant:N,events:D}=r?.[f]??{},R=Qd({participant:N,eventType:S}),U=D?.[I]?.ranking;y===wS&&i.push(f),s[f].push({participantType:N?.participantType,participantId:f,tournamentId:e,eventType:S,eventId:I,drawId:A,entryStatus:y,entryStage:E,...R,ranking:U,mainSeeding:T,qualifyingSeeding:h})};for(let f of t.events??[]){let g={},I=R=>{g[R]||(g[R]={count:0}),g[R].count+=1},{drawDefinitions:S=[],eventType:h,eventId:T}=f,y=S.flatMap(R=>{let{drawId:U,entries:b}=R;u+=1;let C=({stage:F,stageSequence:x})=>F===W&&x===1||F===Z,v=(R.structures??[]).filter(C).flatMap(({positionAssignments:F})=>F).filter(Boolean).map(({participantId:F})=>F),w=({participantId:F})=>v.includes(F),L=F=>{let{participantId:x,entryStatus:k,entryStage:G}=F;I(k);let V=r?.[x]?.draws?.[U]?.seedAssignments,B=V?.[W]?.seedValue??V?.[W]?.seedNumber;return{qualifyingSeeding:V?.[Z]?.seedValue??V?.[Z]?.seedNumber,participantId:x,mainSeeding:B,entryStatus:k,entryStage:G,drawId:U}};return b?.filter(w).map(L)}),E=R=>{let U=R.participantId,b=r?.[U].participant.individualParticipantIds?.filter(C=>o.includes(C));return U&&{[U]:{individualParticipantIds:b}}};h===si?(()=>{let R=Object.assign({},...y.map(E).filter(Boolean)),U=b=>{R[b.participantId].individualParticipantIds.forEach(C=>{p({id:C,eventType:h,eventId:T,entry:b})})};y.forEach(U)})():y.forEach(R=>{p({id:R?.participantId,eventType:h,eventId:T,entry:R})});let N=Object.values(g).reduce((R,U)=>R+U.count,0);Object.keys(g).forEach(R=>{g[R].pct=g[R].count/N*100}),c[T]={tournamentId:e,eventId:T,entries:y,entryStatuses:g};let D=Object.assign({},...yr.flatMap(R=>[{[R+"_count"]:g[R]?.count},{[R+"_pct"]:g[R]?.pct}]));a[T]={tournamentId:e,eventId:T,...D}}let m=Object.values(r??{}).filter(({participant:{participantType:f,participantRole:g}})=>f===St&&g===Ve),d=m.filter(({participant:f})=>!o.includes(f.participantId)).map(({participant:f})=>f.participantId),l={nonParticipatingEntriesCount:d.length,individualParticipantsCount:m.length,eventsCount:Object.values(c).length,nonParticipatingParticipantIds:d,drawDefinitionsCount:u,tournamentId:e};return{entryStatusReports:Object.values(a).flat(),participantEntryReports:Object.values(s).flat(),eventReports:Object.values(c).flat(),withDrawnParticipantIds:i,tournamentEntryReport:l}}function gV({tournamentRecord:t}){if(!t)return{error:j};let{participantMap:e}=bt({withScaleValues:!0,withSeeding:!0,withEvents:!0,withDraws:!0,tournamentRecord:t}),{matchUps:r}=qt({tournamentRecord:t});return{venues:t.venues??[],participantMap:e??{},matchUps:r??[],tournamentRecord:t}}function IV({eventType:t,matchUps:e,eventId:r,drawId:n}){let o={},i=g=>{let I=g?.matchUpFormat;I&&(o[I]||(o[I]=0),o[I]+=1)},s=e.filter(g=>r?g.eventId===r:g.drawId===n).reduce((g,I)=>(i(I),(I.sides??[]).flatMap(S=>(S?.participant?.individualParticipants||[S?.participant]).filter(Boolean)).forEach(S=>g[S.participantId]=S),g),{}),a=Object.values(s),c=a.map(g=>Qd({participant:g,eventType:t})).filter(({wtnRating:g})=>g),u=(a.length-c.length)/a.length*100,p=c.reduce((g,I)=>{let{wtnRating:S,confidence:h}=I;return g.totalWTN+=S,g.totalConfidence+=h,g},{totalWTN:0,totalConfidence:0}),m=c?.length?p.totalWTN/c.length:0,d=c?.length?p.totalConfidence/c.length:0,f=Object.values(o).reduce((g,I)=>g+(I||0),0);return{matchUpFormatCounts:o,matchUpsCount:f,avgConfidence:d,pctNoRating:u,avgWTN:m}}function BN(t){let{tournamentRecord:e,extensionProfiles:r,firstFlightOnly:n,firstStageSequenceOnly:o=!0}=t;if(!e)return{error:ac};let i=[],s={},a={},c=[],u=S=>h=>h.structureId===S,p=Object.assign({},...(r??[]).map(({name:S,label:h,accessor:T})=>{let y=ot({element:e,name:S})?.extension?.value,E=T?Bi({element:y,accessor:T})?.value:y;return{[h??S]:E}})),m=e?.tournamentId,l=qt({participantsProfile:{withScaleValues:!0},tournamentRecord:e}).matchUps??[],f=S=>Jr({itemType:GI,itemSubTypes:[Eo],element:{timeItems:S}})?.timeItem?.itemValue?.scaleBasis,g=({positionManipulations:S})=>{S?.forEach(h=>{let{structureId:T,name:y}=h,E=h.drawPositions??[h.drawPosition];s[T]??=[],s[T].push(`${y}: ${E.join("/")}`)})},I=e?.events?.flatMap(({timeItems:S,drawDefinitions:h=[],extensions:T,eventType:y,eventName:E,eventId:A,category:N})=>{let R=T?.find(F=>F.name===on)?.value?.flights?.map(F=>({[F.drawId]:F.flightNumber})),U=R&&Object.assign({},...R),b=T?.find(F=>F.name===Ic),C=S?.find(F=>F.itemType===Ic),_=b?.value?.length??C?.itemValue??0,v=Object.values(U??{}),w=U&&Math.min(...v),L=f(S);return a[A]={seedingBasis:L?JSON.stringify(L):void 0,totalPositionManipulations:0,maxPositionManipulations:0,generatedDrawsCount:0,drawDeletionsCount:_,tournamentId:m,eventId:A},h.filter(F=>!n||!R||U[F.drawId]===w).flatMap(F=>{let{matchUpFormat:x,tieFormat:k,timeItems:G,extensions:V,structures:B,drawName:z,drawType:H,drawId:K}=F,{matchUpFormatCounts:Y,matchUpsCount:J,avgConfidence:ct,pctNoRating:Et,avgWTN:Ht}=IV({eventType:y,matchUps:l,drawId:K}),Ut=f(G)??L,pe=vZ({extensions:V}),ye=pe?.length??0;return g({positionManipulations:pe}),a[A].totalPositionManipulations+=ye,a[A].generatedDrawsCount+=1,ye>a[A].maxPositionManipulations&&(a[A].maxPositionManipulations=ye),B?.filter(Jt=>(Jt.stageSequence===1||!o)&&[Z,W,me,Vt].includes(Jt.stage)).map(Jt=>{let pr=[W,Vt].includes(Jt.stage)?OZ(l,Jt.structureId):void 0;Jt.stage===W&&i.push({eventName:E,drawName:z,structureId:Jt.structureId});let zr=_Z(pr)?.participant,so=xZ(zr),Zo=wZ(zr),ti=Qd({participant:Zo?.[0]??zr,eventType:y}),{personId:la,personOtherId:fa,tennisId:ga,confidence:bm,wtnRating:Gc}=ti??{},Cm=Qd({participant:Zo?.[1],eventType:y}),{personId:we,personOtherId:Ai,tennisId:as,confidence:ic,wtnRating:An}=Cm??{},{ageCategoryCode:Vc,categoryName:tp,subType:Ia}=N??{},Vn=Jt.matchUpFormat??x,TD=(Y[Vn]??0)/J*100,{tieFormatName:RT,tieFormatDesc:_g}=Wf(k),{tieFormatName:yD,tieFormatDesc:Bc}=Wf(Jt.tieFormat),sc=_g===Bc,ED=!sc&&yD,Sa=Jt.tieFormat&&!sc&&Bc,bT=pe?.filter(u(Jt.structureId))?.length??0;return{...p,tournamentId:m,eventId:A,structureId:Jt.structureId,drawId:K,eventType:y,category:Ia,categoryName:tp,ageCategoryCode:Vc,flightNumber:U?.[K],drawType:H,stage:Jt.stage,seedingBasis:Ut?JSON.stringify(Ut):void 0,winningPersonId:la,winningPersonOtherId:fa,winningPersonTennisId:ga,winningPersonWTNrating:Gc,winningPersonWTNconfidence:bm,winningPerson2Id:we,winningPerson2OtherId:Ai,winningPerson2TennisId:as,winningPerson2WTNrating:An,winningPerson2WTNconfidence:ic,winningTeamId:so,positionManipulations:bT,pctNoRating:Et,matchUpFormat:Vn,pctInitialMatchUpFormat:TD,matchUpsCount:J,drawTieFormatName:RT,drawTieFormatDesc:_g,tieFormatName:ED,tieFormatDesc:Sa,avgConfidence:ct,avgWTN:Ht}})})});return i.forEach(({eventName:S,drawName:h,structureId:T})=>{s[T]?.length&&c.push({eventName:S,drawName:h,actions:s[T]})}),{eventStructureReports:Object.values(a),structureReports:I,flightReports:c}}function vZ({extensions:t}){return t?.find(({name:e})=>e===mu)?.value?.slice(1)}function OZ(t,e){return t.find(r=>r.structureId===e&&r.finishingRound===1&&r.winningSide)}function _Z(t){if(t?.sides)return t.sides.find(e=>e.sideNumber===t.winningSide)}function xZ(t){return t?.participantType===ur?t.participantId:void 0}function wZ(t){return t?.participantType===lt?t.individualParticipants??[]:[]}function LZ(t,e){return!t||!e?"":t<e?"Overperformed":t>e?"Underperformed":"As expected"}function FZ(t){let e=t?.finishingPositionRange,r=e?.[0]??"",n=e?.[1]??r;return r===n?`${r}`:`${r}-${n}`}function kZ(t,e,r,n){let o=Ef({drawDefinition:e,tournamentRecord:n,event:t});if(!o||o.error)return[];let i=[];for(let[s,a]of Object.entries(o)){let c=r?.[s];if(!c)continue;let u=c.draws?.[e.drawId]?.seedAssignments?.[W],p=u?.seedValue??u?.seedNumber;if(!p)continue;let m=FZ(a),d=a.finishingPositionRange?.[0]??0;i.push({participantId:s,participantName:c.participant?.participantName??"",eventName:t.eventName??"",drawName:e.drawName??"",seedValue:p,finishingPosition:m,expectedPosition:`${p}`,performance:LZ(d,p)})}return i}function SV({tournamentRecord:t}){let{participantMap:e}=bt({withSeeding:!0,withDraws:!0,tournamentRecord:t}),r=[{key:"participantName",title:"Participant",type:"string"},{key:"eventName",title:"Event",type:"string"},{key:"drawName",title:"Draw",type:"string"},{key:"seedValue",title:"Seed",type:"number"},{key:"finishingPosition",title:"Finish",type:"string"},{key:"expectedPosition",title:"Expected",type:"string"},{key:"performance",title:"Performance",type:"string"}],n=[];for(let o of t.events??[])for(let i of o.drawDefinitions??[])n.push(...kZ(o,i,e,t));return n.sort((o,i)=>(o.seedValue??99)-(i.seedValue??99)),{reportId:hm,generatedAt:new Date().toISOString(),columns:r,rows:n}}function TV({tournamentRecord:t}){let{participantMap:e}=bt({tournamentRecord:t}),{matchUps:r}=qt({matchUpFilters:{matchUpTypes:[Os,ei]},tournamentRecord:t});if(!r)return{error:"No matchUps found"};let n=r.filter(c=>Ot.includes(c.matchUpStatus)),o={},i=c=>{o[c]||(o[c]={wins:0,losses:0,setsWon:0,setsLost:0,gamesWon:0,gamesLost:0})};for(let c of n){let u=hV(c.sides?.[0],c.matchUpType??""),p=hV(c.sides?.[1],c.matchUpType??""),m=c.winningSide??0,l=[[],u,p][m]??[],g=[[],p,u][m]??[],I=c.score?.sets??[],S=0,h=0,T=0,y=0;for(let N of I){let D=N.side1Score??0,R=N.side2Score??0;T+=D,y+=R,D>R?S++:R>D&&h++}for(let N of l)i(N),o[N].wins++;for(let N of g)i(N),o[N].losses++;let E={setsWon:S,setsLost:h,gamesWon:T,gamesLost:y},A={setsWon:h,setsLost:S,gamesWon:y,gamesLost:T};for(let N of u)i(N),o[N].setsWon+=E.setsWon,o[N].setsLost+=E.setsLost,o[N].gamesWon+=E.gamesWon,o[N].gamesLost+=E.gamesLost;for(let N of p)i(N),o[N].setsWon+=A.setsWon,o[N].setsLost+=A.setsLost,o[N].gamesWon+=A.gamesWon,o[N].gamesLost+=A.gamesLost}let s=[{key:"participantName",title:"Participant",type:"string"},{key:"wins",title:"Wins",type:"number"},{key:"losses",title:"Losses",type:"number"},{key:"winPct",title:"Win %",type:"number"},{key:"setsWon",title:"Sets Won",type:"number"},{key:"setsLost",title:"Sets Lost",type:"number"},{key:"gamesWon",title:"Games Won",type:"number"},{key:"gamesLost",title:"Games Lost",type:"number"}],a=Object.entries(o).map(([c,u])=>{let p=e?.[c]?.participant?.participantName??c,m=u.wins+u.losses,d=m>0?Math.round(u.wins/m*100):0;return{participantId:c,participantName:p,wins:u.wins,losses:u.losses,winPct:d,setsWon:u.setsWon,setsLost:u.setsLost,gamesWon:u.gamesWon,gamesLost:u.gamesLost}}).sort((c,u)=>u.wins-c.wins||c.losses-u.losses);return{reportId:fm,generatedAt:new Date().toISOString(),columns:s,rows:a}}function hV(t,e){return t?e===ei?t.participant?.individualParticipantIds??[t.participantId].filter(Boolean):[t.participantId??t.participant?.participantId].filter(Boolean):[]}function yV({tournamentRecord:t}){let{matchUps:e}=qt({tournamentRecord:t});if(!e)return{error:"No matchUps found"};let r=e.filter(i=>Ot.includes(i.matchUpStatus)),n=[{key:"roundName",title:"Round",type:"string"},{key:"side1",title:"Side 1",type:"string"},{key:"side2",title:"Side 2",type:"string"},{key:"score",title:"Score",type:"string"},{key:"competitiveness",title:"Competitiveness",type:"string"},{key:"pctSpread",title:"Spread %",type:"number"}],o=r.toSorted((i,s)=>(i.roundNumber??0)-(s.roundNumber??0)||(i.roundPosition??0)-(s.roundPosition??0)).map(i=>{let s=js({matchUp:i,tournamentRecord:t});return{roundName:i.roundName??`R${i.roundNumber??""}`,side1:i.sides?.[0]?.participant?.participantName??"",side2:i.sides?.[1]?.participant?.participantName??"",score:i.score?.scoreStringSide1??"",competitiveness:s.competitiveness??"",pctSpread:s.pctSpread??""}});return{reportId:Tm,generatedAt:new Date().toISOString(),columns:n,rows:o}}function EV({tournamentRecord:t}){let{matchUps:e}=qt({tournamentRecord:t});if(!e)return{error:"No matchUps found"};let r=e.filter(c=>Ot.includes(c.matchUpStatus)),n={},o={};for(let c of t.events??[]){n[c.eventId]=c.eventName??"";for(let u of c.drawDefinitions??[])o[u.drawId]=u.drawName??""}let i={};for(let c of r){let u=c.eventId??"unknown",p=c.matchUpStatus??"UNKNOWN";i[u]??={},i[u][p]=(i[u][p]??0)+1}let s=[{key:"eventName",title:"Event",type:"string"},{key:"status",title:"Status",type:"string"},{key:"count",title:"Count",type:"number"},{key:"percentage",title:"% of Event",type:"number"}],a=[];for(let[c,u]of Object.entries(i)){let p=Object.values(u).reduce((m,d)=>m+d,0);for(let[m,d]of Object.entries(u))a.push({eventId:c,eventName:n[c]||c,status:m,count:d,percentage:p>0?Math.round(d/p*100):0})}return a.sort((c,u)=>c.eventName.localeCompare(u.eventName)||u.count-c.count),{reportId:Sm,generatedAt:new Date().toISOString(),columns:s,rows:a}}function AV({tournamentRecord:t}){let{matchUps:e}=qt({tournamentRecord:t});if(!e)return{error:"No matchUps found"};let r=e.filter(i=>Ot.includes(i.matchUpStatus)),n=[{key:"roundName",title:"Round",type:"string"},{key:"side1",title:"Side 1",type:"string"},{key:"side2",title:"Side 2",type:"string"},{key:"score",title:"Score",type:"string"},{key:"matchUpStatus",title:"Status",type:"string"},{key:"winnerName",title:"Winner",type:"string"}],o=r.toSorted((i,s)=>(i.roundNumber??0)-(s.roundNumber??0)||(i.roundPosition??0)-(s.roundPosition??0)).map(i=>{let s=i.sides?.[0]?.participant?.participantName??"",a=i.sides?.[1]?.participant?.participantName??"",c=i.winningSide?i.sides?.[i.winningSide-1]:void 0,u=i.score?.scoreStringSide1??"";return{roundName:i.roundName??`R${i.roundNumber??""}`,side1:s,side2:a,score:u,matchUpStatus:i.matchUpStatus??"",winnerName:c?.participant?.participantName??""}});return{reportId:Im,generatedAt:new Date().toISOString(),columns:n,rows:o}}function PV({tournamentRecord:t}){let e=VN({tournamentRecord:t});if(e.error)return e;let r={};for(let a of t.participants??[])r[a.participantId]=a.participantName??"";let n={},o={};for(let a of t.events??[]){n[a.eventId]=a.eventName??"";for(let c of a.drawDefinitions??[])o[c.drawId]=c.drawName??""}let i=[{key:"participantName",title:"Participant",type:"string"},{key:"eventName",title:"Event",type:"string"},{key:"drawName",title:"Draw",type:"string"},{key:"entryStatus",title:"Entry Status",type:"string"},{key:"entryStage",title:"Stage",type:"string"},{key:"ranking",title:"Ranking",type:"number"},{key:"mainSeeding",title:"Main Seed",type:"number"},{key:"qualifyingSeeding",title:"Qualifying Seed",type:"number"}],s=(e.participantEntryReports??[]).map(a=>({participantId:a.participantId??"",participantName:r[a.participantId]||"",eventId:a.eventId??"",eventName:n[a.eventId]||"",drawId:a.drawId??"",drawName:o[a.drawId]||"",entryStatus:a.entryStatus??"",entryStage:a.entryStage??"",ranking:a.ranking??"",mainSeeding:a.mainSeeding??"",qualifyingSeeding:a.qualifyingSeeding??""}));return{reportId:mm,generatedAt:new Date().toISOString(),columns:i,rows:s,summary:e.tournamentEntryReport??{}}}function NV({tournamentRecord:t}){let e=wN({tournamentRecord:t});if(e.error)return e;let r=[{key:"participantName",title:"Participant",type:"string"},{key:"matchUpsWon",title:"Wins",type:"number"},{key:"matchUpsLost",title:"Losses",type:"number"},{key:"matchUpsRatio",title:"Win %",type:"number"},{key:"setsWon",title:"Sets Won",type:"number"},{key:"setsLost",title:"Sets Lost",type:"number"},{key:"gamesWon",title:"Games Won",type:"number"},{key:"gamesLost",title:"Games Lost",type:"number"},{key:"tiebreaksWon",title:"TBs Won",type:"number"},{key:"tiebreaksLost",title:"TBs Lost",type:"number"}],n=(e.allParticipantStats??[]).map(o=>({participantName:o.participantName??"",matchUpsWon:o.matchUps?.[0]??0,matchUpsLost:o.matchUps?.[1]??0,matchUpsRatio:o.matchUpsRatio??0,setsWon:o.sets?.[0]??0,setsLost:o.sets?.[1]??0,gamesWon:o.games?.[0]??0,gamesLost:o.games?.[1]??0,tiebreaksWon:o.tiebreaks?.[0]??0,tiebreaksLost:o.tiebreaks?.[1]??0}));return{reportId:lm,generatedAt:new Date().toISOString(),columns:r,rows:n,summary:{participatingTeamsCount:e.participatingTeamsCount??0}}}function DV({tournamentRecord:t}){let e=BN({tournamentRecord:t});if(e.error)return e;let r={},n={},o={};for(let c of t.events??[]){r[c.eventId]=c.eventName??"";for(let u of c.drawDefinitions??[]){n[u.drawId]=u.drawName??"";let p=u.structures?.find(m=>m.stage==="MAIN"&&m.stageSequence===1);p?.positionAssignments&&(o[u.drawId]=p.positionAssignments.length)}}let i={};for(let c of t.participants??[])i[c.participantId]=c.participantName??"",c.person?.personId&&(i[c.person.personId]=c.participantName??"");let s=[{key:"eventName",title:"Event",type:"string"},{key:"drawName",title:"Draw",type:"string"},{key:"stage",title:"Stage",type:"string"},{key:"drawType",title:"Draw Type",type:"string"},{key:"drawSize",title:"Draw Size",type:"number"},{key:"matchUpsCount",title:"MatchUps",type:"number"},{key:"winner",title:"Winner",type:"string"},{key:"seedingBasis",title:"Seeding Basis",type:"string"}],a=(e.structureReports??[]).map(c=>{let u=i[c.winningPersonId]||i[c.winningTeamId]||"";return{eventId:c.eventId??"",eventName:r[c.eventId]||"",drawId:c.drawId??"",drawName:n[c.drawId]||"",stage:c.stage??"",drawType:c.drawType??"",drawSize:o[c.drawId]??"",matchUpsCount:c.matchUpsCount??"",winner:u,seedingBasis:c.seedingBasis??""}});return{reportId:dm,generatedAt:new Date().toISOString(),columns:s,rows:a,summary:{eventStructureReports:e.eventStructureReports??[],flightReports:e.flightReports??[]}}}function WN({ignoreDisabled:t=!0,tournamentRecords:e,tournamentId:r,venueIds:n=[],dates:o=[]}){if(!Array.isArray(o))return{error:O,dates:o};if(!Array.isArray(n))return{error:O,venueIds:n};if(!((e&&Object.keys(e).filter(l=>!r||l===r))??[]).length)return{error:kt};if(!o.every(Me))return{error:ae};let a=kn({tournamentRecords:e,ignoreDisabled:t,dates:o});if(a.error)return a;let c=a?.venues?.filter(({venueId:l})=>!n?.length||n.includes(l)),u=a.courts?.reduce((l,f)=>(f.dateAvailability?.forEach(g=>{let I=g.date;l.includes(I)||l.push(I)}),l),[]).filter(l=>!o.length||o.includes(l)),p={venueIds:c?.map(({venueId:l})=>l)},{matchUps:m}=cn({afterRecoveryTimes:!0,tournamentRecords:e,matchUpFilters:p});return{venuesReport:c?.map(l=>GZ(u,l,m))}}function GZ(t,e,r){let{venueId:n,courts:o,venueName:i}=e,s={};return t.forEach(a=>{let c=0,u=0,p=0;for(let l of o){let f=l.dateAvailability.find(S=>S.date===a),I=(f&&pa({courtDate:f}).timeSlots)?.reduce((S,h)=>{let{startTime:T,endTime:y}=h,E=jt(y)-jt(T);return S+E},0);I&&(p+=1),c+=I}let m=r.filter(({schedule:l})=>l.venueId===n&&Xn(a,l.scheduledDate));m.forEach(({schedule:l})=>{let f=$t(l.scheduledTime),g=Yr(f,l.averageMinutes),I=jt(g)-jt(f);u+=I});let d=c?(u/c*100).toFixed(2):"100";s[a]={scheduledMatchUpsCount:m.length,availableCourts:p,availableMinutes:c,scheduledMinutes:u,percentUtilization:d}}),{venueId:n,venueName:i,venueReport:s}}function UV({tournamentRecord:t}){let e=t?.tournamentId,r=e?{[e]:t}:{},n=WN({tournamentRecords:r});if(n.error)return n;let o=[{key:"venueName",title:"Venue",type:"string"},{key:"date",title:"Date",type:"date"},{key:"availableCourts",title:"Courts",type:"number"},{key:"scheduledMatchUpsCount",title:"Scheduled MatchUps",type:"number"},{key:"availableMinutes",title:"Available Minutes",type:"number"},{key:"scheduledMinutes",title:"Scheduled Minutes",type:"number"},{key:"percentUtilization",title:"Utilization %",type:"number"}],i=[];for(let s of n.venuesReport??[])for(let[a,c]of Object.entries(s.venueReport??{})){let u=c;i.push({venueName:s.venueName??"",date:a,availableCourts:u.availableCourts??0,scheduledMatchUpsCount:u.scheduledMatchUpsCount??0,availableMinutes:u.availableMinutes??0,scheduledMinutes:u.scheduledMinutes??0,percentUtilization:u.percentUtilization??"0"})}return{reportId:gm,generatedAt:new Date().toISOString(),columns:o,rows:i}}var VZ={error:"Invalid reportId"},BZ={[mm]:PV,[dm]:DV,[Im]:AV,[Sm]:EV,[Tm]:yV,[fm]:TV,[hm]:SV,[lm]:NV,[gm]:UV};function RV({tournamentRecord:t,reportId:e}){if(!t)return{error:j};let r=BZ[e];return r?r({tournamentRecord:t}):VZ}var h_={};Gt(h_,{addCourtGridBooking:()=>g_,addMatchUpCourtOrder:()=>cN,addMatchUpEndTime:()=>pN,addMatchUpOfficial:()=>Zv,addMatchUpResumeTime:()=>dN,addMatchUpScheduleItems:()=>Hd,addMatchUpScheduledDate:()=>Wu,addMatchUpScheduledTime:()=>yi,addMatchUpStartTime:()=>uN,addMatchUpStopTime:()=>mN,addSchedulingProfileRound:()=>Oh,allocateTeamMatchUpCourts:()=>Wd,assignMatchUpCourt:()=>Ms,assignMatchUpVenue:()=>nc,bulkRescheduleMatchUps:()=>p_,bulkScheduleMatchUps:()=>ju,bulkScheduleTournamentMatchUps:()=>pm,bulkUpdateCourtAssignments:()=>s_,calculateScheduleTimes:()=>Lh,clearMatchUpSchedule:()=>l_,clearScheduledMatchUps:()=>qu,courtGridRows:()=>qf,findMatchUpFormatTiming:()=>_d,findVenue:()=>Ln,generateBookings:()=>Yd,generateVirtualCourts:()=>Gd,getMatchUpsToSchedule:()=>Yf,getPersonRequests:()=>is,getProfileRounds:()=>jf,getScheduledRoundsDetails:()=>sm,getSchedulingProfile:()=>bo,getSchedulingProfileIssues:()=>EP,matchUpScheduleChange:()=>m_,modifyMatchUpFormatTiming:()=>mh,mutate:()=>S_,proAutoSchedule:()=>Fh,proConflicts:()=>c_,publicFindCourt:()=>SE,query:()=>av,removeCourtGridBooking:()=>I_,removeEventMatchUpFormatTiming:()=>Zf,removeMatchUpCourtAssignment:()=>i_,reorderUpcomingMatchUps:()=>u_,scheduleMatchUps:()=>a_,scheduleProfileGrid:()=>d_,scheduleProfileRounds:()=>jd,setMatchUpDailyLimits:()=>f_,setMatchUpHomeParticipantId:()=>Ah,setSchedulingProfile:()=>Fu,toggleParticipantCheckInState:()=>rg,validateSchedulingProfile:()=>xd});var S_={};Gt(S_,{addCourtGridBooking:()=>g_,addMatchUpCourtOrder:()=>cN,addMatchUpEndTime:()=>pN,addMatchUpOfficial:()=>Zv,addMatchUpResumeTime:()=>dN,addMatchUpScheduleItems:()=>Hd,addMatchUpScheduledDate:()=>Wu,addMatchUpScheduledTime:()=>yi,addMatchUpStartTime:()=>uN,addMatchUpStopTime:()=>mN,addSchedulingProfileRound:()=>Oh,allocateTeamMatchUpCourts:()=>Wd,assignMatchUpCourt:()=>Ms,assignMatchUpVenue:()=>nc,bulkRescheduleMatchUps:()=>p_,bulkScheduleMatchUps:()=>ju,bulkScheduleTournamentMatchUps:()=>pm,bulkUpdateCourtAssignments:()=>s_,calculateScheduleTimes:()=>Lh,clearMatchUpSchedule:()=>l_,clearScheduledMatchUps:()=>qu,findMatchUpFormatTiming:()=>_d,generateBookings:()=>Yd,generateVirtualCourts:()=>Gd,matchUpScheduleChange:()=>m_,modifyMatchUpFormatTiming:()=>mh,proAutoSchedule:()=>Fh,proConflicts:()=>c_,removeCourtGridBooking:()=>I_,removeEventMatchUpFormatTiming:()=>Zf,removeMatchUpCourtAssignment:()=>i_,reorderUpcomingMatchUps:()=>u_,scheduleMatchUps:()=>a_,scheduleProfileGrid:()=>d_,scheduleProfileRounds:()=>jd,setMatchUpDailyLimits:()=>f_,setMatchUpHomeParticipantId:()=>Ah,setSchedulingProfile:()=>Fu,toggleParticipantCheckInState:()=>rg,validateSchedulingProfile:()=>xd});function Lh({calculateStartTimeFromCourts:t=!0,defaultRecoveryMinutes:e=0,averageMatchUpMinutes:r=90,remainingScheduleTimes:n,clearScheduleDates:o,tournamentRecords:i,periodLength:s,scheduleDate:a,startTime:c,venueIds:u,endTime:p}){if(typeof i!="object"||!Object.keys(i).length)return{error:kt};s=s??cm({recoveryMinutes:e,averageMatchUpMinutes:r});let{courts:m,venues:d}=kn({dates:[a],ignoreDisabled:!0,tournamentRecords:i}),l=m?.filter(b=>!u||u.includes(b.venueId));c||(c=l?.reduce((b,C)=>{let v=C.dateAvailability?.find(w=>!w.date||Xn(a,w.date))?.startTime??C.startTime;return v&&(!b||jt(v)<jt(b))?v:b},void 0)),p||(p=l?.reduce((b,C)=>{let v=C.dateAvailability?.find(w=>!w.date||Xn(a,w.date))?.endTime??C.endTime;return v&&(!b||jt(v)>jt(b))?v:b},void 0));let f=Object.values(i),g=Object.assign({},...f.map(b=>(b.events??[]).map(C=>{let{scheduleTiming:_}=Ac({tournamentRecord:b,event:C});return{[C.eventId]:{event:C,scheduleTiming:_}}})).flat()),S=am({sortDateMatchUps:!1,tournamentRecords:i,matchUpFilters:{scheduledDate:a,venueIds:u}}),h=S?.dateMatchUps??[],T=S?.completedMatchUps??[],y=[];y.push(...h),y.push(...T);let E={averageTimes:[{minutes:{default:r}}],recoveryTimes:[{minutes:{default:e}}]},A=y?.map(({eventId:b,schedule:C,matchUpFormat:_})=>{let{event:v,scheduleTiming:w}=g[b],L=v?.eventType,F={...w,defaultTiming:E,matchUpFormat:_},{averageMinutes:x,recoveryMinutes:k}=id({eventType:L,timingDetails:F}),{courtId:G,venueId:V}=C,B=$t(C.scheduledTime),z=Yr(B,x);return{recoveryMinutes:k,averageMinutes:x,periodLength:s,startTime:B,endTime:z,courtId:G,venueId:V}}),N={calculateStartTimeFromCourts:t,remainingScheduleTimes:n,averageMatchUpMinutes:r,date:a,clearScheduleDates:o,periodLength:s,startTime:c,endTime:p,bookings:A,courts:l},{scheduleTimes:D}=eg(N),R=u?.length===1&&u[0]||d?.length===1&&d[0].venueId||void 0,U=y.map(Te);return{venueId:R,scheduleTimes:D,dateScheduledMatchUpIds:U}}function i_(t){let e=X(t,[{[Ee]:!0}]);if(e.error)return e;let{removePriorValues:r,tournamentRecords:n,tournamentId:o,courtDayDate:i,matchUpId:s,courtId:a,drawId:c}=t,u=n[o];if(!u)return{error:j};let{drawDefinition:p,event:m}=zo({tournamentRecord:u,drawId:c});if(!p)return{error:$};let d=Wt({drawDefinition:p,event:m,matchUpId:s});if(d.error)return d;if(d?.matchUp?.matchUpType===Ir){let{itemValue:l}=Ii({timeItems:d.matchUp.timeItems??[],itemType:Io}),f=a&&l.filter(I=>I.courtId!==a);return Kr({duplicateValues:!1,removePriorValues:r,tournamentRecord:u,drawDefinition:p,matchUpId:s,timeItem:{itemType:Io,itemValue:f}})}else return Ms({tournamentRecord:u,drawDefinition:p,courtDayDate:i,courtId:"",matchUpId:s})}function Fh({scheduleCompletedMatchUps:t,minCourtGridRows:e=10,tournamentRecords:r,scheduledDate:n,courtIds:o,matchUps:i}){if(!Rr(i))return{error:O};if(i.some(({hasContext:S})=>!S))return{info:"matchUps must have { inContext: true, nextMatchUps: true }",error:ap};let a=am({courtCompletedMatchUps:!0,withCourtGridRows:!0,minCourtGridRows:e,tournamentRecords:r,matchUpFilters:{localPerspective:!0,scheduledDate:n}});if(a.error)return a;let{rows:c}=a,u=[],p=S=>[(S.sides??[]).map(h=>[h.participantId,h.participant?.individualParticipantIds]),(S.potentialParticipants??[]).flat().map(h=>[h.participantId,h.individualParticipantIds])].flat(1/0).filter(Boolean),m=c?.reduce((S,h)=>{let T=[],y=[];Object.values(h).forEach(A=>{if(Tt(A)&&(A.matchUpId&&(T.push(A.matchUpId),u.push(A)),A.sides)){let N=p(A);y.push(...N)}});let E=Object.values(h).filter(A=>Tt(A)&&!A.matchUpId&&!A.isBlocked&&(!o?.length||o.includes(A.schedule?.courtId)));return S.concat({matchUpIds:T,availableCourts:E,rowId:h.rowId,participantIds:y})},[]);i.filter(({matchUpStatus:S})=>S&&S!=="BYE"&&(t||!Ot.includes(S))).sort(Qi);let d=tn({matchUps:i.concat(u),includeParticipantDependencies:!0,tournamentRecords:r}).matchUpDependencies,l=[],f=[];for(;i.length&&m.length;){let S=m.shift(),h=[];for(;i.length&&S.availableCourts.length;){let T=i.concat(h).map(C=>C.matchUpId),y=i.shift(),E=y?.matchUpId,A=E&&d[E].matchUpIds.concat(d[E].dependentMatchUpIds),N=E&&T.some(C=>d[E].matchUpIds.includes(C)),D=E&&f.some(C=>d[E].dependentMatchUpIds.includes(C)),R=S.matchUpIds.some(C=>A.includes(C)),U=p(y),b=S.participantIds.some(C=>U.includes(C));if(y&&!R&&!N&&!b&&!D){let C=S.availableCourts.shift();Object.assign(y.schedule,C.schedule),Object.assign(C,y),l.push(y),S.participantIds.push(...U),S.matchUpIds.push(E)}else y&&h.push(y)}i.push(...h),f.push(...S.matchUpIds)}let g=l.map(({matchUpId:S,tournamentId:h,schedule:T,drawId:y})=>({tournamentId:h,matchUpId:S,drawId:y,schedule:{...T,scheduledDate:n}}));return a=ju({tournamentRecords:r,matchUpDetails:g}),{...a,scheduled:l,notScheduled:i}}function s_(t){let{courtDayDate:e}=t,r=X(t,[{courtAssignments:!0,[Ge]:ke,[Lr]:nt},{[Ee]:!0}]);if(r.error)return r;let n=t.courtAssignments.reduce((s,a)=>{let{tournamentId:c}=a;return s[c]||(s[c]=[]),s[c].push(a),s},{}),o;return Object.keys(n).every(s=>{let a=t[Ee][s];if(!a)return o={error:j},!1;let c=n[s].reduce((p,m)=>{let{drawId:d}=m;return p[d]||(p[d]=[]),p[d].push(m),p},{});Object.keys(c).every(p=>{let{drawDefinition:m}=_e({tournamentRecord:a,drawId:p});return m?(c[p].every(d=>{let{matchUpId:l,courtId:f}=d,g=Ms({tournamentRecord:a,drawDefinition:m,courtDayDate:e,matchUpId:l,courtId:f});if(g.success)return g?.success;o={error:xU}}),!0):(o={error:$},!1)})}),o||P}function a_(t){let{tournamentRecords:e,allDateMatchUpIds:r=[],averageMatchUpMinutes:n=90,recoveryMinutes:o=0,recoveryMinutesMap:i,matchUpPotentialParticipantIds:s={},individualParticipantProfiles:a={},matchUpNotBeforeTimes:c={},matchUpDailyLimits:u={},checkPotentialRequestConflicts:p=!0,remainingScheduleTimes:m,clearScheduleDates:d,periodLength:l=30,scheduleDate:f,matchUpIds:g,venueIds:I,startTime:S,endTime:h,dryRun:T}=t,y=X(t,[{[Ee]:!0,[cu]:!0},{[$e]:Me,[Lr]:ae,[Xw]:!0},{[$e]:Y=>!Y||!isNaN(Y),[rL]:!1,[Lr]:O,[nL]:!1,[oL]:!1}]);if(y.error)return y;let E=t.competitionMatchUps??cn({nextMatchUps:!0,tournamentRecords:e}).matchUps??[],A=t.matchUpDependencies??tn({includeParticipantDependencies:!0,matchUps:E,tournamentRecords:e}).matchUpDependencies;E.forEach(Y=>{Y.schedule?.scheduledDate&&Xn(f,mt(Y.schedule.scheduledDate))&&Za({matchUpPotentialParticipantIds:s,matchUpNotBeforeTimes:c,matchUp:Y})});let N=g.map(Y=>E.find(J=>J.matchUpId===Y)).filter(Boolean),{venueId:D,scheduleTimes:R,dateScheduledMatchUpIds:U}=Lh({tournamentRecords:e,remainingScheduleTimes:m,startTime:$t(S),endTime:$t(h),scheduleDate:mt(f),averageMatchUpMinutes:n,clearScheduleDates:d,periodLength:l,venueIds:I}),b={},C=[],_={},v={},w={};E.filter(({matchUpId:Y})=>U?.includes(Y)).forEach(Y=>{bh({matchUpPotentialParticipantIds:s,individualParticipantProfiles:a,matchUp:Y,value:1});let J=Y.schedule?.scheduledTime;if(J){_[Y.matchUpId]=J;let ct=i?.[Y.matchUpId];Hu({recoveryMinutes:ct||o,matchUpPotentialParticipantIds:s,individualParticipantProfiles:a,matchUpNotBeforeTimes:c,averageMatchUpMinutes:n,matchUpDependencies:A,scheduleTime:J,matchUp:Y})}});let F=N.filter(Y=>{let J=U?.includes(Y.matchUpId),ct=["BYE",Mt,ie,Fr,De,vt].includes(Y?.matchUpStatus);return!J&&!Y.winningSide&&!ct}),{matchUpMap:x,overLimitMatchUpIds:k,participantIdsAtLimit:G}=F.reduce((Y,J)=>{let{drawId:ct,tournamentId:Et,matchUpType:Ht}=J,{participantIdsAtLimit:Ut,relevantParticipantIds:pe}=ug({individualParticipantProfiles:a,matchUpPotentialParticipantIds:s,matchUpDailyLimits:u,matchUp:J});return Ut?.length?(Y.overLimitMatchUpIds.push(J.matchUpId),Y.participantIdsAtLimit.push(...Ut),Y):(pe.forEach(ye=>{Lc({individualParticipantProfiles:a,participantId:ye});let Jt=a[ye].counters;Jt[Ht]?Jt[Ht]+=1:Jt[Ht]=1,Jt[So]?Jt[So]+=1:Jt[So]=1}),Y.matchUpMap[Et]||(Y.matchUpMap[Et]={}),Y.matchUpMap[Et][ct]?Y.matchUpMap[Et][ct].push(J):Y.matchUpMap[Et][ct]=[J],Za({matchUpPotentialParticipantIds:s,matchUpNotBeforeTimes:c,matchUp:J}),Y)},{matchUpMap:{},overLimitMatchUpIds:[],participantIdsAtLimit:[]});F=F.filter(({matchUpId:Y})=>!k.includes(Y));let V=0,B=R?.length??0,{personRequests:z}=is({tournamentRecords:e,requestType:Yu});for(;R?.length&&F.length&&V<=B;){V++;let{scheduleTime:Y}=R.shift(),J=F.find(ct=>{let{matchUpId:Et}=ct,{dependenciesScheduled:Ht,remainingDependencies:Ut}=sg({matchUpScheduleTimes:_,matchUpDependencies:A,allDateMatchUpIds:r,matchUp:ct});if(!Ht)return w[Et]||(w[Et]=[]),w[Et].push({scheduleTime:Y,remainingDependencies:Ut}),!1;let{enoughTime:pe}=cg({individualParticipantProfiles:a,matchUpNotBeforeTimes:c,matchUpDependencies:A,scheduleTime:Y,matchUp:ct});if(!pe)return v[Et]||(v[Et]=[]),v[Et].push({scheduleTime:Y}),!1;let{conflicts:ye}=ag({potentials:p,averageMatchUpMinutes:n,requestConflicts:b,personRequests:z,scheduleTime:Y,scheduleDate:f,matchUp:ct});if(ye?.length)return!1;let Jt=i?.[ct.matchUpId];return Hu({recoveryMinutes:Jt||o,matchUpPotentialParticipantIds:s,individualParticipantProfiles:a,matchUpNotBeforeTimes:c,averageMatchUpMinutes:n,matchUpDependencies:A,scheduleTime:Y,matchUp:ct}),_[ct.matchUpId]=Y,!0});F=F.filter(({matchUpId:ct})=>ct!==J?.matchUpId),J||C.push(Y)}F.forEach(Y=>{bh({individualParticipantProfiles:a,matchUpPotentialParticipantIds:s,value:-1,matchUp:Y})});let H=[];Object.keys(x).forEach(Y=>{let J=e[Y];J&&Object.keys(x[Y]).forEach(ct=>{let{drawDefinition:Et}=zo({tournamentRecord:J,drawId:ct});Et&&x[Y][ct].forEach(({matchUpId:Ut})=>{let pe=_[Ut];if(pe){let ye=pe.split(":").map(co).join(":"),Jt=`${mt(f)}T${ye}`;T?H.push(Ut):(yi({drawDefinition:Et,matchUpId:Ut,scheduledTime:Jt}).success&&H.push(Ut),D&&nc({tournamentRecords:e,tournamentRecord:J,drawDefinition:Et,matchUpId:Ut,venueId:D}))}})})});let K=bl(F);return{...P,requestConflicts:Object.values(b),remainingScheduleTimes:R?.map(({scheduleTime:Y})=>Y),individualParticipantProfiles:a,matchUpNotBeforeTimes:c,participantIdsAtLimit:G,skippedScheduleTimes:C,overLimitMatchUpIds:k,scheduledMatchUpIds:H,noTimeMatchUpIds:K,recoveryTimeDeferred:v,dependencyDeferred:w}}function c_({useDeepDependencies:t=!1,tournamentRecords:e,matchUps:r}){if(!Rr(r))return{error:Bn};if(r.some(({matchUpId:A,hasContext:N})=>A&&!N))return{info:"matchUps must have { inContext: true, nextMatchUps: true }",error:ap};let n=Math.max(...r.map(({schedule:A})=>A?.courtOrder||1).map(A=>st(A))),o=Q(1,n+1).map(A=>r.filter(N=>st(N.schedule?.courtOrder)===A)),i={},s={},a={};o.flat().filter(Boolean).sort(Qi).forEach(({schedule:A})=>delete A[aS]);let u=pt(r.map(({drawId:A})=>A)),p=tn({includeParticipantDependencies:!0,tournamentRecords:e,drawIds:u}),m=p.matchUpDependencies,d=t?p.positionDependencies??{}:{},l=o.map((A,N)=>A.reduce((D,R)=>{if(!R.matchUpId)return D;let{matchUpId:U,winnerMatchUpId:b,loserMatchUpId:C,schedule:_,sides:v,potentialParticipants:w}=R,L=_?.courtId;i[U]=N,s[L]=[],D.matchUpIds.push(U),a[U]=R;let F=m[U].matchUpIds;F.length&&D.sourceMatchUpIds.push(...F);let x=v?.flatMap(G=>[G.participant?.individualParticipantIds,G.participantId]).flat().filter(Boolean)??[],k=w?.flat().flatMap(({individualParticipantIds:G,participantId:V})=>[G,V]).flat().filter(Boolean)??[];return D.participantIds.push(...k,...x),b&&D.targetMatchUpIds.push(b),C&&D.targetMatchUpIds.push(C),D},{sourceMatchUpIds:[],targetMatchUpIds:[],participantIds:[],matchUpIds:[]})),f=(A,N)=>m[A].sources.reduce((D,R,U)=>R.includes(N)&&U+1||D,0),g=l.map(()=>[]),I=(A,N,D)=>{D[A]||(D[A]={}),D[A][zs]||(D[A][zs]=N.filter(R=>R!==A))},S=(A,N,D)=>{N.participantIds.filter(U=>A.participantIds.includes(U)).forEach(U=>{let b=N.matchUpIds.concat(A.matchUpIds).filter(C=>m[C].participantIds.includes(U));b.forEach(C=>{I(C,b,D)})})},h=(A,N,D)=>{D[A]||(D[A]={}),D[A][Ks]||(D[A][Ks]=N.filter(R=>R!==A))},T=A=>{let N={},D=mn(A.participantIds),R=new Set(Object.keys(D).filter(b=>D[b]>1)),U=A.matchUpIds.filter(b=>m[b].participantIds.some(C=>R.has(C)));return U.forEach(b=>{h(b,U,N)}),N},y=A=>{let N={},D={};return A.forEach(R=>{let{matchUpId:U,schedule:b}=R;if(!U||!b?.courtId||!b?.scheduledDate)return;let C=`${b.courtId}|${b.scheduledDate}`;D[C]||(D[C]=[]),D[C].push(U)}),Object.values(D).forEach(R=>{R.length>1&&R.forEach(U=>{N[U]=R.filter(b=>b!==U)})}),N},E=(A,N,D,R)=>{if(!a[A].schedule[aS]){a[A].schedule[aS]=N,a[A].schedule[Ub]=R,g[i[A]].push({matchUpId:A,issueType:D,issueIds:R,issue:N});let U=a[A].schedule.courtId;s[U]||(s[U]=[]),s[U].push({matchUpId:A,issue:N,issueType:D,issueIds:R})}};if(l.forEach((A,N)=>{let D=N?l[N-1]:void 0,R=l.slice(N+1),U=T(A),b=y(o[N].filter(C=>A.matchUpIds.includes(C.matchUpId)));D&&S(D,A,U),A.matchUpIds.forEach(C=>{let _=m[C].matchUpIds;for(let w of R){let L=w.matchUpIds.filter(F=>_.includes(F));L?.length&&(L.forEach(F=>E(F,Hl,gi,[C])),E(C,Hl,gi,L))}if(b[C]&&E(C,Ks,Nb,b[C]),U[C]?.[Ks]&&E(C,Ks,dE,U[C][Ks]),A.sourceMatchUpIds.includes(C)){let w=A.matchUpIds.filter(L=>m[L].matchUpIds.includes(C));E(C,Ks,gi,w),A.matchUpIds.filter(L=>m[L].matchUpIds.includes(C)).forEach(L=>E(L,Ks,gi,[C]))}let v=D?.matchUpIds?.filter(w=>f(C,w)>1);if(v?.length&&(E(C,Yl,gi,v),v.forEach(w=>E(w,Yl,gi,[C]))),U[C]?.[zs]&&E(C,zs,dE,U[C][zs]),D?.targetMatchUpIds?.includes(C)){let w=a[C].schedule.courtId,L=_.filter(x=>D.matchUpIds.includes(x));L.some(x=>a[x].schedule.courtId===w)||(L.forEach(x=>E(x,zs,gi,[C])),E(C,zs,gi,L))}})}),t){let A=new Set(Object.keys(i)),N={};for(let U of A)N[U]=new Set(m[U]?.dependentMatchUpIds??[]);let D=0;for(let U of A){let b=m[U]?.sources?.length??0;b>D&&(D=b)}let R=U=>{let b=new Set(U.participantIds),C={};for(let _ of U.matchUpIds){let v=m[_]?.participantIds??[];for(let w of v)b.has(w)||(C[w]||(C[w]=new Set),C[w].add(_))}return C};if(l.forEach((U,b)=>{let C=R(U);for(let[,_]of Object.entries(C))if(_.size>1){let v=[..._];for(let w of v)E(w,zs,lE,v.filter(L=>L!==w))}if(b>0){let _=l[b-1],v=R(_);for(let[w,L]of Object.entries(C))if(v[w]){let F=[...new Set([...L,...v[w]])];for(let x of F)E(x,zs,lE,F.filter(k=>k!==x))}}}),l.forEach((U,b)=>{for(let C of U.matchUpIds)for(let _=2;_<=Math.min(b,D);_++){let v=l[b-_];for(let w of v.matchUpIds){let L=f(C,w);L>0&&_<L&&(E(C,Yl,gi,[w]),E(w,Yl,gi,[C]))}}}),l.forEach((U,b)=>{for(let C of U.matchUpIds){let _=N[C];if(!_?.size)continue;for(let w=0;w<b;w++){let L=l[w].matchUpIds.filter(F=>_.has(F));if(L.length){for(let F of L)E(F,Hl,gi,[C]);E(C,Hl,gi,L)}}let v=U.matchUpIds.filter(w=>w!==C&&_.has(w));if(v.length){for(let w of v)E(w,Ks,gi,[C]);E(C,Ks,gi,v)}}}),Object.keys(d).length){let U=new Set(Object.values(d).flat());l.forEach(b=>{for(let C of b.matchUpIds){let w=(m[C]?.matchUpIds??[]).filter(L=>U.has(L)).filter(L=>!A.has(L));w.length&&E(C,zs,Db,w)}})}}return{courtIssues:s,rowIssues:g}}function u_(t){let e="reorderUpcomingMatchUps",{tournamentRecords:r}=t;if(typeof r!="object"||!Object.keys(r).length)return M({result:{error:kt},stack:e});let{matchUpsContextIds:n,firstToLast:o}=t;if(!n)return M({result:{error:nt},stack:e});let i=n?.length;if(!i)return{...P};let s=0;return n.forEach((c,u)=>{let{tournamentId:p,drawId:m,matchUpId:d}=c,l=u+(o?-1:1);l<0&&(l=i-1),l===i&&(l=0);let f=n[l].schedule.scheduledTime,g=a({tournamentId:p,scheduledTime:f,matchUpId:d,drawId:m});if(g.success)s++;else return g}),s===i?P:M({result:{error:_U},stack:e});function a({tournamentId:c,scheduledTime:u,matchUpId:p,drawId:m}){let d=r[c],{drawDefinition:l}=zo({tournamentRecord:d,drawId:m});return l?yi({drawDefinition:l,scheduledTime:u,matchUpId:p}):{error:Mr}}}function p_(t){let{scheduleChange:e,matchUpIds:r,dryRun:n}=t;if(!r||!Array.isArray(r))return{error:xs};if(typeof e!="object")return{error:O};let o=Dr(t),i=[],s=[];for(let c of Object.values(o)){let u=WZ({tournamentRecord:c,scheduleChange:e,matchUpIds:r,dryRun:n});if(u.error)return u;Array.isArray(u.notRescheduled)&&s.push(...u.notRescheduled);let p=bl(u.notRescheduled),m=[];u.rescheduled?.forEach(d=>{let{matchUpId:l}=d;p.includes(l)&&m.push(l),i.push(d)}),m.length&&(s=u?.notRescheduled?.filter(({matchUpId:d})=>!m.includes(d))??[])}let a=!!(i.length&&!s.length);return{...P,rescheduled:i,notRescheduled:s,allRescheduled:a}}function WZ({tournamentRecord:t,scheduleChange:e,matchUpIds:r,dryRun:n}){if(!t)return{error:j};if(!r||!Array.isArray(r))return{error:xs};if(typeof e!="object")return{error:O};let{minutesChange:o,daysChange:i}=e;if(!o&&!i)return{...P};if(o&&isNaN(o))return{error:O};if(i&&isNaN(i))return{error:O};let s=HZ({tournamentRecord:t,matchUpIds:r});if(!s?.length)return{...P};let{tournamentInfo:a}=ia({tournamentRecord:t}),{startDate:c,endDate:u}=a,p=YZ(s),m=[],d=[];for(let S of Object.keys(p)){let h=zo({tournamentRecord:t,drawId:S});if(h.error)return h;let T=h.drawDefinition,y=p[S].filter(E=>r.includes(E));for(let E of y){if(!E||!T)continue;let A=jZ({scheduledNotCompletedMatchUps:s,rescheduledMatchUpIds:m,notRescheduledMatchUpIds:d,drawDefinition:T,minutesChange:o,daysChange:i,startDate:c,matchUpId:E,endDate:u,dryRun:n});if(A?.error)return A}}let l=qt({matchUpFilters:{matchUpIds:r},tournamentRecord:t}).matchUps??[],f=l.filter(({matchUpId:S})=>m.includes(S)),g=l.filter(({matchUpId:S})=>d.includes(S)),I=f.length&&!g.length;return{...P,rescheduled:f,notRescheduled:g,allRescheduled:I}}function HZ({tournamentRecord:t,matchUpIds:e}){let{matchUps:r}=qt({matchUpFilters:{matchUpIds:e},tournamentRecord:t}),n=({matchUpStatus:o})=>!Ot.includes(o);return r?.filter(o=>_c({schedule:o.schedule})).filter(o=>n({matchUpStatus:o.matchUpStatus}))}function YZ(t){return t.reduce((e,r)=>{let{matchUpId:n,drawId:o}=r;return e[o]?e[o].push(n):e[o]=[n],e},{})}function jZ({scheduledNotCompletedMatchUps:t,rescheduledMatchUpIds:e,notRescheduledMatchUpIds:r,drawDefinition:n,minutesChange:o,daysChange:i,startDate:s,matchUpId:a,endDate:c,dryRun:u}){let d=t.find(h=>h.matchUpId===a)?.schedule,{scheduledTime:l,scheduledDate:f}=d,g,I,S;if(!g&&i&&f){let h=mt(f);S=Wm(h,i),g=new Date(S)<new Date(s)||new Date(S)>new Date(c)}if(o&&l){let h=mt(l),y=jt($t(l))+o;if(g=y<0||y>1440,!g){let E=Yr(l,o),A=h&&S||f===h&&h;I=A?`${A}T${E}`:E}}if(g){r.push(a);return}if(!u){if(I){let h=yi({scheduledTime:I,drawDefinition:n,matchUpId:a});if(h.error)return h}if(S){let h=Wu({scheduledDate:S,drawDefinition:n,matchUpId:a});if(h.error)return h}}(I||S)&&e.push(a)}function m_(t){let e="matchUpScheduleChange",{tournamentRecords:r}=t;if(typeof r!="object"||!Object.keys(r).length)return{error:kt};let{sourceMatchUpContextIds:n,targetMatchUpContextIds:o,sourceCourtId:i,targetCourtId:s,courtDayDate:a}=t??{},{drawId:c,matchUpId:u,tournamentId:p}=n??{},{drawId:m,matchUpId:d,tournamentId:l}=o??{};if(!u&&!d)return M({result:{error:nt},stack:e});let{matchUps:f}=cn({matchUpFilters:{matchUpIds:[u,d].filter(Boolean),drawIds:[c,m].filter(Boolean)},tournamentRecords:t.tournamentRecords}),g=f?.find(({matchUpId:y})=>y===u),I=f?.find(({matchUpId:y})=>y===d),S=0;if(s&&u&&!d){let y=h({tournamentId:p,matchUpId:u,courtId:s,matchUp:g,drawId:c,tournamentRecords:r,sourceCourtId:i,courtDayDate:a});if(y?.success&&S++,y.error)return M({result:y,stack:e})}else if(i&&s&&u&&d){let y=h({tournamentId:p,matchUpId:u,courtId:s,matchUp:g,drawId:c,tournamentRecords:r,sourceCourtId:i,courtDayDate:a});if(y.success&&S++,y.error)return M({result:y,stack:e,info:"source"});let E=h({tournamentId:l,sourceCourtId:s,matchUpId:d,matchUp:I,courtId:i,drawId:m,tournamentRecords:r,courtDayDate:a});if(E.success&&S++,E.error)return M({result:E,stack:e,info:"target"})}else return{error:nt};return S?P:M({result:{error:Na},stack:e});function h(y){let{tournamentRecords:E,tournamentId:A,matchUp:N,drawId:D}=y,R=E[A],{drawDefinition:U}=zo({tournamentRecord:R,drawId:D});return N.matchUpType===xt?T({...y,tournamentRecord:R,drawDefinition:U}):Ms({...y,tournamentRecord:R,drawDefinition:U})}function T({removePriorValues:y,tournamentRecords:E,tournamentRecord:A,drawDefinition:N,sourceCourtId:D,courtDayDate:R,matchUpId:U,matchUp:b,courtId:C}){let _=[C].concat(b.schedule.allocatedCourts.map(({courtId:v})=>v).filter(v=>v!==D));return Wd({removePriorValues:y,tournamentRecords:E,tournamentRecord:A,drawDefinition:N,courtDayDate:R,matchUpId:U,courtIds:_})}}function qZ(t,e,r,n,o,i){let s=t.filter(p=>p.structureId===e&&p.roundNumber===r&&p.drawId===n),a=Math.ceil(s.length/o),c=s.sort((p,m)=>(p.roundPosition??0)-(m.roundPosition??0)).map(p=>p.matchUpId),u=(i-1)*a;return c.slice(u,u+a)}function $Z(t,e,r){let{structureId:n,roundNumber:o,drawId:i,roundSegment:s}=t,a=r[n]??n,c=s?new Set(qZ(e,n,o,i,s.segmentsCount,s.segmentNumber)):null;return e.filter(u=>u.matchUpStatus==="BYE"||u.schedule?.courtId||u.schedule?.courtOrder||u.roundNumber!==o||u.drawId!==i||(r[u.structureId]??u.structureId)!==a?!1:c?c.has(u.matchUpId):!0)}function KZ(t,e){return e||t.length?t:void 0}function zZ(t,e,r,n,o){let i=[],s=[];for(let a of t.venues??[]){let c=e.get(a.venueId)??[],u=r?c.filter(p=>r.has(p)):c;s.push(...u);for(let p of a.rounds??[])i.push(...$Z(p,n,o))}return{dateMatchUps:i,dateCourtIds:s}}function d_(t){let{scheduleCompletedMatchUps:e,minCourtGridRows:r=10,clearScheduleDates:n,scheduleDates:o=[],tournamentRecords:i,courtIds:s}=t,a=Array.isArray(s)?new Set(s):null,c=X(t,[{[Ee]:!0},{[$e]:E=>!E||Array.isArray(E)&&E.every(A=>Me(A)),[hl]:!1,[Ge]:ke}]);if(c.error)return c;let u=bo({tournamentRecords:i});if(u.error)return u;if(!u.schedulingProfile.length)return{...P};let{schedulingProfile:p=[]}=u,m=Object.assign({},...Object.values(i).map(E=>ji({tournamentRecord:E}).containedStructures)),d=new Set(o.map(E=>Me(E)?mt(E):void 0).filter(Boolean)),l=p.map(E=>E.scheduleDate).map(E=>Me(E)&&mt(E)).filter(E=>E&&(!o.length||d.has(E)));if(!l.length)return{error:qg};if(n){let E=Array.isArray(n)?n:[];qu({tournamentRecords:i,scheduledDates:E})}let{matchUps:f}=cn({matchUpFilters:{matchUpTypes:[Ct,Rt]},nextMatchUps:!0,tournamentRecords:i}),{courts:g}=kn({ignoreDisabled:!1,tournamentRecords:i}),I=new Map;for(let E of g??[]){let A=E.venueId;I.has(A)||I.set(A,[]),I.get(A)?.push(E.courtId)}let S=p.filter(E=>{let A=mt(E?.scheduleDate);return l.includes(A)}).sort((E,A)=>new Date(E.scheduleDate).getTime()-new Date(A.scheduleDate).getTime()),h={},T={},y=[];for(let E of S){let A=mt(E.scheduleDate),{dateMatchUps:N,dateCourtIds:D}=zZ(E,I,a,f??[],m);if(!N.length||a&&!D.length)continue;let R=Fh({courtIds:KZ(D,a),scheduleCompletedMatchUps:e,minCourtGridRows:r,tournamentRecords:i,matchUps:N,scheduledDate:A});if(R.error)continue;let U=(R.scheduled??[]).map(C=>C.matchUpId),b=(R.notScheduled??[]).map(C=>C.matchUpId);U.length&&(h[A]=U,y.push(A)),b.length&&(T[A]=b)}return{...P,scheduledMatchUpIds:h,notScheduledMatchUpIds:T,scheduledDates:y}}function l_({scheduleAttributes:t=[Io,li,Ts,ys,Es,fi,As,qs,Fa],tournamentRecord:e,drawDefinition:r,matchUpId:n}){let o="clearMatchUpSchedule",i=r?rr({matchUpFilters:{matchUpIds:[n]},inContext:!1,drawDefinition:r}).matchUps?.[0]:qt({matchUpFilters:{matchUpIds:[n]},tournamentRecord:e,inContext:!1}).matchUps?.[0];if(!i)return{error:Be};let s=(i.timeItems??[]).filter(a=>a?.itemType&&!t.includes(a?.itemType));return i.timeItems=s,It({tournamentId:e.tournamentId,context:o,drawDefinition:r,matchUp:i}),{...P}}function f_(t){let{tournamentRecord:e,tournamentId:r,dailyLimits:n}=t,o=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(typeof o!="object"||!Object.keys(o).length)return{error:kt};if(typeof n!="object")return{error:yo};let i=Object.keys(o).filter(s=>!r||r===s);if(r&&!i.includes(r))return{error:O};for(let s of i){let a=o[s],c=ut({extension:{name:Np,value:{dailyLimits:n}},element:a});if(c.error)return c}return{...P}}function g_(t){let{tournamentRecord:e,disableNotice:r,scheduledDate:n,bookingType:o,courtOrder:i,rowCount:s=1,courtId:a,notes:c}=t;if(!e)return M({result:{error:O},info:"tournamentRecord is required"});if(!a)return{error:vo};if(!n)return M({result:{error:O},info:"scheduledDate is required"});if(!o)return M({result:{error:O},info:"bookingType is required"});if(i==null)return M({result:{error:O},info:"courtOrder is required"});if(!Number.isInteger(i)||i<1)return M({result:{error:O},info:"courtOrder must be a positive integer"});if(!Number.isInteger(s)||s<1)return M({result:{error:O},info:"rowCount must be a positive integer"});let{court:u,venue:p}=Si({tournamentRecord:e,courtId:a});if(!u)return{error:vo};if(!Qo({court:u,date:n})){u.dateAvailability??=[];let f={date:n,bookings:[]};u.dateAvailability.push(f)}let d=Qo({court:u,date:n});if(d.bookings){for(let f of d.bookings)if(typeof f.courtOrder=="number"){let g=f.courtOrder,I=g+(f.rowCount||1)-1,S=i,h=i+s-1;if(S<=I&&h>=g)return M({result:{error:DU},info:`Booking conflicts with existing booking at rows ${g}-${I}`})}}let l={courtOrder:i,rowCount:s,bookingType:o,notes:c,createdAt:new Date().toISOString()};return d.bookings??=[],d.bookings.push(l),!r&&p&&at({payload:{venue:p,tournamentId:e.tournamentId},topic:No,key:p.venueId}),{...P,booking:l}}function I_(t){let{tournamentRecord:e,disableNotice:r,scheduledDate:n,courtOrder:o,courtId:i}=t;if(!e)return M({result:{error:O},info:"tournamentRecord is required"});if(!i)return{error:vo};if(!n)return M({result:{error:O},info:"scheduledDate is required"});if(o==null)return M({result:{error:O},info:"courtOrder is required"});let{court:s,venue:a}=Si({tournamentRecord:e,courtId:i});if(!s)return{error:vo};let c=Qo({court:s,date:n});if(!c?.bookings)return M({result:{error:qT},info:"No bookings found for this date"});let u=c.bookings.findIndex(m=>m.courtOrder===o);if(u===-1)return M({result:{error:qT},info:`No booking found at row ${o}`});let p=c.bookings.splice(u,1)[0];return!r&&a&&at({payload:{venue:a,tournamentId:e.tournamentId},topic:No,key:a.venueId}),{...P,booking:p}}var b_={};Gt(b_,{addCollectionDefinition:()=>Vh,addCollectionGroup:()=>D_,aggregateTieFormats:()=>N_,compareTieFormats:()=>Ti,getTieFormat:()=>Hf,modifyCollectionDefinition:()=>kh,modifyTieFormat:()=>U_,mutate:()=>R_,orderCollectionDefinitions:()=>E_,query:()=>rv,removeCollectionDefinition:()=>Gh,removeCollectionGroup:()=>P_,removeOrphanedTieFormats:()=>Nh,tieFormatGenderValidityCheck:()=>ml,validateCollectionDefinition:()=>gp});var R_={};Gt(R_,{addCollectionDefinition:()=>Vh,addCollectionGroup:()=>D_,aggregateTieFormats:()=>N_,modifyCollectionDefinition:()=>kh,modifyTieFormat:()=>U_,orderCollectionDefinitions:()=>E_,removeCollectionDefinition:()=>Gh,removeCollectionGroup:()=>P_,removeOrphanedTieFormats:()=>Nh});function Ei({drawDefinition:t,structureId:e,matchUpId:r,structure:n,matchUp:o,eventId:i,event:s}){let a="getTieFormat",c;if(e=n?.structureId??e,r=o?.matchUpId??r,(r||e)&&!t)return{error:$};if(i&&s)c=Yo(s);else if(r){if(t&&(!o||!n)){let u=Wt({drawDefinition:t,matchUpId:r});if(u.error)return u;if(u.matchUp?.matchUpType!==Ir)return M({result:{error:cr},stack:a});n||(n=u.structure),o||(o=u.matchUp)}c=ed({item:o,drawDefinition:t,structure:n,event:s})||ed({item:n,drawDefinition:t,structure:n,event:s})||Yo(t)||Yo(s)}else if(t&&e){if(!n){let u=tt({drawDefinition:t,structureId:e});if(u.error)return u;n=u?.structure}c=ed({item:n,drawDefinition:t,structure:n,event:s})||Yo(t)||Yo(s)}else c=Yo(t)||Yo(s);return c?{...P,structure:n,tieFormat:c,matchUp:o}:M({result:{error:ya},stack:a})}function Sg({matchUp:t,updateInProgressMatchUps:e}){return!t.winningSide&&![Ot].includes(t.matchUpStatus)&&(e||t.matchUpStatus!==Cn&&!ue(t))}function T_({from:t,to:e}){let r=Object.keys(t),n=Yt(r,Object.keys(e)).length===r.length,i=r.filter(c=>t[c]!==e[c]).map(c=>({countChange:e[c]-t[c],collectionId:c})),s=r.every(c=>t[c]===e[c]);return{equivalent:n&&s,matchUpsCountChanges:i}}function CV({updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:r,structure:n,tieFormat:o,eventId:i,matchUp:s,event:a,uuids:c}){let u="updateTieFormat",p=e?.tournamentId,m=0,d=0,l=0,f=0,g=o?.collectionDefinitions.reduce((A,N)=>(A[N.collectionId]=(A[N.collectionId]||0)+N.matchUpCount,A),{}),I=({tieFormat:A})=>{let N=A?.collectionDefinitions.reduce((D,R)=>(D[R.collectionId]=(D[R.collectionId]||0)+R.matchUpCount,D),{});return T_({from:N,to:g}).equivalent},S=Ei({drawDefinition:r})?.tieFormat,h=Ei({event:a})?.tieFormat;if(a&&i){for(let A of a.drawDefinitions??[])T({drawDefinition:A});En({target:a,tieFormat:nr(o),event:a}),f+=1}else if(s){if(!s.tieMatchUps)return M({result:{error:cr},stack:u});let A=mn(s.tieMatchUps?.map(({collectionId:b})=>b)),N=T_({to:g,from:A}),{changes:D,changesArePossible:R,cannotChangeReaon:U}=bV({matchUp:s,check:N});if(N.equivalent)if(Sg({matchUp:s,updateInProgressMatchUps:t}))En({target:s,tieFormat:nr(o),event:a}),f+=1;else return M({result:{error:Kg},info:"matchUp is IN_PROGRESS or COMPLETE",stack:u});else if(R)E({tieFormat:o,matchUp:s,changes:D,uuids:c});else return M({context:{collectionMap:g,matchUpMap:A},result:{error:ri},info:U||"specified changes not possible",stack:u});d+=1,It({eventId:a?.eventId,context:u,drawDefinition:r,tournamentId:p,matchUp:s})}else if(n){let N=y({inheritedTieFormat:S??h,structure:n})?.modifiedMatchUpsCount;N&&(d+=N,m+=1,f+=1);let D=n.tieFormat??(n.tieFormatId?Ei({drawDefinition:r,structure:n,event:a})?.tieFormat:void 0),R=!D||Ti({ancestor:D,descendant:o}).different;R&&(En({target:n,tieFormat:nr(o),event:a}),m+=1,f+=1),(N||R)&&r&&Ft({structureIds:[n.structureId],eventId:a?.eventId,drawDefinition:r})}else if(r)T({drawDefinition:r}),En({target:r,tieFormat:nr(o),event:a}),f+=1;else return{error:$};return{modifiedStructuresCount:m,modifiedMatchUpsCount:d,addedMatchUpsCount:l,modifiedCount:f,...P,tieFormat:o};function T({drawDefinition:A}){let N=A.structures??[],D=[];for(let R of N){if(R.tieFormat||R.tieFormatId)continue;let b=y({inheritedTieFormat:h,structure:R})?.modifiedMatchUpsCount;if(b){m+=1,d+=b;let C=R.structureId;D.push(C)}}return Ft({structureIds:D,eventId:a?.eventId,drawDefinition:A}),D.length}function y({inheritedTieFormat:A,structure:N}){let D=0,R=ht({matchUpFilters:{matchUpTypes:[xt]},structure:N})?.matchUps??[];for(let U of R){let b=Sg({matchUp:U,updateInProgressMatchUps:t}),C=!1,_=mn(U.tieMatchUps?.map(({collectionId:w})=>w)),v=T_({from:_,to:g});if(v.equivalent)(U.tieFormat||U.tieFormatId)&&I(U)&&b&&(En({target:U,tieFormat:nr(o),event:a}),C=!0);else{let{changes:w,changesArePossible:L}=bV({matchUp:U,check:v});if(L&&!U.tieFormat&&!U.tieFormatId)E({changes:w,matchUp:U,tieFormat:o,uuids:c});else if(A){let F=U.tieFormat??(U.tieFormatId?a?.tieFormats?.find(k=>k.tieFormatId===U.tieFormatId):void 0);(!F||Ti({ancestor:A,descendant:F}).different)&&(En({target:U,tieFormat:A,event:a}),C=!0)}else return M({result:{error:ya},stack:u})}C&&(D+=1,It({tournamentId:e?.tournamentId,drawDefinition:r,context:u,eventId:i,matchUp:U}))}return{modifiedMatchUpsCount:D}}function E({uuids:A,matchUp:N,tieFormat:D,changes:R}){En({target:N,tieFormat:nr(D),event:a});let U=[],b=[];return R.forEach(C=>{if(C.countChange>0){let _=Math.max(0,...N.tieMatchUps.filter(L=>L.collectionId===C.collectionId).map(Vr("collectionPosition"))),v=D.collectionDefinitions.find(L=>L.collectionId===C.collectionId),w=Qp({matchUpsLimit:C.countChange,collectionPositionOffset:_,collectionDefinition:v,matchUp:N,uuids:A});b.push(...q(w,!1,!0)),l+=b.length,N.tieMatchUps.push(...w)}else{let _=C.toBePlayedTieMatchUpIds.slice(0,Math.abs(C.countChange));U.push(..._),N.tieMatchUps=N.tieMatchUps.filter(({matchUpId:v})=>!_.includes(v))}}),b.length&&Ho({matchUps:b,drawDefinition:r,tournamentId:p,eventId:i}),U.length&&wn({matchUpIds:U,action:"updateTieFormat",drawDefinition:r,tournamentId:p,eventId:i}),{matchUpIdsRemoved:U,matchUpsAdded:b}}}function bV({check:t,matchUp:e}){let r="",n=[];return{changesArePossible:t.matchUpsCountChanges.every(({collectionId:i,countChange:s})=>{let a=e.tieMatchUps.filter(u=>u.collectionId===i&&u.matchUpStatus===zt).map(Vr("matchUpId")),c=a.length+s>=0||s>0;return!c&&s<0&&(r="Insufficient TO_BE_PLAYED matchUps"),n.push({toBePlayedTieMatchUpIds:a,collectionId:i,countChange:s}),c}),changes:n,cannotChangeReaon:r}}function ym({appliedPolicies:t,drawDefinition:e,auditData:r}){if(!t?.audit?.[Dl])return;let{extension:n}=ot({name:Dl,element:e}),o={value:Array.isArray(n?.value)?n?.value.concat(r):[r],name:Dl};ut({element:e,extension:o})}function kh({updateInProgressMatchUps:t=!1,tournamentRecord:e,collectionOrder:r,collectionName:n,tieFormatName:o,drawDefinition:i,matchUpFormat:s,matchUpCount:a,collectionId:c,matchUpType:u,structureId:p,matchUpId:m,category:d,eventId:l,gender:f,event:g,collectionValueProfiles:I,collectionValue:S,matchUpValue:h,scoreValue:T,setValue:y}){let E="modifyCollectionDefinition",A={collectionValueProfiles:I,collectionValue:S,matchUpValue:h,scoreValue:T,setValue:y},N=QZ({collectionName:n,matchUpFormat:s,matchUpCount:a,matchUpType:u,collectionOrder:r,valueAssignments:A,category:d,gender:f,stack:E});if(N)return N;let D=Ei({drawDefinition:i,structureId:p,matchUpId:m,eventId:l,event:g});if(D.error)return M({result:D,stack:E});let{matchUp:R,structure:U,tieFormat:b}=D,C=nr(b),_=b?.collectionDefinitions.find(H=>H.collectionId===c),v=C?.collectionDefinitions.find(H=>H.collectionId===c);if(!_)return M({info:"source collectionDefinition",result:{error:fe},context:{collectionId:c},stack:E});let w=XZ({collectionValueProfiles:I,sourceCollectionDefinition:_,collectionValue:S,matchUpValue:h,matchUpCount:a,scoreValue:T,setValue:y,stack:E});if(w?.error)return w;let L=[];if(JZ({collectionValueProfiles:I,sourceCollectionDefinition:_,collectionValue:S,matchUpValue:h,scoreValue:T,setValue:y})&&(v.collectionValueProfiles=void 0,v.collectionValue=void 0,v.matchUpValue=void 0,v.scoreValue=void 0,v.setValue=void 0,Object.assign(v,A),L.push({collectionId:c,...et(A)})),(yt(T)||yt(y))&&v.collectionGroupNumber){let H=v.collectionGroupNumber;C.collectionDefinitions=C.collectionDefinitions.map(K=>{let{collectionGroupNumber:Y,...J}=K;return Y===H?J:K}),C.collectionGroups=C.collectionGroups.filter(({groupNumber:K})=>K!==H),L.push({collectionId:c,change:"collectionGroupNumber removed"})}let{aggregateValue:x,valueGoal:k}=ua(C),G=et({aggregateValue:x,valueGoal:k});(G.aggregateValue!==b?.winCriteria.aggregateValue||G.valueGoal!==b?.winCriteria.valueGoal)&&(C.winCriteria=G,L.push({collectionId:c,winCriteria:G}));let V=ZZ({targetCollectionDefinition:v,sourceCollectionDefinition:_,collectionOrder:r,collectionName:n,matchUpFormat:s,matchUpCount:a,matchUpType:u,collectionId:c,modifications:L,category:d,gender:f,stack:E});if(V?.error)return V;let B=et(C);if(D=or({tieFormat:B}),D.error)return M({result:D,stack:E});if(!L.length)return M({result:{...P,modifications:L}});if(b?.tieFormatName!==o?(B.tieFormatName=o,L.push({tieFormatName:o})):L.length&&(delete B.tieFormatName,L.push("tieFormatName removed: modifications without new tieFormatName")),D=CV({tieFormat:B,updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:i,structure:U,eventId:l,matchUp:R,event:g}),!D.error){if(f&&_.gender!==f){let J=ttt({matchUp:R,structure:U,drawDefinition:i});for(let ct of J)ett(ct,c)}let{appliedPolicies:K}=ft({tournamentRecord:e}),Y=et({collectionDefinition:v,drawId:i?.drawId,action:E,structureId:p,matchUpId:m,eventId:l});ym({appliedPolicies:K,drawDefinition:i,auditData:Y})}return M({result:{...D,modifications:L},stack:E})}function QZ({collectionName:t,matchUpFormat:e,matchUpCount:r,matchUpType:n,collectionOrder:o,valueAssignments:i,category:s,gender:a,stack:c}){if(e&&!xr({matchUpFormat:e}))return M({result:{error:O},context:{matchUpFormat:e},stack:c});if(t&&typeof t!="string")return M({result:{error:O},context:{collectionName:t},stack:c});if(a&&!Object.values(pl).includes(a))return M({result:{error:O},context:{gender:a},stack:c});if(s&&typeof s!="object")return M({result:{error:O},context:{category:s},stack:c});let u=Object.values(i).filter(Boolean).length;if(!u&&!o&&!t&&!e&&!r&&!n)return M({result:{error:nt},stack:c});if(u>1)return M({info:"Only one value assignment allowed per collectionDefinition",result:{error:O},stack:c})}function XZ({collectionValueProfiles:t,sourceCollectionDefinition:e,collectionValue:r,matchUpValue:n,matchUpCount:o,scoreValue:i,setValue:s,stack:a}){let c=r??n??i??s;if(t?.length){let u=LT({matchUpCount:o??e?.matchUpCount??0,collectionValueProfiles:t});if(u.errors)return M({result:{error:O},info:u.errors,stack:a})}else if(c&&!yt(c))return M({result:{error:O},info:"value is not an integer",context:{value:c},stack:a})}function JZ({collectionValueProfiles:t,sourceCollectionDefinition:e,collectionValue:r,matchUpValue:n,scoreValue:o,setValue:i}){let s=(c,u)=>Yt(Object.keys(c),Object.keys(u)).length===Object.keys(c).length&&Yt(Object.values(c),Object.values(u)).length===Object.values(c).length,a=t&&(!e.collectionValueProfiles||!s(e.collectionValueProfiles,t));return yt(r)&&e.collectionValue!==r||yt(n)&&e.matchUpValue!==n||yt(o)&&e.scoreValue!==o||yt(i)&&e.setValue!==i||a}function ZZ({targetCollectionDefinition:t,sourceCollectionDefinition:e,collectionOrder:r,collectionName:n,matchUpFormat:o,matchUpCount:i,matchUpType:s,collectionId:a,modifications:c,category:u,gender:p,stack:m}){if(yt(r)&&e.collectionOrder!==r&&(t.collectionOrder=r,c.push({collectionId:a,collectionOrder:r})),n&&e.collectionName!==n&&(t.collectionName=n,c.push({collectionId:a,collectionName:n})),o&&e.matchUpFormat!==o&&(t.matchUpFormat=o,c.push({collectionId:a,matchUpFormat:o})),yt(i)&&e.matchUpCount!==i&&(t.matchUpCount=i,c.push({collectionId:a,matchUpCount:i})),s&&e.matchUpType!==s)return M({result:{error:iI},context:{matchUpType:s},stack:m});u&&e.category!==u&&(t.category=u,c.push({collectionId:a,category:u})),p&&e.gender!==p&&(t.gender=p,c.push({collectionId:a,gender:p}))}function ttt({matchUp:t,structure:e,drawDefinition:r}){if(t)return[t];if(e)return ht({matchUpFilters:{matchUpTypes:[xt]},structure:e})?.matchUps??[];if(r){let n=[];for(let o of r.structures??[]){let i=ht({matchUpFilters:{matchUpTypes:[xt]},structure:o})?.matchUps??[];n.push(...i)}return n}return[]}function ett(t,e){for(let r of t?.sides??[])r.lineUp=(r.lineUp??[]).map(n=>({participantId:n.participantId,collectionAssignments:(n?.collectionAssignments??[]).filter(o=>o.collectionId!==e)}))}function hg({tieFormat:t,orderMap:e}){let r=nr(t);return r.collectionDefinitions?.forEach(n=>{let o=e[n.collectionId];o&&(n.collectionOrder=o)}),r.collectionDefinitions?.sort((n,o)=>Wc(n.collectionOrder)-Wc(o.collectionOrder)),r}function E_({tournamentRecord:t,drawDefinition:e,structureId:r,matchUpId:n,orderMap:o,eventId:i,matchUp:s,event:a}){if(typeof o!="object"||!Object.values(o).every(p=>yt(p)))return M({result:{error:O},context:{orderMap:o}});let c=r?tt({drawDefinition:e,structureId:r}):void 0;if(c?.error)return c;let u=c?.structure;if(i&&a?.tieFormat)MV({tournamentRecord:t,event:a,orderMap:o});else if(n){let p=e&&Wt({drawDefinition:e,matchUpId:n});if(p?.error)return p;if(s=p.matchUp,!s)return{error:Xe};let m=Hf({tournamentRecord:t,matchUpId:n,structure:u,drawDefinition:e,event:a})?.tieFormat;s.tieFormat=hg({tieFormat:m,orderMap:o}),It({tournamentId:t?.tournamentId,eventId:a?.eventId,drawDefinition:e,matchUp:s})}else if(r)if(u?.tieFormat)u.tieFormat=hg({tieFormat:u.tieFormat,orderMap:o}),vV({eventId:a?.eventId,tournamentRecord:t,drawDefinition:e,structure:u,orderMap:o}),Ft({drawDefinition:e,structureIds:[u.structureId]});else if(e.tieFormat)y_({structureIds:[r],tournamentRecord:t,drawDefinition:e,orderMap:o,event:a});else if(a?.tieFormat)MV({structureIds:[r],tournamentRecord:t,orderMap:o,event:a});else return{error:fe};else if(e?.tieFormat)y_({tournamentRecord:t,drawDefinition:e,orderMap:o,event:a});else return{error:fe};return{...P}}function MV({tournamentRecord:t,structureIds:e,orderMap:r,event:n}){let o=hg({tieFormat:n.tieFormat,orderMap:r});e?.length||(n.tieFormat=o);for(let i of n.drawDefinitions??[])y_({tournamentRecord:t,drawDefinition:i,structureIds:e,orderMap:r,event:n})}function y_({tournamentRecord:t,drawDefinition:e,structureIds:r,orderMap:n,event:o}){let i=e.tieFormat??o?.tieFormat,s=hg({tieFormat:i,orderMap:n});r?.length||(e.tieFormat=s);let a=[];for(let c of e.structures??[])r?.length&&!r.includes(c.structureId)||((c.tieFormat||r?.includes(c.structureId))&&(c.tieFormat=hg({tieFormat:c.tieFormat??e.tieFormat??o?.tieFormat,orderMap:n})),vV({eventId:o?.eventId,tournamentRecord:t,drawDefinition:e,structure:c,orderMap:n}),a.push(c.structureId));Ft({drawDefinition:e,structureIds:a})}function vV({tournamentRecord:t,drawDefinition:e,structure:r,orderMap:n,eventId:o}){let i=ht({matchUpFilters:{matchUpTypes:[xt]},structure:r})?.matchUps;for(let s of i)s.tieFormat&&(s.tieFormat=hg({tieFormat:s.tieFormat,orderMap:n}),It({tournamentId:t?.tournamentId,drawDefinition:e,eventId:o,matchUp:s}))}function Gh({updateInProgressMatchUps:t=!0,tieFormatComparison:e,tournamentRecord:r,drawDefinition:n,tieFormatName:o,collectionId:i,structureId:s,matchUpId:a,eventId:c,matchUp:u,event:p}){let m="removeCollectionDefinition",d=u?void 0:Ei({drawDefinition:n,structureId:s,matchUpId:a,eventId:c,event:p});if(d?.error)return M({result:d,stack:m});let l=d?.structure;u=u??d?.matchUp;let f=d?.tieFormat,g=nr(f);if(d=or({tieFormat:g}),d.error)return M({result:d,stack:m});let I=g?.collectionDefinitions?.find(b=>b.collectionId===i);if(!I)return M({result:{error:fe,collectionId:i}});g.collectionDefinitions=g.collectionDefinitions.filter(b=>b.collectionId!==i),I.collectionGroupNumber&&(g.collectionDefinitions=g.collectionDefinitions.map(b=>{let{collectionGroupNumber:C,..._}=b;return _}),g.collectionGroups=g.collectionGroups.filter(({groupNumber:b})=>b!==I.collectionGroupNumber));let{aggregateValue:S,valueGoal:h}=ua(g);g.winCriteria=et({aggregateValue:S,valueGoal:h});let T=f?.winCriteria.valueGoal,y=f?.winCriteria.aggregateValue;(T&&T!==h||S&&!y)&&(o?g.tieFormatName=o:delete g.tieFormatName);let E=rtt({matchUpId:a,matchUp:u,structureId:s,structure:l,drawDefinition:n,event:p}),A=stt({updateInProgressMatchUps:t,tieFormatComparison:e,collectionId:i,tieFormat:g,matchUps:E});if(!A.length)return{error:Na};let{appliedPolicies:N}=ft({tournamentRecord:r});if(a&&u&&t){let b=ntt({tournamentRecord:r,appliedPolicies:N,drawDefinition:n,collectionId:i,matchUpId:a,matchUp:u,event:p});if(b.error)return b;u=b.matchUp}let D=[];for(let b of A){ott({deletedMatchUpIds:D,tournamentRecord:r,drawDefinition:n,collectionId:i,tieFormat:g,stack:m,event:p,matchUp:b});let C=itt({updateInProgressMatchUps:t,tournamentRecord:r,appliedPolicies:N,drawDefinition:n,matchUp:b,event:p});if(C?.error)return C}D.length&&wn({tournamentId:r?.tournamentId,matchUpIds:D,eventId:p?.eventId,drawDefinition:n});let R=et(g);if(d=or({tieFormat:R}),d.error)return M({result:d,stack:m});if(c&&p)En({target:p,tieFormat:R,event:p});else if(a&&u)En({target:u,tieFormat:R,event:p});else if(l)En({target:l,tieFormat:R,event:p});else if(n)En({target:n,tieFormat:R,event:p});else if(!u||!n)return{error:$};Ft({drawDefinition:n,eventId:p?.eventId});let U=et({drawId:n?.drawId,action:m,collectionId:i,structureId:s,matchUpId:a,eventId:c});return ym({appliedPolicies:N,drawDefinition:n,auditData:U}),{tieFormat:R,deletedMatchUpIds:D,targetMatchUps:A,...P}}function rtt({matchUpId:t,matchUp:e,structureId:r,structure:n,drawDefinition:o,event:i}){return t&&e?[e]:r&&n?ht({matchUpFilters:{matchUpTypes:[xt]},structure:n})?.matchUps??[]:o?rr({matchUpFilters:{matchUpTypes:[xt]},drawDefinition:o})?.matchUps??[]:i?vn({matchUpFilters:{matchUpTypes:[xt]},drawDefinition:o})?.matchUps??[]:[]}function ntt({tournamentRecord:t,appliedPolicies:e,drawDefinition:r,collectionId:n,matchUpId:o,matchUp:i,event:s}){let a=i.tieMatchUps?.filter(u=>u.collectionId===n),c=i;for(let u of a??[]){let p=vi({matchUpId:u.matchUpId,tieMatchUpId:c?.matchUpId,winningSide:void 0,removeScore:!0,tournamentRecord:t,appliedPolicies:e,drawDefinition:r,event:s});if(p.error||(p=Wt({drawDefinition:r,matchUpId:o}),p.error))return p;c=p?.matchUp}return{matchUp:c}}function ott({deletedMatchUpIds:t,collectionId:e,tieFormat:r,stack:n,event:o,matchUp:i,tournamentRecord:s,drawDefinition:a}){for(let c of i?.sides??[])c.lineUp=(c.lineUp??[]).map(u=>({participantId:u.participantId,collectionAssignments:(u?.collectionAssignments??[]).filter(p=>p.collectionId!==e)}));i.tieMatchUps=(i.tieMatchUps??[]).filter(c=>{let u=c.collectionId===e;return u&&t.push(c.matchUpId),!u}),(i.tieFormat||i.tieFormatId)&&En({target:i,tieFormat:nr(r),event:o}),It({tournamentId:s?.tournamentId,eventId:o?.eventId,drawDefinition:a,context:n,matchUp:i})}function itt({updateInProgressMatchUps:t,tournamentRecord:e,appliedPolicies:r,drawDefinition:n,matchUp:o,event:i}){if(t)return ho({matchUpId:o.matchUpId,exitWhenNoValues:!0,tournamentRecord:e,appliedPolicies:r,drawDefinition:n,event:i})}function stt({updateInProgressMatchUps:t,tieFormatComparison:e,collectionId:r,tieFormat:n,matchUps:o}){return(o??[]).filter(i=>{let a=i.tieMatchUps?.filter(u=>u.collectionId===r)?.some(ue);if(t&&!a)return!0;if(i.winningSide||i.matchUpStatus===ie)return!1;let c=e&&i.tieFormat?Ti({descendant:i.tieFormat,ancestor:n})?.different:!1;return t||i.matchUpStatus!==Cn&&!ue(i)&&!c})}function Vh({updateInProgressMatchUps:t=!0,collectionDefinition:e,referenceCategory:r,tournamentRecord:n,policyDefinitions:o,enforceCategory:i,referenceGender:s,drawDefinition:a,tieFormatName:c,enforceGender:u,structureId:p,matchUpId:m,matchUp:d,eventId:l,uuids:f,event:g}){let I="addCollectionDefinition",S=ft({tournamentRecord:n,drawDefinition:a,event:g}).appliedPolicies??{},{checkCategory:h,checkGender:T}=att({policyDefinitions:o,appliedPolicies:S,enforceCategory:i,enforceGender:u,referenceCategory:r,referenceGender:s,event:g}),y=gp({referenceCategory:r??g?.category,collectionDefinition:e,referenceGender:s,checkCategory:h,checkGender:T,event:g});if(y.error)return M({result:y,stack:I});let E=d?.tieFormat?void 0:Ei({drawDefinition:a,structureId:p,matchUpId:m,eventId:l,event:g});if(E?.error)return M({result:{error:E.error},stack:I});let A=E?.structure;d=d??E?.matchUp;let N=d?.tieFormat??E?.tieFormat,D=nr(N);if(E=or({tieFormat:D}),E?.error)return M({result:{error:E.error},stack:I});if(e.collectionId){if(D.collectionDefinitions.map(({collectionId:G})=>G).includes(e.collectionId))return M({context:{collectionId:e.collectionId},result:{error:LU}})}else e.collectionId=it();D.collectionDefinitions.push(e),D.collectionDefinitions.sort((k,G)=>(k.collectionOrder||0)-(G.collectionOrder||0)).forEach((k,G)=>k.collectionOrder=G+1);let{aggregateValue:R,valueGoal:U}=ua(D);D.winCriteria=et({aggregateValue:R,valueGoal:U});let b=N?.winCriteria.valueGoal,C=N?.winCriteria.aggregateValue;(b&&b!==U||R&&!C)&&(c?D.tieFormatName=c:delete D.tieFormatName);let _=[],v=[],w=[],L=et(D);if(E=or({tieFormat:L}),E?.error)return M({result:{error:E.error},stack:I});let F=ctt({updateInProgressMatchUps:t,collectionDefinition:e,modifiedStructureIds:_,prunedTieFormat:L,tournamentRecord:n,drawDefinition:a,targetMatchUps:w,addedMatchUps:v,structureId:p,structure:A,matchUpId:m,matchUp:d,eventId:l,event:g,uuids:f,stack:I});if(F?.error)return F;w=F?.targetMatchUps??w;let x=et({drawId:a?.drawId,collectionDefinition:e,action:I,structureId:p,matchUpId:m,eventId:l});return ym({appliedPolicies:S,drawDefinition:a,auditData:x}),{tieFormat:L,targetMatchUps:w,addedMatchUps:v,...P}}function att({policyDefinitions:t,appliedPolicies:e,enforceCategory:r,enforceGender:n,referenceCategory:o,referenceGender:i,event:s}){let a=t?.[He]??e?.[He],c=r??a?.participants?.enforceCategory,u=(n??a?.participants?.enforceGender)!==!1,p=!!((o??s?.category)&&c!==!1),m=!!((i??s?.gender)&&u);return{checkCategory:p,checkGender:m}}function ctt({updateInProgressMatchUps:t,collectionDefinition:e,modifiedStructureIds:r,prunedTieFormat:n,tournamentRecord:o,drawDefinition:i,targetMatchUps:s,addedMatchUps:a,structureId:c,structure:u,matchUpId:p,matchUp:m,eventId:d,event:l,uuids:f,stack:g}){if(d&&l){En({target:l,tieFormat:n,event:l});for(let I of l.drawDefinitions??[])if(!(I.tieFormat||I.tieFormatId))for(let S of I.structures??[]){if(S.tieFormat||S.tieFormatId)continue;let h=A_({updateInProgressMatchUps:t,collectionDefinition:e,structure:S,uuids:f});a.push(...h.newMatchUps),s.push(...h.targetMatchUps),r.push(S.structureId)}return HN({modifiedMatchUps:s,eventId:l?.eventId,modifiedStructureIds:r,tournamentRecord:o,drawDefinition:i,addedMatchUps:a,stack:g}),{targetMatchUps:s}}if(c&&u){En({target:u,tieFormat:n,event:l});let I=A_({updateInProgressMatchUps:t,collectionDefinition:e,structure:u,uuids:f});a.push(...I.newMatchUps);let S=I.targetMatchUps;return HN({modifiedMatchUps:S,eventId:l?.eventId,modifiedStructureIds:r,tournamentRecord:o,drawDefinition:i,addedMatchUps:a,stack:g}),{targetMatchUps:S}}if(p&&m){if(!Sg({matchUp:m,updateInProgressMatchUps:t}))return M({result:{error:Kg},stack:g});En({target:m,tieFormat:n,event:l});let I=Qp({collectionDefinition:e,matchUp:m,uuids:f});return Array.isArray(m.tieMatchUps)||(m.tieMatchUps=[]),m.tieMatchUps.push(...I),a.push(...I),HN({modifiedMatchUps:[m],eventId:l?.eventId,modifiedStructureIds:r,tournamentRecord:o,drawDefinition:i,addedMatchUps:a,stack:g}),{targetMatchUps:s}}if(i){En({target:i,tieFormat:n,event:l});for(let I of i.structures??[]){let S=A_({updateInProgressMatchUps:t,collectionDefinition:e,structure:I,uuids:f});r.push(I.structureId),a.push(...S.newMatchUps),s.push(...S.targetMatchUps)}return HN({modifiedMatchUps:s,eventId:l?.eventId,tournamentRecord:o,drawDefinition:i,addedMatchUps:a,stack:g}),{targetMatchUps:s}}return{error:$}}function A_({updateInProgressMatchUps:t,collectionDefinition:e,structure:r,uuids:n}){let o=[],s=(ht({matchUpFilters:{matchUpTypes:[xt]},structure:r})?.matchUps).filter(a=>Sg({matchUp:a,updateInProgressMatchUps:t})&&!a.tieFormat&&!a.tieFormatId);for(let a of s){let c=Qp({collectionDefinition:e,matchUp:a,uuids:n});Array.isArray(a.tieMatchUps)||(a.tieMatchUps=[]),a.tieMatchUps.push(...c),o.push(...c)}return{newMatchUps:o,targetMatchUps:s}}function HN({modifiedStructureIds:t,tournamentRecord:e,modifiedMatchUps:r,drawDefinition:n,addedMatchUps:o,eventId:i,stack:s}){Ho({tournamentId:e?.tournamentId,matchUps:o,drawDefinition:n,eventId:i}),r?.forEach(a=>{It({tournamentId:e?.tournamentId,drawDefinition:n,context:s,matchUp:a,eventId:i})}),Ft({structureIds:t,drawDefinition:n,eventId:i})}function OV({updateInProgressMatchUps:t,drawDefinition:e,structureId:r,structure:n,matchUpId:o,matchUp:i}){let s=[];return o&&i?s=[i]:r&&n?s=ht({matchUpFilters:{matchUpTypes:[xt]},structure:n})?.matchUps??[]:e&&(s=rr({matchUpFilters:{matchUpTypes:[xt]},drawDefinition:e})?.matchUps??[]),{targetMatchUps:s.filter(c=>!c.winningSide&&c.matchUpStatus!==ie&&(t||c.matchUpStatus!==Cn&&!ue(c)))}}function _V({updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:r,targetMatchUps:n,tieFormat:o,event:i}){for(let s of n){let a=!!s.tieFormat;a&&(s.tieFormat=nr(o));let c;if(t){let u=ft({tournamentRecord:e,drawDefinition:r,event:i}).appliedPolicies,p=ho({matchUpId:s.matchUpId,exitWhenNoValues:!0,tournamentRecord:e,appliedPolicies:u,drawDefinition:r,event:i});if(p.error)return p;c=p.score}a&&!c&&It({tournamentId:e?.tournamentId,context:"updateTargetTeamMatchUps",eventId:i?.eventId,matchUp:s,drawDefinition:r})}return{...P}}function YN({updateInProgressMatchUps:t,originalValueGoal:e,tournamentRecord:r,wasAggregateValue:n,tieFormatName:o,drawDefinition:i,structureId:s,structure:a,tieFormat:c,matchUpId:u,matchUp:p,eventId:m,event:d}){let{aggregateValue:l,valueGoal:f}=ua(c);c.winCriteria=et({aggregateValue:l,valueGoal:f}),(e&&e!==f||l&&!n)&&(o?c.tieFormatName=o:delete c.tieFormatName);let{targetMatchUps:g}=OV({updateInProgressMatchUps:t,drawDefinition:i,structureId:s,structure:a,matchUpId:u,matchUp:p});_V({updateInProgressMatchUps:t,tournamentRecord:r,targetMatchUps:g,drawDefinition:i,tieFormat:c,event:d});let I=et(c),S=or({tieFormat:I});if(S.error)return S;if(m&&d)En({target:d,tieFormat:I,event:d});else if(u&&p)En({target:p,tieFormat:I,event:d});else if(a)En({target:a,tieFormat:I,event:d});else if(i)En({target:i,tieFormat:I,event:d});else if(!p||!i)return{error:$};return Ft({drawDefinition:i,eventId:d?.eventId}),{...P}}function P_({updateInProgressMatchUps:t=!0,collectionGroupNumber:e,tournamentRecord:r,drawDefinition:n,tieFormatName:o,structureId:i,matchUpId:s,matchUp:a,eventId:c,event:u}){if(!e)return{error:nt};if(Number.isNaN(Number(e)))return{error:O};let p="removeCollectionGroup",m=a?void 0:Ei({drawDefinition:n,structureId:i,matchUpId:s,eventId:c,event:u});if(m?.error)return M({result:m,stack:p});let d=m?.structure;a=a??m?.matchUp;let l=m?.tieFormat,f=l?.winCriteria.valueGoal,g=l?.winCriteria.aggregateValue,I=nr(l);if(m=or({tieFormat:I}),m.error)return M({result:m,stack:p});let S=[];if(I.collectionDefinitions=(I.collectionDefinitions??[]).map(h=>{let{collectionGroupNumber:T,...y}=h;return T===e?(S.push(h.collectionId),y):h}),I.collectionGroups=(I.collectionGroups??[]).filter(({groupNumber:h})=>h!==e),m=YN({updateInProgressMatchUps:t,originalValueGoal:f,wasAggregateValue:g,tournamentRecord:r,drawDefinition:n,tieFormatName:o,structureId:i,structure:d,tieFormat:I,matchUpId:s,matchUp:a,eventId:c,event:u}),!m.error){let{appliedPolicies:h}=ft({tournamentRecord:r}),T=et({drawId:n?.drawId,collectionGroupNumber:e,action:p,structureId:i,matchUpId:s,eventId:c});ym({appliedPolicies:h,drawDefinition:n,auditData:T})}return M({result:{...m,modifiedCollectionIds:S},stack:p})}function N_({tournamentRecord:t}){if(!t)return{error:j};let e=0;for(let r of t.events??[]){let n=r.tieFormats??[],o=u=>{if(!u.tieFormat)return;let p;for(let m of n)Ti({descendant:u.tieFormat,ancestor:m}).different||(p=m.tieFormatId);if(p)u.tieFormatId=p,delete u.tieFormat;else{let m=q(u.tieFormat,void 0,!0);m.tieFormatId??=it(),u.tieFormatId=m.tieFormatId,delete u.tieFormat,n.push(m),e+=1}};o(r);for(let u of r.drawDefinitions??[]){o(u);for(let p of u.structures??[])o(p)}let i=(u,p)=>{let m=a.matchUps?.find(d=>d.matchUpId===u);m&&(m.tieFormatId=p,delete m.tieFormat,It({tournamentId:t?.tournamentId,eventId:r.eventId,matchUp:m}))},s=u=>{let p=q(u.tieFormat,void 0,!0);p.tieFormatId??=it(),n.push(p),e+=1,i(u.matchUpId,p.tieFormatId)},a=vn({matchUpFilters:{matchUpTypes:[Ir]},event:r}),c=a.matchUps??[];for(let u of c){let p;for(let m of n)u.tieFormat&&Ti({descendant:u.tieFormat,ancestor:m}).different||(p=m.tieFormatId);p?i(u.matchUpId,p):s(u)}n.length&&(r.tieFormats=n)}return{...P,addedCount:e}}function D_({updateInProgressMatchUps:t=!0,tournamentRecord:e,groupDefinition:r,drawDefinition:n,collectionIds:o,tieFormatName:i,structureId:s,matchUpId:a,matchUp:c,eventId:u,event:p}){let m="addCollectionGroup";if(!Array.isArray(o))return M({result:{error:nt},stack:m});let d=c?void 0:Ei({drawDefinition:n,structureId:s,matchUpId:a,eventId:u,event:p});if(d?.error)return M({result:d,stack:m});let l=d?.structure;c=c||d?.matchUp;let f=d?.tieFormat,g=f?.winCriteria.valueGoal,I=nr(f);if(d=or({tieFormat:I}),d.error)return M({result:d,stack:m});for(let T of I.collectionDefinitions){let{collectionId:y,collectionGroupNumber:E}=T;if(E&&o.includes(y))return M({info:"collectionIds cannot be part of other collectionGroups",result:{error:O},stack:m})}let h=(I.collectionGroups??[]).reduce((T,y)=>y.groupNumber>T?y.groupNumber:T,0)+1;return r.groupNumber=h,I.collectionDefinitions=I.collectionDefinitions.map(T=>o.includes(T.collectionId)?{...T,collectionGroupNumber:h}:T),I.collectionGroups=[...I.collecitonGroups??[],r],YN({updateInProgressMatchUps:t,originalValueGoal:g,tournamentRecord:e,drawDefinition:n,tieFormatName:i,structureId:s,structure:l,tieFormat:I,matchUpId:a,matchUp:c,eventId:u,event:p})}function U_({updateInProgressMatchUps:t=!1,tieFormatComparison:e,modifiedTieFormat:r,tournamentRecord:n,considerations:o,drawDefinition:i,structureId:s,matchUpId:a,eventId:c,uuids:u,event:p}){let m="modifyTieFormat";if(!or({tieFormat:r}).valid)return M({result:{error:ri},info:"falied validation",stack:m});let d=Ei({drawDefinition:i,structureId:s,matchUpId:a,eventId:c,event:p});if(d.error)return M({result:d,stack:m});let{matchUp:l,tieFormat:f}=d,g=nr(f),I=Ti({descendant:r,ancestor:g,considerations:o});if(I.invalid)return M({context:{invalid:I.invalid},result:{error:ri},stack:m});if(!I?.different)return M({result:{...P},info:"Nothing to do",stack:m});let S=g.collectionDefinitions.map(({collectionId:U})=>U),h=r.collectionDefinitions.map(({collectionId:U})=>U),T=S.filter(U=>!h.includes(U)),y=r.collectionDefinitions.filter(({collectionId:U})=>!S.includes(U)),E=y.map(Vr("collectionId")),A=[],N,D=r.tieFormatName;for(let U of r.collectionDefinitions){if(E.includes(U.collectionId))continue;let b=kh({updateInProgressMatchUps:t,...U,tournamentRecord:n,tieFormatName:D,drawDefinition:i,structureId:s,matchUpId:a,eventId:c,event:p});if(b.modifications&&A.push(...b.modifications),b.error)return M({result:b,stack:m});b.tieFormat&&(N=b.tieFormat)}for(let U of y){let b=Vh({updateInProgressMatchUps:t,collectionDefinition:U,tournamentRecord:n,drawDefinition:i,tieFormatName:D,structureId:s,matchUpId:a,matchUp:l,eventId:c,uuids:u,event:p});if(b.error)return M({result:b,stack:m});b.tieFormat&&(N=b.tieFormat)}for(let U of T){let b=Gh({updateInProgressMatchUps:t,tieFormatComparison:e,tournamentRecord:n,drawDefinition:i,tieFormatName:D,collectionId:U,structureId:s,matchUpId:a,eventId:c,matchUp:l,event:p});if(b.error)return M({result:b,stack:m});b.tieFormat&&(N=b.tieFormat)}return f?.tieFormatName!==D?(N.tieFormatName=D,A.push({tieFormatName:D})):(A.length||E.length||T.length)&&(delete N.tieFormatName,A.push("tieFormatName removed: modifications without new tieFormatName")),N.collectionDefinitions=N.collectionDefinitions.sort((U,b)=>Wc(U.collectionOrder)-Wc(b.collectionOrder)).map((U,b)=>({...U,collectionOrder:b+1})),{processedTieFormat:nr(N),modifications:A,...P}}var q_={};Gt(q_,{addDrawDefinitionExtension:()=>_I,addEventExtension:()=>Go,addEventTimeItem:()=>Rs,addExtension:()=>ut,addMutationLock:()=>O_,addNotes:()=>Sd,addOnlineResource:()=>L_,addParticipantExtension:()=>vR,addParticipantTimeItem:()=>ES,addTimeItem:()=>oo,addTournamentExtension:()=>OI,addTournamentTimeItem:()=>vu,analyzeDraws:()=>Xp,analyzeTournament:()=>IP,cleanExpiredMutationLocks:()=>aP,copyTournamentRecord:()=>C_,createTournamentRecord:()=>qd,generate:()=>M_,getAggregateTeamResults:()=>pP,getAllowedDrawTypes:()=>kf,getAllowedMatchUpFormats:()=>sP,getApplicableAwardProfileLevels:()=>vd,getAppliedPolicies:()=>ft,getCompetitionDateRange:()=>Vf,getCompetitionPenalties:()=>cP,getEventRankingPoints:()=>Od,getMutationLocks:()=>SP,getPolicyDefinitions:()=>fo,getRegistrationProfile:()=>uP,getTournamentInfo:()=>ia,getTournamentPenalties:()=>Gf,getTournamentPersons:()=>mP,getTournamentPoints:()=>Ja,getTournamentStructures:()=>jE,getTournamentTimeItem:()=>_l,hydrateTournamentRecord:()=>__,mutate:()=>j_,query:()=>tv,removeDrawDefinitionExtension:()=>OR,removeEventExtension:()=>Qm,removeExtension:()=>dr,removeMutationLock:()=>v_,removeNotes:()=>FS,removeOnlineResource:()=>w_,removeParticipantExtension:()=>_R,removeTournamentExtension:()=>xI,setRegistrationProfile:()=>B_,setTournamentCategories:()=>W_,setTournamentDates:()=>Bh,setTournamentEndDate:()=>Y_,setTournamentLocalTimeZone:()=>G_,setTournamentName:()=>F_,setTournamentNotes:()=>k_,setTournamentStartDate:()=>H_,setTournamentStatus:()=>x_,setTournamentTier:()=>V_,suggestFormatPlans:()=>gP});var M_={};Gt(M_,{copyTournamentRecord:()=>C_,createTournamentRecord:()=>qd});function C_(t){let e=X(t,[{tournamentRecord:!0,startDate:!0,endDate:!1,tournamentName:!0}]);if(e.error)return e;let{startDate:r,endDate:n}=t.tournamentRecord,o=1440*60*1e3,s=(r&&n?new Date(mt(n)).getTime()-new Date(mt(r)).getTime():0)/o,a=t.endDate||oy(t.startDate,s),c=l=>l?.filter(({itemType:f})=>t.itemTypeList?.includes(f)),u=l=>l?.filter(({name:f})=>t.extensionList?.includes(f)),p=l=>{let{timeItems:f,extensions:g,...I}=l;return q({...I,timeItems:c(f),extensions:u(g)},!1,!0)},m=l=>{let{drawDefinitions:f,timeItems:g,extensions:I,startDate:S,endDate:h,...T}=l;return q({extensions:u(I),timeItems:c(g),startDate:t.startDate,endDate:a,...T},!1,!0)},d={participants:t.copyParticipants?t.tournamentRecord.participants?.map(p)??[]:[],parentOrganisation:q({...t.tournamentRecord.parentOrganisation},!1,!0),venues:q(t.tournamentRecord.venues??[],!1,!0),extensions:u(t.tournamentRecord.extensions),timeItems:c(t.tournamentRecord.timeItems),events:t.tournamentRecord.events?.map(m)??[],weekdays:[...t.tournamentRecord.weekdays??[]],tournamentName:t.tournamentName,startDate:t.startDate,tournamentId:it(),endDate:a};return{...P,tournamentRecord:d}}var j_={};Gt(j_,{addDrawDefinitionExtension:()=>_I,addEventExtension:()=>Go,addEventTimeItem:()=>Rs,addExtension:()=>ut,addMutationLock:()=>O_,addNotes:()=>Sd,addOnlineResource:()=>L_,addParticipantExtension:()=>vR,addParticipantTimeItem:()=>ES,addTimeItem:()=>oo,addTournamentExtension:()=>OI,addTournamentTimeItem:()=>vu,hydrateTournamentRecord:()=>__,removeDrawDefinitionExtension:()=>OR,removeEventExtension:()=>Qm,removeExtension:()=>dr,removeMutationLock:()=>v_,removeNotes:()=>FS,removeOnlineResource:()=>w_,removeParticipantExtension:()=>_R,removeTournamentExtension:()=>xI,setRegistrationProfile:()=>B_,setTournamentCategories:()=>W_,setTournamentDates:()=>Bh,setTournamentEndDate:()=>Y_,setTournamentLocalTimeZone:()=>G_,setTournamentName:()=>F_,setTournamentNotes:()=>k_,setTournamentStartDate:()=>H_,setTournamentStatus:()=>x_,setTournamentTier:()=>V_});function v_(t){let{tournamentRecord:e,drawDefinition:r,event:n,venueId:o,lockId:i,scope:s,lockToken:a,forceRelease:c}=t;if(!e)return{error:j};if(!i&&!s)return{error:nt,info:"Provide lockId or scope to identify the lock"};let u;if(r)u=r;else if(n)u=n;else if(o){let f=Ln({tournamentRecord:e,venueId:o});if(f.error)return{error:f.error};u=f.venue}else u=e;let{extension:p}=ot({element:u,name:sn}),m=p?.value??{locks:[]},d=m.locks.findIndex(f=>i?f.lockId===i:f.scope===s);if(d===-1)return{error:HU};let l=m.locks[d];return!c&&l.lockToken!==a?{error:YU}:(m.locks.splice(d,1),ut({element:u,extension:{name:sn,value:m},creationTime:!1}),{...P})}function O_(t){let{tournamentRecord:e,drawDefinition:r,event:n,venueId:o,scope:i,lockToken:s,methods:a}=t,c=t.expiresAt??null;if(!e)return{error:j};if(!i||!s)return{error:nt,info:i?"Missing lockToken":"Missing scope"};if(c!==null&&isNaN(Date.parse(c)))return{error:O,info:"Invalid expiresAt; must be ISO 8601 or null"};let u;if(r)u=r;else if(n)u=n;else if(o){let I=Ln({tournamentRecord:e,venueId:o});if(I.error)return{error:I.error};u=I.venue}else u=e;let{extension:p}=ot({element:u,name:sn}),m=p?.value??{locks:[]},d=new Date().toISOString();m.locks=m.locks.filter(I=>I.expiresAt===null||I.expiresAt>d);let l=m.locks.find(I=>I.scope!==i?!1:!I.methods||!a?!0:I.methods.some(S=>a.includes(S)));if(l)return l.lockToken===s?(l.expiresAt=c,a?l.methods=a:delete l.methods,ut({element:u,extension:{name:sn,value:m},creationTime:!1}),{...P,lockId:l.lockId}):{error:WU};let f=it(),g={lockId:f,lockToken:s,scope:i,expiresAt:c,createdAt:d,...a&&{methods:a}};return m.locks.push(g),ut({element:u,extension:{name:sn,value:m},creationTime:!1}),utt(e,u),{...P,lockId:f}}function utt(t,e){if(e===t){let{extension:n}=ot({element:t,name:sn});n?.value&&!n.value.enabled&&(n.value.enabled=!0,ut({element:t,extension:{name:sn,value:n.value},creationTime:!1}));return}let{extension:r}=ot({element:t,name:sn});r?.value?r.value.enabled||(r.value.enabled=!0,ut({element:t,extension:{name:sn,value:r.value},creationTime:!1})):ut({element:t,extension:{name:sn,value:{enabled:!0,locks:[]}},creationTime:!1})}function __(t){let{tournamentRecord:e,eventProfiles:r=[],directives:n,policyDefinitions:o}=t;return e?((e.events??[]).forEach(s=>{let a=r.find(c=>c.eventId&&c.eventId===s.eventId);(a?.directives?.hydrateRoundNames||n?.hydrateRoundNames)&&s.drawDefinitions?.forEach(c=>{(a?.policyDefinitions?.[Fo]||o?.[Fo])&&tP({drawDefinition:c,appliedPolicies:o})})}),{tournamentRecord:e}):{error:j}}function x_({tournamentRecord:t,status:e}){return t?e&&!Object.keys(cA).includes(e)?{error:O,info:"Unknown status"}:(t.tournamentStatus=e,{...P}):{error:j}}function w_(t){let e=X(t,[{tournamentRecord:!0,onlineResource:!0}]);if(e.error)return e;let{tournamentRecord:r,onlineResource:n,organisationId:o,participantId:i,personId:s,courtId:a,venueId:c}=t;if(o){if(r.parentOrganisation?.parentOrganisationId!==o)return M({result:{error:fe}});Tg({element:r.parentOrganisation,onlineResource:n})}else if(i||s){let u=(r.participants??[]).find(p=>s&&p.person?.personId===s||p.participantId===i);if(!u)return s?M({result:{error:fe}}):M({result:{error:ee}});if(s){if(u.person?.personId!==s)return M({result:{error:xi}});Tg({element:u.person,onlineResource:n})}else Tg({element:u,onlineResource:n})}else if(a){let u=(r.venues??[]).filter(p=>!c||p.venueId===c).flatMap(p=>(p.courts??[]).filter(m=>m.courtId===a))?.[0];if(!u)return M({result:{error:vo}});Tg({element:u,onlineResource:n})}else if(c){let u=(r.venues??[]).find(p=>p.venueId===c);if(!u)return M({result:{error:wi}});Tg({element:u,onlineResource:n})}else Tg({element:r,onlineResource:n}),at({payload:{parentOrganisation:r.parentOrganisation,onlineResources:r.onlineResources,tournamentId:r.tournamentId},topic:mi});return{...P}}function Tg({element:t,onlineResource:e}){let r=(t.onlineResources??[]).filter(n=>!(n?.[gl]===e[gl]&&n?.[Il]===e[Il]&&n?.[nu]===e[nu]));t.onlineResources=r}function L_(t){let e=X(t,[{tournamentRecord:!0,onlineResource:!0}]);if(e.error)return e;let{tournamentRecord:r,onlineResource:n,organisationId:o,participantId:i,personId:s,courtId:a,venueId:c}=t;if(o){if(r.parentOrganisation?.parentOrganisationId!==o)return M({result:{error:fe}});yg({element:r.parentOrganisation,onlineResource:n})}else{if(i&&s&&i!==s)return M({result:{error:xi}});if(i||s){let u=(r.participants??[]).find(p=>s&&p.person?.personId===s||p.participantId===i);if(!u)return s?M({result:{error:fe}}):M({result:{error:ee}});if(s){if(u.person?.personId!==s)return M({result:{error:xi}});yg({element:u.person,onlineResource:n})}else yg({element:u,onlineResource:n})}else if(a){let u=(r.venues??[]).filter(p=>!c||p.venueId===c).flatMap(p=>(p.courts??[]).filter(m=>m.courtId===a))?.[0];if(!u)return M({result:{error:vo}});yg({element:u,onlineResource:n})}else if(c){let u=(r.venues??[]).find(p=>p.venueId===c);if(!u)return M({result:{error:wi}});yg({element:u,onlineResource:n})}else yg({element:r,onlineResource:n}),at({payload:{parentOrganisation:r.parentOrganisation,onlineResources:r.onlineResources,tournamentId:r.tournamentId},topic:mi})}return{...P}}function yg({element:t,onlineResource:e}){let r=(t.onlineResources??[]).filter(n=>n?.[sy]!==e[sy]&&n?.[nu]!==e[nu]);return r.push(e),t.onlineResources=r,{...P}}function F_({tournamentRecord:t,promotionalName:e,tournamentName:r,formalName:n}){let o=dt({tournamentRecord:t},[rt]);if(o.error)return o;let i=t.tournamentId,s={tournamentId:i};return r&&r!==t.tournamentName&&(t.tournamentName=r,s.tournamentName=r),e&&e!==t.promotionalName&&(t.promotionalName=e,s.promotionalName=e),n&&n!==t.formalName&&(t.formalName=n,s.formalName=n),t.promotionalName===t.tournamentName&&(delete t.promotionalName,s.promotionalName=""),t.formalName===t.tournamentName&&(delete t.formalName,s.formalName=""),Object.keys(s).length>1&&at({topic:mi,payload:{parentOrganisation:t.parentOrganisation,tournamentId:i,...s}}),{...P}}function k_({tournamentRecord:t,notes:e}){let r=dt({tournamentRecord:t},[rt]);if(r.error)return r;let n=e?Sd({element:t,notes:e}):FS({element:t});return n.error?n:(at({topic:mi,payload:{parentOrganisation:t.parentOrganisation,tournamentId:t.tournamentId,notes:e??""}}),{...P})}function G_({tournamentRecord:t,localTimeZone:e}){let r=dt({tournamentRecord:t},[rt]);if(r.error)return r;let n=typeof e=="string"?e.trim():"";if(n)try{new Intl.DateTimeFormat(void 0,{timeZone:n})}catch{return{error:op}}let o=t.localTimeZone;return n===(o??"")?{...P}:(n?t.localTimeZone=n:delete t.localTimeZone,at({topic:mi,payload:{parentOrganisation:t.parentOrganisation,tournamentId:t.tournamentId,localTimeZone:n}}),{...P})}function V_({tournamentRecord:t,tournamentTier:e}){let r=dt({tournamentRecord:t},[rt]);if(r.error)return r;if(e&&typeof e=="object"){if(!e.system||!e.value)return{error:"TierClassification requires system and value"};t.tournamentTier={system:String(e.system).trim(),value:String(e.value).trim(),...e.numericRank!==void 0?{numericRank:Number(e.numericRank)}:{}}}else delete t.tournamentTier;return at({topic:mi,payload:{parentOrganisation:t.parentOrganisation,tournamentId:t.tournamentId,tournamentTier:t.tournamentTier??null}}),{...P}}function B_({tournamentRecord:t,registrationProfile:e}){let r=dt({tournamentRecord:t},[rt]);return r.error?r:(e&&typeof e=="object"?t.registrationProfile={...t.registrationProfile,...e}:delete t.registrationProfile,at({topic:mi,payload:{parentOrganisation:t.parentOrganisation,tournamentId:t.tournamentId,registrationProfile:t.registrationProfile??null}}),{...P})}function W_({tournamentRecord:t,categories:e}){let r=dt({tournamentRecord:t},[rt]);return r.error?r:(e=(e??[]).filter(n=>n.categoryName&&n.type),t.tournamentCategories=e,at({topic:mi,payload:{parentOrganisation:t.parentOrganisation,tournamentId:t.tournamentId,categories:e}}),{...P})}function xV({tournamentRecord:t}){if(!t)return{error:j};let{startDate:e,endDate:r}=t,n=Ua(e,r),o=[];for(let i of t.venues??[])i?.courts?.length&&o.push(...i.courts);for(let i of o){let{startTime:s,endTime:a}=(i.dateAvailability??[]).reduce((p,m)=>{let d=jt(p.startTime),l=jt(p.endTime);return m.startTime&&jt(m.startTime)<d&&(p.startTime=m.startTime),m.endTime&&jt(m.endTime)>l&&(p.endTime=m.endTime),p},{startTime:"08:00",endTime:"18:00"}),c=n.map(p=>i.dateAvailability?.find(d=>d.date===p)??{date:p,startTime:s,endTime:a}),u=i.dateAvailability?.find(p=>!p.date);u&&c.unshift(u),i.dateAvailability=c}return{...P}}function Bh(t){let{tournamentRecord:e,startDate:r,endDate:n,weekdays:o}=t,i=t.activeDates?.filter(Boolean),s=X(t,[{tournamentRecord:!0},{[$e]:l=>_o.test(l),[Lr]:ae,startDate:!1,endDate:!1},{[$e]:l=>l.filter(Boolean).every(f=>_o.test(f)),[Lr]:ae,activeDates:!1},{[$e]:KP,weekdays:!1}]);if(s.error)return s;if(n&&r&&new Date(n)<new Date(r))return{error:O};if(n&&r&&new Date(r)>new Date(n))return{error:O};if(i?.length){let l=r||e.startDate,f=n||e.endDate,g=!l||i.every(S=>new Date(S)>=new Date(l)),I=!f||i.every(S=>new Date(S)<=new Date(f));if(!g||!I)return{error:ae}}let a;(r&&e.startDate&&new Date(r)>new Date(e.startDate)||n&&e.endDate&&new Date(n)<new Date(e.endDate))&&(a=!0);let c=Ua(e.startDate,e.endDate);r&&(e.startDate=r),n&&(e.endDate=n);let u=Ua(e.startDate,e.endDate),p=c.filter(l=>!u.includes(l)),m=u.filter(l=>!c.includes(l));if(ptt({tournamentRecord:e,startDate:r,endDate:n}),mtt({tournamentRecord:e,startDate:r,endDate:n}),i){let l=dtt({tournamentRecord:e,activeDates:i});if(l)return l}o&&(e.weekdays=o);let d=a&<t({tournamentRecord:e})?.unscheduledMatchUpIds;return xV({tournamentRecord:e}),at({payload:et({parentOrganisation:e.parentOrganisation,tournamentId:e.tournamentId,activeDates:i,startDate:r,weekdays:o,endDate:n}),topic:mi}),{...P,unscheduledMatchUpIds:d,datesAdded:m,datesRemoved:p}}function ptt({tournamentRecord:t,startDate:e,endDate:r}){for(let n of t.events??[])e&&n.startDate&&new Date(n.startDate)<new Date(e)&&(n.startDate=e),r&&n.startDate&&new Date(n.startDate)>new Date(r)&&(n.startDate=e??r),r&&n.endDate&&new Date(n.endDate)>new Date(r)&&(n.endDate=r),e&&n.endDate&&new Date(n.endDate)<new Date(e)&&(n.endDate=r??e)}function mtt({tournamentRecord:t,startDate:e,endDate:r}){e&&t.endDate&&new Date(e)>new Date(t.endDate)&&(t.endDate=e),r&&t.startDate&&new Date(r)<new Date(t.startDate)&&(t.startDate=r)}function dtt({tournamentRecord:t,activeDates:e}){let r=t.activeDates??[],n=new Set(e),o=r.filter(i=>!n.has(i));if(o.length){let i=qt({tournamentRecord:t}).matchUps??[],s=new Set(o),a=i.filter(c=>c.schedule?.scheduledDate&&s.has(c.schedule.scheduledDate));if(a.length){let c=[...new Set(a.map(u=>u.schedule.scheduledDate))].sort();return{error:{...O,message:`Cannot remove active dates with scheduled matchUps: ${c.join(", ")}`},info:`${a.length} matchUp(s) scheduled on dates being removed`}}}t.activeDates=e}function H_({tournamentRecord:t,startDate:e}){return e?Bh({tournamentRecord:t,startDate:e}):{error:ae}}function Y_({tournamentRecord:t,endDate:e}){return e?Bh({tournamentRecord:t,endDate:e}):{error:ae}}function ltt({tournamentRecord:t}){let e=qt({tournamentRecord:t}).matchUps??[],r=t.startDate&&new Date(t.startDate),n=t.endDate&&new Date(t.endDate),o=[],i=[];for(let s of e){let{schedule:a,matchUpId:c}=s;if(a&&a.scheduledDate){let u=new Date(a.scheduledDate);(r&&u<r||n&&u>n)&&(i.push(c),o.includes(a.scheduledDate)||o.push(a.scheduledDate))}}return o.length&&!qu({scheduledDates:o,tournamentRecord:t}).clearedScheduleCount?{error:MD}:{unscheduledMatchUpIds:i}}var ax={};Gt(ax,{BLOCK_TYPES:()=>Xt,EvaluatorRegistry:()=>zN,adjacentBlockEvaluator:()=>tx,applyTemporalAvailabilityToTournamentRecord:()=>iB,blockDurationEvaluator:()=>rx,buildDayRange:()=>FV,buildEdges:()=>K_,buildSchedulingProfileFromUISelections:()=>sB,calculateCapacityStats:()=>GV,calculateCourtHours:()=>mB,clampDragToCollisions:()=>jV,clampToDayRange:()=>$_,compareCapacityCurves:()=>WV,computePlanItemId:()=>Hh,courtDayKey:()=>Eg,courtKey:()=>Em,courtOverlapEvaluator:()=>J_,createFollowByEvaluator:()=>KV,dayBoundaryEvaluator:()=>nx,defaultEvaluators:()=>$V,deriveRailSegments:()=>$N,diffMinutes:()=>Ag,extractDay:()=>Qu,filterCapacityCurve:()=>VV,findBlocksContainingTime:()=>YV,formatConflicts:()=>XV,generateCapacityCurve:()=>KN,getHighestSeverity:()=>QV,groupConflictsBySeverity:()=>zV,hhmmToMinutes:()=>Wh,intervalsOverlap:()=>HV,iterateDayTicks:()=>ZV,lightingEvaluator:()=>ex,maintenanceWindowEvaluator:()=>ox,matchWindowEvaluator:()=>Z_,mergeAdjacentSegments:()=>Q_,mergeOverlappingAvailability:()=>pB,minutesToHhmm:()=>QN,overlappingRange:()=>LV,railsToDateAvailability:()=>sx,rangesOverlap:()=>qN,resolveCourtId:()=>zu,resolveStatus:()=>jN,resolveVenueId:()=>Ku,runValidationPipeline:()=>rB,sampleCapacityCurve:()=>BV,snapIsoToGranularity:()=>JV,snapToGranularity:()=>ix,sortBlocksByStart:()=>qV,sortEdges:()=>z_,timeInsideBlock:()=>X_,todsAvailabilityToBlocks:()=>aB,validateDateAvailability:()=>uB,validateSchedulingProfileFormat:()=>cB,validateSegments:()=>kV,venueDayKey:()=>wV,venueKey:()=>Am});var Xt={MAINTENANCE:"MAINTENANCE",PRACTICE:"PRACTICE",RESERVED:"RESERVED",BLOCKED:"BLOCKED",CLOSED:"CLOSED",SCHEDULED:"SCHEDULED",SOFT_BLOCK:"SOFT_BLOCK",HARD_BLOCK:"HARD_BLOCK",LOCKED:"LOCKED",AVAILABLE:"AVAILABLE",UNSPECIFIED:"UNSPECIFIED"};function Eg(t,e){return`${t.tournamentId}|${t.venueId}|${t.courtId}|${e}`}function Em(t){return`${t.tournamentId}|${t.venueId}|${t.courtId}`}function Am(t,e){return`${t}|${e}`}function wV(t,e,r){return`${t}|${e}|${r}`}function Ku(t){return t.venueId||t.venueName||"unknown-venue"}function zu(t){return t.courtId||t.courtName||"unknown-court"}function $_(t,e){let r=t.start,n=t.end,o=e?.start,i=e?.end;if(n<=o||r>=i)return null;let s=r<o?o:r,a=n>i?i:n;return{...t,start:s,end:a}}function qN(t,e){return t?.start<e?.end&&e?.start<t?.end}function LV(t,e){let r=t?.start>e?.start?t?.start:e?.start,n=t?.end<e?.end?t?.end:e?.end;return{start:r,end:n}}function Ag(t,e){let r=new Date(t),o=(new Date(e).getTime()-r.getTime())/(1e3*60);return Number.isNaN(o)?0:o}function jN(t,e,r){if(t.length===0||!r||r.length===0)return Xt.AVAILABLE;let n=new Map(r.map((s,a)=>[s,a])),o=Xt.AVAILABLE,i=1/0;for(let s of t){let a=e.get(s);if(!a)continue;let c=n.get(a.type);c!==void 0&&c<i&&(i=c,o=a.type)}return o}function K_(t){let e=[];if(!Array.isArray(t))return e;for(let r of t)e.push({time:r.start,type:"START",blockId:r.id}),e.push({time:r.end,type:"END",blockId:r.id});return e}function z_(t){return Array.isArray(t)?t.slice().sort((e,r)=>{let n=e.time.localeCompare(r.time);return n!==0?n:e.type==="END"&&r.type==="START"?-1:e.type==="START"&&r.type==="END"?1:0}):[]}function $N(t,e,r){if(!Array.isArray(t)||!e||!r)return[];let n=t.map(u=>$_(u,e)).filter(u=>u!==null);if(n.length===0)return[{start:e.start,end:e.end,status:Xt.AVAILABLE,contributingBlocks:[]}];let o=new Map(n.map(u=>[u.id,u])),i=z_(K_(n)),s=new Set,a=[],c=e.start;for(let u of i){let p=u.time;if(p>c){let m=Array.from(s),d=jN(m,o,r.typePrecedence);a.push({start:c,end:p,status:d,contributingBlocks:m})}u.type==="START"?s.add(u.blockId):s.delete(u.blockId),c=p}if(c<e.end){let u=Array.from(s),p=jN(u,o,r.typePrecedence);a.push({start:c,end:e.end,status:p,contributingBlocks:u})}return Q_(a)}function Q_(t){if(t.length===0)return t;let e=[],r={...t[0]};for(let n=1;n<t.length;n++){let o=t[n],i=r.status===o.status,s=r.contributingBlocks.length===o.contributingBlocks.length&&r.contributingBlocks.every(c=>o.contributingBlocks.includes(c)),a=r.end===o.start;i&&s&&a?r.end=o.end:(e.push(r),r={...o})}return e.push(r),e}function Qu(t){return mt(t)}function FV(t,e){return{start:`${t}T${e?.dayStartTime}:00`,end:`${t}T${e?.dayEndTime}:00`}}function kV(t){for(let e=0;e<t.length;e++){let r=t[e];if(r.start>=r.end)return!1;if(e<t.length-1){let n=t[e+1];if(r.end>n.start||r.end!==n.start)return!1}}return!0}function KN(t,e){let r=new Set;if(!Array.isArray(e))return{day:t,points:[]};for(let i of e)for(let s of i.rails)for(let a of s.segments)r.add(a.start),r.add(a.end);let n=Array.from(r).sort(),o=n.map(i=>({time:i,courtsAvailable:0,courtsSoftBlocked:0,courtsHardBlocked:0}));for(let i of e)for(let s of i.rails)for(let a=0;a<n.length;a++){let c=n[a],u=ftt(s.segments,c);if(u){let p=o[a];gtt(u,p)}}return{day:t,points:o}}function ftt(t,e){for(let r of t)if(e>=r.start&&e<r.end)return r;return null}function gtt(t,e){switch(t.status){case Xt.AVAILABLE:e.courtsAvailable++;break;case Xt.RESERVED:case Xt.SOFT_BLOCK:e.courtsSoftBlocked++;break;case Xt.BLOCKED:case Xt.PRACTICE:case Xt.MAINTENANCE:case Xt.CLOSED:e.courtsSoftBlocked++;break;case Xt.SCHEDULED:case Xt.HARD_BLOCK:case Xt.LOCKED:e.courtsHardBlocked++;break;case Xt.UNSPECIFIED:break}}function GV(t){if(!t.points||t.points.length===0)return{peakAvailable:0,peakTime:"",minAvailable:0,minTime:"",avgAvailable:0,totalCourtHours:0,utilizationPercent:0,peakUnavailable:0,peakUnavailableTime:"",totalCourts:0,totalAvailableHours:0,totalUnavailableHours:0,availablePercent:0,avgBlockedHoursPerCourt:0};let e=0,r=t.points[0].time,n=1/0,o=t.points[0].time,i=0,s=t.points[0].time,a=0,c=0,u=0;for(let I=0;I<t.points.length-1;I++){let S=t.points[I],h=t.points[I+1],T=(new Date(h.time).getTime()-new Date(S.time).getTime())/(1e3*60*60),y=S.courtsAvailable+S.courtsSoftBlocked+S.courtsHardBlocked;u=Math.max(u,y);let E=S.courtsSoftBlocked+S.courtsHardBlocked;S.courtsAvailable>e&&(e=S.courtsAvailable,r=S.time),S.courtsAvailable<n&&(n=S.courtsAvailable,o=S.time),E>i&&(i=E,s=S.time),a+=S.courtsAvailable*T,c+=E*T}let p=(new Date(t.points.at(-1).time).getTime()-new Date(t.points[0].time).getTime())/(1e3*60*60),m=u*p,d=m>0?a/m*100:0,l=m>0?c/m*100:0,f=u>0?c/u:0,g=t.points.length>1?t.points.slice(0,-1).reduce((I,S)=>I+S.courtsAvailable,0)/(t.points.length-1):0;return{peakAvailable:e,peakTime:r,minAvailable:n===1/0?0:n,minTime:o,avgAvailable:g,totalCourtHours:m,utilizationPercent:l,peakUnavailable:i,peakUnavailableTime:s,totalCourts:u,totalAvailableHours:a,totalUnavailableHours:c,availablePercent:d,avgBlockedHoursPerCourt:f}}function VV(t,e){let r=t.points?.filter(n=>n.time>=e.start&&n.time<=e.end);return{...t,points:r}}function BV(t,e){if(!t.points||t.points.length===0)return t;let r=[],n=new Date(t.points[0].time),o=new Date(t.points.at(-1).time),i=new Date(n);for(;i<=o;){let s=i.toISOString(),a=Itt(t.points,s);a&&r.push(a),i=new Date(i.getTime()+e*60*1e3)}return{...t,points:r}}function Itt(t,e){for(let r=t.length-1;r>=0;r--)if(t[r].time<=e)return{time:e,courtsAvailable:t[r].courtsAvailable,courtsSoftBlocked:t[r].courtsSoftBlocked,courtsHardBlocked:t[r].courtsHardBlocked};return null}function WV(t,e){let r=[],n=new Set;t.points?.forEach(i=>n.add(i.time)),e?.points?.forEach(i=>n.add(i.time));let o=Array.from(n).sort();for(let i of o){let s=t.points?.find(c=>c.time===i)||{time:i,courtsAvailable:0,courtsSoftBlocked:0,courtsHardBlocked:0},a=e.points?.find(c=>c.time===i)||{time:i,courtsAvailable:0,courtsSoftBlocked:0,courtsHardBlocked:0};r.push({time:i,availableDelta:a.courtsAvailable-s.courtsAvailable,softBlockedDelta:a.courtsSoftBlocked-s.courtsSoftBlocked,hardBlockedDelta:a.courtsHardBlocked-s.courtsHardBlocked})}return r}function da(t){return new Date(t?.endsWith("Z")?t:t+"Z").getTime()}function HV(t,e){return da(t.start)<da(e.end)&&da(t.end)>da(e.start)}function X_(t,e){return da(e?.start)<=t&&t<da(e?.end)}function YV(t,e){return Array.isArray(e)?e.filter(r=>X_(t,r)):[]}function jV(t,e,r){let n=e>=t?"forward":"backward",o=Math.min(t,e),i=Math.max(t,e);return n==="forward"?Stt(t,i,r):htt(t,o,r)}function Stt(t,e,r){let n=e,o=!1,i;for(let s of r){let a=da(s.start);a>t&&a<e&&a<n&&(n=a,o=!0,i=s);let c=da(s.end);a<e&&c>t&&a<n&&a>t&&(n=a,o=!0,i=s)}return{start:t,end:n,clamped:o,clampedBy:i,direction:"forward"}}function htt(t,e,r){let n=e,o=!1,i;if(Array.isArray(r))for(let s of r){let a=da(s.end);a<t&&a>e&&a>n&&(n=a,o=!0,i=s),da(s.start)<t&&a>e&&a>n&&a<t&&(n=a,o=!0,i=s)}return{start:n,end:t,clamped:o,clampedBy:i,direction:"backward"}}function qV(t){Array.isArray(t)&&t.sort((e,r)=>da(e.start)-da(r.start))}var J_={id:"COURT_OVERLAP",description:"Prevent double-booking courts or overriding hard blocks",evaluate:(t,e)=>{let r=[];for(let n of e){if(n.kind==="REMOVE_BLOCK")continue;let o=n.block,i=mt(o.start),s=`${o.court.tournamentId}|${o.court.venueId}|${o.court.courtId}|${i}`,a=t.blocksByCourtDay.get(s)??[];for(let c of a){if(c===o.id)continue;let u=t.blocksById.get(c);if(u&&qN(o,u)){let m=u.type===Xt.HARD_BLOCK||u.type===Xt.LOCKED||o.type===Xt.HARD_BLOCK||o.type===Xt.LOCKED?"ERROR":"WARN",d=o.start>u.start?o.start:u.start,l=o.end<u.end?o.end:u.end;r.push({code:"COURT_OVERLAP",message:`Block overlaps existing ${u.type.toLowerCase()} (${u.reason||"no reason"}) on court ${o.court.courtId}`,severity:m,timeRange:{start:d,end:l},courts:[o.court]})}}}return r}},Z_={id:"MATCH_WINDOW",description:"Ensure availability windows are large enough for typical matches",evaluate:(t,e)=>{let r=[],o=new Set;for(let i of e){let s=i.block,a=mt(s.start),c=`${s.court.tournamentId}|${s.court.venueId}|${s.court.courtId}|${a}`;o.add(c)}for(let i of o){let c=(t.blocksByCourtDay.get(i)??[]).map(p=>t.blocksById.get(p)).filter(Boolean).slice().sort((p,m)=>p.start.localeCompare(m.start)),u=null;for(let p of c)if(p.type!==Xt.AVAILABLE&&p.type!==Xt.SOFT_BLOCK&&p.type!==Xt.RESERVED){if(u){let m=Ag(u,p.start);m>0&&m<60&&r.push({code:"MATCH_WINDOW_TOO_SMALL",message:`Availability window (${m} minutes) is smaller than typical match duration (60 minutes)`,severity:"WARN",timeRange:{start:u,end:p.start},courts:[p.court]})}u=p.end}}return r}},tx={id:"ADJACENT_BLOCK",description:"Warn about blocks with no transition time",evaluate:(t,e)=>{let r=[];for(let o of e){if(o.kind==="REMOVE_BLOCK")continue;let i=o.block,s=mt(i.start),a=`${i.court.tournamentId}|${i.court.venueId}|${i.court.courtId}|${s}`,c=t.blocksByCourtDay.get(a)??[];for(let u of c){if(u===i.id)continue;let p=t.blocksById.get(u);if(!p)continue;(p.end===i.start||i.end===p.start)&&p.type!==i.type&&r.push({code:"NO_TRANSITION_TIME",message:`${i.type} immediately follows ${p.type} with no transition time (recommended: 15 minutes)`,severity:"INFO",timeRange:{start:p.end,end:i.start},courts:[i.court]})}}return r}},ex={id:"LIGHTING",description:"Prevent scheduling on unlit courts after sunset",evaluate:(t,e)=>{let r=[],n="19:00";for(let o of e){if(o.kind==="REMOVE_BLOCK")continue;let i=o.block;i.end.slice(11,16)>n&&(i.type===Xt.AVAILABLE||i.type===Xt.RESERVED)&&r.push({code:"AFTER_SUNSET",message:`Court scheduled after sunset (${n}). Verify court has adequate lighting.`,severity:"WARN",timeRange:{start:`${i.start.slice(0,11)}${n}:00`,end:i.end},courts:[i.court]})}return r}},rx={id:"BLOCK_DURATION",description:"Validate block durations are reasonable",evaluate:(t,e)=>{let r=[];for(let i of e){if(i.kind==="REMOVE_BLOCK")continue;let s=i.block,a=Ag(s.start,s.end);a<15?r.push({code:"BLOCK_TOO_SHORT",message:`Block duration (${a} minutes) is unusually short. Minimum recommended: 15 minutes.`,severity:"WARN",timeRange:s,courts:[s.court]}):a>720&&r.push({code:"BLOCK_TOO_LONG",message:`Block duration (${a/60} hours) is unusually long. Maximum recommended: ${720/60} hours.`,severity:"WARN",timeRange:s,courts:[s.court]})}return r}},nx={id:"DAY_BOUNDARY",description:"Ensure blocks do not span multiple days",evaluate:(t,e)=>{let r=[];for(let n of e){if(n.kind==="REMOVE_BLOCK")continue;let o=n.block,i=mt(o.start),s=mt(o.end);i!==s&&r.push({code:"SPANS_MULTIPLE_DAYS",message:`Block spans from ${i} to ${s}. Blocks should be contained within a single day.`,severity:"ERROR",timeRange:o,courts:[o.court]})}return r}},ox={id:"MAINTENANCE_WINDOW",description:"Validate maintenance scheduling practices",evaluate:(t,e)=>{let r=[],n="09:00",o="17:00";for(let s of e){if(s.kind==="REMOVE_BLOCK")continue;let a=s.block;if(a.type===Xt.MAINTENANCE){let c=a.start.slice(11,16),u=a.end.slice(11,16),p=Ag(a.start,a.end);(c>=n&&c<o||u>n&&u<=o)&&r.push({code:"MAINTENANCE_DURING_PEAK",message:`Maintenance scheduled during peak hours (${n}-${o}). Consider scheduling during off-peak times.`,severity:"INFO",timeRange:a,courts:[a.court]}),p<30&&r.push({code:"MAINTENANCE_TOO_SHORT",message:`Maintenance duration (${p} minutes) may be insufficient. Recommended minimum: 30 minutes.`,severity:"INFO",timeRange:a,courts:[a.court]})}}return r}},$V=[J_,nx,rx,Z_,tx,ex,ox],zN=class{constructor(){this.evaluators=new Map}register(e){this.evaluators.set(e.id,e)}unregister(e){this.evaluators.delete(e)}get(e){return this.evaluators.get(e)}getAll(){return Array.from(this.evaluators.values())}clear(){this.evaluators.clear()}},KV=t=>({id:"FOLLOW_BY",description:"Player rest and follow-by conflicts using Competition Factory",evaluate:(e,r)=>[]});function zV(t){return Array.isArray(t)?{errors:t?.filter(e=>e.severity==="ERROR"),warnings:t.filter(e=>e.severity==="WARN"),info:t.filter(e=>e.severity==="INFO")}:{errors:[],warnings:[],info:[]}}function QV(t){return Array.isArray(t)?t.some(e=>e.severity==="ERROR")?"ERROR":t.some(e=>e.severity==="WARN")?"WARN":t.some(e=>e.severity==="INFO")?"INFO":null:null}function XV(t){return Array.isArray(t)?t.map(e=>{let r=e.courts.map(o=>o.courtId).join(", "),n=`${e.timeRange.start.slice(11,16)}-${e.timeRange.end.slice(11,16)}`;return`[${e.severity}] ${e.code}: ${e.message} (${r} @ ${n})`}):[]}function Wh(t){if(typeof t!="string")return 0;let[e,r]=t.split(":").map(Number);return e*60+r}function QN(t){let e=Math.max(0,Math.min(1439,Math.round(t))),r=Math.floor(e/60),n=e%60;return`${String(r).padStart(2,"0")}:${String(n).padStart(2,"0")}`}function ix(t,e,r="round"){if(e<=0)return t;switch(r){case"floor":return Math.floor(t/e)*e;case"ceil":return Math.ceil(t/e)*e;case"round":return Math.round(t/e)*e}}function JV(t,e,r="round"){if(!t||typeof t!="string")return t;let n=t.slice(0,10),o=t.slice(11,16),i=Wh(o),s=ix(i,e,r),a=QN(s);return`${n}T${a}:00`}function*ZV(t,e,r){if(r<=0)return;let n=Wh(t),o=Wh(e);for(let i=n;i<o;i+=r)yield QN(i)}function Hh(t){let e=[t.day,t.venueId,t.eventId];return t.drawId&&e.push(t.drawId),e.push(`R${t.roundNumber}`),e.join("|")}function Ttt(t,e){let r=[],n=new Set(t.getTournamentDays()),o=t.listCourtMeta(),i=new Set(o.map(s=>s.ref.venueId));for(let s of e){n.has(s.day)||r.push({ruleId:"PRECHECK_INVALID_DAY",phase:"PRECHECK",severity:"ERROR",message:`Day '${s.day}' is not within the tournament date range`,context:{day:s.day}});for(let a of s.items)i.has(a.venueId)||r.push({ruleId:"PRECHECK_INVALID_VENUE",phase:"PRECHECK",severity:"ERROR",message:`Venue '${a.venueId}' does not exist in the tournament record`,context:{day:s.day,venueId:a.venueId,planItemId:a.planItemId}}),a.notBeforeTime&&!/^\d{2}:\d{2}$/.test(a.notBeforeTime)&&r.push({ruleId:"PRECHECK_INVALID_TIME_FORMAT",phase:"PRECHECK",severity:"ERROR",message:`notBeforeTime '${a.notBeforeTime}' is not valid HH:MM format`,context:{day:s.day,planItemId:a.planItemId}}),a.roundNumber<1&&r.push({ruleId:"PRECHECK_INVALID_ROUND",phase:"PRECHECK",severity:"ERROR",message:`roundNumber must be >= 1, got ${a.roundNumber}`,context:{day:s.day,planItemId:a.planItemId}})}return r}function ytt(t,e){let r=[],n=new Set;for(let o of e)for(let i of o.items)n.has(i.planItemId)&&r.push({ruleId:"INTEGRITY_DUPLICATE_PLAN_ITEM",phase:"INTEGRITY",severity:"ERROR",message:`Duplicate plan item '${i.planItemId}'`,context:{day:o.day,planItemId:i.planItemId}}),n.add(i.planItemId);return r}function Ett(t,e){let r=[],n=new Map;for(let o of e)for(let i of o.items){let s=`${i.eventId}|${i.drawId||""}`,a=n.get(s)??[];a.push({day:o.day,roundNumber:i.roundNumber,planItemId:i.planItemId}),n.set(s,a)}for(let[o,i]of n.entries()){if(i.length<2)continue;let s=[...i].sort((a,c)=>a.roundNumber-c.roundNumber);for(let a=1;a<s.length;a++){let c=s[a-1],u=s[a];u.day<c.day&&r.push({ruleId:"ORDERING_ROUND_DAY_SEQUENCE",phase:"ORDERING",severity:"WARN",message:`Round ${u.roundNumber} is scheduled on ${u.day} which is before round ${c.roundNumber} on ${c.day} (event: ${o.split("|")[0]})`,context:{day:u.day,planItemId:u.planItemId},fixAction:{type:"MOVE_PLAN_ITEM",description:`Move round ${u.roundNumber} to ${c.day} or later`,payload:{planItemId:u.planItemId,suggestedDay:c.day}}})}}return r}function Att(t,e){let r=[];for(let n of e){let o=0,i=n.items.filter(f=>f.estimatedDurationMinutes);for(let f of i)o+=f.estimatedDurationMinutes;if(o===0)continue;let s=t.getVisibleTimeRange(n.day),a=tB(s.startTime),u=tB(s.endTime)-a,p=t.listCourtMeta(),m=new Set(n.items.map(f=>f.venueId)),l=(m.size===1?p.filter(f=>f.ref.venueId===[...m][0]):p).length*u;o>l?r.push({ruleId:"CAPACITY_DEMAND_EXCEEDS_SUPPLY",phase:"CAPACITY",severity:"WARN",message:`Estimated demand (${Math.round(o/60)}h) exceeds available court-hours (${Math.round(l/60)}h) on ${n.day}`,context:{day:n.day}}):o>l*.9&&r.push({ruleId:"CAPACITY_NEAR_LIMIT",phase:"CAPACITY",severity:"INFO",message:`Demand is at ${Math.round(o/l*100)}% of capacity on ${n.day}`,context:{day:n.day}})}return r}function tB(t){let[e,r]=t.split(":").map(Number);return e*60+r}var eB=["PRECHECK","INTEGRITY","ORDERING","CAPACITY"],Ptt={PRECHECK:Ttt,INTEGRITY:ytt,ORDERING:Ett,CAPACITY:Att};function rB(t){let{engine:e,day:r,phases:n}=t,o;if(r){let c=e.getDayPlan(r);o=c?[c]:[]}else o=e?.getAllPlans();let i=n?eB.filter(c=>n.includes(c)):eB,s=[];for(let c of i){let u=Ptt[c],p=u(e,o);if(s.push(...p),c==="PRECHECK"&&p.some(m=>m.severity==="ERROR"))break}let a=new Map;for(let c of s){let u=c.context?.planItemId||"__global__",p=a.get(u)??[];p.push(c),a.set(u,p)}return{results:s,issueIndex:a}}var Ntt={courtToCourtId:t=>t.courtId,isSchedulableStatus:t=>t===Xt.AVAILABLE||t===Xt.SOFT_BLOCK||t===Xt.RESERVED,aggregateByVenue:!1};function sx(t,e={}){let r={...Ntt,...e},n=[];for(let o of t){let{day:i,venueId:s,rails:a}=o;for(let c of a){let{court:u,segments:p}=c,m=r.courtToCourtId(u),d=Dtt(p,r);for(let l of d)n.push({date:i,startTime:nB(l.start),endTime:nB(l.end),venueId:s,courtIds:[m]})}}return r.aggregateByVenue?Utt(n):n}function Dtt(t,e){let r=[],n=null,o=null;for(let i of t)e.isSchedulableStatus(i.status)?(n||(n=i.start),o=i.end):(n&&o&&r.push({start:n,end:o}),n=null,o=null);return n&&o&&r.push({start:n,end:o}),r}function nB(t){return t.slice(11,16)}function Utt(t){let e=new Map;for(let r of t){let n=`${r.venueId}|${r.date}|${r.startTime}|${r.endTime}`;if(e.has(n)){let o=e.get(n);r.courtIds&&(o.courtIds=[...o.courtIds??[],...r.courtIds])}else e.set(n,{...r})}return Array.from(e.values())}function iB(t){let{tournamentRecord:e,timelines:r,config:n={},engine:o}=t,i=sx(r,n),s=structuredClone(e),a=new Map;for(let c of i){let u=a.get(c.venueId)??[];u.push(c),a.set(c.venueId,u)}if(s.venues&&Array.isArray(s.venues)){let u=o?.getConfig()?.tournamentId;for(let p of s.venues){let m=Ku(p),d=a.get(m);if(d&&(p.dateAvailability=d),o&&u){let l=o.getVenueAvailability(u,m);l&&(p.defaultStartTime=l.startTime,p.defaultEndTime=l.endTime)}}}return s}function sB(t){let e=[];for(let r of t)!r.scheduleDate||!r.venueIds.length||e.push({scheduleDate:r.scheduleDate,venueIds:r.venueIds,rounds:r.rounds??[]});return e}function aB(t){let{venue:e,tournamentId:r,blockType:n=Xt.AVAILABLE}=t,o=[];if(!e.dateAvailability)return o;let i=Ku(e);for(let s of e.dateAvailability){let{date:a,startTime:c,endTime:u,courtIds:p}=s;if(p&&p.length>0)for(let m of p)o.push({court:{tournamentId:r,venueId:i,courtId:m},start:`${a}T${c}:00`,end:`${a}T${u}:00`,type:n});else if(e.courts&&e.courts.length>0)for(let m of e.courts){let d=zu(m);o.push({court:{tournamentId:r,venueId:i,courtId:d},start:`${a}T${c}:00`,end:`${a}T${u}:00`,type:n})}}return o}function cB(t){let e=[];if(!Array.isArray(t))return e.push("Profile must be an array"),{valid:!1,errors:e};for(let r=0;r<t.length;r++){let n=t[r];if(n.scheduleDate?/^\d{4}-\d{2}-\d{2}$/.test(n.scheduleDate)||e.push(`Item ${r}: invalid scheduleDate format (expected YYYY-MM-DD)`):e.push(`Item ${r}: missing scheduleDate`),(!n.venueIds||!Array.isArray(n.venueIds)||n.venueIds.length===0)&&e.push(`Item ${r}: missing or empty venueIds array`),n.rounds)if(!Array.isArray(n.rounds))e.push(`Item ${r}: rounds must be an array`);else for(let o=0;o<n.rounds.length;o++)n.rounds[o].eventId||e.push(`Item ${r}, round ${o}: missing eventId`)}return{valid:e.length===0,errors:e}}function uB(t){let e=[];if(!Array.isArray(t))return e.push("Entries must be an array"),{valid:!1,errors:e};for(let r=0;r<t.length;r++){let n=t[r];(!n.date||!/^\d{4}-\d{2}-\d{2}$/.test(n.date))&&e.push(`Entry ${r}: invalid or missing date`),(!n.startTime||!/^\d{2}:\d{2}$/.test(n.startTime))&&e.push(`Entry ${r}: invalid or missing startTime (expected HH:MM)`),(!n.endTime||!/^\d{2}:\d{2}$/.test(n.endTime))&&e.push(`Entry ${r}: invalid or missing endTime (expected HH:MM)`),n.startTime&&n.endTime&&n.startTime>=n.endTime&&e.push(`Entry ${r}: startTime must be before endTime`),n.venueId||e.push(`Entry ${r}: missing venueId`)}return{valid:e.length===0,errors:e}}function pB(t){if(t.length===0)return t;let e=new Map;for(let n of t){let o=`${n.venueId}|${n.date}`,i=e.get(o)??[];i.push(n),e.set(o,i)}let r=[];for(let n of e.values()){n.sort((i,s)=>i.startTime.localeCompare(s.startTime));let o={...n[0]};for(let i=1;i<n.length;i++){let s=n[i];s.startTime<=o.endTime?(o.endTime=s.endTime>o.endTime?s.endTime:o.endTime,o.courtIds&&s.courtIds&&(o.courtIds=[...new Set([...o.courtIds,...s.courtIds])])):(r.push(o),o={...s})}r.push(o)}return r}function mB(t){let e=0;for(let r of t){let n=oB(r.startTime),i=(oB(r.endTime)-n)/60,s=r.courtIds?.length||1;e+=i*s}return e}function oB(t){let[e,r]=t.split(":").map(Number);return e*60+r}var hx={};Gt(hx,{addCertification:()=>sT,addCertificationRequirement:()=>Qh,addEvaluation:()=>uT,addEvaluationPolicy:()=>Zh,addSuspension:()=>cT,assignOfficial:()=>aT,createOfficialRecord:()=>tT,getEvaluationSummary:()=>gT,getEvaluationTemplate:()=>dT,getEvaluations:()=>ST,getOfficialAssignments:()=>fT,getOfficialCertifications:()=>pT,getOfficialEligibility:()=>lT,modifyCertification:()=>eT,modifyEvaluation:()=>nT,mutate:()=>gx,query:()=>Sx,queryOfficialRecord:()=>IT,removeCertification:()=>rT,removeEvaluation:()=>oT,removeOfficialAssignment:()=>Jh,removeSuspension:()=>iT,transitionAssignmentStatus:()=>Xh,transitionCertificationStatus:()=>Kh,transitionEvaluationStatus:()=>zh,validateCertification:()=>mT,validateOfficiatingStatusTransition:()=>Ix});var gx={};Gt(gx,{addCertification:()=>sT,addCertificationRequirement:()=>Qh,addEvaluation:()=>uT,addEvaluationPolicy:()=>Zh,addSuspension:()=>cT,assignOfficial:()=>aT,createOfficialRecord:()=>tT,modifyCertification:()=>eT,modifyEvaluation:()=>nT,removeCertification:()=>rT,removeEvaluation:()=>oT,removeOfficialAssignment:()=>Jh,removeSuspension:()=>iT,transitionAssignmentStatus:()=>Xh,transitionCertificationStatus:()=>Kh,transitionEvaluationStatus:()=>zh});var Pm="ACTIVE",cx="EXPIRED",dB="SUSPENDED",XN="REVOKED",ux="PENDING_RENEWAL",Xd="DRAFT",tD="SUBMITTED",lB="REVIEWED",px="APPROVED",JN="REJECTED",Yh="PROPOSED",fB="CONFIRMED",mx="DECLINED",ZN="CANCELLED",dx="COMPLETED",jh={ACTIVE:[cx,dB,XN,ux],EXPIRED:[Pm,ux],SUSPENDED:[Pm,XN],REVOKED:[],PENDING_RENEWAL:[Pm,cx]},qh={DRAFT:[tD],SUBMITTED:[lB,JN],REVIEWED:[px,JN],APPROVED:[],REJECTED:[Xd]},$h={PROPOSED:[fB,mx,ZN],CONFIRMED:[ZN,dx],DECLINED:[],CANCELLED:[],COMPLETED:[]},Rtt=[XN],btt=[px],Ctt=[mx,ZN,dx],lx=[Xd,JN],$n=[{value:1,label:"Unsatisfactory"},{value:2,label:"Below Average"},{value:3,label:"Average"},{value:4,label:"Good"},{value:5,label:"Excellent"}],Se={message:"Missing officialRecord",code:"ERR_MISSING_OFFICIAL_RECORD"},fx={message:"OfficialRecord not found",code:"ERR_NOT_FOUND_OFFICIAL_RECORD"},gB={message:"OfficialRecord already exists",code:"ERR_EXISTING_OFFICIAL_RECORD"};var Nm={message:"Certification not found",code:"ERR_NOT_FOUND_CERTIFICATION"},IB={message:"Certification has expired",code:"ERR_CERTIFICATION_EXPIRED"},Pg={message:"Evaluation not found",code:"ERR_NOT_FOUND_EVALUATION"},SB={message:"Evaluation is not editable in current status",code:"ERR_EVALUATION_NOT_EDITABLE"},eD={message:"Assignment not found",code:"ERR_NOT_FOUND_ASSIGNMENT"};var hB={message:"Evaluation scores do not satisfy policy requirements",code:"ERR_INVALID_EVALUATION_SCORES"},Xu={message:"Invalid status transition",code:"ERR_INVALID_OFFICIATING_STATUS_TRANSITION"},TB={message:"Suspension not found",code:"ERR_NOT_FOUND_SUSPENSION"};var yB={message:"Missing evaluation policy",code:"ERR_MISSING_EVALUATION_POLICY"};var EB={CERT_ACTIVE:Pm,CERT_EXPIRED:cx,CERT_SUSPENDED:dB,CERT_REVOKED:XN,CERT_PENDING_RENEWAL:ux,EVAL_DRAFT:Xd,EVAL_SUBMITTED:tD,EVAL_REVIEWED:lB,EVAL_APPROVED:px,EVAL_REJECTED:JN,ASSIGN_PROPOSED:Yh,ASSIGN_CONFIRMED:fB,ASSIGN_DECLINED:mx,ASSIGN_CANCELLED:ZN,ASSIGN_COMPLETED:dx,VALID_CERTIFICATION_TRANSITIONS:jh,VALID_EVALUATION_TRANSITIONS:qh,VALID_ASSIGNMENT_TRANSITIONS:$h,CERTIFICATION_TERMINAL:Rtt,EVALUATION_TERMINAL:btt,ASSIGNMENT_TERMINAL:Ctt,EVALUATION_EDITABLE:lx,EVALUATION_SCALE_OPTIONS:$n};function Kh({officialRecord:t,certificationId:e,toStatus:r,transitionedBy:n,reason:o}){if(!t)return{error:Se};if(!e)return{error:O,context:{message:"Missing certificationId"}};if(!r)return{error:O,context:{message:"Missing toStatus"}};let i=t.certifications.find(c=>c.certificationId===e);if(!i)return{error:Nm,context:{certificationId:e}};let s=jh[i.status];if(!s?.includes(r))return{error:Xu,context:{fromStatus:i.status,toStatus:r,validTargets:s}};let a=new Date().toISOString();return i.statusHistory??=[],i.statusHistory.push({fromStatus:i.status,toStatus:r,transitionedAt:a,transitionedBy:n,reason:o}),i.status=r,t.updatedAt=a,{...P,certification:i}}function zh({officialRecord:t,evaluationId:e,toStatus:r,transitionedBy:n,reason:o}){if(!t)return{error:Se};if(!e)return{error:O,context:{message:"Missing evaluationId"}};if(!r)return{error:O,context:{message:"Missing toStatus"}};let i=t.evaluations.find(c=>c.evaluationId===e);if(!i)return{error:Pg,context:{evaluationId:e}};let s=qh[i.status];if(!s?.includes(r))return{error:Xu,context:{fromStatus:i.status,toStatus:r,validTargets:s}};if(r===tD&&i.policyName){let c=t.evaluationPolicies.find(u=>u.policyName===i.policyName);if(c){let u=c.sections.flatMap(d=>d.criteria.filter(l=>l.required)),p=new Set(i.scores.map(d=>d.criterionId)),m=u.filter(d=>!p.has(d.criterionId));if(m.length>0)return{error:hB,context:{missingCriteria:m.map(d=>d.criterionId)}}}}let a=new Date().toISOString();return i.statusHistory??=[],i.statusHistory.push({fromStatus:i.status,toStatus:r,transitionedAt:a,transitionedBy:n,reason:o}),i.status=r,t.updatedAt=a,{...P,evaluation:i}}function Qh({officialRecord:t,requirementId:e,certificationFamily:r,certificationLevel:n,organisationId:o,description:i,requirements:s,prerequisiteLevels:a,minimumAssignments:c,minimumEvaluationScore:u,validityPeriodMonths:p,extensions:m}){if(!t)return{error:Se};if(!r)return{error:O,context:{message:"Missing certificationFamily"}};if(!n)return{error:O,context:{message:"Missing certificationLevel"}};if(!o)return{error:O,context:{message:"Missing organisationId"}};if(!Array.isArray(s)||s.length===0)return{error:O,context:{message:"Requirements must be a non-empty array"}};let d={requirementId:e||it(),certificationFamily:r,certificationLevel:n,organisationId:o,description:i,requirements:s.map(l=>({...l,itemId:l.itemId||it()})),prerequisiteLevels:a,minimumAssignments:c,minimumEvaluationScore:u,validityPeriodMonths:p,extensions:m??[]};return t.certificationRequirements.push(d),t.updatedAt=new Date().toISOString(),{...P,certificationRequirement:d}}function Xh({officialRecord:t,assignmentId:e,toStatus:r,transitionedBy:n,reason:o}){if(!t)return{error:Se};if(!e)return{error:O,context:{message:"Missing assignmentId"}};if(!r)return{error:O,context:{message:"Missing toStatus"}};let i=t.assignments.find(c=>c.assignmentId===e);if(!i)return{error:eD,context:{assignmentId:e}};let s=$h[i.status];if(!s?.includes(r))return{error:Xu,context:{fromStatus:i.status,toStatus:r,validTargets:s}};let a=new Date().toISOString();return i.statusHistory??=[],i.statusHistory.push({fromStatus:i.status,toStatus:r,transitionedAt:a,transitionedBy:n,reason:o}),i.status=r,t.updatedAt=a,{...P,assignment:i}}function Jh({officialRecord:t,assignmentId:e}){if(!t)return{error:Se};if(!e)return{error:O,context:{message:"Missing assignmentId"}};let r=t.assignments.findIndex(n=>n.assignmentId===e);return r===-1?{error:eD,context:{assignmentId:e}}:(t.assignments.splice(r,1),t.updatedAt=new Date().toISOString(),{...P})}function Zh({officialRecord:t,evaluationPolicy:e}){return t?e?e.policyName?!Array.isArray(e.sections)||e.sections.length===0?{error:O,context:{message:"Policy must include at least one section"}}:(t.evaluationPolicies.push(e),t.updatedAt=new Date().toISOString(),{...P,evaluationPolicy:e}):{error:O,context:{message:"Missing policyName"}}:{error:O,context:{message:"Missing evaluationPolicy"}}:{error:Se}}function tT({officialRecordId:t,personId:e,organisationId:r,extensions:n}){if(!e)return{error:O,context:{message:"Missing personId"}};let o=new Date().toISOString(),i={officialRecordId:t||it(),personId:e,organisationId:r,certifications:[],evaluations:[],assignments:[],suspensions:[],certificationRequirements:[],evaluationPolicies:[],createdAt:o,updatedAt:o,extensions:n??[]};return{...P,officialRecord:i}}function eT({officialRecord:t,certificationId:e,updates:r}){if(!t)return{error:Se};if(!e)return{error:O,context:{message:"Missing certificationId"}};let n=t.certifications.find(o=>o.certificationId===e);return n?(r.certificationLevel!==void 0&&(n.certificationLevel=r.certificationLevel),r.validFrom!==void 0&&(n.validFrom=r.validFrom),r.validUntil!==void 0&&(n.validUntil=r.validUntil),r.documentReferences!==void 0&&(n.documentReferences=r.documentReferences),r.notes!==void 0&&(n.notes=r.notes),r.extensions!==void 0&&(n.extensions=r.extensions),t.updatedAt=new Date().toISOString(),{...P,certification:n}):{error:Nm,context:{certificationId:e}}}function rT({officialRecord:t,certificationId:e}){if(!t)return{error:Se};if(!e)return{error:O,context:{message:"Missing certificationId"}};let r=t.certifications.findIndex(n=>n.certificationId===e);return r===-1?{error:Nm,context:{certificationId:e}}:(t.certifications.splice(r,1),t.updatedAt=new Date().toISOString(),{...P})}function nT({officialRecord:t,evaluationId:e,updates:r}){if(!t)return{error:Se};if(!e)return{error:O,context:{message:"Missing evaluationId"}};let n=t.evaluations.find(o=>o.evaluationId===e);return n?lx.includes(n.status)?(r.overallRating!==void 0&&(n.overallRating=r.overallRating),r.scores!==void 0&&(n.scores=r.scores),r.comments!==void 0&&(n.comments=r.comments),r.documentReference!==void 0&&(n.documentReference=r.documentReference),r.tournamentId!==void 0&&(n.tournamentId=r.tournamentId),r.tournamentName!==void 0&&(n.tournamentName=r.tournamentName),r.matchUpId!==void 0&&(n.matchUpId=r.matchUpId),r.policyName!==void 0&&(n.policyName=r.policyName),r.extensions!==void 0&&(n.extensions=r.extensions),t.updatedAt=new Date().toISOString(),{...P,evaluation:n}):{error:SB,context:{status:n.status}}:{error:Pg,context:{evaluationId:e}}}function oT({officialRecord:t,evaluationId:e}){if(!t)return{error:Se};if(!e)return{error:O,context:{message:"Missing evaluationId"}};let r=t.evaluations.findIndex(n=>n.evaluationId===e);return r===-1?{error:Pg,context:{evaluationId:e}}:(t.evaluations.splice(r,1),t.updatedAt=new Date().toISOString(),{...P})}function iT({officialRecord:t,suspensionId:e}){if(!t)return{error:Se};if(!e)return{error:O,context:{message:"Missing suspensionId"}};let r=t.suspensions.findIndex(n=>n.suspensionId===e);return r===-1?{error:TB,context:{suspensionId:e}}:(t.suspensions.splice(r,1),t.updatedAt=new Date().toISOString(),{...P})}function sT({officialRecord:t,certificationId:e,organisationId:r,certificationFamily:n,certificationLevel:o,status:i,validFrom:s,validUntil:a,documentReferences:c,notes:u,extensions:p}){if(!t)return{error:Se};if(!r)return{error:O,context:{message:"Missing organisationId"}};if(!n)return{error:O,context:{message:"Missing certificationFamily"}};let m=new Date().toISOString(),d={certificationId:e||it(),personId:t.personId,organisationId:r,certificationFamily:n,certificationLevel:o,status:i??Pm,validFrom:s,validUntil:a,documentReferences:c??[],notes:u,statusHistory:[{fromStatus:i??Pm,toStatus:i??Pm,transitionedAt:m,reason:"Certification created"}],extensions:p??[]};return t.certifications.push(d),t.updatedAt=m,{...P,certification:d}}function aT({officialRecord:t,assignmentId:e,tournamentId:r,roleSubtype:n,assignedDate:o,startDate:i,endDate:s,assignedBy:a,notes:c,extensions:u}){if(!t)return{error:Se};if(!r)return{error:O,context:{message:"Missing tournamentId"}};if(!n)return{error:O,context:{message:"Missing roleSubtype"}};let p=new Date().toISOString(),m={assignmentId:e||it(),personId:t.personId,tournamentId:r,roleSubtype:n,status:Yh,assignedDate:o??p.split("T")[0],startDate:i,endDate:s,assignedBy:a,notes:c,statusHistory:[{fromStatus:Yh,toStatus:Yh,transitionedAt:p,reason:"Assignment created"}],extensions:u??[]};return t.assignments.push(m),t.updatedAt=p,{...P,assignment:m}}function cT({officialRecord:t,suspensionId:e,organisationId:r,suspensionType:n,suspensionNotes:o,suspendedFrom:i,suspendedUntil:s,extensions:a}){if(!t)return{error:Se};let c={suspensionId:e||it(),personId:t.personId,organisationId:r,suspensionType:n,suspensionNotes:o,suspendedFrom:i,suspendedUntil:s,extensions:a??[]};return t.suspensions.push(c),t.updatedAt=new Date().toISOString(),{...P,suspension:c}}function uT({officialRecord:t,evaluationId:e,evaluatorPersonId:r,subjectPersonId:n,tournamentId:o,tournamentName:i,matchUpId:s,evaluationDate:a,overallRating:c,policyName:u,scores:p,comments:m,documentReference:d,extensions:l}){if(!t)return{error:Se};if(!r)return{error:O,context:{message:"Missing evaluatorPersonId"}};if(c==null)return{error:O,context:{message:"Missing overallRating"}};if(typeof c!="number"||c<0)return{error:O,context:{message:"overallRating must be a non-negative number"}};let f=new Date().toISOString(),g={evaluationId:e||it(),evaluatorPersonId:r,subjectPersonId:n??t.personId,tournamentId:o,tournamentName:i,matchUpId:s,evaluationDate:a??f.split("T")[0],overallRating:c,status:Xd,policyName:u,scores:p??[],comments:m,documentReference:d,statusHistory:[{fromStatus:Xd,toStatus:Xd,transitionedAt:f,reason:"Evaluation created"}],extensions:l??[]};return t.evaluations.push(g),t.updatedAt=f,{...P,evaluation:g}}var Sx={};Gt(Sx,{getEvaluationSummary:()=>gT,getEvaluationTemplate:()=>dT,getEvaluations:()=>ST,getOfficialAssignments:()=>fT,getOfficialCertifications:()=>pT,getOfficialEligibility:()=>lT,queryOfficialRecord:()=>IT,validateCertification:()=>mT,validateOfficiatingStatusTransition:()=>Ix});function Ix({entityType:t,fromStatus:e,toStatus:r}){let n;switch(t){case"certification":n=jh;break;case"evaluation":n=qh;break;case"assignment":n=$h;break;default:return{error:O,context:{message:`Unknown entityType: ${t}`}}}let o=n[e];return o?o.includes(r)?{...P,valid:!0}:{error:Xu,context:{entityType:t,fromStatus:e,toStatus:r,validTargets:o}}:{error:Xu,context:{entityType:t,fromStatus:e,message:`Unknown status: ${e}`}}}function pT({officialRecord:t,certificationFamily:e,certificationLevel:r,organisationId:n,activeOnly:o}){if(!t)return{error:Se};let i=[...t.certifications];return e&&(i=i.filter(s=>s.certificationFamily===e)),r&&(i=i.filter(s=>s.certificationLevel===r)),n&&(i=i.filter(s=>s.organisationId===n)),o&&(i=i.filter(s=>s.status==="ACTIVE")),{...P,certifications:i}}function mT({officialRecord:t,certificationId:e,asOfDate:r}){if(!t)return{error:Se};if(!e)return{error:O,context:{message:"Missing certificationId"}};let n=t.certifications.find(a=>a.certificationId===e);if(!n)return{error:Nm,context:{certificationId:e}};let o=[],i=r??new Date().toISOString().split("T")[0];n.status!=="ACTIVE"&&o.push(`Certification status is ${n.status}`),n.validUntil&&n.validUntil<i&&o.push(`Certification expired on ${n.validUntil}`),n.validFrom&&n.validFrom>i&&o.push(`Certification not yet valid until ${n.validFrom}`);let s=o.length===0;return!s&&n.validUntil&&n.validUntil<i?{error:IB,valid:s,certification:n,reasons:o}:{...P,valid:s,certification:n,reasons:o}}function dT({officialRecord:t,policyName:e,evaluationPolicy:r}){let n=r;if(!n&&e){if(!t)return{error:Se};n=t.evaluationPolicies.find(i=>i.policyName===e)}if(!n)return e?{error:yB,context:{policyName:e}}:{error:O,context:{message:"Missing evaluationPolicy or policyName"}};let o=[];for(let i of n.sections)for(let s of i.criteria)o.push({fieldId:`${i.sectionId}.${s.criterionId}`,sectionId:i.sectionId,sectionName:i.sectionName,criterionId:s.criterionId,criterionName:s.criterionName,description:s.description,scoringType:s.scoringType,scaleOptions:s.scaleOptions,numericRange:s.numericRange,required:s.required,weight:s.weight,sectionWeight:i.weight});return{...P,fields:o,evaluationPolicy:n}}function lT({officialRecord:t,certificationFamily:e,certificationLevel:r,organisationId:n,asOfDate:o}){if(!t)return{error:Se};let i=[],s=o??new Date().toISOString().split("T")[0];t.suspensions.filter(m=>{let d=m.suspendedFrom??"0000-00-00",l=m.suspendedUntil??"9999-12-31";return d<=s&&l>=s}).length>0&&i.push("Official has active suspension(s)");let c=t.certifications.filter(m=>m.certificationFamily===e&&m.status==="ACTIVE");if(n&&(c=c.filter(m=>m.organisationId===n)),r&&(c=c.filter(m=>m.certificationLevel===r)),c.length===0){let m=r?` ${r}`:"";i.push(`No active ${e}${m} certification`)}let u=c.filter(m=>!(m.validUntil&&m.validUntil<s||m.validFrom&&m.validFrom>s));if(c.length>0&&u.length===0&&i.push("Matching certification(s) are expired or not yet valid"),r){let m=t.certificationRequirements.find(d=>d.certificationFamily===e&&d.certificationLevel===r&&(!n||d.organisationId===n));m&&Mtt({certificationFamily:e,officialRecord:t,requirement:m,reasons:i})}let p=i.length===0;return{...P,eligible:p,reasons:i}}function Mtt({certificationFamily:t,officialRecord:e,requirement:r,reasons:n}){if(r.minimumAssignments!==void 0){let o=e.assignments.filter(i=>i.status==="COMPLETED");o.length<r.minimumAssignments&&n.push(`Insufficient completed assignments: ${o.length}/${r.minimumAssignments}`)}r.minimumEvaluationScore!==void 0&&vtt({officialRecord:e,requirement:r,reasons:n}),r.prerequisiteLevels?.length&&(r.prerequisiteLevels.some(i=>e.certifications.some(s=>s.certificationFamily===t&&s.certificationLevel===i&&(s.status==="ACTIVE"||s.status==="EXPIRED")))||n.push(`Missing prerequisite certification level: ${r.prerequisiteLevels.join(" or ")}`))}function vtt({officialRecord:t,requirement:e,reasons:r}){let n=t.evaluations.filter(i=>i.status==="APPROVED");if(n.length===0){r.push("No approved evaluations");return}let o=n.reduce((i,s)=>i+s.overallRating,0)/n.length;o<e.minimumEvaluationScore&&r.push(`Average evaluation score ${o.toFixed(2)} below minimum ${e.minimumEvaluationScore}`)}function fT({officialRecord:t,tournamentId:e,roleSubtype:r,status:n}){if(!t)return{error:Se};let o=[...t.assignments];return e&&(o=o.filter(i=>i.tournamentId===e)),r&&(o=o.filter(i=>i.roleSubtype===r)),n&&(o=o.filter(i=>i.status===n)),{...P,assignments:o}}function gT({officialRecord:t,policyName:e,approvedOnly:r=!0}){if(!t)return{error:Se};let n=t.evaluations;if(r&&(n=n.filter(u=>u.status==="APPROVED")),n.length===0)return{...P,summary:{evaluationCount:0,averageRating:0}};let o=n.map(u=>u.overallRating),i=o.reduce((u,p)=>u+p,0)/o.length,a=[...n].sort((u,p)=>p.evaluationDate>u.evaluationDate?1:-1)[0],c={evaluationCount:n.length,averageRating:Math.round(i*100)/100,latestRating:a.overallRating,latestDate:a.evaluationDate};if(e){let u=t.evaluationPolicies.find(p=>p.policyName===e);if(u){let p=n.filter(m=>m.policyName===e);p.length>0&&(c.sectionAverages=u.sections.map(m=>{let d=new Set(m.criteria.map(f=>f.criterionId)),l=[];for(let f of p){let g=f.scores.filter(I=>d.has(I.criterionId)&&typeof I.value=="number").map(I=>I.value);g.length>0&&l.push(g.reduce((I,S)=>I+S,0)/g.length)}return{sectionId:m.sectionId,sectionName:m.sectionName,average:l.length>0?Math.round(l.reduce((f,g)=>f+g,0)/l.length*100)/100:0}}),u.passingThreshold!==void 0&&(c.meetsThreshold=c.averageRating>=u.passingThreshold))}}return{...P,summary:c}}function IT({officialRecord:t}){return t?{...P,officialRecord:t}:{error:Se}}function ST({officialRecord:t,evaluatorPersonId:e,status:r,tournamentId:n,policyName:o}){if(!t)return{error:Se};let i=[...t.evaluations];return e&&(i=i.filter(s=>s.evaluatorPersonId===e)),r&&(i=i.filter(s=>s.status===r)),n&&(i=i.filter(s=>s.tournamentId===n)),o&&(i=i.filter(s=>s.policyName===o)),{...P,evaluations:i}}var Cx={};Gt(Cx,{addCourt:()=>mg,addCourts:()=>_h,addVenue:()=>yu,deleteCourt:()=>yx,deleteCourts:()=>Ex,deleteVenue:()=>nD,deleteVenues:()=>Ax,disableCourts:()=>Px,disableVenues:()=>Nx,enableCourts:()=>Dx,enableVenues:()=>Ux,generate:()=>Tx,generateCourts:()=>Sh,getCompetitionVenues:()=>hd,getCourts:()=>kP,getVenuesAndCourts:()=>kn,modifyCourt:()=>TT,modifyCourtAvailability:()=>hT,modifyVenue:()=>Rx,mutate:()=>bx,publicFindVenue:()=>IE,query:()=>lv});var Tx={};Gt(Tx,{generateCourts:()=>Sh});var bx={};Gt(bx,{addCourt:()=>mg,addCourts:()=>_h,addVenue:()=>yu,deleteCourt:()=>yx,deleteCourts:()=>Ex,deleteVenue:()=>nD,deleteVenues:()=>Ax,disableCourts:()=>Px,disableVenues:()=>Nx,enableCourts:()=>Dx,enableVenues:()=>Ux,modifyCourt:()=>TT,modifyCourtAvailability:()=>hT,modifyVenue:()=>Rx});function Ng(t){if(!t?.tournamentRecord&&!Array.isArray(t?.venueMatchUps))return{error:j};if(!t?.courtId)return{error:jg};let{scheduleVisibilityFilters:e,tournamentRecord:r,matchUpFilters:n,venueMatchUps:o,courtId:i}=t,{schedulingProfile:s}=bo({tournamentRecord:r});if(Array.isArray(o))return{matchUps:u({matchUps:o,courtId:i})};let{matchUps:a}=qt({scheduleVisibilityFilters:e,tournamentRecord:r,matchUpFilters:n});return{matchUps:u({matchUps:a,courtId:i})};function u({matchUps:p,courtId:m}){let d=p.filter(l=>{let f=l.schedule?.allocatedCourts?.map(({courtId:g})=>g);return l.schedule?.courtId===m||f?.includes(m)});return zf({matchUps:d,schedulingProfile:s})}}function AB({scheduleVisibilityFilters:t,tournamentRecord:e,matchUpFilters:r,venueId:n}){let o=dt({tournamentRecord:e,venueId:n},[rt,Tp]);if(o.error)return o;let{schedulingProfile:i}=bo({tournamentRecord:e}),{matchUps:s}=qt({scheduleVisibilityFilters:t,tournamentRecord:e,matchUpFilters:r});return{matchUps:c({matchUps:s,venueId:n})};function c({matchUps:u,venueId:p}){let m=u.filter(d=>{let l=d.schedule?.allocatedCourts?.map(({venueId:f})=>f);return d.schedule?.venueId===p||l?.includes(p)});return zf({matchUps:m,schedulingProfile:i})}}function hT({tournamentRecord:t,dateAvailability:e,disableNotice:r,venueMatchUps:n,courtId:o,force:i}){let s=dt({tournamentRecord:t,courtId:o},[rt,Ws]);if(s.error)return s;let a=kp({dateAvailability:e});if(a.error)return a;let{updatedDateAvailability:c,totalMergeCount:u}=Ott(e);e=c;let p=Si({tournamentRecord:t,courtId:o});if(p.error)return p;let{court:m,venue:d}=p,{matchUps:l}=Ng({tournamentRecord:t,venueMatchUps:n,courtId:o});if(l?.length){let f=ft({tournamentRecord:t})?.appliedPolicies,g=i??f?.[ko]?.allowDeletionWithScoresPresent?.courts,I=l.filter(S=>{let{scheduledDate:h,scheduledTime:T}=S.schedule??{};if(!h||!T)return!1;let y=e.filter(A=>A.date===h);if(!y.length)return!0;let E=ve(T);return!y.some(A=>{let N=ve(A.startTime),D=ve(A.endTime);return ks(N,E,!1)<=0&&ks(E,D,!1)<=0})});if(I.length&&!g)return{error:OD,info:`${I.length} matchUp(s) scheduled outside new availability`,matchUpIds:I.map(S=>S.matchUpId)}}return m&&(m.dateAvailability=e,!r&&d&&at({payload:{venue:d,tournamentId:t.tournamentId},topic:No,key:d.venueId})),{...P,totalMergeCount:u}}function Ott(t){let e=0,r=t.reduce((o,i)=>{let{date:s,startTime:a,endTime:c,bookings:u}=i;return o[s]||(o[s]=[]),o[s].push({startTime:a,endTime:c,bookings:u}),o},{}),n=[];return Object.keys(r).forEach(o=>{r[o].sort(jL);let{mergedAvailability:i,mergeCount:s}=_tt(r[o]);n.push(...i.map(a=>({date:o,...a}))),e+=s}),{updatedDateAvailability:n,totalMergeCount:e}}function _tt(t){let e,r,n,o=t.length,i=0,s=[];for(;t.length&&o;){let c=t.shift(),{startTime:u,endTime:p,bookings:m}=c;if(o-=1,e)if(ks(ve(r),ve(u),!1)>0){let l={startTime:e,endTime:r};n?.length&&(l.bookings=n),s.push(l),e=u,n=m,r=p}else m&&(n?n.push(m):n=m),r=p,i+=1;else e=u,n=m,r=p}let a={startTime:e,endTime:r};return n?.length&&(a.bookings=n),s.push(a),{mergedAvailability:s,mergeCount:i}}function rD({tournamentRecord:t,drawDefinition:e,matchUpId:r,drawId:n}){let o="removeCourtAssignment";if(!r)return{error:mr};if(!e&&!n)return{error:Nn};let i;if(!e){if(!t)return{error:j};({drawDefinition:e}=_e({tournamentRecord:t,drawId:n}))}if(e)({matchUp:i}=Wt({drawDefinition:e,matchUpId:r}));else{if(!t)return{error:j};let s=qt({tournamentRecord:t,inContext:!1}).matchUps??[];({matchUp:i}=tA({matchUps:s,matchUpId:r}))}return i?(i.timeItems&&i.timeItems.find(a=>[li,Io].includes(a.itemType))&&(i.timeItems=i.timeItems.filter(({itemType:a})=>![li,Io].includes(a)),It({tournamentId:t?.tournamentId,context:o,drawDefinition:e,matchUp:i})),{...P}):{error:Be}}function Dg({matchUpsCount:t=0}){let r=`Schedule would be deleted from ${t} ${t===1?"matchUp":"matchUps"}; use { force: true }`;return{error:jU,info:r}}function yx(t){let{courtId:e,disableNotice:r,force:n}=t,o=Dr(t),i=X(t,[{[Ee]:!0,[Ws]:!0}]);if(i.error)return i;let s,a;for(let c of Object.values(o)){if(a=PB({tournamentRecord:c,disableNotice:r,courtId:e,force:n}),a.error&&a.error!==vo)return a;a.success&&(s=!0)}return s?{...P}:a}function PB({tournamentRecord:t,disableNotice:e,courtId:r,force:n}){let o=Si({tournamentRecord:t,courtId:r});if(o.error)return o;let i=o.venue,{matchUps:s}=Ng({tournamentRecord:t,courtId:r}),a=ft({tournamentRecord:t})?.appliedPolicies,c=n??a?.[ko]?.allowDeletionWithScoresPresent?.courts;if(!s?.length||c){for(let u of s??[]){let p=rD({matchUpId:u.matchUpId,drawId:u.drawId,tournamentRecord:t});if(p.error)return p}i&&(i.courts=(i.courts??[]).filter(u=>u.courtId!==r),e||at({payload:{venue:i,tournamentId:t.tournamentId},topic:No,key:i.venueId}))}else return Dg({matchUpsCount:s.length});return{...P}}function Ex(t){let{tournamentRecord:e,courtIds:r,force:n}=t;if(!e)return{error:j};if(!Array.isArray(r))return{error:O};for(let o of r){let i=PB({tournamentRecord:e,courtId:o,force:n});if(i.error)return i}return{...P}}function nD(t){if(typeof t?.venueId!="string")return{error:Ls};let{tournamentRecord:e,venueId:r,force:n}=t,o=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!Object.keys(o).length)return{error:j};let s=cn({tournamentRecords:o,contextFilters:{venueIds:[r]}}).matchUps??[],a=ft({tournamentRecord:e})?.appliedPolicies,c=n??a?.[ko]?.allowDeletionWithScoresPresent?.venues;if(!s.length||c)for(let u of Object.values(o)){for(let m of s){let d=rD({matchUpId:m.matchUpId,drawId:m.drawId,tournamentRecord:u});if(d.error)return d}let p;u.venues=(u.venues??[]).filter(m=>m?.venueId!==r?!0:(p=!0,!1)),p&&at({payload:{venueId:r,tournamentId:u.tournamentId},topic:BI,key:r})}else return Dg({matchUpsCount:s.length});return ku({tournamentRecords:o}),{...P}}function Ax({tournamentRecord:t,venueIds:e,force:r}){if(!t)return{error:j};if(!Array.isArray(e))return{error:O};for(let n of t.venues??[]){let{venueId:o}=n;if(e.includes(o)){let{venueId:i}=n,s=nD({tournamentRecord:t,venueId:i,force:r});if(s.error)return s}}return{...P}}function Px(t){let{courtIds:e,dates:r}=t,n=Dr(t),o=[{[Ee]:!0,[Km]:!0}],i=X(t,o);if(i.error)return i;for(let s of Object.values(n))xtt({tournamentRecord:s,courtIds:e,dates:r});return{...P}}function xtt({tournamentRecord:t,courtIds:e,dates:r}){let n=Array.isArray(r)&&r.length?{dates:r}:!0,o=i=>ut({extension:{value:n,name:lo},creationTime:!1,element:i});for(let i of t.venues??[])for(let s of i.courts??[])if(e?.includes(s.courtId)){let a=o(s);if(a.error)return a}return{...P}}function Nx(t){let{tournamentRecords:e,tournamentId:r,venueIds:n}=t,o=[{[Ee]:!0,[zm]:!0}],i=X(t,o);if(i.error)return i;let s=Object.keys(e).filter(a=>!r||a===r);for(let a of s){let c=e[a];wtt({tournamentRecord:c,venueIds:n})}return{...P}}function wtt({tournamentRecord:t,venueIds:e}){for(let r of t.venues??[])if(e?.includes(r.venueId)){let n=ut({creationTime:!1,element:r,extension:{name:lo,value:!0}});if(n.error)return n}return{...P}}function Dx(t){let e=Dr(t),r=[{[Ee]:!0}];!t.enableAll&&r.push({[Km]:!0});let n=X(t,r);if(n.error)return n;let{enableAll:o,courtIds:i,dates:s}=t;for(let a of Object.values(e))Ltt({tournamentRecord:a,courtIds:i,enableAll:o,dates:s});return{...P}}function Ltt({tournamentRecord:t,courtIds:e,enableAll:r,dates:n}){for(let o of t.venues??[])for(let i of o.courts??[])if(r||e?.includes(i.courtId))if(Array.isArray(n)){let{extension:s}=ot({element:i,name:lo});if(s){let a=s.value;Array.isArray(a.dates)&&(a.dates=a.dates.filter(c=>!n.includes(c))),ut({extension:{name:lo,value:a},creationTime:!1,element:i})}}else dr({element:i,name:lo});return{...P}}function Ux(t){let e=Dr(t),r=[{[Ee]:!0}];!t.enableAll&&r.push({[zm]:!0});let n=X(t,r);if(n.error)return n;let{venueIds:o,enableAll:i}=t;for(let s of Object.values(e))for(let a of s.venues??[])(i||o?.includes(a.venueId))&&dr({element:a,name:lo});return{...P}}function TT(t){let{disableNotice:e,modifications:r,courtId:n,force:o,venueMatchUps:i}=t,s=Dr(t);if(!Object.keys(s).length)return{error:kt};let a;for(let c of Object.values(s)){let u=Ftt({tournamentRecord:c,disableNotice:e,venueMatchUps:i,modifications:r,courtId:n,force:o});if(u?.error)return u;a=!0}return a?{...P}:void 0}function Ftt({tournamentRecord:t,disableNotice:e,venueMatchUps:r,modifications:n,courtId:o,force:i}){let s=dt({tournamentRecord:t,courtId:o},[rt,Ws]);if(s.error)return s;if(!n||typeof n!="object")return{error:yo};let a=Si({tournamentRecord:t,courtId:o});if(a.error)return a;let{venue:c,court:u}=a,p=Object.keys(cV()).filter(f=>f!=="courtId");if(!Object.keys(n).filter(f=>p.includes(f)).length)return{error:Xc};let d=new Set(p.filter(f=>!["dateAvailability"].includes(f))),l=Object.keys(n).filter(f=>d.has(f));if(u&&l.forEach(f=>Object.assign(u,{[f]:n[f]})),n.dateAvailability){let f=hT({dateAvailability:n.dateAvailability,tournamentRecord:t,venueMatchUps:r,disableNotice:e,courtId:o,force:i});if(f.error)return f}return e||at({payload:{venue:c,tournamentId:t.tournamentId},topic:No,key:c?.venueId}),{...P,court:q(u)}}var ktt=()=>({venueId:void 0,venueName:"",venueAbbreviation:"",onlineResources:[],venueType:void 0,defaultStartTime:void 0,defaultEndTime:void 0,isPrimary:void 0,dateAvailability:[],addresses:[],contacts:[],courts:[],roles:[]}),NB=ktt;function Rx(t){let{modifications:e,venueId:r,force:n}=t,o=Dr(t);if(!Object.keys(o).length)return{error:kt};if(typeof r!="string")return{error:Ls};let i,s;for(let a of Object.values(o)){let c=Btt({tournamentRecord:a,modifications:e,venueId:r,force:n});if(c.success&&(s=!0),c.error&&(i=c.error),c.error&&c.error!==wi)return c}return ku({tournamentRecords:o}),s?{...P}:{error:i}}function Gtt({venue:t,modifications:e,tournamentRecord:r,venueMatchUps:n,allowModificationWhenMatchUpsScheduled:o}){let i=t?.courts?.map(u=>u.courtId)??[],s=e.courts?.map(u=>u.courtId)??[],a=s.length?i.filter(u=>!s.includes(u)):e?.courts&&i,c=[];if(a?.length){let p=t?.courts?.filter(m=>a.includes(m.courtId))?.map(m=>{let d=Ng({courtId:m.courtId,tournamentRecord:r,venueMatchUps:n});for(let l of d.matchUps??[])c.push({matchUpId:l.matchUpId,drawId:l.drawId});return d.matchUps?.length??0}).reduce((m,d)=>m+d);return t&&(!p||o)?(t.courts=t.courts?.filter(m=>s.includes(m.courtId)),pm({schedule:{courtId:"",scheduledDate:""},matchUpDetails:c,removePriorValues:!0,tournamentRecord:r}),{success:!0}):Dg({matchUpsCount:p})}return{success:!0}}function Vtt({modifications:t,tournamentRecord:e,venueMatchUps:r,venueId:n,force:o}){if(t.courts)for(let i of t.courts){let{courtId:s}=i??{},a=TT({modifications:i,disableNotice:!0,tournamentRecord:e,venueMatchUps:r,courtId:s,force:o});if(a?.error===vo&&(a=mg({disableNotice:!0,tournamentRecord:e,venueId:n,court:i})),a?.error)return a}return{success:!0}}function Btt({tournamentRecord:t,modifications:e,venueId:r,force:n}){let o=dt({tournamentRecord:t,venueId:r},[rt,Tp]);if(o.error)return o;if(!e||typeof e!="object")return{error:yo};let i=t,s=ft({tournamentRecord:i})?.appliedPolicies,a=n??s?.[ko]?.allowDeletionWithScoresPresent?.venues,{matchUps:c}=AB({tournamentRecord:i,venueId:r}),u=Ln({tournamentRecord:i,venueId:r});if(u.error)return u;let p=u.venue,m=Object.keys(NB()).filter(T=>T!=="venueId");if(!Object.keys(e).filter(T=>m.includes(T)).length)return{error:Xc};let l=new Set(m.filter(T=>!["courts","onlineResources","dateAvailability","isPrimary"].includes(T))),f=Object.keys(e).filter(T=>l.has(T));if(!p)return{error:wi};let g=e.defaultStartTime??p.defaultStartTime,I=e.defaultEndTime??p.defaultEndTime;if(g||I){if(!g||!I)return{error:O,info:"both defaultStartTime and defaultEndTime are required"};if(!ql({startTime:g,endTime:I}))return{error:O,info:"defaultEndTime must be after defaultStartTime"}}if(f.forEach(T=>Object.assign(p,{[T]:e[T]})),"isPrimary"in e&&(e.isPrimary?(gE({tournamentRecord:i}),p.isPrimary=!0):delete p.isPrimary),e.dateAvailability!==void 0){if(Array.isArray(e.dateAvailability)&&e.dateAvailability.length){let T=kp({dateAvailability:e.dateAvailability});if(T.error)return T}p.dateAvailability=e.dateAvailability}let S=Gtt({venue:p,modifications:e,tournamentRecord:i,venueMatchUps:c,allowModificationWhenMatchUpsScheduled:a});if("error"in S&&S.error)return S;let h=Vtt({modifications:e,tournamentRecord:i,venueMatchUps:c,venueId:r,force:n});return h?.error?h:(ku({tournamentRecord:i}),p&&at({payload:{venue:p,tournamentId:i.tournamentId},topic:No,key:p?.venueId}),{...P,venue:q(p)})}var Mx={};Gt(Mx,{JSON2CSV:()=>MB,UUID:()=>it,UUIDS:()=>ay,allNumeric:()=>xT,attributeFilter:()=>hs,chunkArray:()=>he,chunkByNth:()=>wg,chunkSizeProfile:()=>UD,constantToString:()=>xe,countValues:()=>uw,createMap:()=>vT,dateTime:()=>iy,definedAttributes:()=>et,dehydrateMatchUps:()=>CB,extractAttributes:()=>Mb,flattenJSON:()=>iD,generateDateRange:()=>Ua,generateHashCode:()=>ow,generateRange:()=>Q,generateTimeCode:()=>vN,groupValues:()=>ND,hasAttributeValues:()=>nw,instanceCount:()=>mn,intersection:()=>Yt,isConvertableInteger:()=>yt,isNumeric:()=>Le,isOdd:()=>OT,isPowerOf2:()=>en,isValidEmbargoDate:()=>Ra,makeDeepCopy:()=>q,matchUpScheduleSort:()=>bB,matchUpSort:()=>Qi,nearestPowerOf2:()=>rl,nextPowerOf2:()=>Pi,noNulls:()=>cw,noNumeric:()=>wT,numericSort:()=>Zt,occurrences:()=>pw,overlap:()=>Re,randomMember:()=>Pn,randomPop:()=>Sr,shuffleArray:()=>ar,structureSort:()=>Hi,subSort:()=>mw,timeZone:()=>XG,undefinedToNull:()=>MT,unique:()=>pt,visualizeScheduledMatchUps:()=>DB});function DB({scheduledMatchUps:t,showGlobalLog:e}){u0();let r=t?.reduce((o,{structureId:i})=>o.includes(i)?o:o.concat(i),[]),n=Array.isArray(r)&&{...r.map(o=>{let{structureName:i,matchUpType:s}=t.find(a=>a.structureId===o);return{[o]:`${i} ${s}`}})};r?.forEach(o=>{Pe({color:"blue",method:"draw",structure:n[o],keyColors:{structure:"magenta"}},!0);let i=t.filter(a=>a.structureId===o),s=Ue({matchUps:i})?.roundMatchUps||[];Object.keys(s).forEach(a=>{Pe({roundNumber:a,keyColors:{roundNumber:"brightcyan"}},!0),s[a].forEach(({matchUpId:c,schedule:u})=>{let p=$t(u.scheduledTime);Pe({matchUpId:c,time:p,date:u.scheduledDate,venue:u.venueId,keyColors:{time:"brightcyan",date:"brightcyan",matchUpId:"yellow",venue:"magenta"}},!0)})})}),e&&c0()}var{extractTime:UB,timeStringMinutes:RB}=iy;function bB(t,e){let r=t.schedule??{},n=e.schedule??{};if(r.scheduledDate&&!n.scheduledDate)return 1;if(n.scheduledDate&&!r.scheduledDate)return-1;if(r.scheduledDate&&n.scheduledDate){if(r.scheduledDate===n.scheduledDate){if(r.scheduledTime&&!n.scheduledTime)return 1;if(n.scheduledTime&&!r.scheduledTime)return-1;if(r.scheduledTime&&n.scheduledTime){let o=RB(UB(r.scheduledTime)),i=RB(UB(n.scheduledTime));return o-i}}return new Date(r.scheduledDate).getTime()-new Date(n.scheduledDate).getTime()}return 0}function CB({tournamentRecord:t}){if(!t)return{error:j};if(typeof t!="object"||!t.tournamentId)return{error:O};let{matchUps:e}=qt({tournamentRecord:t,inContext:!1});if(e?.length){let r=Wtt({tournamentRecord:t});Ytt(e,r)}return{...P}}function Wtt({tournamentRecord:t}){let e={};for(let r of t.events??[]){r.matchUpFormat&&(e[r.eventId]=r.matchUpFormat);for(let n of r.drawDefinitions??[]){n.matchUpFormat&&(e[n.drawId]=n.matchUpFormat);for(let o of n.structures??[]){o.matchUpFormat&&(e[o.structureId]=o.matchUpFormat);for(let i of o.structures??[])i.matchUpFormat&&(e[i.structureId]=i.matchUpFormat)}}}return e}var Htt=["collectionId","collectionPosition","drawPositions","extensions","finishingPositionRange","finishingRound","isMock","matchUpId","matchUpStatus","matchUpStatusCodes","orderOfFinish","processCodes","roundNumber","tieFormat","tieMatchUps","roundPosition","score","sides","winnerMatchUpId","loserMatchUpId","matchUpDuration","winningSide"];function Ytt(t,e={}){for(let r of t){let{structureId:n,drawId:o,eventId:i}=r,s=e[n]||e[o]||e[i],a=r.matchUpFormat===s?void 0:r.matchUpFormat;for(let c of Object.keys(r))Htt.includes(c)||delete r[c];r.sides&&r.drawPositions&&!r.tieMatchUps&&delete r.sides,a&&(r.matchUpFormat=a)}}function MB(t,e){if(e&&typeof e!="object")return{error:O};let{columnTransform:r={}}=e??{},{includeTransformAccessors:n,includeHeaderRow:o=!0,returnTransformedJSON:i,removeEmptyColumns:s,onlyHeaderRow:a,columnAccessors:c=[],functionMap:u={},columnMap:p={},valuesMap:m={},context:d={},delimiter:l='"',columnJoiner:f=",",rowJoiner:g=`\r
|