tods-competition-factory 2.1.29 → 2.1.30
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 +2 -2
- 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 +6 -6
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var oL=Object.defineProperty;var Xt=(t,e)=>{for(var r in e)oL(t,r,{get:e[r],enumerable:!0})};function Va(){return"2.1.29"}var hA={};Xt(hA,{competitionGovernor:()=>DU,drawsGovernor:()=>MN,entriesGovernor:()=>xN,eventGovernor:()=>$N,generationGovernor:()=>ZN,matchUpFormatGovernor:()=>Oy,matchUpGovernor:()=>yM,mocksGovernor:()=>fI,participantGovernor:()=>QM,policyGovernor:()=>nN,publishingGovernor:()=>iR,queryGovernor:()=>DN,reportGovernor:()=>sR,scheduleGovernor:()=>SR,scoreGovernor:()=>Hg,tieFormatGovernor:()=>RR,tournamentGovernor:()=>VR,venueGovernor:()=>QR});var DU={};Xt(DU,{getLinkedTournamentIds:()=>iu,getTournamentIds:()=>Ip,linkTournaments:()=>yU,mutate:()=>UU,query:()=>PU,unlinkTournament:()=>EU,unlinkTournaments:()=>AU});var UU={};Xt(UU,{linkTournaments:()=>yU,unlinkTournament:()=>EU,unlinkTournaments:()=>AU});var aa="SINGLES",xt="SINGLES",vi="DOUBLES",_t="DOUBLES",xr="TEAM",jt="TEAM",sC={SINGLES_MATCHUP:aa,SINGLES:xt,DOUBLES_MATCHUP:vi,DOUBLES:_t,TEAM_MATCHUP:xr,TEAM:jt};var EI={[xt]:[xt,"S"],[_t]:[_t,"D"],[jt]:[jt,"T"],S:[xt,"S"],D:[_t,"D"],T:[jt,"T"]};function me(t,e){return(t??0)-(e??0)}function pt(t){return typeof t=="number"?parseInt(t.toString()):typeof t=="string"?parseInt(t):0}function vn(t){return isNaN(t)?!1:t&&(t&t-1)===0}function AA(t){if(!t.length)return;let e=[...t].sort(me),r=Math.floor(e.length/2);return e.length%2?e[r]:(e[r-1]+e[r])/2}function aC(t){if(!vn(t))return!1;let e=t,r=1;for(;e!==2;)r+=1,e=e/2;return r}function hm(t){return isNaN(t)?0:t%2&&t+1||t}function Sm(t){return Math.pow(2,Math.round(Math.log(t)/Math.log(2)))}function Zt(t){return!isNaN(parseFloat(t))}function UI(t){let e=pt(t);if(!isNaN(e))return e===0?!1:(e&-e)===1}function es(t){if(isNaN(t))return!1;for(;!vn(t);)t++;return t}function po(t,e){return t=Math.ceil(t),e=Math.floor(e),Math.floor(Math.random()*(e-t+1))+t}function It(t){return Number.isSafeInteger(typeof t=="string"?+t:t)}function cC(t=1,e=3,r=!0){let n=0;for(let o=0;o<e;o++)n+=Math.random()*(t/e);return r&&t>1?Math.round(n):n}function iL(t,e){e||(e=1);let r=1/e;return Math.round(t*r)/r}function EA(t,e,r,n,o=2){let i=1-Math.random(),s=1-Math.random(),a=Math.sqrt(-2*Math.log(i))*Math.cos(2*Math.PI*s);return a=a/10+.5,a>1||a<0?a=EA(t,e,r):(a=Math.pow(a,r),a*=e-t,a+=t),n&&(a=iL(a,n)),parseFloat(a.toFixed(o))}function _l(t,e=2){return parseFloat(Number(Math.round(t*1e3)/1e3).toFixed(e))}function ut(t){return Array.isArray(t)?t?.filter((e,r,n)=>n.lastIndexOf(e)===r):[]}function uC(t){return Array.isArray(t)?t?.map(e=>e===null?void 0:e):t}function Ir(t){return Array.isArray(t)?t.map(e=>[Math.random(),e]).sort((e,r)=>e[0]-r[0]).map(e=>e[1]):[]}function Ba(t){return It(t)?t:1/0}function Sr(t){return Array.isArray(t)?t.reduce((e,r)=>(e[r]||(e[r]=0),e[r]++,e),{}):{}}function pC(t){return UA(Sr(t))}function UA(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return e[n]?e[n].push(r):e[n]=[r],e},{})}function sL(t,e,r){return r.indexOf(t)===e}function PI(t){return t.filter(sL)}function tn(t){return Array.isArray(t)&&t.length?t.splice(Math.floor(Math.random()*t.length),1)[0]:void 0}function yn(t){let e=Math.floor(Math.random()*t.length);return t[e]}function et(t,e){return Array.from({length:e-t},(r,n)=>n+t)}function mo(t,e){return e.reduce((r,n,o)=>(n===t&&r.push(o),r),[])}function Yt(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(r=>e.indexOf(r)!==-1).filter((r,n,o)=>o.indexOf(r)===n)}function PA(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(r=>!e.includes(r))}function Fe(t,e){return!Array.isArray(t)||!Array.isArray(e)?!1:t.some(r=>e.includes(r))}function mC(t,e){return Array.isArray(e)&&e.reduce((r,n)=>(r[n]=1+r[n]||1,r),{})[t]||0}function dC(t,e,r,n){return Array.isArray(t)?[].concat(...t.slice(0,e),...t.slice(e,e+r).sort(n),...t.slice(e+r,t.length)):[]}function ye(t,e){return Array.isArray(t)?t.reduce((r,n,o)=>{let i=Math.floor(o/e);return r[i]=[].concat(r[i]||[],n),r},[]):[]}function DA(t,[e,...r]){return t.length?[t.slice(0,e),...DA(t.slice(e),[...r,e])]:[]}function lC(t){return t.reduce((e,r)=>{let n=e[e.length-1];return(!n||n[n.length-1]!==r-1)&&e.push([]),e[e.length-1].push(r),e},[])}function DI(t){return Array.isArray(t)?t.reduce((e,r)=>!isNaN(parseInt(r))&&e,!0):!1}function NI(t){return Array.isArray(t)?t.reduce((e,r)=>isNaN(parseInt(r))&&e,!0):!1}function xl(t,e,r){return Array.isArray(t)?t.reduce((n,o,i)=>{let s=r?!!(Math.floor(i/e)%2):!1,a=i%e,c=s?e-1-a:a;return n[c]||(n[c]=[]),n[c].push(o),n},[]):[]}function fC(t,e=1){if(!Array.isArray(t)||!t.every(It))return[];let r=Math.min(...t,e),n=Math.max(...t);return et(r,n+1).filter(o=>!t.includes(o))}function Wr(t){return typeof t=="function"}function Vt(t){return typeof t=="string"}function ht(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function gC(t,e){if(!ht(t)||!ht(e))return!1;let r=Object.keys(t),n=Object.keys(e);if(r.length!==n.length)return!1;for(let o of r)if(t[o]!==e[o])return!1;return!0}function RI(t,e){return Array.isArray(t)?Object.assign({},...(t??[]).filter(ht).map(r=>r[e]&&{[r[e]]:r}).filter(Boolean)):{}}var IC=t=>e=>Object.keys(t).every(r=>e[r]===t[r]);function MI(t,e){if(t===void 0)return null;if(!ht(t)||t===null)return t;let r=Object.keys(t),n=o=>o===void 0?null:o;return Object.assign({},...r.map(o=>Array.isArray(t[o])?{[o]:e?t[o]:t[o].map(i=>MI(i))}:{[o]:e?n(t[o]):MI(t[o])}))}function NA(t){return Array.isArray(t)?t.length+t.map(NA).reduce((e,r)=>e+r,0):ht(t)&&t!==null?Object.keys(t).length+Object.keys(t).map(e=>NA(t[e])).reduce((e,r)=>e+r,0):0}function hC(t){if(t===null||typeof t!="object")return;let e=JSON.stringify(t),r=NA(t),n=e.split("").reduce((o,i)=>o+i.charCodeAt(0),0);return[e.length,r,n].map(o=>o.toString(36)).join("")}function Lc(t,e){return!Array.isArray(t)||!Vt(e)?!1:Yt(t,EI[e]).length}var C={success:!0},MA="error",SC={SUCCESS:C,ERROR:MA};function CI({collectionValueProfiles:t,matchUpCount:e}){let r=[];if(!Array.isArray(t))return r.push(`collectionValueProfiles is not an array: ${t}`),{errors:r};if(t.length&&t.length!==e)return r.push("collectionValueProfiles do not align with matchUpsCount"),{errors:r};for(let o of t){if(typeof o!="object")return r.push(`valueProfile is not type object: ${o}`),{errors:r};let{matchUpValue:i,collectionPosition:s}=o;if(typeof i!="number"||typeof s!="number"||s>e||s<1)return r.push("Invalid value profile: value and collectionPosition must be numeric. collectionPosition cannot be greater than matchUpCount"),{errors:r}}let n=t.map(o=>o.collectionPosition);return n.length!==ut(n).length?(r.push("collectionPositions are not unique"),{errors:r}):{...C}}var bC={};Xt(bC,{addNotice:()=>mt,callListener:()=>Pm,createInstanceState:()=>wE,cycleMutationStatus:()=>cf,deepCopyEnabled:()=>af,deleteNotice:()=>YI,deleteNotices:()=>Fi,disableNotifications:()=>LE,enableNotifications:()=>sf,getDevContext:()=>Ur,getMethods:()=>uf,getNotices:()=>jI,getProvider:()=>qI,getTopics:()=>Lr,getTournamentId:()=>ns,getTournamentRecord:()=>pf,getTournamentRecords:()=>Fo,globalLog:()=>GE,handleCaughtError:()=>op,hasTopic:()=>rp,removeTournamentRecord:()=>kE,setDeepCopy:()=>Hc,setDevContext:()=>Bc,setGlobalLog:()=>MC,setGlobalMethods:()=>RC,setGlobalSubscriptions:()=>LL,setMethods:()=>CC,setStateMethods:()=>VE,setStateProvider:()=>xL,setSubscriptions:()=>FL,setTournamentId:()=>np,setTournamentRecord:()=>FE,setTournamentRecords:()=>Dm,timeKeeper:()=>wL});var bI={message:"Chronological error; time violation.",code:"ANACHRONISM"},Tm={message:"Duplicate entry",code:"DUPLICATE_ENTRY"},RA={message:"Cannot remove main structure",code:"ERR_CANNOT_REMOVE_MAIN_STRUCTURE"},vI={message:"records must be an object with tournamentId keys",code:"ERR_INVALID_TOURNAMENTS"},wt={message:"Missing tournamentRecords",code:"ERR_MISSING_TOURNAMENTS"},Y={message:"Missing tournamentRecord",code:"ERR_MISSING_TOURNAMENT"},Ha={message:"Invalid tournamentRecord",code:"ERR_INVALID_TOURNAMENT"},ca={message:"Missing tournamentId",code:"ERR_MISSING_TOURNAMENT_ID"},ua={message:"Invalid drawDefinition",code:"ERR_INVALID_DRAWDEF"},Z={message:"Missing drawDefinition",code:"ERR_MISSING_DRAWDEF"},CA={message:"Existing drawDefinition(s)",code:"ERR_EXISTING_DRAWDEFS"},Mr={message:"drawDefinition not found",code:"ERR_NOT_FOUND_DRAWDEF"},Qo={message:"Invalid structure",code:"ERR_INVALID_STRUCTURE"},wl={message:"Incomplete source structure",code:"ERR_INCOMPLETE_STRUCTURE"},Ll={message:"Invalid drawPosition for seedAssignment",code:"ERR_INVALID_SEEDING_POSITION"},Wa={message:"drawPosition already assigned",code:"ERR_EXISTING_POSITION_ASSIGNMENT"},bA={message:"Schedule not cleared",code:"ERR_UNCHANGED_SCHEDULE_NOT_CLEARED"},vA={message:"drawPosition not cleared",code:"ERR_FAILURE_POSITION_NOT_CLEARED"},aL={message:"drawPosition not found",code:"ERR_NOT_FOUND_DRAW_POSITION"},Fl={message:"Unrecognized drawType",code:"ERR_UNRECOGNIZED_DRAW_TYPE"},ja={message:"Missing drawPositions",code:"ERR_MISSING_DRAW_POSITIONS"},Yu={message:"drawPosition is active",code:"ERR_ACTIVE_DRAW_POSITION"},TC={message:"drawPosition is occupied",code:"ERR_OCCUPIED_DRAW_POSITION"},Rs={message:"Invlid drawPosition",code:"ERR_INVALID_DRAW_POSITION"},Cs={message:"Missing drawPosition",code:"ERR_MISSING_DRAW_POSITION"},ym={message:"Invalid drawType",code:"ERR_INVALID_DRAW_TYPE"},qu={message:"Invalid drawSize",code:"ERR_INVALID_DRAW_SIZE"},OI={message:"Cannot set drawSize to be less than existing entries",code:"ERR_INVALID_DRAW_SIZE_MISMATCH"},Ya={message:"Missing drawSize",code:"ERR_MISSING_DRAW_SIZE"},an={message:"Missing drawId",code:"ERR_MISSING_DRAW_ID"},OA={message:"drawId exists",code:"ERR_EXISTING_DRAW_ID"},_A={message:"participantId cannot be assigned to multiple seedNumbers",code:"INVALID_PARTICIPANT_SEEDING"},xA={message:"seedsCount greater than drawSize",code:"ERR_INVALID_SEED_COUNT"},wA={message:"Missing seedCountThresholds",code:"ERR_MISSING_SEED_COUNT_THRESHOLD"},LA={message:"Invalid action",code:"ERR_INVALID_ACTION"},_I={message:"Invalid assignment",code:"ERR_INVALID_ASSIGNMENT"},FA={message:"Missing seedAssignments",code:"ERR_MISSING_SEED_ASSIGNMENTS"},kA={message:"Invalid seedNumber",code:"ERR_INVALID_SEED_NUMBER"},GA={message:"Invalid seedPosition",code:"ERR_INVALID_SEED_POSITION"},kl={message:"Missing targetLink",code:"ERR_MISSING_LINK_TARGET"},VA={message:"Existing round",code:"ERR_EXISTING_ROUND"},cL={message:"Missing roundNumber",code:"ERR_MISSING_ROUND_NUMBER"},Er={message:"Missing structureId",code:"ERR_MISSING_STRUCTURE_ID"},kt={message:"structure not found",code:"ERR_NOT_FOUND_STRUCTURE"},Gl={message:"Missing structures",code:"ERR_MISSING_STRUCTURES"},pi={message:"Missing structure",code:"ERR_MISSING_STRUCTURE"},BA={message:"drawDefinition contains unlinked structures",code:"ERR_MISSING_STRUCTURE_LINKS"},Bn={message:"Invalid eventType",code:"ERR_INVALID_EVENT_TYPE"};var vt={message:"Missing event / eventId",code:"ERR_MISSING_EVENT_ID"},jr={message:"Event not found",code:"ERR_NOT_FOUND_EVENT"},HA={message:"Event exists",code:"ERR_EXISTING_EVENT"},WA={message:"Missing entries",code:"ERR_MISSING_ENTRIES"},jA={message:"Invalid entries",code:"ERR_INVALID_ENTRIES"},Vl={message:"Missing assignments",code:"ERR_MISSING_ASSIGNMENTS"},YA={message:"Missing stage",code:"ERR_MISSING_STAGE"},Oi={message:"Invalid stage",code:"ERR_INVALID_STAGE"},qA={message:"stageSequence limit",code:"ERR_LIMIT_STAGE_SEQUENCE"},$A={message:"Missing positionAssignments",code:"ERR_MISSING_POSITION_ASSIGNMENTS"},KA={message:"Cannot Assign BYE status if no assignment: { bye: true }",code:"ERR_UNCHANGED_CANNOT_ASSIGN_BYE"},xI={message:"Unrecognized matchUpStatus",code:"ERR_UNRECOGNIZED_MATCHUP_STATUS"},qa={message:"Unrecognized matchUpFormat",code:"ERR_UNRECOGNIZED_MATCHUP_FORMAT"},Bl={message:"Incompatible matchUpStatus",code:"ERR_INCOMPATIBLE_MATCHUP_STATUS"},pa={message:"Invalid matchUpStatus",code:"ERR_INVALID_MATCHUP_STATUS"},Lo={message:"Invalid tieFormat",code:"ERR_INVALID_TIE_FORMAT"},Hl={message:"Invalid matchUpFormat",code:"ERR_INVALID_MATCHUP_FORMAT"},Wl={message:"Missing matchUpFormat",code:"ERR_MISSING_MATCHUP_FORMAT"},zA={message:"Missing collectionDefinition",code:"ERR_MISSING_COLLECTION_DEFINITION"},bs={message:"Missing tieFormat",code:"ERR_MISSING_TIE_FORMAT"},sr={message:"Missing matchUpId",code:"ERR_MISSING_MATCHUP_ID"},rs={message:"Missing matchUpIds",code:"ERR_MISSING_MATCHUP_IDS"},Le={message:"matchUp not found",code:"ERR_NOT_FOUND_MATCHUP"},Xn={message:"Missing matchUps",code:"ERR_MISSING_MATCHUPS"},hr={message:"Missing matchUp",code:"ERR_MISSING_MATCHUP"},dr={message:"Invalid matchUp",code:"ERR_INVALID_MATCHUP"},wI={message:"Missing policyType",code:"ERR_MISSING_POLICY_TYPE"},$u={message:"Missing policyDefinitions",code:"ERR_MISSING_POLICY_DEFINITIONS"},uL={message:"Missing seeding policy",code:"ERR_MISSING_POLICY_SEEDING"},QA={message:"Missing avoidance policy",code:"ERR_MISSING_POLICY_AVOIDANCE"},LI={message:"Missing policy attributes",code:"ERR_MISSING_POLICY_ATTRIBUTES"},XA={message:"Invalid policyDefinitions",code:"ERR_INVALID_POLICY_DEFINITIONS"},FI={message:"existing policyType",code:"ERR_EXISTING_POLICY_TYPE"},pL={message:"Policy not attached",code:"ERR_FAILURE_POLICY_NOT_ATTACHED"},Fc={message:"Policy not found",code:"ERR_NOT_FOUND_POLICY"},mL={message:"Missing scoring policy / matchUpFormats",code:"ERR_MISSING_POLICY_SCORING_MATCHUP_FORMATS"},jl={message:"Invalid sideNumber",code:"ERR_INVALID_SIDE_NUMBER"},dL={message:"Invalid setNumber",code:"ERR_INVALID_SET_NUMBER"},Yl={message:"Missing setObject",code:"ERR_MISSING_SET_ATTRIBUTE"},lL={message:"Missing setNumber",code:"ERR_MISSING_SET_NUMBER"},fL={message:"Missing sideNumber",code:"ERR_MISSING_SIDE_NUMBER"},_i={message:"Missing courtId",code:"ERR_MISSING_COURT_ID"},st={message:"Missing value",code:"ERR_MISSING_VALUE"},JA={message:"Missing birthdate",code:"ERR_MISSING_BIRTH_DATE"},ZA={message:"Missing date",code:"ERR_MISSING_DATE"},tE={message:"No valid dates",code:"ERR_NO_VALID_DATES"},Am={message:"Invalid bookings",code:"ERR_INVALID_BOOKINGS"},ql={message:"Invalid dateAvailability",code:"ERR_INVALID_DATE_AVAILABILITY"},eE={message:"Missing dateAvailability",code:"ERR_MISSING_DATE_AVAILABILITY"},je={message:"Invalid Date",code:"ERR_INVALID_DATE"},Eo={message:"Invalid time",code:"ERR_INVALID_TIME"},rE={message:"Invalid tournament dates",code:"ERR_INVALID_DATES_TOURNAMENT"};var kI={message:"Invalid game scores",code:"ERR_INVALID_SCORES_GAME"},nE={message:"Invalid score",code:"ERR_INVALID_SCORE"},Em={message:"Invalid winningSide",code:"ERR_INVALID_WINNING_SIDE"};var yC={message:"No participants generated",code:"ERR_NO_PARTICIPANTS_GENERATED"},$l={message:"Cannot modify tieFormat",code:"ERR_UNCHANGED_CANNOT_MODIFY_TIEFORMAT"},oE={message:"Cannot modify participantType",code:"ERR_UNCHANGED_CANNOT_MODIFY_PARTICIPANT_TYPE"},Ku={message:"Cannot remove participants",code:"ERR_UNCHANGED_CANNOT_REMOVE_PARTICIPANTS"},GI={message:"Participant category mismatch",code:"ERR_CATEGORY_MISMATCH"},Um={message:"Cannot change winningSide",code:"ERR_UNCHANGED_CANNOT_CHANGE_WINNING_SIDE"},xi={message:"Invalid participant",code:"ERR_INVALID_PARTICIPANT"},mn={message:"Invalid participantId",code:"ERR_INVALID_PARTICIPANT_ID"},wr={message:"Invalid participantIds",code:"ERR_INVALID_PARTICIPANT_IDS"},iE={message:"Invalid participantRole",code:"ERR_INVALID_PARTICIPANT_ROLE"},An={message:"Invalid participantType",code:"ERR_INVALID_PARTICIPANT_TYPE"},sE={message:"Missing participantRole",code:"ERR_MISSING_PARTICIPANT_ROLE"},wi={message:"Missing participant",code:"ERR_MISSING_PARTICIPANT"},$a={message:"Missing participants",code:"ERR_MISSING_PARTICIPANTS"},oe={message:"Missing participantId",code:"ERR_MISSING_PARTICIPANT_ID"},te={message:"Participant Not Found",code:"ERR_NOT_FOUND_PARTICIPANT"},aE={message:"participantId exists",code:"ERR_EXISTING_PARTICIPANT_ID"},gL={message:"participant pair exists",code:"ERR_EXISTING_PARTICIPANT_PAIR"},cE={message:"No participant removed",code:"ERR_UNCHANGED_NO_PARTICIPANT_REMOVED"},Uo={message:"Missing participantIds",code:"ERR_MISSING_PARTICIPANT_IDS"},uE={message:"Missing participantsCount",code:"ERR_MISSING_PARTICIPANT_COUNT"},pE={message:"Participant not checked in",code:"ERR_UNCHANGED_PARTICIPANT_NOT_CHECKED_IN"},mE={message:"Missing person details",code:"ERR_MISSING_PERSON_DETAILS"},vs={message:"Existing participant drawPosition assignment",code:"ERR_EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT"},zu={message:"Existing participant",code:"ERR_EXISTING_PARTICIPANT"},Kl={message:"participantsCount exceeds drawSize",code:"ERR_INVALID_PARTICIPANT_COUNT"},zl={message:"Invalid entry status",code:"ERR_INVALID_ENTRY_STATUS"},VI={message:"Participant Entry Not Found",code:"ERR_NOT_FOUND_PARTICIPANT_ENTRY"},AC={message:"Participant not entered in stage",code:"ERR_UNCHANGED_PARTICIPANT_NOT_ENTERED"},EC={message:"Participant not found in stageSequence",code:"ERR_NOT_FOUND_PARTICIPANT_IN_STAGE"},dE={message:"entryStatus not allowed in stage",code:"ERR_INVALID_ENTRY_STATUS_IN_STAGE"},lE={message:"entryStatus not allowed for event",code:"ERR_INVALID_ENTRY_STATUS_IN_EVENT"},BI={message:"No stage space available for entryStatus",code:"ERR_UNCHANGED_NO_AVAILABLE_STAGE_SPACE"},fE={message:"Insufficient drawPositions to accommodate qualifiers",code:"ERR_UNCHANGED_NO_DRAW_POSITIONS_FOR_QUALIFIERS"},Ql={message:"Insufficient drawPositions to accommodate entries",code:"ERR_INSUFFICIENT_DRAW_POSITIONS"},gE={message:"Missing penaltyType",code:"ERR_MISSING_PENALTY_TYPE"},Xl={message:"Missing penaltyId",code:"ERR_MISSING_PENALTY_ID"},kc={message:"Penalty not found",code:"ERR_NOT_FOUND_PENALTY"},IE={message:"Missing courtsCount/courtNames",code:"ERR_MISSING_COURTS_INFO"},Os={message:"Court not found",code:"ERR_NOT_FOUND_COURT"},hE={message:"Court exists",code:"ERR_EXISTING_COURT"},SE={message:"Venue exists",code:"ERR_EXISTING_VENUE"},Li={message:"Venue not found",code:"ERR_NOT_FOUND_VENUE"},Xo={message:"Missing venueId",code:"ERR_MISSING_VENUE_ID"},TE={message:"Invalid endTime",code:"ERR_INVALID_END_TIME"},HI={message:"Existing endTime",code:"ERR_EXISTING_END_TIME"},yE={message:"Invalid stopTime",code:"ERR_INVALID_STOP_TIME"},AE={message:"Invalid startTime",code:"ERR_INVALID_START_TIME"},UC={message:"Invalid resumeTime",code:"ERR_INVALID_RESUME_TIME"},Jl={message:"Invalid timeItem",code:"ERR_INVALID_TIME_ITEMS"},EE={message:"Missing async state provider",code:"ERR_MISSING_ASYNC_STATE_PROVIDER"},Zl={message:"Missing timeItem",code:"ERR_MISSING_TIME_ITEM"},tf={message:"Missing timeItems",code:"ERR_MISSING_TIME_ITEMS"},Gc={message:"Missing context",code:"ERR_MISSING_CONTEXT"},UE={message:"Missing schedule",code:"ERR_MISSING_SCHEDULE"},Ka={message:"Invalid scaleItem",code:"ERR_INVALID_SCALE_ITEM"},PE={message:"Modifications failed",code:"ERR_FAILURE_MODIFICATIONS"},_s={message:"No modifications applied",code:"ERR_UNCHANGED_NO_MODIFICATIONS_APPLIED"},DE={message:"Unable to assign court",code:"ERR_UNCHANGED_COURT_NOT_ASSIGNED"},Qu={message:"No Candidates",code:"ERR_UNCHANGED_NO_CANDIDATES"},NE={message:"Invalid configuration",code:"ERR_INVALID_CONFIG"},ME={message:"Invalid collectionDefinition",code:"ERR_INVALID_COLLECTION_DEFINITION"},lo={message:"Invalid object",code:"ERR_INVALID_OBJECT"},Xu={message:"Invalid gender",code:"ERR_INVALID_GENDER"},Vc={message:"Invalid category",code:"ERR_INVALID_CATEGORY"},G={message:"Invalid values",code:"ERR_INVALID_VALUES"},RE={message:"Duplicate value",code:"ERR_DUPLICATE_VALUE"},ef={message:"Team not found",code:"ERR_NOT_FOUND_TEAM"},CE={message:"No valid actions",code:"ERR_NO_VALID_ACTIONS"},Ju={message:"No valid attributes",code:"ERR_NO_VALID_ATTRIBUTES"},rf={message:"Value unchanged",code:"ABORT_UNCHANGED"},ve={message:"Not found",code:"ERR_NOT_FOUND"},Zu={message:"Not implemented",code:"ERR_NOT_IMPLEMENTED"},bE={message:"Existing flight",code:"ERR_EXISTING_FLIGHT"},nf={message:"Existing flight profile",code:"ERR_EXISTING_FLIGHT_PROFILE"},vE={message:"Existing outcome",code:"ERR_EXISTING_OUTCOME"},OE={message:"Existing matchUpId",code:"ERR_EXISTING_MATCHUP_ID"},WI={message:"Existing stage",code:"ERR_EXISTING_STAGE"},of={message:"Existing structure",code:"ERR_EXISTING_STRUCTURE"},za={message:"Method not found",code:"ERR_NOT_FOUND_METHOD"},_E={message:"Scheduled matchUps",code:"ERR_SCHEDULED_MATCHUPS"},tp={message:"Scores present",code:"ERR_SCORES_PRESENT"},PC={ANACHRONISM:bI,CANNOT_CHANGE_WINNING_SIDE:Um,CANNOT_MODIFY_TIEFORMAT:$l,CANNOT_MODIFY_PARTICIPANT_TYPE:oE,CANNOT_REMOVE_MAIN_STRUCTURE:RA,CANNOT_REMOVE_PARTICIPANTS:Ku,CATEGORY_MISMATCH:GI,COURT_EXISTS:hE,COURT_NOT_FOUND:Os,DRAW_DEFINITION_NOT_FOUND:Mr,DRAW_ID_EXISTS:OA,DRAW_POSITION_ACTIVE:Yu,DRAW_POSITION_ASSIGNED:Wa,DRAW_POSITION_NOT_CLEARED:vA,DRAW_POSITION_NOT_FOUND:aL,DRAW_SIZE_MISMATCH:OI,DUPLICATE_ENTRY:Tm,DUPLICATE_VALUE:RE,ENTRY_STATUS_NOT_ALLOWED_FOR_EVENT:lE,ENTRY_STATUS_NOT_ALLOWED_IN_STAGE:dE,EVENT_EXISTS:HA,EVENT_NOT_FOUND:jr,EXISTING_DRAW_DEFINITIONS:CA,EXISTING_END_TIME:HI,EXISTING_FLIGHT:bE,EXISTING_MATCHUP_ID:OE,EXISTING_OUTCOME:vE,EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT:vs,EXISTING_PARTICIPANT:zu,EXISTING_POLICY_TYPE:FI,EXISTING_PROFILE:nf,EXISTING_ROUND:VA,EXISTING_STAGE:WI,EXISTING_STRUCTURE:of,INCOMPATIBLE_MATCHUP_STATUS:Bl,INCOMPLETE_SOURCE_STRUCTURE:wl,INSUFFICIENT_DRAW_POSITIONS:Ql,INVALID_ACTION:LA,INVALID_ASSIGNMENT:_I,INVALID_BOOKINGS:Am,INVALID_CATEGORY:Vc,INVALID_COLLECTION_DEFINITION:ME,INVALID_CONFIGURATION:NE,INVALID_DATE_AVAILABILITY:ql,INVALID_DATE:je,INVALID_DRAW_DEFINITION:ua,INVALID_DRAW_POSITION_FOR_SEEDING:Ll,INVALID_DRAW_POSITION:Rs,INVALID_DRAW_SIZE:qu,INVALID_END_TIME:TE,INVALID_ENTRIES:jA,INVALID_EVENT_TYPE:Bn,INVALID_GAME_SCORES:kI,INVALID_GENDER:Xu,INVALID_MATCHUP_FORMAT:Hl,INVALID_MATCHUP_STATUS:pa,INVALID_MATCHUP_STATUS_BYE:KA,INVALID_MATCHUP:dr,INVALID_OBJECT:lo,INVALID_PARTICIPANT_ID:mn,INVALID_PARTICIPANT_IDS:wr,INVALID_PARTICIPANT_ROLE:iE,INVALID_PARTICIPANT_SEEDING:_A,INVALID_PARTICIPANT_TYPE:An,INVALID_PARTICIPANT:xi,INVALID_POLICY_DEFINITION:XA,INVALID_RECORDS:vI,INVALID_SCALE_ITEM:Ka,INVALID_SEED_NUMBER:kA,INVALID_SEED_POSITION:GA,INVALID_SET_NUMBER:dL,INVALID_SIDE_NUMBER:jl,INVALID_SCORE:nE,INVALID_STAGE:Oi,INVALID_START_TIME:AE,INVALID_STRUCTURE:Qo,INVALID_STOP_TIME:yE,INVALID_TIE_FORMAT:Lo,INVALID_TIME:Eo,INVALID_TIME_ITEM:Jl,INVALID_TOURNAMENT_DATES:rE,INVALID_TOURNAMENT_RECORD:Ha,INVALID_VALUES:G,INVALID_WINNING_SIDE:Em,MATCHUP_NOT_FOUND:Le,METHOD_NOT_FOUND:za,MISSING_ASSIGNMENTS:Vl,MISSING_ASYNC_STATE_PROVIDER:EE,MISSING_AVOIDANCE_POLICY:QA,MISSING_BIRTH_DATE:JA,MISSING_COLLECTION_DEFINITION:zA,MISSING_COURT_ID:_i,MISSING_COURTS_INFO:IE,MISSING_DATE_AVAILABILITY:eE,MISSING_DATE:ZA,MISSING_DRAW_DEFINITION:Z,MISSING_DRAW_ID:an,MISSING_DRAW_POSITION:Cs,MISSING_DRAW_POSITIONS:ja,MISSING_DRAW_SIZE:Ya,MISSING_ENTRIES:WA,MISSING_EVENT:vt,MISSING_MATCHUP_FORMAT:Wl,MISSING_MATCHUP_ID:sr,MISSING_MATCHUP_IDS:rs,MISSING_MATCHUP:hr,MISSING_MATCHUPS:Xn,MISSING_PARTICIPANT_COUNT:uE,MISSING_PARTICIPANT_ID:oe,MISSING_PARTICIPANT_IDS:Uo,MISSING_PARTICIPANT_ROLE:sE,MISSING_PARTICIPANT:wi,MISSING_PARTICIPANTS:$a,MISSING_PENALTY_ID:Xl,MISSING_PENALTY_TYPE:gE,MISSING_PERSON_DETAILS:mE,MISSING_POLICY_ATTRIBUTES:LI,MISSING_POLICY_DEFINITION:$u,MISSING_POLICY_TYPE:wI,MISSING_POSITION_ASSIGNMENTS:$A,MISSING_ROUND_NUMBER:cL,MISSING_SCHEDULE:UE,MISSING_SCORING_POLICY:mL,MISSING_SEED_ASSIGNMENTS:FA,MISSING_SEEDCOUNT_THRESHOLDS:wA,MISSING_SEEDING_POLICY:uL,MISSING_SET_NUMBER:lL,MISSING_SET_OBJECT:Yl,MISSING_SIDE_NUMBER:fL,MISSING_STAGE:YA,MISSING_STRUCTURE_ID:Er,MISSING_STRUCTURE:pi,MISSING_STRUCTURES:Gl,MISSING_TARGET_LINK:kl,MISSING_TIE_FORMAT:bs,MISSING_TIME_ITEM:Zl,MISSING_TIME_ITEMS:tf,MISSING_TOURNAMENT_ID:ca,MISSING_TOURNAMENT_RECORD:Y,MISSING_TOURNAMENT_RECORDS:wt,MISSING_VALUE:st,MISSING_VENUE_ID:Xo,MODIFICATIONS_FAILED:PE,NO_CANDIDATES:Qu,NO_DRAW_POSITIONS_AVAILABLE_FOR_QUALIFIERS:fE,NO_MODIFICATIONS_APPLIED:_s,NO_STAGE_SPACE_AVAILABLE_FOR_ENTRY_STATUS:BI,NO_PARTICIPANT_REMOVED:cE,NO_VALID_ACTIONS:CE,NO_VALID_ATTRIBUTES:Ju,NO_VALID_DATES:tE,NOT_FOUND:ve,NOT_IMPLEMENTED:Zu,PARTICIPANT_COUNT_EXCEEDS_DRAW_SIZE:Kl,PARTICIPANT_ID_EXISTS:aE,PARTICIPANT_NOT_CHECKED_IN:pE,PARTICIPANT_NOT_FOUND:te,PARTICIPANT_PAIR_EXISTS:gL,PENALTY_NOT_FOUND:kc,POLICY_NOT_ATTACHED:pL,POLICY_NOT_FOUND:Fc,SCHEDULE_NOT_CLEARED:bA,SCHEDULED_MATCHUPS:_E,SCORES_PRESENT:tp,SEEDSCOUNT_GREATER_THAN_DRAW_SIZE:xA,STAGE_SEQUENCE_LIMIT:qA,STRUCTURE_NOT_FOUND:kt,TEAM_NOT_FOUND:ef,UNABLE_TO_ASSIGN_COURT:DE,UNLINKED_STRUCTURES:BA,UNRECOGNIZED_DRAW_TYPE:Fl,UNRECOGNIZED_MATCHUP_FORMAT:qa,UNRECOGNIZED_MATCHUP_STATUS:xI,VALUE_UNCHANGED:rf,VENUE_EXISTS:SE};var Ze={disableNotifications:!1,tournamentId:void 0,tournamentRecords:{},subscriptions:{},modified:!1,methods:{},notices:[]},xE={addNotice:ML,callListener:OL,cycleMutationStatus:NL,deleteNotice:bL,deleteNotices:CL,disableNotifications:IL,enableNotifications:hL,getMethods:ep,getNotices:RL,getTopics:vL,getTournamentId:DC,getTournamentRecord:SL,getTournamentRecords:TL,removeTournamentRecord:UL,setMethods:DL,setSubscriptions:PL,setTournamentId:AL,setTournamentRecord:yL,setTournamentRecords:EL,handleCaughtError:_L};function IL(){Ze.disableNotifications=!0}function hL(){Ze.disableNotifications=!1}function DC(){return Ze.tournamentId}function SL(t){return Ze.tournamentRecords[t]}function TL(){return Ze.tournamentRecords}function yL(t){let e=t?.tournamentId;return e?(Ze.tournamentRecords[e]=t,{success:!0}):{error:Ha}}function AL(t){return t?Ze.tournamentRecords[t]?(Ze.tournamentId=t,{success:!0}):{error:Y}:(Ze.tournamentId=void 0,{success:!0})}function EL(t){Ze.tournamentRecords=t;let e=Object.keys(t);e.length===1?Ze.tournamentId=e[0]:e.length||(Ze.tournamentId=void 0)}function UL(t){if(typeof t!="string")return{error:G};if(!Ze.tournamentRecords[t])return{error:ve};delete Ze.tournamentRecords[t];let e=Object.keys(Ze.tournamentRecords);return e.length===1?Ze.tournamentId=e[0]:e.length||(Ze.tournamentId=void 0),{success:!0}}function PL(t){return typeof t.subscriptions!="object"?{error:G}:(Object.keys(t.subscriptions).forEach(e=>{typeof t.subscriptions[e]=="function"?Ze.subscriptions[e]=t.subscriptions[e]:delete Ze.subscriptions[e]}),{...C})}function DL(t){return typeof t!="object"?{error:G}:(Object.keys(t).forEach(e=>{typeof t[e]=="function"&&(Ze.methods[e]=t[e])}),{...C})}function NL(){let t=Ze.modified;return Ze.modified=!1,t}function ML({topic:t,payload:e,key:r},n){if(!(typeof t!="string"||typeof e!="object")&&(Ze.disableNotifications||(Ze.modified=!0),!(Ze.disableNotifications||!Ze.subscriptions[t]&&!n)))return r&&(Ze.notices=Ze.notices.filter(o=>!(o.topic===t&&o.key===r))),Ze.notices.push({topic:t,payload:e,key:r}),{...C}}function ep(){return Ze.methods??{}}function RL({topic:t}){return Ze.notices.filter(e=>e.topic===t).map(e=>e.payload)}function CL(){Ze.notices=[]}function bL({topic:t,key:e}){Ze.notices=Ze.notices.filter(r=>(!t||r.topic===t)&&r.key!==e)}function vL(){return{topics:Object.keys(Ze.subscriptions)}}function OL({topic:t,notices:e},r){let n=Ze.subscriptions[t];n&&typeof n=="function"&&n(e);let o=r?.[t];o&&typeof o=="function"&&o(e)}function _L({engineName:t,methodName:e,params:r,err:n}){let o;return typeof n=="string"?o=n.toUpperCase():n instanceof Error&&(o=n.message),console.log("ERROR",{tournamentId:DC(),params:JSON.stringify(r),engine:t,methodName:e,error:o}),{error:o}}var Oe={timers:{default:{elapsedTime:0}},globalSubscriptions:{},deepCopyAttributes:{stringify:[],ignore:[],toJSON:[]},globalMethods:[],deepCopy:!0},cn=xE,NC=["addNotice","callListener","cycleMutationStatus","deleteNotice","deleteNotices","disableNotifications","enableNotifications","getMethods","getNotices","getTopics","getTournamentId","getTournamentRecord","getTournamentRecords","removeTournamentRecord","setSubscriptions","setTournamentId","setTournamentRecord","setTournamentRecords"];function xL(t){if(typeof t!="object")throw new Error("Global state provider can not be undefined or null");if(Yt(Object.keys(t),NC).length!==NC.length)throw new Error("Global state provider is missing required methods");return cn=t,{success:!0}}function wE(){if(cn.createInstanceState){try{cn.createInstanceState()}catch(t){return{error:t}}return{success:!0}}else return{error:EE}}function Ur(t){return!t||typeof t!="object"?Oe.devContext??!1:typeof Oe.devContext!="object"?!1:Object.keys(t).every(e=>Oe.devContext?.[e]===t[e])&&Oe.devContext}function wL(t="reset",e="default"){let r=Date.now();if(t==="report"){if(e==="allTimers")return Object.keys(Oe.timers).filter(o=>o!=="default"||Oe.timers[o].startTime).map(o=>{let i=Oe.timers[o],s=i.state==="stopped"?0:(r-(i?.startTime??0))/1e3,a=i.elapsedTime+s;return{state:Oe.timers[o].state,elapsedTime:a.toFixed(2),timer:o}});{let n=Oe.timers[e].state==="stopped"?0:(r-(Oe.timers[e]?.startTime??0))/1e3,o=Oe.timers[e].elapsedTime+n;return{state:Oe.timers[e].state,elapsedTime:o.toFixed(2),timer:e}}}if(!Oe.timers[e]||t==="reset"){if(e==="allTimers")return Oe.timers={default:{elapsedTime:0}},!0;Oe.timers[e]={startTime:r,state:"active",elapsedTime:0}}return Oe.timers[e].elapsedTime||(Oe.timers[e].elapsedTime=0),t==="stop"&&Oe.timers[e].state!=="stopped"&&(Oe.timers[e].state="stopped")&&(Oe.timers[e].elapsedTime+=(r-(Oe.timers[e]?.startTime??0))/1e3),t==="start"&&(Oe.timers[e].startTime=r)&&(Oe.timers[e].state="active"),Oe.timers[e]}function MC(t){Wr(t)?Oe.globalLog=t:delete Oe.globalLog}function Bc(t){Oe.devContext=t}function LE(){cn.disableNotifications()}function sf(){cn.enableNotifications()}function Hc(t,e){typeof t=="boolean"&&(Oe.deepCopy=t),typeof e=="object"&&(Array.isArray(e.ignore)&&(Oe.deepCopyAttributes.ignore=e.ignore),Array.isArray(e.toJSON)&&(Oe.deepCopyAttributes.toJSON=e.toJSON),Array.isArray(e.stringify)&&(Oe.deepCopyAttributes.stringify=e.stringify),e.threshold&&(Oe.deepCopyAttributes.threshold=e.threshold))}function af(){return{enabled:Oe.deepCopy,...Oe.deepCopyAttributes}}function LL(t){return t?.subscriptions?(Object.keys(t.subscriptions).forEach(e=>{Oe.globalSubscriptions[e]=t.subscriptions[e]}),{...C}):{error:st,info:"missing subscriptions"}}function FL(t){return t?.subscriptions?cn.setSubscriptions({subscriptions:t.subscriptions}):{error:st,info:"missing subscriptions"}}function RC(t){return t?typeof t!="object"?{error:G}:(Object.keys(t).forEach(e=>{Wr(t[e])&&(Oe.globalMethods[e]=t[e])}),{...C}):{error:st,info:"missing method declarations"}}function CC(t){return t?typeof t!="object"?{error:G}:cn.setMethods(t):{error:st,info:"missing method declarations"}}function cf(){return cn.cycleMutationStatus()}function mt(t){if(typeof t?.topic!="string")return;let e=Oe.globalSubscriptions[t.topic];return cn.addNotice(t,e)}function uf(){return{...Oe.globalMethods,...cn.getMethods()}}function jI(t){return cn.getNotices(t)}function YI({key:t,topic:e}){return cn.deleteNotice({key:t,topic:e})}function Fi(){return cn.deleteNotices()}function Lr(){return cn.getTopics()}function rp(t){return Lr()?.topics?.includes(t)}async function Pm(t){return cn.callListener(t,Oe.globalSubscriptions)}function ns(){return cn.getTournamentId()}function pf(t){return cn.getTournamentRecord(t)}function Fo(){return cn.getTournamentRecords()}function FE(t){return cn.setTournamentRecord(t)}function Dm(t){return cn.setTournamentRecords(t)}function np(t){return cn.setTournamentId(t)}function kE(t){return cn.removeTournamentRecord(t)}function qI(){return cn}function op({engineName:t,methodName:e,params:r,err:n}){let o=Wr(cn.handleCaughtError)&&cn.handleCaughtError||xE.handleCaughtError,{tournamentRecord:i,...s}=r;return o({params:s,engineName:t,methodName:e,err:n})}function GE(t,e){if(Oe.globalLog)try{Oe.globalLog({log:t,engine:e})}catch(r){console.log("globalLog error",r),console.log(e,t),MC()}else console.log(e,t)}function VE(t,e,r,n){if(!ht(t))return{error:G};Zt||(r=1);let o=Array.isArray(e)?e:[],i={},s=(a,c=0)=>{Object.keys(a).forEach(u=>{Wr(a[u])?i[u]=a[u]:ht(a[u])&&(e===!0||o?.includes(u))&&(r===void 0||c<r)&&s(a[u],c+1)})};return s(t),n?RC(i):CC(i),{methods:i}}function kL(t,e,r){return Object.keys(t).filter(n=>!e.includes(t[n])&&(!r||(Array.isArray(t[n])?t[n].length:!0)))}function ot(t,e,r,n){if(typeof t!="object"||t===null)return t;af()?.enabled||(n=!0);let i=["",void 0,null];e&&i.push(!1);let s=kL(t,i,r);return Object.assign({},...s.map(a=>Array.isArray(t[a])?{[a]:n?t[a]:t[a].map(c=>ot(c))}:{[a]:n?t[a]:ot(t[a])}))}function _({context:t,result:e,stack:r,info:n}){return e&&!Array.isArray(e?.stack)&&(e.stack=[]),e&&Array.isArray(e?.stack)&&typeof r=="string"&&e.stack.push(r),e&&n&&(e.info=n),e&&typeof t=="object"&&Object.keys(t).length&&Object.assign(e,ot(t)),e&&!e?.error&&!e?.success&&Object.assign(e,{...C}),e??{success:!0}}var Pn="ANY",$t="MALE",Tr="MIXED",os="OTHER",ne="FEMALE",Nm={ANY:Pn,MALE:$t,FEMALE:ne,MIXED:Tr,OTHER:os};var GL="MIXED events can not contain mixed singles or { gender: ANY } collections",VL="events with { gender: ANY } can not contain MIXED singles collections";function Mm(t){let e="tieFormatGenderValidityCheck",{referenceGender:r,matchUpType:n,gender:o}=t;return r&&o&&[$t,ne].includes(r)&&r!==o?_({result:{valid:!1,error:Xu},context:{gender:o},stack:e}):r===Tr&&(o===Pn||o===Tr&&n!==_t)?_({result:{error:Xu,valid:!1},info:GL,stack:e}):r===Pn&&o===Tr&&n!==_t?_({result:{error:Xu,valid:!1},info:VL,stack:e}):{valid:!0}}var BL="normal",BE="timed",HL="final",mf="NOAD",Rm="SET",vC={S:BL,F:HL};function ip(t,e){if(ht(t),(t?.bestOf||t?.exactly)&&t?.setFormat)return WL(t,e)}function df(t){return!isNaN(Number(t))&&Number(t)}function xC(t){let e=`T${t.minutes}`;return t.based&&(e+=t.based),t.modifier&&(e+=`@${t.modifier}`),e}function WL(t,e){let r=df(t.bestOf)||void 0,n=df(t.exactly)||void 0,o=r||n;if(t.setFormat?.timed&&t.simplified&&o===1)return xC(t.setFormat);let i=o&&`${Rm}${o}`||"",s=OC(t.setFormat,e),a=s&&`S:${s}`||"",c=OC(t.finalSetFormat,e),u=o&&o>1&&c&&s!==c&&`F:${c}`||"";if(i&&s)return[i,a,u].filter(m=>m).join("-")}function OC(t,e){if(typeof t=="object"&&Object.keys(t).length){if(t.timed)return xC(t);if(t.tiebreakSet)return _C(t.tiebreakSet);let r=df(t.setTo);if(r){let n=t.NoAD&&mf||"",o=_C(t.tiebreakFormat),i=o&&`/${o}`||"",s=df(t.tiebreakAt),a=s&&(s!==r||e)&&`@${s}`||"";if(o!==!1)return`${r}${n}${i}${a}`}}}function _C(t){if(t){if(typeof t=="object"&&!t.tiebreakTo)return"";if(typeof t=="object"&&df(t.tiebreakTo)){let e=`TB${t.tiebreakTo}${t.NoAD?mf:""}`;return t.modifier&&(e+=`@${t.modifier}`),e}else return!1}}function Ye(t){if(Vt(t)){let e=t.startsWith("T")&&BE||t.startsWith(Rm)&&Rm||"";if(e===BE){let r=kC(t),n={simplified:!0,setFormat:r,bestOf:1};if(r)return n}if(e===Rm)return jL(t)}}function jL(t){let e=t.split("-"),r=lf(e[0].slice(3)),n=r===1||r%2!==0?r:void 0,o=r!==1&&r%2===0?r:void 0,i=e&&wC(e[1]),s=e&&wC(e[2]),a=i&&i.timed||s&&s.timed,c=n&&n<6||a&&o,u=!e[2]||s,p=i,m=ot({setFormat:i,exactly:o,bestOf:n});if(s&&(m.finalSetFormat=s),c&&p&&u)return m}function wC(t){if(t?.[1]===":"){let e=t.split(":"),r=vC[e[0]],n=e[1];if(r&&n){if(n.startsWith("TB")){let I=LC(n);return I===!1?!1:typeof I=="object"?{tiebreakSet:I}:void 0}if(n.startsWith("T"))return kC(n);let s=t.match(/^[FS]:(\d+)([A-Za-z]*)/),a=s&&GC(s[2])||!1,c=!s?.[2]||a,u=s?lf(s[1]):void 0,p=FC(n),m=p!==!1,d=m&&p||u,l=LC(n.split("/")[1]),f=l!==!1,g={setTo:u};return a&&(g.NoAD=!0),l?(g.tiebreakFormat=l,g.tiebreakAt=d):g.noTiebreak=!0,u&&c&&f&&m&&g||!1}}}function FC(t,e=!0){let r=t?.indexOf("@")>0&&t.split("@");if(r)return(e?lf(r[1]):r[1])||!1}function LC(t){if(t)if(t.startsWith("TB")){let e=FC(t,!1),r=t.match(/^TB(\d+)([A-Za-z]*)/),n=r?.[1],o=r&&GC(r[2]),i=!r?.[2]||o,s=lf(n);if(s&&i){let a={tiebreakTo:s};return e&&typeof e=="string"&&!It(e)&&(a.modifier=e),o&&(a.NoAD=!0),a}else return!1}else return!1}function kC(t){let e=t.slice(1),r=e.match(/^(\d+)(@?[A-Za-z]*)/),n=lf(r?.[1]);if(!n)return;let o={timed:!0,minutes:n},i=r?.[2],s=[void 0,"P","G"].includes(i);if(i&&!s){let a=e.match(/^(\d+)(@)([A-Za-z]+)$/)?.[3];return a?(o.modifier=a,o):void 0}return i&&(o.based=r[2]),o}function GC(t){return t&&t.indexOf(mf)>=0}function lf(t){return isNaN(Number(t))?0:Number(t)}function Pr({matchUpFormat:t}){if(!Vt(t)||t==="")return!1;let e=Ye(t),r=t.match(/-S:([1-9])+\/TB([0-9]{1,2})@?([1-9]?)*/),n=r?.[1],o=r?.[2],i=r?.[3],s=t.match(/-F:([1-9])+\/TB([0-9]{1,2})@?([1-9]?)*/),a=s?.[1],c=s?.[2],u=s?.[3];return ip(e,!!(r&&o&&n===i||s&&c&&a===u))===t}var Cm=/^[\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1])$/,$I=/^((0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)([.,][0-9]{3})?$/,Po=/^([\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1]))([ T](0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)?([.,][\d]{3})?Z?$/,xs=/^([\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1]))?([ T]?(0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)?([.,][\d]{3})?Z?$/;function bm(t){let{scheduledDate:e}=t;if(!e&&t.scheduledTime&&(e=Et(t.scheduledTime)),!e)return;let r=Kt(t.scheduledTime),n=Et(e);return n&&r&&(n+=`T${r}`),n}function VC(t){return typeof t!="object"||Array.isArray(t)?!1:Object.prototype.toString.call(t)==="[object Date]"}function Wc(t){let e=typeof t=="string"?t?.split(" "):[];return t&&e?.length>1&&!["AM","PM"].includes(e[1].toUpperCase())?!1:!!(!t||xs.test(Xa(t,!0,!0)))}function Rr(t){return Qa(t)||Cm.test(t)}function YL(t){let e=new Date(t),r=e.getSeconds()+60*e.getMinutes()+60*60*e.getHours();return qL(r,{displaySeconds:!1})}function qL(t,e){let r=parseInt(t,10),n=Math.floor(r/3600),o=Math.floor((r-n*3600)/60),i=r-n*3600-o*60;return(!e||e?.displaySeconds?n+":"+o+":"+i:n+":"+o).split(":").map(Jn).join(":")}var If=t=>{let e=ff(t)||Qa(t)?new Date(t):new Date,r=e.getUTCMonth()+1,n=r<10?`0${r}`:`${r}`;return`${e.getUTCFullYear()}-${Jn(n)}-${Jn(e.getUTCDate())}`};function $L(t){let e=ff(t)||Qa(t)?new Date(t):new Date;return Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())}function Hn(t,e="-",r="YMD"){if(!t)return"";typeof t=="string"&&t.indexOf("T")<0&&(t=t+"T00:00");let n=new Date(t),o=""+(n.getMonth()+1),i=""+n.getDate(),s=n.getFullYear();return o.length<2&&(o="0"+o),i.length<2&&(i="0"+i),r==="DMY"?[i,o,s].join(e):r==="MDY"?[o,i,s].join(e):r==="YDM"?[s,i,o].join(e):r==="DYM"?[i,s,o].join(e):r==="MYD"?[o,s,i].join(e):[s,o,i].join(e)}function KI(t){let e=t?new Date(t):new Date,r=e.getTimezoneOffset();return new Date(e.getTime()-r*60*1e3)}function KL(t){return KI(t).getTime()}function ff(t){if(typeof t=="boolean")return!1;let e=t instanceof Date&&t||!isNaN(t)&&new Date(t)||!1;return e&&!isNaN(e.valueOf())}function ws(t,e){if(!Rr(t)||!Rr(e))return[];let r=Et(t)+"T00:00",n=Et(e)+"T00:00",o=new Date(r),i=new Date(n),s=ff(i)&&ff(o)&&u(o,i),a=[],c=0;if(s){let p=o,m=p.getTime();for(;m<=i.getTime()&&c<300;)c+=1,a.push(new Date(p)),m=p.setDate(p.getDate()+1)}return a.map(p=>Hn(p));function u(p,m){return p<=m}}var zL=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;function Qa(t){return typeof t!="string"?!1:zL.test(t)}function QI(t){if(typeof t!="string")return!1;let r=t.split("Z")[0].split(":"),n=r.every(i=>!isNaN(parseInt(i)));return!(r.length<2||!n||parseInt(r[0])>23||parseInt(r[1])>60)}function qt(t){let e=Kt(t);if(!e)return 0;let[r,n]=e.split(":").map(o=>parseInt(o));return r*60+n}function BC(t){let e=Math.floor(t/60),r=t-e*60;return e>23&&(e=e%24),[Jn(e),Jn(r)].join(":")}function gf(t){return QI(t)?t.split(":").slice(0,2).map(Jn).join(":"):void 0}function Kt(t){return Qa(t)&&t.indexOf("T")>0?gf(t.split("T").reverse()[0]):gf(t)}function Et(t){return Qa(t)||Po.test(t)?t.split("T")[0]:void 0}function sp(t,e){let r=new Date(t);return r.setDate(r.getDate()+e),Et(r.toISOString())}function zI(t){t=typeof t!="string"?"00:00":t;let e={},r={};return{0:e.time,1:e.ampm}=t.split(" ")||[],{0:r.hours,1:r.minutes}=e.time.split(":")||[],r.ampm=e.ampm,isNaN(r.hours)||isNaN(r.minutes)||r.ampm&&!["AM","PM"].includes(r.ampm.toUpperCase())?{}:r}function QL(t){let e=zI(t);return e.ampm&&e.hours&&(e.ampm.toLowerCase()==="pm"&&parseInt(e.hours)<12&&(e.hours=(e.hours&&parseInt(e.hours)||0)+12),e.ampm.toLowerCase()==="am"&&e.hours==="12"&&(e.hours="00")),`${e.hours||"12"}:${e.minutes||"00"}`.split(":").map(Jn).join(":")}function XL(t){let e=zI(t);if(!(typeof e=="object"&&!Object.keys(e).length))return e.ampm?t:(e.hours>12?(e.hours-=12,e.ampm="PM"):e.hours==="12"?e.ampm="PM":(e.hours==="00"&&(e.hours="12"),e.ampm="AM"),e.hours?.[0]==="0"&&(e.hours=e.hours.slice(1)),`${e.hours||"12"}:${e.minutes||"00"} ${e.ampm}`)}function Xa(t,e,r){let n=Et(t),o=Kt(t),i=n?o:t;return t?e&&(n&&r&&t||QL(i))||XL(i):void 0}function XI(t,e){let r=zI(t),n=zI(e);if(parseInt(r.hours)<parseInt(n.hours))return-1;if(parseInt(r.hours)>parseInt(n.hours))return 1;if(r.hours===n.hours){if(parseInt(r.minutes)<parseInt(n.minutes))return-1;if(parseInt(r.minutes)>parseInt(n.minutes))return 1}return 0}function JI(t,e=7){let r=Et(t)+"T00:00",n=new Date(r),o=new Date(n.setDate(n.getDate()+e));return Hn(o)}function JL(t){return JI(t)}function ZL(t,e,r,n=!1){let o=new Date(e,0,1+(t-1)*7),i=n?0:1;return o.setDate(o.getDate()+(i-o.getDay())),Hn(o,r)}function HC(t,e,r){let n=new Date(t,0);return Hn(new Date(n.setDate(e)),r)}function ke(t,e=void 0){let[r,n]=(t||"00:00").split(":").map(Jn),o=KI(e).setHours(r,n,0,0);return KI(o)}function ma(t,e,r=!0){let n=new Date(t),i=(new Date(e).getTime()-n.getTime())/1e3/60;return r?Math.abs(Math.round(i)):Math.round(i)}function Yr(t,e){let r=Kt(t);if(!r)return"00:00";let n=isNaN(e)?0:e;return Kt(hf(ke(r),n).toISOString())}function hf(t,e){let r=new Date(t);return new Date(r.getTime()+e*6e4)}function Jn(t){return t.toString()[1]?t:"0"+t}function Wn(t,e){let r=new Date(t),n=new Date(e);return r.getFullYear()===n.getFullYear()&&r.getMonth()===n.getMonth()&&r.getDate()===n.getDate()}var ZI={addDays:JI,addWeek:JL,addMinutesToTimeString:Yr,convertTime:Xa,getIsoDateString:bm,getUTCdateString:If,DateHHMM:YL,extractDate:Et,extractTime:Kt,formatDate:Hn,getDateByWeek:ZL,isISODateString:Qa,isDate:ff,isTimeString:QI,offsetDate:KI,offsetTime:KL,sameDay:Wn,timeStringMinutes:qt,timeToDate:ke,timeUTC:$L,validTimeValue:Wc,validDateString:Cm,timeValidation:xs,dateValidation:Po};var tF=(t,e)=>t.filter(Boolean).every(r=>typeof r===e),eF=t=>t.filter(Boolean).every(Zt);function Ls(t){let e=t.category;if(typeof e!="object")return{error:Vc};let{ageCategoryCode:r,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s}=e,a=e.categoryName,c;if(!tF([r,n,o,a],"string")||!eF([i,s]))return{error:Vc};let u=t.consideredDate??Et(new Date().toLocaleDateString("sv"));if(!Rr(u))return{error:je};let[p]=u.split("-").slice(0,3).map(w=>parseInt(w)),m=sp(u,-1),[d,l]=m.split("-").slice(1,3).map(w=>parseInt(w)),f=`${Jn(d)}-${Jn(l)}`,g=sp(u,1),[I,h]=g.split("-").slice(1,3).map(w=>parseInt(w)),S=`${Jn(I)}-${Jn(h)}`,T=s&&sp(u,-1*365*s),y=i&&sp(u,-1*365*i),P=[],U=w=>!P.includes(w)&&P.push(w);r=r??a;let E=/^([UO]?)(\d{1,2})([UO]?)$/,A=/^C(\d{1,2})-(\d{1,2})$/,N=r?.includes("-"),D=N&&r?.match(A),M=r?.match(E),R=(w,V)=>`${w}-${V}`,b=w=>{let V=p-w,k=R(V,S);e.ageMinDate&&e.ageMinDate!==k&&U(`Invalid submitted ageMinDate: ${o}`),o=k,r&&(e.ageMax&&e.ageMax!==w-1&&(U(`Invalid submitted ageMax: ${i}`),y=void 0),i=w-1)},v=w=>{let V=p-w-1,k=R(V,S);e.ageMin&&e.ageMin>w&&U(`Invalid submitted ageMin: ${s}`),e.ageMax&&e.ageMax>w&&U(`Invalid submitted ageMax: ${i}`),e.ageMinDate&&e.ageMinDate!==k&&U(`Invalid submitted ageMinDate: ${o}`),o=k,r&&(e.ageMax&&e.ageMax!==w&&(U(`Invalid submitted ageMax: ${i}`),T=void 0),i=w)},O=w=>{let V=p-w,k=R(V,f);e.ageMaxDate&&e.ageMaxDate!==k&&U(`Invalid submitted ageMaxDate: ${n}`),n=k,r&&(e.ageMin&&e.ageMin!==w+1&&(U(`Invalid submitted ageMin: ${s}`),T=void 0),s=w+1)},x=w=>{let V=p-w-1,k=R(V,f);e.ageMaxDate&&e.ageMaxDate!==k&&U(`Invalid submitted ageMaxDate: ${n}`),n=k,r&&(e.ageMin&&e.ageMin!==w&&(U(`Invalid submitted ageMin: ${s}`),T=void 0),s=w)},F=w=>{let[V,k,W]=(w.match(E)||[]).slice(1),H=parseInt(k);V==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&U(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),b(H)):V==="O"&&O(H),W==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&U(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),v(H)):W==="O"&&x(H),n=n??T,o=o??y};if(D){if(n=void 0,o=void 0,i=void 0,s=void 0,e.ageMin){let k=p-e.ageMin;n=R(k,f)}if(e.ageMax){let k=p-e.ageMax-1;o=R(k,S)}let[w,V]=(r?.match(A)??[]).slice(1).map(k=>parseInt(k));w<=V?(s=w,i=V,c=!0):U(`Invalid combined age range ${r}`)}else N?r?.split("-").forEach(F):M?F(r):(s&&O(s),i&&v(i));i&&e.ageMin&&e.ageMin>i&&(U(`Invalid submitted ageMin: ${e.ageMin}`),s=void 0);let L=ot({consideredDate:u,combinedAge:c,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s});return P.length&&(L.errors=P),L}function jc({category:t}){if(!ht(t))return{error:G};let e=Ls({category:t});if(e.error)return{error:e};let{ratingMax:r,ratingMin:n}=t;return r&&!Zt(r)?_({result:{error:G},context:{ratingMax:r}}):n&&!Zt(n)?_({result:{error:G},context:{ratingMin:n}}):{...e}}function Yc({childCategory:t,withDetails:e,category:r}){let n=jc({category:r}),o=jc({category:t}),i=o.ageMin&&(n.ageMin&&o.ageMin<n.ageMin||n.ageMax&&o.ageMin>n.ageMax),s=o.ageMax&&(n.ageMax&&o.ageMax>n.ageMax||n.ageMin&&o.ageMax<n.ageMin),a=o.ageMinDate&&n.ageMaxDate&&new Date(o.ageMinDate)>new Date(n.ageMaxDate),c=o.ageMaxDate&&n.ageMinDate&&new Date(o.ageMaxDate)<new Date(n.ageMinDate),p=r?.ratingType&&t?.ratingType&&r.ratingType===t.ratingType&&(r.ratingMin&&t.ratingMin&&t.ratingMin<r.ratingMin||r.ratingMax&&t.ratingMax&&t.ratingMax>r.ratingMax||r.ratingMin&&t.ratingMax&&t.ratingMax<r.ratingMin||r.ratingMax&&t.ratingMin&&t.ratingMin>r.ratingMax),m=r?.ballType&&t?.ballType&&r.ballType!==t.ballType,f=ot({invalidRatingRange:p,invalidAgeMinDate:a,invalidAgeMaxDate:c,invalidBallType:m,invalidAgeMax:s,invalidAgeMin:i,valid:!p&&!a&&!c&&!m&&!s&&!i},!0);return e&&Object.assign(f,{categoryDetails:n,childCategoryDetails:o}),f}function qc({checkCategory:t=!0,collectionDefinition:e,checkCollectionIds:r,checkGender:n=!0,referenceCategory:o,referenceGender:i,event:s}){i=i??s?.gender;let a="validateCollectionDefinition",c=[];if(typeof e!="object")return c.push(`collectionDefinition must be an object: ${e}`),_({result:{errors:c,error:lo},stack:a});let{collectionValueProfiles:u,collectionGroupNumber:p,collectionValue:m,collectionId:d,matchUpCount:l,matchUpFormat:f,matchUpValue:g,matchUpType:I,scoreValue:h,setValue:S,category:T,gender:y}=e;if(r&&typeof d!="string"&&c.push(`collectionId is not type string: ${d}`),typeof l!="number"&&c.push(`matchUpCount is not type number: ${l}`),I&&!Lc([xt,_t],I)&&c.push(`matchUpType must be SINGLES or DOUBLES: ${I}`),[!!u?.length].concat([g,m,h,S].map(It)).filter(Boolean).length!==1&&c.push("Missing value definition for matchUps: matchUpValue, collectionValue, or collectionValueProfiles"),g&&typeof g!="number"&&c.push(`matchUpValue is not type number: ${g}`),m&&typeof m!="number"&&c.push(`collectionValue is not type number: ${m}`),u&&l){let U=CI({collectionValueProfiles:u,matchUpCount:l});U.errors&&c.push(...U.errors)}if(p&&typeof p!="number"&&c.push(`collectionGroupNumber is not type number: ${m}`),f&&!Pr({matchUpFormat:f})&&c.push(`Invalid matchUpFormat: ${f}`),n){let U=Mm({referenceGender:i,matchUpType:I,gender:y});if(U.error)return _({context:{referenceGender:i,gender:y},result:U,stack:a})}if(t&&o&&T){let U=Yc({category:o,childCategory:T});if(!U.valid)return _({result:{error:Vc},context:U,stack:a})}return c.length?_({result:{errors:c,error:ME},stack:a}):{valid:!0}}function ar(t){let e=!!(t?.enforceCategory!==!1&&t?.category),r=!!(t?.enforceGender!==!1&&t?.gender),n=t?.checkCollectionIds,o=t?.tieFormat,i=t?.event,s="validateTieFormat",a=[],c=rF({...t,stack:s});if(c?.error)return c;let u,p=o.collectionDefinitions.every(I=>{let{setValue:h,scoreValue:S,collectionValue:T}=I;(h||S)&&!T&&(u=!0);let{valid:y,errors:P}=qc({referenceCategory:t.category,referenceGender:t.gender,collectionDefinition:I,checkCollectionIds:n,checkCategory:e,checkGender:r,event:i});return y?!0:(Array.isArray(P)&&a.push(...P),!1)}),m=typeof o.winCriteria?.valueGoal=="number"&&o.winCriteria?.valueGoal>0&&!u||o.winCriteria?.aggregateValue;if(!(m||o.winCriteria?.aggregateValue))return u?a.push("aggregateValue is required"):a.push("Either non-zero valueGoal, or { aggregateValue: true } must be specified in winCriteria"),_({context:{tieFormat:o,errors:a,aggregateValueImperative:u},result:{error:Lo},stack:s});let d=o.collectionDefinitions.map(({collectionId:I})=>I),l=!n||d.length===ut(d).length,f=p&&m&&l,g={valid:f,errors:a};return f?g:_({result:{error:Lo},context:{tieFormat:o,errors:a},stack:s})}function rF(t){let{tieFormat:e,stack:r}=t;return!t||!e||!ht(e)?_({result:{error:Lo},context:{tieFormat:e,message:"tieformat must be an object"},stack:r}):ht(e.winCriteria)?Array.isArray(e.collectionDefinitions)?{...C}:_({result:{error:Lo},context:{tieFormat:e,message:"collectionDefinitions must be an array"},stack:r}):_({result:{error:Lo},context:{tieFormat:e,message:"tieformat.winCritiera must be an object"},stack:r})}var Ja="resourceSubType",Za="resourceType",tc="identifier",WC={RESOURCE_SUB_TYPE:Ja,RESOURCE_TYPE:Za,IDENTIFIER:tc};function J(t,e,r,n,o=0){if(qI().makeDeepCopy)return qI().makeDeepCopy(t,e,r,n);let i=af(),{stringify:s,toJSON:a,ignore:c,modulate:u}=i||{};if(!i?.enabled&&!r||typeof t!="object"||Wr(t)||t===null||typeof i?.threshold=="number"&&o>=i.threshold)return t;let p=Array.isArray(t)?[]:{},m=Object.keys(t).filter(l=>!r||!c||Array.isArray(c)&&!c.includes(l)||Wr(c)&&!c(l)),d=(l,f)=>{p[l]=Wr(f?.toString)?f.toString():JSON.stringify(f)};for(let l of m){let f=t[l],g=Wr(u)?u(f):void 0;if(g!==void 0)p[l]=g;else if(e&&l==="extensions"&&Array.isArray(f)){let I=Sf(f);Object.assign(p,...I)}else n&&l==="extensions"?p[l]=[]:Array.isArray(s)&&s.includes(l)?d(l,f):Array.isArray(a)&&a.includes(l)&&Wr(f?.toJSON)?p[l]=f.toJSON():f===null?p[l]=void 0:VC(f)?p[l]=new Date(f).toISOString():p[l]=J(f,e,r,n,o+1)}return p}function Sf(t){return t?.map(e=>{let{name:r,value:n}=e;return r&&n&&{[`_${r}`]:n}}).filter(Boolean)}function th(t=1,e){return et(0,t).map(()=>Dt(e))}function Dt(t){let e=[];for(let a=0;a<256;a++)e[a]=(a<16?"0":"")+a.toString(16);let r=Math.random()*4294967295|0,n=Math.random()*4294967295|0,o=Math.random()*4294967295|0,i=Math.random()*4294967295|0,s=e[r&255]+e[r>>8&255]+e[r>>16&255]+e[r>>24&255]+"-"+e[n&255]+e[n>>8&255]+"-"+e[n>>16&15|64]+e[n>>24&255]+"-"+e[o&63|128]+e[o>>8&255]+"-"+e[o>>16&255]+e[o>>24&255]+e[i&255]+e[i>>8&255]+e[i>>16&255]+e[i>>24&255];return typeof t=="string"?`${t}_${s.replace(/-/g,"")}`:s}var eh={collectionDefinitions:[{collectionName:"Male Singles",matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpCount:4,matchUpValue:1,gender:"MALE"},{collectionName:"Female Singles",matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",gender:"FEMALE",matchUpCount:4,matchUpValue:1},{collectionName:"Male Doubles",matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",matchUpCount:2,matchUpValue:1,gender:"MALE"},{collectionName:"Female Doubles",matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",gender:"FEMALE",matchUpCount:2,matchUpValue:1},{collectionName:"Mixed Doubles",matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",matchUpCount:4,matchUpValue:1,gender:"MIXED"}],tieFormatName:"USTA_GOLD_TEAM_CHALLENGE",winCriteria:{valueGoal:9}};var rh={collectionDefinitions:[{collectionName:"Round 1",matchUpCount:3,matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Round 2",matchUpCount:3,matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Round 3",matchUpCount:3,matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"Doubles Shuffle",unrestrictedSelections:!0,winCriteria:{aggregateValue:!0}};var nh={collectionDefinitions:[{collectionName:"Male Singles",gender:"MALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Mixed Doubles",gender:"MIXED",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],tieFormatName:"USTA_SOUTHERN_LEVEL_5",winCriteria:{valueGoal:8}};var oh={collectionDefinitions:[{category:{ageCategoryCode:"16U"},collectionName:"16U Singles",matchUpCount:4,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Singles",matchUpCount:4,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Doubles",matchUpCount:2,matchUpFormat:"SET1-S:6/TB7",matchUpType:"DOUBLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Doubles",matchUpCount:2,matchUpFormat:"SET1-S:6/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Tiebreak Doubles",matchUpCount:1,matchUpFormat:"SET1-S:TB10",matchUpType:"DOUBLES",matchUpValue:1,processCodes:["RANKING.IGNORE"]}],tieFormatName:"USTA_SECTION_BATTLE",winCriteria:{valueGoal:9}};var ih={collectionDefinitions:[{collectionName:"Male Singles",gender:"MALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Mixed Doubles",gender:"MIXED",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],tieFormatName:"USTA_INTERSECTIONAL",winCriteria:{valueGoal:8}};var sh={collectionDefinitions:[{scoreValue:1,matchUpType:"SINGLES",collectionName:"Men's Singles",matchUpFormat:"SET1-S:T60",gender:"MALE",matchUpCount:1},{scoreValue:1,matchUpType:"SINGLES",collectionName:"Women's Singles",matchUpFormat:"SET1-S:T60",gender:"FEMALE",matchUpCount:1},{matchUpValue:1,matchUpType:"DOUBLES",collectionName:"Mixed Doubles",matchUpFormat:"SET1-S:T60",gender:"MIXED",matchUpCount:1}],tieFormatName:"Time Tennis Pro Circuit",winCriteria:{aggregateValue:!0}};var ah={collectionDefinitions:[{collectionName:"Mixed Doubles",gender:"MIXED",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Male Singles",matchUpCount:1,gender:"MALE",matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"DOMINANT_DUO_MIXED",winCriteria:{valueGoal:2}};var ch={collectionDefinitions:[{scoreValue:1,matchUpType:"SINGLES",collectionName:"Men's Singles",matchUpFormat:"SET1-S:T60",gender:"MALE",matchUpCount:3},{scoreValue:1,matchUpType:"SINGLES",collectionName:"Women's Singles",matchUpFormat:"SET1-S:T60",gender:"FEMALE",matchUpCount:3},{scoreValue:1,matchUpType:"DOUBLES",collectionName:"Men's Doubles",matchUpFormat:"SET1-S:T60",gender:"MALE",matchUpCount:1},{matchUpValue:1,matchUpType:"DOUBLES",collectionName:"Women's Doubles",matchUpFormat:"SET1-S:T60",gender:"FEMALE",matchUpCount:1},{matchUpValue:1,matchUpType:"DOUBLES",collectionName:"Mixed Doubles",matchUpFormat:"SET1-S:T60",gender:"MIXED",matchUpCount:1}],tieFormatName:"Time Tennis Dual",winCriteria:{aggregateValue:!0}};var uh={collectionDefinitions:[{category:{ageCategoryCode:"14U"},collectionName:"14U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"14U"},collectionName:"14U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],collectionGroups:[{groupNumber:1,groupName:"Doubles",groupValue:1,winCriteria:{valueGoal:2}}],tieFormatName:"USTA_BREWER_CUP",winCriteria:{valueGoal:4}};var ph={winCriteria:{valueGoal:23},tieFormatName:"USTA_OZAKI_CUP",collectionDefinitions:[{category:{ageCategoryCode:"18U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"18U Boys Singles",matchUpType:"SINGLES",matchUpCount:3,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"18U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"18U Girls Singles",matchUpType:"SINGLES",gender:"FEMALE",matchUpCount:3,matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Boys Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",matchUpCount:1,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"18U"},collectionName:"18U Girls Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"FEMALE",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Mixed Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"MIXED",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"16U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"16U Boys Singles",matchUpType:"SINGLES",matchUpCount:3,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"16U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"16U Girls Singles",matchUpType:"SINGLES",gender:"FEMALE",matchUpCount:3,matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Boys Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",matchUpCount:1,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"16U"},collectionName:"16U Girls Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"FEMALE",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Mixed Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"MIXED",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"14U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"14U Boys Singles",matchUpType:"SINGLES",matchUpCount:3,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"14U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"14U Girls Singles",matchUpType:"SINGLES",gender:"FEMALE",matchUpCount:3,matchUpValue:1},{category:{ageCategoryCode:"14U"},collectionName:"14U Boys Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",matchUpCount:1,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"14U"},collectionName:"14U Girls Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"FEMALE",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"14U"},collectionName:"14U Mixed Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"MIXED",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"12U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"12U Boys Singles",matchUpType:"SINGLES",matchUpCount:3,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"12U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"12U Girls Singles",matchUpType:"SINGLES",gender:"FEMALE",matchUpCount:3,matchUpValue:1},{category:{ageCategoryCode:"12U"},collectionName:"12U Boys Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",matchUpCount:1,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"12U"},collectionName:"12U Girls Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"FEMALE",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"12U"},collectionName:"12U Mixed Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"MIXED",matchUpCount:1,matchUpValue:1}]};var Dn="SET3-S:6/TB7",lF="SET3-S:6NOAD",HE="SET3-S:6/TB7-F:TB10",fF="SET3-S:4/TB7",gF="SET3-S:4/TB5@3",IF="SET1-S:T20",hF="SET1-S:8/TB7",SF="SET1-S:8/TB7@7",jC={FORMAT_STANDARD:Dn,FORMAT_STANDARD_NOAD:lF,FORMAT_ATP_DOUBLES:HE,FORMAT_SHORT_SETS:fF,FORMAT_FAST4:gF,FORMAT_PRO_SET:hF,FORMAT_COLLEGE_PRO_SET:SF,TIMED20:IF};var mh={collectionDefinitions:[{collectionName:"Doubles",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"DOMINANT_DUO",winCriteria:{valueGoal:2}};var dh={collectionDefinitions:[{collectionName:"Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",collectionValue:1},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"USTA_COLLEGE",winCriteria:{valueGoal:4}};var lh={collectionDefinitions:[{collectionName:"Male Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Female Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Male Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Female Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],tieFormatName:"USTA_LEVEL_1",winCriteria:{valueGoal:10}};var fh={collectionDefinitions:[{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Male Singles",matchUpCount:1,gender:"MALE",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Overtime",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"USTA_WTT_ITT",winCriteria:{aggregateValue:!0}};var gh={collectionDefinitions:[{collectionName:"Male Singles",gender:"MALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Mixed Doubles",gender:"MIXED",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],tieFormatName:"USTA_ZONAL",winCriteria:{valueGoal:10}};var Ih={collectionDefinitions:[{collectionGroupNumber:1,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:1},{collectionGroupNumber:1,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:1},{collectionGroupNumber:2,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:2},{collectionGroupNumber:2,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:2},{collectionGroupNumber:3,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:3},{collectionGroupNumber:3,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:3}],collectionGroups:[{groupNumber:1,groupName:"Day 1"},{groupNumber:2,groupName:"Day 2"},{groupNumber:3,groupName:"Day 3"}],tieFormatName:"LAVER_CUP",winCriteria:{valueGoal:13}};var hh={collectionDefinitions:[{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Male Singles",matchUpCount:1,gender:"MALE",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Overtime",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"USTA_TOC",winCriteria:{aggregateValue:!0}};var vm="COLLEGE_DEFAULT",Sh="COLLEGE_JUCO",Th="COLLEGE_D3",WE="DOMINANT_DUO",jE="DOMINANT_DUO_MIXED",YE="LAVER_CUP",qE="TEAM_DOUBLES_3_AGGREGATION",$E="TIME_TENNIS_DUAL",KE="TIME_TENNIS_PRO_CIRCUIT",zE="USTA_BREWER_CUP",QE="USTA_OZAKI_CUP",XE="USTA_COLLEGE",JE="USTA_GOLD_TEAM_CHALLENGE",ZE="USTA_LEVEL_1",tU="USTA_INTERSECTIONAL",eU="USTA_SECTION_BATTLE",rU="USTA_SOUTHERN_LEVEL_5",nU="USTA_TOC",oU="USTA_WTT_ITT",iU="USTA_ZONAL",YC={COLLEGE_D3:Th,COLLEGE_DEFAULT:vm,COLLEGE_JUCO:Sh,DOMINANT_DUO:WE,DOMINANT_DUO_MIXED:jE,LAVER_CUP:YE,TEAM_DOUBLES_3_AGGREGATION:qE,TIME_TENNIS_DUAL:$E,TIME_TENNIS_PRO_CIRCUIT:KE,USTA_BREWER_CUP:zE,USTA_OZAKI_CUP:QE,USTA_COLLEGE:XE,USTA_GOLD_TEAM_CHALLENGE:JE,USTA_INTERSECTIONAL:tU,USTA_LEVEL_1:ZE,USTA_SECTION_BATTLE:eU,USTA_SOUTHERN_LEVEL_5:rU,USTA_TOC:nU,USTA_WTT_ITT:oU,USTA_ZONAL:iU};var $C="STANDARD",qC={[$C]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1},singles:{matchUpCount:6,matchUpValue:1},valueGoal:5},[Th]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7@7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:Dn,matchUpCount:6,matchUpValue:1},tieFormatName:Th,valueGoal:5},[vm]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:6/TB7",collectionValue:1,matchUpCount:3},singles:{matchUpFormat:Dn,matchUpCount:6,matchUpValue:1},tieFormatName:vm,valueGoal:4},[Sh]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:Dn,matchUpCount:6,matchUpValue:1},tieFormatName:Sh,valueGoal:5},[YE]:Ih,[WE]:mh,[jE]:ah,[qE]:rh,[$E]:ch,[KE]:sh,[zE]:uh,[QE]:ph,[XE]:dh,[JE]:eh,[tU]:ih,[ZE]:lh,[eU]:oh,[rU]:nh,[oU]:fh,[nU]:hh,[iU]:gh},NF=t=>{let e=t?.namedFormat&&Object.keys(qC).includes(t.namedFormat)?t.namedFormat:$C,r=Array.isArray(t?.uuids)?t?.uuids:[],n,{category:o,gender:i}=t?.event??{},s=J(qC[e],!1,!0),a=c=>{if(!t?.isMock&&!t?.event?.isMock||!t.event)return r?.pop()??Dt();let u=t?.event?.eventId;return r.pop()??`${u}-COL-${c+1}`};return s.hydrate?(n={winCriteria:{valueGoal:s.valueGoal},collectionDefinitions:[{collectionId:a(0),matchUpFormat:HE,collectionName:"Doubles",matchUpType:_t,...s.doubles},{collectionId:a(1),matchUpFormat:Dn,collectionName:"Singles",matchUpType:xt,...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},Zn=NF;var jn="SINGLES",Fs="SINGLES",qr="DOUBLES",ko="DOUBLES",_e="TEAM",Cr="TEAM",MF="AGE",RF="RATING",CF="BOTH",KC={AGE:MF,BOTH:CF,DOUBLES:qr,DOUBLES_EVENT:ko,RATING:RF,SINGLES:jn,SINGLES_EVENT:Fs,TEAM_EVENT:Cr,TEAM:_e};var nt="MAIN",ct="QUALIFYING",qe="CONSOLATION",$e="VOLUNTARY_CONSOLATION",de="PLAY_OFF",$c=[nt,ct,qe,de,$e],ks={[ct]:1,[nt]:2,[de]:3,[qe]:3,[$e]:4},sU="finishingPositions",aU="aggregateEventStructures",cU={[nt]:1,[de]:2,[qe]:3,[ct]:4,[$e]:5},zC={[de]:1,[nt]:2,[qe]:3,[ct]:4,[$e]:5},Kc="CLUSTER",QC="SEPARATE",mi="WATERFALL",ap="ITEM",Ge="CONTAINER",dn="DRAW",cp="RANDOM",En="TOP_DOWN",di="BOTTOM_UP",to="POSITION",fo="WINNER",eo="LOSER",On="FIRST_MATCHUP",$r="AD_HOC",bF="AD_HOC",da="FEED_IN",zc="COMPASS",Qc="OLYMPIC",vF="SINGLE_ELIMINATION";var go="SINGLE_ELIMINATION",Xc="DOUBLE_ELIMINATION",Jc="FIRST_MATCH_LOSER_CONSOLATION",up="FIRST_ROUND_LOSER_CONSOLATION",ki="LUCKY_DRAW",Tf="CURTIS_CONSOLATION",XC="CURTIS_CONSOLATION",yh="FEED_IN_CHAMPIONSHIP_TO_SF",Om="FEED_IN_CHAMPIONSHIP_TO_SF",Ah="FEED_IN_CHAMPIONSHIP_TO_QF",_m="FEED_IN_CHAMPIONSHIP_TO_QF",Eh="FEED_IN_CHAMPIONSHIP_TO_R16",xm="FEED_IN_CHAMPIONSHIP_TO_R16",uU="MODIFIED_FEED_IN_CHAMPIONSHIP",wm="MODIFIED_FEED_IN_CHAMPIONSHIP",pp="FEED_IN_CHAMPIONSHIP",JC="DOUBLE_ROUND_ROBIN",Nn="ROUND_ROBIN",Io="ROUND_ROBIN_WITH_PLAYOFF",pU="DECIDER",mU="BACKDRAW",yf={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-3":{name:"Northeast",abbreviation:"NE"},"0-1-1":{name:"South",abbreviation:"S"},"0-1-2":{name:"Southwest",abbreviation:"SW"},"0-2-1":{name:"Northwest",abbreviation:"NW"},"0-1-1-1":{name:"Southeast",abbreviation:"SE"}},Af={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-1-1":{name:"South",abbreviation:"S"}},li="WIN_RATIO",Gi="ROUND_OUTCOME",dU=[zc,Tf,_m,xm,Om,pp,Ah,Eh,yh,Jc,up,ki,wm,Qc,de,Io],OF=[$r,zc,Tf,Xc,_m,xm,Om,pp,da,Jc,up,ki,wm,Qc,de,Nn,Io,go],lU={MAIN:nt,QUALIFYING:ct,CONSOLATION:qe,ITEM:ap,CONTAINER:Ge,FIRST_MATCHUP:On,WINNER:fo,LOSER:eo,AD_HOC:$r,FEED_IN:da,FLEX_ROUNDS:bF,COMPASS:zc,PLAY_OFF:de,OLYMPIC:Qc,KNOCKOUT:vF,SINGLE_ELIMINATION:go,DOUBLE_ELIMINATION:Xc,CURTIS:Tf,FICSF:yh,FICQF:Ah,FICR16:Eh,MFIC:uU,VOLUNTARY_CONSOLATION:$e,FIRST_MATCH_LOSER_CONSOLATION:Jc,FIRST_ROUND_LOSER_CONSOLATION:up,MODIFIED_FEED_IN_CHAMPIONSHIP:wm,FEED_IN_CHAMPIONSHIP_TO_R16:xm,FEED_IN_CHAMPIONSHIP_TO_QF:_m,FEED_IN_CHAMPIONSHIP_TO_SF:Om,FEED_IN_CHAMPIONSHIP:pp,LUCKY_DRAW:ki,ROUND_ROBIN_WITH_PLAYOFF:Io,ROUND_ROBIN:Nn,DECIDER:pU,BACKDRAW:mU,COMPASS_ATTRIBUTES:yf,OLYMPIC_ATTRIBUTES:Af,DRAW:dn,RANDOM:cp,TOP_DOWN:En,BOTTOM_UP:di,WATERFALL:mi,WIN_RATIO:li,ROUND_OUTCOME:Gi,MULTI_STRUCTURE_DRAWS:dU,generatedDrawTypes:OF,stageOrder:ks,finishOrder:cU,AGGREGATE_EVENT_STRUCTURES:aU,FINISHING_POSITIONS:sU},ZC=lU;var Re="tournamentRecords",Ef="policyDefinitions",ie="tournamentRecord",Uh="onlineResource",Ve="drawDefinition",Ph="tieFormatName",Lm="matchUpFormat",ro="participantId",Dh="scheduleDates",tb="tournamentId",eb="scheduleDate",rb="roundNumber",Zc="structureId",Uf="participant",ec="matchUpIds",Nh="entryStage",nb="policyType",fU="structures",Pf="eventType",ln="matchUpId",Fm="tieFormat",tu="inContext",mp="structure",dp="courtIds",ob="personId",lp="venueIds",Df="matchUps",Mh="courtId",Rh="eventId",_n="matchUp",Ch="drawId",fn="error",Do="event",is="param",Nf="uuids",ib="averageMatchUpMinutes",sb="recoveryMinutes",ab="periodLength",cb="number";var Kr="object",Be="array";var tr="_validate",bh="_message",Fr="_invalid",He="_ofType",km="_anyOf",Gs="_oneOf";var ub={[Uh]:t=>Yt(Object.keys(t),[Ja,Za,tc]).length===3,[Ph]:t=>t&&Zn({namedFormat:t}),[Nf]:t=>!t||Array.isArray(t)&&t.every(Vt),[Fm]:t=>!ar({tieFormat:t}).error,[Pf]:t=>[jn,qr,_e].includes(t),[Nh]:t=>$c.includes(t)},_F={[Re]:wt,[ie]:Y,[Ef]:$u,[Ve]:Z,[ro]:oe,[Lm]:Wl,[tb]:ca,[Zc]:Er,[ec]:rs,[Uf]:wi,[Uh]:lo,[Pf]:Bn,[fU]:Gl,[ln]:sr,[Fm]:Lo,[mp]:pi,[Mh]:_i,[Df]:Xn,[Rh]:jr,[_n]:hr,[dp]:st,[lp]:st,[Ch]:an,[Do]:vt},xF={[Re]:Kr,[Ef]:Kr,[ie]:Kr,[Ve]:Kr,[Uh]:Kr,[Dh]:Be,[Uf]:Kr,[ec]:Be,[fU]:Be,[Fm]:Kr,[mp]:Kr,[dp]:Be,[lp]:Be,[Df]:Be,[_n]:Kr,[Do]:Kr,[Nf]:Be};function rt(t,e,r){if(!t&&!ht(t))return{error:G};if(!e?.length||t?._bypassParamCheck)return{valid:!0};if(!Array.isArray(e))return{error:G};let{paramError:n,errorParam:o}=FF(t,e);if(!n)return{valid:!0};let i=n[tr]&&(n[fn]||n[Fr])||t?.[o]===void 0&&(n[fn]||n[Fr]||_F[o]||G)||G,s=o??(n[Gs]&&Object.keys(n[Gs]).join(", "));return _({info:{param:s,message:n[bh]},result:{error:i},stack:r})}function pb(t,e){let r=Object.keys(t),n=Object.keys(e);return Yt(r,n)}function wF(t,e){if(!e)return;let r=pb(t,e);return r.length!==1?{error:G}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function LF(t,e){if(!e)return;let r=pb(t,e).filter(n=>t[n]);return r.length<1?{error:G}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function FF(t,e){let r,n;return{paramError:e.find(({_ofType:i,_oneOf:s,_anyOf:a,_validate:c,_info:u,...p})=>{let m=s&&wF(t,s);if(m?.error)return m.error;m&&Object.assign(p,m);let d=a&&LF(t,a);if(d?.error)return d.error;d&&Object.assign(p,d);let l=Object.keys(p).filter(g=>typeof p[g]=="boolean"),f=l.find(g=>{let I=c&&!Wr(c),h=t[g]!==void 0&&!c&&kF(t,g,i),S=p[g]&&[void 0,null].includes(t[g]),y=I||h||S||c&&t[g]!==void 0&&!GF(t[g],c)||ub[g]&&!ub[g](t[g]);return y&&(r=g,n=u),y});return!l.length||f}),errorParam:r,paramInfo:n}}function kF(t,e,r){return r=r||xF[e]||"string",r==="array"?!Array.isArray(t[e]):typeof t[e]!==r}function GF(t,e){return Wr(e)?e(t):!0}var Gm="DYNAMIC",fi="RANKING",gi="RATING",Ii="SCALE",ho="SEEDING",mb={RANKING:fi,RATING:gi,SCALE:Ii,SEEDING:ho};function la(t){let e=rt(t,[{[Uf]:!0}]);if(e.error)return e;let r=t.participant.timeItems?.filter(({itemType:o})=>o?.startsWith(Ii)&&[fi,gi,ho].includes(o.split(".")[1])),n={ratings:{},rankings:{},seedings:{}};if(r?.length){let o=s=>r.filter(a=>a?.itemType===s).sort((a,c)=>new Date(a.createdAt||void 0).getTime()-new Date(c.createdAt||void 0).getTime()).pop(),i=ut(r.map(({itemType:s})=>s));for(let s of i){let a=o(s);if(a){let[,c,u,p,m]=a.itemType.split("."),d=m?`${p}.${m}`:p,l=c===ho&&"seedings"||c===fi&&"rankings"||"ratings";n[l][u]||(n[l][u]=[]),n[l][u].push({scaleValue:a.itemValue,scaleDate:a.itemDate,scaleName:d})}}}return{...C,...n}}function Vi(t){if(t===null)return{};let{source:e,template:r}=t||{};if(!r)return e;let n={};return o(e,r,n),n;function o(i,s,a){if(!i||!s)return;let c=Object.keys(i),u=Object.keys(s),p=Object.assign({},...u.filter(l=>l.indexOf("||")).map(l=>l.split("||").map(f=>({[f]:l}))).flat()),m=u.concat(...Object.keys(p)),d=m.includes("*");for(let l of c)if(m.indexOf(l)>=0||d){let f=p[l]||l,g=s[f]||d,I=i[l];if(typeof g=="object"&&typeof I!="function"&&!Array.isArray(g))if(Array.isArray(I)){let h=I.map(S=>{let T={};return o(S,g,T)!==!1?T:void 0}).filter(Boolean);a[l]=h}else I&&(a[l]={},o(I,g,a[l]));else{let h=i[l];if(Array.isArray(g)&&!g.includes(h))return!1;(s[l]||d&&s[l]!==!1)&&(a[l]=h)}}}}var vh="voluntaryConsolation",hi="competitiveBands",Mf="roundRobinTally",So="positionActions",er="matchUpActions",Rf="rankingPoints",fa="roundNaming",Vs="participant",eu="progression",No="scheduling",ru="avoidance",VF="participant",BF="display",en="scoring",xn="seeding",rc="feedIn",HF="audit",Vm="draws",db={POLICY_TYPE_VOLUNTARY_CONSOLATION:vh,POLICY_TYPE_COMPETITIVE_BANDS:hi,POLICY_TYPE_ROUND_ROBIN_TALLY:Mf,POLICY_TYPE_POSITION_ACTIONS:So,POLICY_TYPE_MATCHUP_ACTIONS:er,POLICY_TYPE_RANKING_POINTS:Rf,POLICY_TYPE_ROUND_NAMING:fa,POLICY_TYPE_PARTICIPANT:Vs,POLICY_TYPE_PROGRESSION:eu,POLICY_TYPE_SCHEDULING:No,POLICY_TYPE_AVOIDANCE:ru,POLICY_TYPE_DISPLAY:BF,POLICY_TYPE_PRIVACY:VF,POLICY_TYPE_FEED_IN:rc,POLICY_TYPE_SCORING:en,POLICY_TYPE_SEEDING:xn,POLICY_TYPE_AUDIT:HF,POLICY_TYPE_DRAWS:Vm};function Go({tournamentParticipants:t=[],policyDefinitions:e={},contextProfile:r,participantId:n,internalUse:o,personId:i}){let s=t.find(c=>n&&c.participantId===n||i&&c.person&&c.person.personId===i),a=J(s,!1,o);if(a){let c=e?.[Vs];if(r?.withScaleValues){let{ratings:u,rankings:p}=la({participant:a});a.rankings=p,a.ratings=u}if(c?.participant)return Vi({template:c.participant,source:a})}return a}var lb="element required",fb="missing name";function gr(t){if(!t||typeof t!="object")return{error:st};if(t.element&&typeof t?.element!="object")return{error:G};if(!t?.name)return{error:st,info:fb};if(!t?.element){if(t.discover&&t.tournamentRecords){for(let e of Object.keys(t.tournamentRecords)){let r=t.tournamentRecords[e],n=gr({element:r,name:t.name});if(n.error)return _({result:n,stack:"removeExtension"})}return{...C}}return{error:st,info:lb}}return t?.element.extensions?(t.element.extensions=t.element.extensions.filter(e=>e?.name!==t.name),{...C}):{...C,info:ve}}function wn({requiredAttributes:t=["name","value"],extension:e}){if(!e||typeof e!="object"||typeof e.name!="string")return!1;let r=Object.keys(e);return t.filter(n=>r.includes(n)).length===t.length}function At(t){if(typeof t!="object")return{error:st};let e="addExtension";if(t?.element&&typeof t.element!="object")return _({result:{error:G},stack:e});if(!wn({extension:t.extension}))return _({result:{error:G,info:"invalid extension"},stack:e});if(!t.element)if(t.discover&&!t.tournamentId&&t.tournamentRecords){for(let o of Object.values(t.tournamentRecords)){let i=At({extension:t.extension,element:o});if(i.error)return _({result:i,stack:e})}return{...C}}else return _({result:{error:st},stack:e});if(t.element.extensions||(t.element.extensions=[]),t?.creationTime??!0){let o=new Date().toISOString();Object.assign(t.extension,{createdAt:o})}let n=t.element.extensions.find(({name:o})=>o===t.extension.name);return n?n.value=t.extension.value:t.extension.value&&t.element.extensions.push(t.extension),{...C}}function Cf(t){return!t||typeof t!="object"?{error:st}:t.tournamentRecord?At({creationTime:t.creationTime,element:t.tournamentRecord,extension:t.extension}):{error:Y}}function fp(t){return!t||typeof t!="object"?{error:st}:t.drawDefinition?At({creationTime:t.creationTime,element:t.drawDefinition,extension:t.extension}):{error:Mr}}function Mo(t){return!t||typeof t!="object"?{error:st}:t.event?At({creationTime:t.creationTime,extension:t.extension,element:t.event}):{error:jr}}function gU(t){if(!t||typeof t!="object")return{error:st};if(!t.participantId)return{error:oe};let e=t.tournamentRecord?.participants||[],r=Go({participantId:t.participantId,tournamentParticipants:e});return r?At({creationTime:t.creationTime,extension:t.extension,element:r}):{error:te}}function bf(t){return!t||typeof t!="object"?{error:st}:t.tournamentRecord?gr({element:t.tournamentRecord,name:t.name}):{error:Y}}function IU(t){return!t||typeof t!="object"?{error:st}:t.drawDefinition?gr({element:t.drawDefinition,name:t.name}):{error:Mr}}function gp(t){return!t||typeof t!="object"?{error:st}:t?.event?gr({element:t.event,name:t.name}):{error:jr}}function hU(t){if(!t||typeof t!="object")return{error:st};if(!t.participantId)return{error:oe};let e=t.tournamentRecord?.participants||[],r=Go({participantId:t.participantId,tournamentParticipants:e});return r?gr({element:r,name:t.name}):{error:te}}function Ip({tournamentRecords:t}){return{tournamentIds:ht(t)?Object.keys(t):[],...C}}var WF="extensionQueries";function dt({discover:t,element:e,name:r,...n}){if(!e||!r){if(t&&n){let s=Object.keys(n).filter(p=>typeof t=="boolean"||Array.isArray(t)&&t.includes(p)).find(p=>Array.isArray(n[p]?.extensions)?n[p].extensions.find(m=>m?.name===r):!1),a=s&&n[s];!a&&n.tournamentRecords&&(a=Object.values(n.tournamentRecords).find(p=>p.extensions?.length));let c=a?.extensions?.find(p=>p?.name===r);return{extension:c,info:c?void 0:ve}}return _({result:{error:st},stack:WF})}if(!Array.isArray(e.extensions))return{info:"no extensions"};let o=e.extensions.find(s=>s?.name===r);return{extension:o,info:o?void 0:ve}}var jF="activeSuspension",nu="appliedPolicies",SU="context",Bm="delegatedOutcome",no="disabled",ga="disableAutoCalc",Hm="disableLinks",Wm="display",Ia="drawDeletions",YF="drawProfile",jm="entryProfile",qF="eventProfile",$F="eventWithdrawalRequests",KF="factory",un="flightProfile",Oh="groupingAttribute",Ro="lineUps",Bs="linkedTournamentsIds",Ym="matchUpHistory",_h="participantRepresentatives",ha="personRequests",nc="positionActions",zF="rankingPoints",QF="registration",Mn="roundTarget",ou="scheduleLimits",Vo="scheduleTiming",Sa="schedulingProfile",XF="statusDetail",oc="subOrder",Jo="tally",qm="tieFormatModification",xh={ACTIVE_SUSPENSION:jF,APPLIED_POLICIES:nu,CONTEXT:SU,DELEGATED_OUTCOME:Bm,DISABLED:no,DISABLE_LINKS:Hm,DISABLE_AUTO_CALC:ga,DISPLAY:Wm,DRAW_DELETIONS:Ia,DRAW_PROFILE:YF,ENTRY_PROFILE:jm,EVENT_PROFILE:qF,EVENT_WITHDRAWAL_REQUESTS:$F,FLIGHT_PROFILE:un,GROUPING_ATTRIBUTE:Oh,LINEUPS:Ro,LINKED_TOURNAMENTS:Bs,MATCHUP_HISTORY:Ym,PARTICIPANT_REPRESENTATIVES:_h,PERSON_REQUESTS:ha,POSITION_ACTIONS:nc,RANKING_POINTS:zF,REGISTRATION:QF,ROUND_TARGET:Mn,SCHEDULE_LIMITS:ou,SCHEDULE_TIMING:Vo,SCHEDULING_PROFILE:Sa,STATUS_DETAIL:XF,SUB_ORDER:oc,TALLY:Jo,TIE_FORMAT_MODIFICATIONS:qm,FACTORY:KF},TU=[Bm,no,ga,Hm,un,Ro,Bs,Ym,_h,ha,Mn,ou,Vo,Sa,oc,Jo,qm];function yU({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:wt};let e=Ip({tournamentRecords:t}),{tournamentIds:r}=e;return r?.length>1?At({tournamentRecords:t,discover:!0,extension:{name:Bs,value:{tournamentIds:r}}}):{...C}}function AU({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:wt};let e=gr({name:Bs,tournamentRecords:t,discover:!0});return _({result:e,stack:"unlinkTournaments"})}function EU({tournamentRecords:t,tournamentId:e}){if(typeof t!="object")return{error:G};if(!e)return{error:ca};let r=Ip({tournamentRecords:t}),{tournamentIds:n}=r;if(!n.includes(e))return{error:ca};let o;return n.every(i=>{let s=t[i],{extension:a}=dt({element:s,name:Bs});if(!a)return!0;let c=a?.value?.tournamentIds||[];if(!c?.length||c.length===1&&c.includes(e)||i===e){let m=bf({name:Bs,tournamentRecord:s});return m.error&&(o=m.error),m.success}let u=c.filter(m=>m!==e);a.value={tournamentIds:u};let p=Cf({tournamentRecord:s,extension:a});return p.error&&(o=p.error),p.success}),o?{error:o}:{...C}}var PU={};Xt(PU,{getLinkedTournamentIds:()=>iu,getTournamentIds:()=>Ip});function iu({tournamentRecords:t}){return typeof t!="object"||!Object.keys(t).length?{error:wt}:{linkedTournamentIds:Object.assign({},...Object.keys(t).map(r=>{let n=t[r],o=n?.tournamentId,{extension:i}=dt({element:n,name:Bs}),s=(i?.value?.tournamentIds||[]).filter(a=>a!==o);return{[r]:s}}))}}var MN={};Xt(MN,{adHocPositionSwap:()=>wP,addAdHocMatchUps:()=>bd,addDrawDefinitionTimeItem:()=>Tg,addFinishingRounds:()=>Ea,addGoesTo:()=>qi,addPlayoffStructures:()=>kp,addQualifyingStructure:()=>xP,addVoluntaryConsolationStage:()=>CP,addVoluntaryConsolationStructure:()=>pg,allPlayoffPositionsFilled:()=>OS,alternateDrawPositionAssignment:()=>SP,assignDrawPosition:()=>zP,assignDrawPositionBye:()=>Hr,attachConsolationStructures:()=>YP,attachPlayoffStructures:()=>Cg,attachQualifyingStructure:()=>Sg,attachStructures:()=>bg,autoSeeding:()=>X_,automatedPlayoffPositioning:()=>Ks,automatedPositioning:()=>Sc,checkValidEntries:()=>_d,deleteAdHocMatchUps:()=>QP,drawMatic:()=>qd,findDrawDefinition:()=>oT,generateAdHocMatchUps:()=>Ou,generateAdHocRounds:()=>Yd,generateAndPopulatePlayoffStructures:()=>Cd,generateDrawDefinition:()=>xa,generateDrawMaticRound:()=>Fd,generateDrawStructuresAndLinks:()=>xd,generateDrawTypeAndModifyDrawDefinition:()=>wd,generateQualifyingStructure:()=>Pd,generateVoluntaryConsolation:()=>PT,getAssignedParticipantIds:()=>Ri,getAvailableMatchUpsCount:()=>vd,getAvailablePlayoffProfiles:()=>Pu,getDrawDefinitionTimeItem:()=>zh,getDrawParticipantRepresentativeIds:()=>rT,getDrawStructures:()=>gn,getDrawTypeCoercion:()=>bu,getEligibleVoluntaryConsolationParticipants:()=>eT,getMatchUpsMap:()=>Ne,getParticipantIdFinishingPositions:()=>nT,getPositionAssignments:()=>Gp,getPositionsPlayedOff:()=>yc,getSeedingThresholds:()=>ES,getSeedsCount:()=>vu,getStructureSeedAssignments:()=>on,getTeamLineUp:()=>ms,getValidGroupSizes:()=>Cp,isAdHoc:()=>cr,isCompletedStructure:()=>si,isValidForQualifying:()=>hT,luckyLoserDrawPositionAssignment:()=>lP,modifyDrawDefinition:()=>qP,modifyDrawName:()=>vg,modifySeedAssignment:()=>TP,mutate:()=>ZP,positionActions:()=>IT,pruneDrawDefinition:()=>KP,qualifierDrawPositionAssignment:()=>hP,query:()=>pD,removeDrawPositionAssignment:()=>Au,removeRoundMatchUps:()=>XP,removeSeededParticipant:()=>_P,removeStructure:()=>RP,renameStructures:()=>MP,resetDrawDefinition:()=>$P,resetVoluntaryConsolationStructure:()=>wU,setDrawParticipantRepresentativeIds:()=>MU,setPositionAssignments:()=>gP,setStructureOrder:()=>NP,setSubOrder:()=>JP,shiftAdHocRounds:()=>fP,swapAdHocRounds:()=>IP,swapDrawPositionAssignments:()=>OP,updateTeamLineUp:()=>Ki,withdrawParticipantAtDrawPosition:()=>mP});var ZP={};Xt(ZP,{adHocPositionSwap:()=>wP,addAdHocMatchUps:()=>bd,addDrawDefinitionTimeItem:()=>Tg,addPlayoffStructures:()=>kp,addQualifyingStructure:()=>xP,addVoluntaryConsolationStage:()=>CP,addVoluntaryConsolationStructure:()=>pg,alternateDrawPositionAssignment:()=>SP,assignDrawPosition:()=>zP,assignDrawPositionBye:()=>Hr,attachConsolationStructures:()=>YP,attachPlayoffStructures:()=>Cg,attachQualifyingStructure:()=>Sg,attachStructures:()=>bg,automatedPlayoffPositioning:()=>Ks,automatedPositioning:()=>Sc,deleteAdHocMatchUps:()=>QP,luckyLoserDrawPositionAssignment:()=>lP,modifyDrawDefinition:()=>qP,modifyDrawName:()=>vg,modifySeedAssignment:()=>TP,pruneDrawDefinition:()=>KP,qualifierDrawPositionAssignment:()=>hP,removeDrawPositionAssignment:()=>Au,removeRoundMatchUps:()=>XP,removeSeededParticipant:()=>_P,removeStructure:()=>RP,renameStructures:()=>MP,resetDrawDefinition:()=>$P,resetVoluntaryConsolationStructure:()=>wU,setDrawParticipantRepresentativeIds:()=>MU,setPositionAssignments:()=>gP,setStructureOrder:()=>NP,setSubOrder:()=>JP,shiftAdHocRounds:()=>fP,swapAdHocRounds:()=>IP,swapDrawPositionAssignments:()=>OP,updateTeamLineUp:()=>Ki,withdrawParticipantAtDrawPosition:()=>mP});var NU=t=>e=>t[e],$m=(t=[])=>t.map(Ae).filter(Boolean),vf=(t=[])=>t.map(St).filter(Boolean),St=(t={})=>NU(t)("participantId");var Ae=(t={})=>NU(t)("matchUpId"),su=(t={})=>NU(t)("drawId");function MU({representativeParticipantIds:t,drawDefinition:e}){if(!e)return{error:Mr};if(!Array.isArray(t))return{error:G};let r=vf(e?.entries||[]);return t.length&&Yt(t,r).length<t.length?{error:G}:fp({drawDefinition:e,extension:{name:_h,value:t}})}var br="ABANDONED",ic="AWAITING_RESULT",Nt="BYE",oo="CANCELLED",le="COMPLETED",au="DEAD_RUBBER",Mt="DEFAULTED",Ce="DOUBLE_DEFAULT",he="DOUBLE_WALKOVER",Ln="IN_PROGRESS",pn="INCOMPLETE",RU="NOT_PLAYED",rr="RETIRED",ss="SUSPENDED",Qt="TO_BE_PLAYED",Ct="WALKOVER",gb=[ic,le,Mt,Ln,pn,rr,ss],wh=[ic,le,Mt,he,Ce,Ln,pn,rr,ss,Ct],Lh=[br,ic,Nt,oo,le,au,Mt,he,Ce,Ln,pn,RU,rr,ss,Qt,Ct],Fh=[Nt,he,Ce,le,Mt,rr,Ct],kh=[br,ic,oo,au,Ln,pn,RU,ss,Qt,void 0],ce=[oo,br,le,au,Mt,he,Ce,rr,Ct],Km=[br,le,Mt,he,Ce,Ln,rr,Ct],Gh=[Ln,pn,ss,Qt],Vh={ABANDONED:br,AWAITING_RESULT:ic,BYE:Nt,CANCELLED:oo,COMPLETED:le,DEAD_RUBBER:au,DEFAULTED:Mt,DOUBLE_WALKOVER:he,DOUBLE_DEFAULT:Ce,IN_PROGRESS:Ln,INCOMPLETE:pn,NOT_PLAYED:RU,RETIRED:rr,SUSPENDED:ss,TO_BE_PLAYED:Qt,WALKOVER:Ct};function Si(t,e,r){let n=m=>dt({element:m,name:Mn})?.extension?.value,o=r?.deprioritizeCompleted,i=r?.mode===aU&&zC,s=r?.mode===sU&&cU,a=s||i||ks,c=m=>m?.stage===nt&&m?.stageSequence===1,u=m=>c(m)?-1:a[m?.stage],p=m=>m?.matchUps.every(({matchUpStatus:d})=>ce.includes(d)?1:-1);return o&&p(t)-p(e)||i&&u(t)-u(e)||(t?.stage&&a[t.stage]||0)-(e?.stage&&a[e.stage]||0)||(n(t)||0)-(n(e)||0)||!s&&!i&&(e?.positionAssignments?.length??1/0)-(t?.positionAssignments?.length??1/0)||(t?.stageSequence??0)-(e?.stageSequence??0)||(Of(t)||0)-(Of(e)||0)}function Of(t){return(t?.matchUps||[]).reduce((e,r)=>{let n=(r.finishingPositionRange?.winner||[]).reduce((o,i)=>o+i,0);return!e||n<e?n:e},void 0)}function at(t){let e=rt(t,[{[Ve]:!0,[Zc]:!0}]);if(e.error)return e;let{drawDefinition:r,structureId:n}=t,{structures:o}=gn({drawDefinition:r}),i=o?.map(c=>c.structures?[...c.structures].concat(c):c).flat(),s=i?.find(c=>c.structureId===n);if(!s)return{error:kt};let a=s.structureType===ap?i?.find(c=>c.structures?.some(u=>u.structureId===n)):void 0;return{structure:s,containingStructure:a}}function gn({withStageGrouping:t,drawDefinition:e,stageSequences:r,stageSequence:n,roundTarget:o,sortConfig:i,stages:s,stage:a}){let c=!e&&Z||!e?.structures&&Gl||void 0;if(c)return{error:c,structures:[],stageStructures:{}};let u=f=>{let g=dt({element:f,name:Mn})?.extension?.value;return!o||o===g},p=e?.structures?.filter(d).filter(l).filter(u).sort((f,g)=>Si(f,g,i))??[],m=t?Object.assign({},...$c.map(f=>{let g=p?.filter(I=>I.stage===f);return g?.length&&{[f]:g}}).filter(Boolean)):{};return{structures:p,stageStructures:m};function d(f){return!a&&!Array.isArray(s)||a&&f.stage===a||Array.isArray(s)&&s.includes(f.stage)}function l(f){return!n&&!Array.isArray(r)||n&&f.stageSequence===n||Array.isArray(r)&&r.includes(f.stageSequence)}}function Bh({drawDefinition:t}){if(!t)return{error:Z};let e={};return{allPositionedParticipantIds:(t.structures||[]).map(n=>{let o=n.stage;e[o]||(e[o]=[]);let{positionAssignments:i}=bt({structure:n}),s=i?.map(St).filter(Boolean)??[];return e[o].push(...s),s}).flat(),stagePositionedParticipantIds:e}}function bt({drawDefinition:t,structureId:e,structure:r}){let n,o=[];if(!r){if(!t)return{positionAssignments:o,error:Z};if({structure:r,error:n}=at({drawDefinition:t,structureId:e}),n)return{positionAssignments:o,error:n}}return r.structures?o=[].concat(...r.structures.map(i=>bt({structure:i}).positionAssignments)):r.positionAssignments?o=r.positionAssignments:n=$A,{positionAssignments:o,error:n}}function Se({drawDefinition:t,structureId:e,structure:r}){let n=bt({drawDefinition:t,structureId:e,structure:r})?.positionAssignments||[],o=n?.filter(u=>u.participantId??u.bye??u.qualifier),i=n&&n?.length===o?.length,s=n?.filter(u=>!u.participantId&&!u.bye&&!u.qualifier),a=n?.filter(u=>!u.participantId&&u.bye),c=n?.filter(u=>!u.participantId&&u.qualifier);return{allPositionsAssigned:i,positionAssignments:n,unassignedPositions:s,assignedPositions:o,qualifierPositions:c,byePositions:a}}var _f="addDrawDefinition",hp="addMatchUps",Zo="addParticipants",xf="addScaleItems",CU="addEvent",Hh="addVenue",Ti="audit",Wh="dataIssue",wf="deleteParticipants",Lf="deleteVenue",Ff="deletedDrawIds",kf="deletedMatchUpIds",Gf="modifyDrawDefinition",bU="modifyDrawEntries",vU="modifyEventEntries",Vf="modifyMatchUp",nr="modifyParticipants",Bf="modifyPositionAssignments",Hf="modifySeedAssignments",Bi="modifyTournamentDetail",yi="modifyVenue",zm="mutations",jh="publishEvent",OU="publishEventSeeding",_U="publishOrderOfPlay",xU="publishParticipants",Wf="unPublishEvent",jf="unPublishEventSeeding",Yf="unPublishOrderOfPlay",Ib="unPublishParticipants",Sp="updateInContextMatchUp",hb={ADD_DRAW_DEFINITION:_f,ADD_MATCHUPS:hp,ADD_PARTICIPANTS:Zo,ADD_SCALE_ITEMS:xf,ADD_EVENT:CU,ADD_VENUE:Hh,AUDIT:Ti,DATA_ISSUE:Wh,DELETE_PARTICIPANTS:wf,DELETE_VENUE:Lf,DELETED_DRAW_IDS:Ff,DELETED_MATCHUP_IDS:kf,MODIFY_DRAW_DEFINITION:Gf,MODIFY_DRAW_ENTRIES:bU,MODIFY_EVENT_ENTRIES:vU,MODIFY_MATCHUP:Vf,MODIFY_PARTICIPANTS:nr,MODIFY_POSITION_ASSIGNMENTS:Bf,MODIFY_SEED_ASSIGNMENTS:Hf,MODIFY_TOURNAMENT_DETAIL:Bi,MODIFY_VENUE:yi,MUTATIONS:zm,PUBLISH_EVENT_SEEDING:OU,PUBLISH_EVENT:jh,PUBLISH_ORDER_OF_PLAY:_U,PUBLISH_PARTICIPANTS:xU,UNPUBLISH_EVENT_SEEDING:jf,UNPUBLISH_EVENT:Wf,UNPUBLISH_ORDER_OF_PLAY:Yf,UPDATE_INCONTEXT_MATCHUP:Sp};function Yh(t,e){if(!t)return{error:Z};let r=Date.now();t.updatedAt&&r===new Date(t.updatedAt).getTime()&&(r+=1);let n=new Date(r).toISOString(),o=e?.filter(Boolean);return t.updatedAt=n,t.structures?.filter(Boolean).forEach(i=>{(!o?.length||o?.includes(i.structureId))&&(i.updatedAt=n)}),{...C}}function Co({drawDefinition:t,tournamentId:e,matchUps:r,eventId:n}){return t&&Yh(t),mt({payload:{matchUps:r,tournamentId:e,eventId:n},topic:hp}),{...C}}function Yn({drawDefinition:t,tournamentId:e,matchUpIds:r,eventId:n,action:o}){t&&Yh(t),mt({topic:kf,payload:{tournamentId:e,matchUpIds:r,eventId:n,action:o}});for(let i of r)YI({key:i});return{...C}}function gt({drawDefinition:t,tournamentId:e,structureId:r,context:n,eventId:o,matchUp:i}){return i?(t&&Ot({drawDefinition:t,structureIds:r?[r]:void 0,tournamentId:e,eventId:o}),mt({topic:Vf,payload:{matchUp:i,tournamentId:e,context:n},key:i.matchUpId}),{...C}):(console.log(hr),{error:hr})}function Sb({tournamentId:t,inContextMatchUp:e}){return e?(mt({payload:{inContextMatchUp:e,tournamentId:t},topic:Sp,key:e.matchUpId}),{...C}):{error:hr}}function Ta({tournamentId:t,eventId:e,drawDefinition:r}){return r?(Yh(r),mt({payload:{drawDefinition:r,tournamentId:t,eventId:e},topic:_f,key:r.drawId}),{...C}):(console.log(Z),{error:Z})}function Tb({tournamentId:t,eventId:e,drawId:r}){return mt({payload:{drawId:r,tournamentId:t,eventId:e},topic:Ff,key:r}),YI({key:r}),{...C}}function Ot({drawDefinition:t,tournamentId:e,structureIds:r,eventId:n}){return t?(Yh(t,r),mt({payload:{tournamentId:e,eventId:n,drawDefinition:t},topic:Gf,key:t.drawId}),{...C}):{error:Z}}function qh({drawDefinition:t,tournamentId:e,structure:r,eventId:n}){if(!t)return{error:Z};if(!r)return{error:pi};let o=r.seedAssignments,i=r.structureId,s=t.drawId;return mt({payload:{tournamentId:e,eventId:n,drawId:s,structureId:i,seedAssignments:o},topic:Hf,key:t.drawId}),Ot({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:n}),{...C}}function bo({drawDefinition:t,tournamentId:e,structure:r,event:n}){if(!t)return{error:Z};if(!r)return{error:pi};let o=bt({structure:r}),i=r.structureId,s=t.drawId,a=n?.eventId;return mt({topic:Bf,payload:{positionAssignments:o,tournamentId:e,structureId:i,eventId:a,drawId:s},key:i}),Ot({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:a}),{...C}}function wU({tournamentRecord:t,drawDefinition:e,resetEntries:r,event:n}){if(!e)return{error:Z};let o=e.structures?.find(s=>s.stage===$e);if(!o)return{error:kt};let i=o.matchUps?.map(({matchUpId:s})=>s)||[];return o.positionAssignments=[],o.seedAssignments=[],o.matchUps=[],Yn({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:i,drawDefinition:e}),r&&(e.entries=e.entries.filter(s=>s.entryStage!==$e)),Ot({tournamentId:t?.tournamentId,eventId:n?.eventId,drawDefinition:e,structureIds:[o.structureId]}),{...C}}function Qm({drawPositions:t,structure:e}){if([ct,nt].includes(e.stage)&&e.stageSequence===1)return;let{positionAssignments:r}=bt({structure:e});r?.filter(({drawPosition:o})=>t?.includes(o))?.forEach(o=>{At({element:o,extension:{name:Hm,value:!0}})})}function cu(t){let{appliedPolicies:e,positionAction:r,drawDefinition:n}=t;if(e?.audit?.[nc]===!1)return;let{extension:o}=dt({name:nc,element:n}),i=Array.isArray(o?.value)?o?.value??[]:[];if(!i?.length){let a=n.structures.find(c=>c.stage===nt);if(a){let c=bt({structure:a}).positionAssignments?.map(({drawPosition:u,participantId:p,bye:m,qualifier:d})=>({drawPosition:u,participantId:p,qualifier:d,bye:m}));i.push({name:"initialMainAssignments",initialAssignments:c})}}let s={value:i.concat(r),name:nc};At({element:n,extension:s})}function as({tournamentRecord:t,drawDefinition:e,event:r}){let o=(t?.events||r&&[r])?.map(c=>c?.drawDefinitions).flat().filter(Boolean)||e&&[e]||[],i={},s={},a=o.map(c=>c?.structures?.filter(u=>u?.structures)).flat().filter(Boolean);for(let c of a){let{structures:u,structureId:p}=c??{};u&&p&&(i[p]=u?.map(m=>m.structureId))&&u.forEach(m=>s[m.structureId]=c?.structureId)}return{containedStructures:i,containerStructures:s}}function uu(t){let{sides:e,matchUpType:r}=t||{},n=t.potentialParticipants?.length?t.potentialParticipants.flat().map(s=>r===_t?s?.individualParticipantIds||[]:s.participantId).flat():[],o=(e||[]).map(s=>r===_t&&(s?.participant?.individualParticipantIds||[])||s?.participantId&&[s.participantId]||[]).flat();return{individualParticipantIds:o.concat(n).flat(),enteredIndividualParticipantIds:o,potentialIndividualParticipantIds:n}}function Dr(t){return t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{}}var sc="SIGN_IN_STATUS",LU="SIGNED_OUT",pu="SIGNED_IN",yr="TEAM",Tt="INDIVIDUAL",zr="GROUP",ft="PAIR",Lt="TEAM",mu={TEAM_PARTICIPANT:yr,INDIVIDUAL:Tt,GROUP:zr,TEAM:Lt,PAIR:ft},yb={INDIVIDUAL:Tt,GROUP:zr,PAIR:ft,TEAM:Lt,SIGN_IN_STATUS:sc,SIGNED_OUT:LU,SIGNED_IN:pu};function Xm({participantsProfile:t,participants:e=[],deepCopy:r}){let n=new Map,o=r!==!1?J(e,t?.convertExtensions,!0):e,i=o.filter(c=>c.participantType===Lt),s=o.filter(c=>c.participantType===zr),a=o.filter(c=>c.participantType===ft);return o.forEach(c=>{if(c.participantType===Tt){let{participantId:u}=c;c.groupParticipantIds=[],c.teamParticipantIds=[],c.pairParticipantIds=[],c.groups=[],c.teams=[],i.forEach(p=>{(p?.individualParticipantIds||[]).forEach(m=>{m===u&&!c.teamParticipantIds?.includes(p.participantId)&&(c.teamParticipantIds.push(p.participantId),n.get(p.participantId)||n.set(p.participantId,{participantName:p.participantName,participantId:p.participantId}),c.teams.push({participantRoleResponsibilities:p.participantRoleResponsibilities,participantOtherName:p.participantOtherName,participantName:p.participantName,participantId:p.participantId,teamId:p.teamId}))})}),a.forEach(p=>{(p?.individualParticipantIds||[]).forEach(m=>{m===u&&!c.pairParticipantIds.includes(p.participantId)&&c.pairParticipantIds.push(p.participantId)})}),s.forEach(p=>{(p?.individualParticipantIds||[]).forEach(m=>{m===u&&!c.groupParticipantIds.includes(p.participantId)&&(c.groupParticipantIds.push(p.participantId),c.groups.push({participantRoleResponsibilities:p.participantRoleResponsibilities,participantOtherName:p.participantOtherName,participantName:p.participantName,participantId:p.participantId}))})})}}),{participantsWithGroupings:o,groupInfo:Object.fromEntries(n)}}function FU(t){return t&&typeof String.fromCodePoint<"u"?t.toUpperCase().replace(/./g,e=>String.fromCodePoint(e.charCodeAt(0)+127397)):t}function Ab(t){let e=Object.assign({},...ti.filter(r=>r.ioc).map(r=>({[r.ioc]:r.iso})));return FU(e[t])}var ti=[{ioc:"",iso2:"",iso:"",label:"NONE",phone:""},{ioc:"AND",iso2:"AD",iso:"AND",label:"Andorra",phone:"376"},{ioc:"UAE",iso2:"AE",iso:"ARE",label:"United Arab Emirates",phone:"971"},{ioc:"AFG",iso2:"AF",iso:"AFG",label:"Afghanistan",phone:"93"},{ioc:"ANT",iso2:"AG",iso:"ATG",label:"Antigua and Barbuda",phone:"1-268"},{ioc:"AIA",iso2:"AI",iso:"AIA",label:"Anguilla",phone:"1-264"},{ioc:"ALB",iso2:"AL",iso:"ALB",label:"Albania",phone:"355"},{ioc:"ARM",iso2:"AM",iso:"ARM",label:"Armenia",phone:"374"},{ioc:"ANG",iso2:"AO",iso:"AGO",label:"Angola",phone:"244"},{ioc:"",iso2:"AQ",iso:"ATA",label:"Antarctica",phone:"672"},{ioc:"ARG",iso2:"AR",iso:"ARG",label:"Argentina",phone:"54"},{ioc:"ASA",iso2:"AS",iso:"ASM",label:"American Samoa",phone:"1-684"},{ioc:"AUT",iso2:"AT",iso:"AUT",label:"Austria",phone:"43"},{ioc:"AUS",iso2:"AU",iso:"AUS",label:"Australia",phone:"61",suggested:!0},{ioc:"ARU",iso2:"AW",iso:"ABW",label:"Aruba",phone:"297"},{ioc:"AZE",iso2:"AZ",iso:"AZE",label:"Azerbaijan",phone:"994"},{ioc:"BIH",iso2:"BA",iso:"BIH",label:"Bosnia and Herzegovina",phone:"387"},{ioc:"BAR",iso2:"BB",iso:"BRB",label:"Barbados",phone:"1-246"},{ioc:"BAN",iso2:"BD",iso:"BGD",label:"Bangladesh",phone:"880"},{ioc:"BEL",iso2:"BE",iso:"BEL",label:"Belgium",phone:"32"},{ioc:"BUR",iso2:"BF",iso:"BFA",label:"Burkina Faso",phone:"226"},{ioc:"BUL",iso2:"BG",iso:"BGR",label:"Bulgaria",phone:"359"},{ioc:"BRN",iso2:"BH",iso:"BHR",label:"Bahrain",phone:"973"},{ioc:"BDI",iso2:"BI",iso:"BDI",label:"Burundi",phone:"257"},{ioc:"BEN",iso2:"BJ",iso:"BEN",label:"Benin",phone:"229"},{ioc:"",iso2:"BL",iso:"BLM",label:"Saint Barthelemy",phone:"590"},{ioc:"BER",iso2:"BM",iso:"BMU",label:"Bermuda",phone:"1-441"},{ioc:"BRU",iso2:"BN",iso:"BRN",label:"Brunei Darussalam",phone:"673"},{ioc:"BOL",iso2:"BO",iso:"BOL",label:"Bolivia",phone:"591"},{ioc:"BRA",iso2:"BR",iso:"BRA",label:"Brazil",phone:"55"},{ioc:"BAH",iso2:"BS",iso:"BHS",label:"Bahamas",phone:"1-242"},{ioc:"BHU",iso2:"BT",iso:"BTN",label:"Bhutan",phone:"975"},{ioc:"",iso2:"BV",iso:"BVT",label:"Bouvet Island",phone:"47"},{ioc:"BOT",iso2:"BW",iso:"BWA",label:"Botswana",phone:"267"},{ioc:"BLR",iso2:"BY",iso:"BLR",label:"Belarus",phone:"375"},{ioc:"BIZ",iso2:"BZ",iso:"BLZ",label:"Belize",phone:"501"},{ioc:"CAN",iso2:"CA",iso:"CAN",label:"Canada",phone:"1",suggested:!0},{ioc:"",iso2:"CC",iso:"CCK",label:"Cocos (Keeling) Islands",phone:"61"},{ioc:"CGO",iso2:"CD",iso:"COG",label:"Congo, Republic of the",phone:"242"},{ioc:"CAF",iso2:"CF",iso:"CAF",label:"Central African Republic",phone:"236"},{ioc:"COD",iso2:"CG",iso:"CGD",label:"Congo, Democratic Republic of the",phone:"243"},{ioc:"SUI",iso2:"CH",iso:"CHE",label:"Switzerland",phone:"41"},{ioc:"CIV",iso2:"CI",iso:"CIV",label:"Cote d'Ivoire",phone:"225"},{ioc:"COK",iso2:"CK",iso:"COK",label:"Cook Islands",phone:"682"},{ioc:"CHI",iso2:"CL",iso:"CHL",label:"Chile",phone:"56"},{ioc:"CMR",iso2:"CM",iso:"CMR",label:"Cameroon",phone:"237"},{ioc:"CHN",iso2:"CN",iso:"CHN",label:"China",phone:"86"},{ioc:"COL",iso2:"CO",iso:"COL",label:"Colombia",phone:"57"},{ioc:"CRC",iso2:"CR",iso:"CRI",label:"Costa Rica",phone:"506"},{ioc:"CUB",iso2:"CU",iso:"CUB",label:"Cuba",phone:"53"},{ioc:"CPV",iso2:"CV",iso:"CPV",label:"Cape Verde",phone:"238"},{ioc:"CUW",iso2:"CW",iso:"CUW",label:"Curacao",phone:"599"},{ioc:"CXR",iso2:"CX",iso:"CXR",label:"Christmas Island",phone:"61"},{ioc:"CYP",iso2:"CY",iso:"CYP",label:"Cyprus",phone:"357"},{ioc:"CZE",iso2:"CZ",iso:"CZE",label:"Czech Republic",phone:"420"},{ioc:"GER",iso2:"DE",iso:"DEU",label:"Germany",phone:"49",suggested:!0},{ioc:"DJI",iso2:"DJ",iso:"DJI",label:"Djibouti",phone:"253"},{ioc:"DEN",iso2:"DK",iso:"DNK",label:"Denmark",phone:"45"},{ioc:"DMA",iso2:"DM",iso:"DMA",label:"Dominica",phone:"1-767"},{ioc:"DOM",iso2:"DO",iso:"DOM",label:"Dominican Republic",phone:"1-809"},{ioc:"ALG",iso2:"DZ",iso:"DZA",label:"Algeria",phone:"213"},{ioc:"ECU",iso2:"EC",iso:"ECU",label:"Ecuador",phone:"593"},{ioc:"EST",iso2:"EE",iso:"ESE",label:"Estonia",phone:"372"},{ioc:"EGY",iso2:"EG",iso:"EGY",label:"Egypt",phone:"20"},{ioc:"",iso2:"EH",iso:"ESH",label:"Western Sahara",phone:"212"},{ioc:"ERI",iso2:"ER",iso:"ERI",label:"Eritrea",phone:"291"},{ioc:"ESP",iso2:"ES",iso:"ESP",label:"Spain",phone:"34"},{ioc:"ETH",iso2:"ET",iso:"ETH",label:"Ethiopia",phone:"251"},{ioc:"FIN",iso2:"FI",iso:"FIN",label:"Finland",phone:"358"},{ioc:"FIJ",iso2:"FJ",iso:"FJI",label:"Fiji",phone:"679"},{ioc:"FLK",iso2:"FK",iso:"FLK",label:"Falkland Islands (Malvinas)",phone:"500"},{ioc:"FSM",iso2:"FM",iso:"FSM",label:"Micronesia, Federated States of",phone:"691"},{ioc:"FAR",iso2:"FO",iso:"FRO",label:"Faroe Islands",phone:"298"},{ioc:"FRA",iso2:"FR",iso:"FRA",label:"France",phone:"33",suggested:!0},{ioc:"GAB",iso2:"GA",iso:"GAB",label:"Gabon",phone:"241"},{ioc:"GBR",iso2:"GB",iso:"GBR",label:"United Kingdom",phone:"44"},{ioc:"GRN",iso2:"GD",iso:"GRD",label:"Grenada",phone:"1-473"},{ioc:"GEO",iso2:"GE",iso:"GEO",label:"Georgia",phone:"995"},{ioc:"FGU",iso2:"GF",iso:"GUF",label:"French Guiana",phone:"594"},{ioc:"",iso2:"GG",iso:"GGY",label:"Guernsey",phone:"44"},{ioc:"",iso2:"GH",iso:"GHA",label:"Ghana",phone:"233"},{ioc:"GIB",iso2:"GI",iso:"GIB",label:"Gibraltar",phone:"350"},{ioc:"GRL",iso2:"GL",iso:"GRL",label:"Greenland",phone:"299"},{ioc:"GAM",iso2:"GM",iso:"GMB",label:"Gambia",phone:"220"},{ioc:"GUI",iso2:"GN",iso:"GIN",label:"Guinea",phone:"224"},{ioc:"GUD",iso2:"GP",iso:"GLP",label:"Guadeloupe",phone:"590"},{ioc:"GEQ",iso2:"GQ",iso:"GNQ",label:"Equatorial Guinea",phone:"240"},{ioc:"GRE",iso2:"GR",iso:"GRC",label:"Greece",phone:"30"},{ioc:"",iso2:"GS",iso:"SGS",label:"South Georgia and the South Sandwich Islands",phone:"500"},{ioc:"GUA",iso2:"GT",iso:"GTM",label:"Guatemala",phone:"502"},{ioc:"GUM",iso2:"GU",iso:"GUM",label:"Guam",phone:"1-671"},{ioc:"GBS",iso2:"GW",iso:"GNB",label:"Guinea-Bissau",phone:"245"},{ioc:"GUY",iso2:"GY",iso:"GUY",label:"Guyana",phone:"592"},{ioc:"HKG",iso2:"HK",iso:"HKG",label:"Hong Kong",phone:"852"},{ioc:"",iso2:"HM",iso:"HMD",label:"Heard Island and McDonald Islands",phone:"672"},{ioc:"HON",iso2:"HN",iso:"HND",label:"Honduras",phone:"504"},{ioc:"CRO",iso2:"HR",iso:"HRV",label:"Croatia",phone:"385"},{ioc:"HAI",iso2:"HT",iso:"HTI",label:"Haiti",phone:"509"},{ioc:"HUN",iso2:"HU",iso:"HUN",label:"Hungary",phone:"36"},{ioc:"INA",iso2:"ID",iso:"IDN",label:"Indonesia",phone:"62"},{ioc:"IRL",iso2:"IE",iso:"IRL",label:"Ireland",phone:"353"},{ioc:"ISR",iso2:"IL",iso:"ISR",label:"Israel",phone:"972"},{ioc:"",iso2:"IM",iso:"IMN",label:"Isle of Man",phone:"44"},{ioc:"IND",iso2:"IN",iso:"IND",label:"India",phone:"91"},{ioc:"",iso2:"IO",iso:"IOT",label:"British Indian Ocean Territory",phone:"246"},{ioc:"IRQ",iso2:"IQ",iso:"IRQ",label:"Iraq",phone:"964"},{ioc:"IRI",iso2:"IR",iso:"IRN",label:"Iran, Islamic Republic of",phone:"98"},{ioc:"ISL",iso2:"IS",iso:"ISL",label:"Iceland",phone:"354"},{ioc:"ITA",iso2:"IT",iso:"ITA",label:"Italy",phone:"39"},{ioc:"",iso2:"JE",iso:"JEY",label:"Jersey",phone:"44"},{ioc:"JAM",iso2:"JM",iso:"JAM",label:"Jamaica",phone:"1-876"},{ioc:"JOR",iso2:"JO",iso:"JOR",label:"Jordan",phone:"962"},{ioc:"JPN",iso2:"JP",iso:"JPN",label:"Japan",phone:"81",suggested:!0},{ioc:"KEN",iso2:"KE",iso:"KEN",label:"Kenya",phone:"254"},{ioc:"KGZ",iso2:"KG",iso:"KGZ",label:"Kyrgyzstan",phone:"996"},{ioc:"CAM",iso2:"KH",iso:"KHM",label:"Cambodia",phone:"855"},{ioc:"KIR",iso2:"KI",iso:"KIR",label:"Kiribati",phone:"686"},{ioc:"COM",iso2:"KM",iso:"COM",label:"Comoros",phone:"269"},{ioc:"SKN",iso2:"KN",iso:"KNA",label:"Saint Kitts and Nevis",phone:"1-869"},{ioc:"KOR",iso2:"KP",iso:"KOR",label:"Korea, Democratic People's Republic of",phone:"850"},{ioc:"PRK",iso2:"KR",iso:"PRK",label:"Korea, Republic of",phone:"82"},{ioc:"KUW",iso2:"KW",iso:"KWT",label:"Kuwait",phone:"965"},{ioc:"CAY",iso2:"KY",iso:"CYM",label:"Cayman Islands",phone:"1-345"},{ioc:"KAZ",iso2:"KZ",iso:"KAZ",label:"Kazakhstan",phone:"7"},{ioc:"LAO",iso2:"LA",iso:"LAO",label:"Lao People's Democratic Republic",phone:"856"},{ioc:"LIB",iso2:"LB",iso:"LBN",label:"Lebanon",phone:"961"},{ioc:"LCA",iso2:"LC",iso:"LCA",label:"Saint Lucia",phone:"1-758"},{ioc:"LIE",iso2:"LI",iso:"LIE",label:"Liechtenstein",phone:"423"},{ioc:"SRI",iso2:"LK",iso:"LKA",label:"Sri Lanka",phone:"94"},{ioc:"LBR",iso2:"LR",iso:"LBR",label:"Liberia",phone:"231"},{ioc:"LES",iso2:"LS",iso:"LSO",label:"Lesotho",phone:"266"},{ioc:"LTU",iso2:"LT",iso:"LTU",label:"Lithuania",phone:"370"},{ioc:"LUX",iso2:"LU",iso:"LUX",label:"Luxembourg",phone:"352"},{ioc:"LAT",iso2:"LV",iso:"LVA",label:"Latvia",phone:"371"},{ioc:"LBA",iso2:"LY",iso:"LBY",label:"Libya",phone:"218"},{ioc:"MAR",iso2:"MA",iso:"MAR",label:"Morocco",phone:"212"},{ioc:"MON",iso2:"MC",iso:"MCO",label:"Monaco",phone:"377"},{ioc:"MDA",iso2:"MD",iso:"MDA",label:"Moldova, Republic of",phone:"373"},{ioc:"MNE",iso2:"ME",iso:"MNE",label:"Montenegro",phone:"382"},{ioc:"",iso2:"MF",iso:"MAF",label:"Saint Martin (French part)",phone:"590"},{ioc:"MAD",iso2:"MG",iso:"MDG",label:"Madagascar",phone:"261"},{ioc:"MSH",iso2:"MH",iso:"MHL",label:"Marshall Islands",phone:"692"},{ioc:"MKD",iso2:"MK",iso:"MKD",label:"Macedonia, the Former Yugoslav Republic of",phone:"389"},{ioc:"MLI",iso2:"ML",iso:"MLI",label:"Mali",phone:"223"},{ioc:"MYA",iso2:"MM",iso:"MMR",label:"Myanmar",phone:"95"},{ioc:"MGL",iso2:"MN",iso:"MNG",label:"Mongolia",phone:"976"},{ioc:"MAC",iso2:"MO",iso:"MAC",label:"Macao",phone:"853"},{ioc:"NMA",iso2:"MP",iso:"NMP",label:"Northern Mariana Islands",phone:"1-670"},{ioc:"MRT",iso2:"MQ",iso:"MTQ",label:"Martinique",phone:"596"},{ioc:"MTN",iso2:"MR",iso:"MRT",label:"Mauritania",phone:"222"},{ioc:"MNT",iso2:"MS",iso:"MSR",label:"Montserrat",phone:"1-664"},{ioc:"MLT",iso2:"MT",iso:"MLT",label:"Malta",phone:"356"},{ioc:"MRI",iso2:"MU",iso:"MUS",label:"Mauritius",phone:"230"},{ioc:"MDV",iso2:"MV",iso:"MDV",label:"Maldives",phone:"960"},{ioc:"MAW",iso2:"MW",iso:"MWI",label:"Malawi",phone:"265"},{ioc:"MEX",iso2:"MX",iso:"MEX",label:"Mexico",phone:"52"},{ioc:"MAS",iso2:"MY",iso:"MYS",label:"Malaysia",phone:"60"},{ioc:"MOZ",iso2:"MZ",iso:"MOZ",label:"Mozambique",phone:"258"},{ioc:"NAM",iso2:"NA",iso:"NAM",label:"Namibia",phone:"264"},{ioc:"NCL",iso2:"NC",iso:"NCL",label:"New Caledonia",phone:"687"},{ioc:"NIG",iso2:"NE",iso:"NER",label:"Niger",phone:"227"},{ioc:"NFI",iso2:"NF",iso:"NFK",label:"Norfolk Island",phone:"672"},{ioc:"NGR",iso2:"NG",iso:"NGA",label:"Nigeria",phone:"234"},{ioc:"NCA",iso2:"NI",iso:"NIC",label:"Nicaragua",phone:"505"},{ioc:"NED",iso2:"NL",iso:"NLD",label:"Netherlands",phone:"31"},{ioc:"NOR",iso2:"NO",iso:"NOR",label:"Norway",phone:"47"},{ioc:"NEP",iso2:"NP",iso:"NPL",label:"Nepal",phone:"977"},{ioc:"NRU",iso2:"NR",iso:"NRU",label:"Nauru",phone:"674"},{ioc:"NIU",iso2:"NU",iso:"NIU",label:"Niue",phone:"683"},{ioc:"NZL",iso2:"NZ",iso:"NZL",label:"New Zealand",phone:"64"},{ioc:"OMA",iso2:"OM",iso:"OMN",label:"Oman",phone:"968"},{ioc:"PAN",iso2:"PA",iso:"PAN",label:"Panama",phone:"507"},{ioc:"PER",iso2:"PE",iso:"PER",label:"Peru",phone:"51"},{ioc:"FPO",iso2:"PF",iso:"PYF",label:"French Polynesia",phone:"689"},{ioc:"PNG",iso2:"PG",iso:"PNG",label:"Papua New Guinea",phone:"675"},{ioc:"PHI",iso2:"PH",iso:"PHL",label:"Philippines",phone:"63"},{ioc:"PAK",iso2:"PK",iso:"PAK",label:"Pakistan",phone:"92"},{ioc:"POL",iso2:"PL",iso:"POL",label:"Poland",phone:"48"},{ioc:"SPM",iso2:"PM",iso:"SPM",label:"Saint Pierre and Miquelon",phone:"508"},{ioc:"",iso2:"PN",iso:"PCN",label:"Pitcairn",phone:"870"},{ioc:"PUR",iso2:"PR",iso:"PRI",label:"Puerto Rico",phone:"1"},{ioc:"PLE",iso2:"PS",iso:"PSE",label:"Palestine, State of",phone:"970"},{ioc:"POR",iso2:"PT",iso:"PRT",label:"Portugal",phone:"351"},{ioc:"PLW",iso2:"PW",iso:"PLW",label:"Palau",phone:"680"},{ioc:"PAR",iso2:"PY",iso:"PRY",label:"Paraguay",phone:"595"},{ioc:"QAT",iso2:"QA",iso:"QAT",label:"Qatar",phone:"974"},{ioc:"REU",iso2:"RE",iso:"REU",label:"Reunion",phone:"262"},{ioc:"ROU",iso2:"RO",iso:"ROU",label:"Romania",phone:"40"},{ioc:"SRB",iso2:"RS",iso:"SRB",label:"Serbia",phone:"381"},{ioc:"RUS",iso2:"RU",iso:"RUS",label:"Russia",phone:"7"},{ioc:"RWA",iso2:"RW",iso:"RWA",label:"Rwanda",phone:"250"},{ioc:"KSA",iso2:"SA",iso:"SAU",label:"Saudi Arabia",phone:"966"},{ioc:"SOL",iso2:"SB",iso:"SLB",label:"Solomon Islands",phone:"677"},{ioc:"SEY",iso2:"SC",iso:"SYC",label:"Seychelles",phone:"248"},{ioc:"SUD",iso2:"SD",iso:"SDN",label:"Sudan",phone:"249"},{ioc:"SWE",iso2:"SE",iso:"SWE",label:"Sweden",phone:"46"},{ioc:"SIN",iso2:"SG",iso:"SGP",label:"Singapore",phone:"65"},{ioc:"HEL",iso2:"SH",iso:"SHN",label:"Saint Helena",phone:"290"},{ioc:"SLO",iso2:"SI",iso:"SVN",label:"Slovenia",phone:"386"},{ioc:"",iso2:"SJ",iso:"SJM",label:"Svalbard and Jan Mayen",phone:"47"},{ioc:"SVK",iso2:"SK",iso:"SVK",label:"Slovakia",phone:"421"},{ioc:"SLE",iso2:"SL",iso:"SLE",label:"Sierra Leone",phone:"232"},{ioc:"SMR",iso2:"SM",iso:"SMR",label:"San Marino",phone:"378"},{ioc:"SEN",iso2:"SN",iso:"SEN",label:"Senegal",phone:"221"},{ioc:"SOM",iso2:"SO",iso:"SOM",label:"Somalia",phone:"252"},{ioc:"SUR",iso2:"SR",iso:"SUR",label:"Suriname",phone:"597"},{ioc:"",iso2:"SS",iso:"SSD",label:"South Sudan",phone:"211"},{ioc:"STP",iso2:"ST",iso:"STP",label:"Sao Tome and Principe",phone:"239"},{ioc:"ESA",iso2:"SV",iso:"SLV",label:"El Salvador",phone:"503"},{ioc:"",iso2:"SX",iso:"SMX",label:"Sint Maarten",phone:"1-721"},{ioc:"SYR",iso2:"SY",iso:"SYR",label:"Syria",phone:"963"},{ioc:"",iso2:"SZ",iso:"SWZ",label:"Swaziland",phone:"268"},{ioc:"TKS",iso2:"TC",iso:"TCA",label:"Turks and Caicos Islands",phone:"1-649"},{ioc:"CHA",iso2:"TD",iso:"TCD",label:"Chad",phone:"235"},{ioc:"",iso2:"TF",iso:"ATF",label:"French Southern Territories",phone:"262"},{ioc:"TOG",iso2:"TG",iso:"TGO",label:"Togo",phone:"228"},{ioc:"THA",iso2:"TH",iso:"THA",label:"Thailand",phone:"66"},{ioc:"TJK",iso2:"TJ",iso:"TJK",label:"Tajikistan",phone:"992"},{ioc:"",iso2:"TK",iso:"TKL",label:"Tokelau",phone:"690"},{ioc:"TLS",iso2:"TL",iso:"TLS",label:"Timor-Leste",phone:"670"},{ioc:"TKM",iso2:"TM",iso:"TKM",label:"Turkmenistan",phone:"993"},{ioc:"TUN",iso2:"TN",iso:"TUN",label:"Tunisia",phone:"216"},{ioc:"TGA",iso2:"TO",iso:"TON",label:"Tonga",phone:"676"},{ioc:"TUR",iso2:"TR",iso:"TUR",label:"Turkey",phone:"90"},{ioc:"TTO",iso2:"TT",iso:"TTO",label:"Trinidad and Tobago",phone:"1-868"},{ioc:"TUV",iso2:"TV",iso:"TUV",label:"Tuvalu",phone:"688"},{ioc:"TPE",iso2:"TW",iso:"TWN",label:"Taiwan",phone:"886"},{ioc:"TAN",iso2:"TZ",iso:"TZA",label:"United Republic of Tanzania",phone:"255"},{ioc:"UKR",iso2:"UA",iso:"UKR",label:"Ukraine",phone:"380"},{ioc:"UGA",iso2:"UG",iso:"UGA",label:"Uganda",phone:"256"},{ioc:"USA",iso2:"US",label:"United States",phone:"1",suggested:!0,iso:"USA"},{ioc:"URU",iso2:"UY",iso:"URY",label:"Uruguay",phone:"598"},{ioc:"UZB",iso2:"UZ",iso:"UZB",label:"Uzbekistan",phone:"998"},{ioc:"",iso2:"VA",iso:"VAT",label:"Holy See (Vatican City State)",phone:"379"},{ioc:"VIN",iso2:"VC",iso:"VCT",label:"Saint Vincent and the Grenadines",phone:"1-784"},{ioc:"VEN",iso2:"VE",iso:"VEN",label:"Venezuela",phone:"58"},{ioc:"IVB",iso2:"VG",iso:"VGB",label:"British Virgin Islands",phone:"1-284"},{ioc:"ISV",iso2:"VI",iso:"VIR",label:"US Virgin Islands",phone:"1-340"},{ioc:"VIE",iso2:"VN",iso:"VNM",label:"Vietnam",phone:"84"},{ioc:"VAN",iso2:"VU",iso:"VUT",label:"Vanuatu",phone:"678"},{ioc:"WAF",iso2:"WF",iso:"WLF",label:"Wallis and Futuna",phone:"681"},{ioc:"SAM",iso2:"WS",iso:"WSM",label:"Samoa",phone:"685"},{ioc:"KOS",iso2:"XK",iso:"KOS",label:"Kosovo",phone:"383"},{ioc:"YEM",iso2:"YE",iso:"YEM",label:"Yemen",phone:"967"},{ioc:"MAY",iso2:"YT",iso:"MYT",label:"Mayotte",phone:"262"},{ioc:"RSA",iso2:"ZA",iso:"ZAF",label:"South Africa",phone:"27"},{ioc:"ZAM",iso2:"ZM",iso:"ZMB",label:"Zambia",phone:"260"},{ioc:"ZIM",iso2:"ZW",iso:"ZWE",label:"Zimbabwe",phone:"263"}];function $h({participant:t,withISO2:e,withIOC:r}){let{person:n,individualParticipants:o}=t,i=[n,o?.map(({person:a})=>a)].flat().filter(Boolean);function s(a){let{nationalityCode:c}=a||{};if(c){let u=ti.find(({iso:p})=>p===c);r&&u?.ioc&&!a.iocNationalityCode&&(a.iocNationalityCode=u.ioc),e&&u?.iso2&&!a.iso2NationalityCode&&(a.iso2NationalityCode=u.iso2),u?.label&&!a.countryName&&(a.countryName=u.label)}}i.forEach(s)}function Eb({participantMap:t,template:e}){let r=Object.values(t);for(let n of r){let o=n.participant;if(o.individualParticipantIds?.length){o.individualParticipants=[];for(let i of o.individualParticipantIds){let s=t[i].participant;o.individualParticipants.push(e?Vi({template:e,source:s}):s)}}}}function To(t){let{tournamentRecord:e,participantId:r}=t,n=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};for(let o of Object.values(n)){let i=o.participants?.find(s=>s.participantId===r);if(i)return{participant:i,tournamentId:o.tournamentId}}return{error:te}}function Kh(t){let{tournamentRecord:e,participantId:r}=t;if(r){let o=To({tournamentRecord:e,participantId:r});return o.participant??o}let n=t.element||t.drawDefinition||t.event||t.tournamentRecord;return n||{error:st}}function rn(t){let{returnPreviousValues:e,itemSubTypes:r,itemType:n}=t,o=Kh(t);if(o.error)return o;if(r&&!Array.isArray(r))return{error:G,context:{itemSubTypes:r}};if(!Array.isArray(o.timeItems))return{error:tf};let i=o.timeItems.filter(a=>a?.itemType===n).filter(a=>!r?.length||r.some(c=>a?.itemSubTypes?.includes(c))).sort((a,c)=>{let u=new Date(a.createdAt||void 0).getTime(),p=new Date(c.createdAt||void 0).getTime();return u-p}),s=J(i.pop(),!1,!0);if(s){let a={timeItem:s,...C};return e&&Object.assign(a,{previousItems:i}),a}else return{info:ve}}function zh({returnPreviousValues:t,drawDefinition:e,itemSubTypes:r,itemType:n}){if(!e)return{error:an};if(!e.timeItems)return{info:ve};let{timeItem:o,previousItems:i,info:s}=rn({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function du({returnPreviousValues:t,itemSubTypes:e,itemType:r,event:n}){if(!n)return{error:vt};if(!n.timeItems)return{info:ve};let{timeItem:o,previousItems:i,info:s}=rn({returnPreviousValues:t,element:n,itemSubTypes:e,itemType:r});return o&&{timeItem:o,previousItems:i}||{info:s}}function Jm({returnPreviousValues:t,tournamentRecord:e,itemSubTypes:r,itemType:n}){if(!e)return{error:Y};if(!e.timeItems)return{info:ve};let{timeItem:o,previousItems:i,info:s}=rn({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function Qh({returnPreviousValues:t,tournamentRecord:e,participantId:r,itemSubTypes:n,itemType:o}){if(!e)return{error:Y};if(!r)return{error:oe};let i=To({tournamentRecord:e,participantId:r});if(i.error)return i;let{participant:s}=i;if(!s?.timeItems)return{info:ve};let{timeItem:a,previousItems:c,info:u}=rn({element:i.participant,returnPreviousValues:t,itemSubTypes:n,itemType:o});return a&&{timeItem:a,previousItems:c}||{info:u}}var JF={[zr]:"groupParticipantIds",[ft]:"pairParticipantIds",[Lt]:"teamParticipantIds"},ZF={[zr]:"groups",[Lt]:"teams"};function Xh({withIndividualParticipants:t,convertExtensions:e,tournamentRecord:r,withSignInStatus:n,withScaleValues:o,internalUse:i,withISO2:s,withIOC:a}){let c=[],u={};for(let p of r.participants??[]){let m=p?.participantId;m&&rk({participantMap:u,participantId:m})}for(let p of r.participants??[]){let m=J(p,e,i),{participantId:d,individualParticipantIds:l,participantType:f}=m;if(!u[d]){c.push(d);continue}if(Object.assign(u[d].participant,m),l){let g=ek({individualParticipantIds:l,participantCopy:m,participantMap:u,participantType:f,participantId:d});g.missingParticipantIds.length&&c.push(...g.missingParticipantIds)}if(n&&(u[d].participant.signedIn=tk(m)),o){let{ratings:g,rankings:I,seedings:h}=la({participant:m});u[d].participant.seedings=h,u[d].participant.rankings=I,u[d].participant.ratings=g}(a||s)&&$h({participant:u[d].participant,withISO2:s,withIOC:a})}if(t){let p=ht(t)?t:void 0;Eb({participantMap:u,template:p})}return{missingParticipantIds:c,participantMap:u}}function tk(t){let{timeItem:e}=rn({itemType:sc,element:t});return e?.itemValue===pu}function ek({individualParticipantIds:t,participantCopy:e,participantMap:r,participantType:n,participantId:o}){let i=[];for(let s of t){let a=r[s]?.participant;if(!a){i.push(s);continue}if(a[JF[n]].push(o),[Lt,zr].includes(n)){let{participantRoleResponsibilities:c,participantOtherName:u,participantName:p,participantId:m,teamId:d}=e,l=ZF[n];a[l].push({participantRoleResponsibilities:c,participantOtherName:u,participantName:p,participantId:m,teamId:d})}if(n===ft){let c=t.find(u=>u!==s);r[s].pairIdMap[o]=c,r[s].pairIdMap[c]=o}}return{missingParticipantIds:i}}function rk({participantMap:t,participantId:e}){if(t[e])return;let r={walkoverWins:0,defaultWins:0,walkovers:0,defaults:0,losses:0,wins:0};t[e]={structureParticipation:{},potentialMatchUps:{},scheduleConflicts:{},scheduleItems:[],participant:{groupParticipantIds:[],pairParticipantIds:[],teamParticipantIds:[],seedings:{},rankings:{},ratings:{},groups:[],teams:[]},statistics:{},opponents:{},pairIdMap:{},matchUps:{},events:{},draws:{},counters:{[xt]:{...r},[_t]:{...r},[Lt]:{...r},...r}}}function Ai({participantsProfile:t,useParticipantMap:e,tournamentRecord:r,contextProfile:n,inContext:o}){if(e)return{participantMap:Xh({...t,...n,tournamentRecord:r})?.participantMap};let i=J(r.participants,!1,!0)||[];(t?.withIOC||t?.withISO2)&&i.forEach(a=>$h({participant:a,...t}));let s;if((o||t?.withGroupings)&&i?.length&&({participantsWithGroupings:i,groupInfo:s}=Xm({participantsProfile:t,deepCopy:!1,participants:i})),t?.withScaleValues&&i?.length)for(let a of i){let{ratings:c,rankings:u}=la({participant:a});a.rankings=u,a.ratings=c}return{participants:i,groupInfo:s}}function yt({onlySpecifiedPolicyTypes:t=!1,policyTypes:e=[],tournamentRecord:r,drawDefinition:n,structure:o,event:i}){if(!Array.isArray(e))return{error:wI};let s={};return r&&a(r),i&&a(i),n&&a(n),o&&a(o),{appliedPolicies:s,...C};function a(c){let p=c?.extensions?.find(m=>m.name===nu)?.value;if(p)for(let m of Object.keys(p))(t?e.includes(m):!e.length||e.includes(m))&&(s[m]=J(p[m],!1,!0))}}function vo({policyTypes:t=[],tournamentRecord:e,drawDefinition:r,structure:n,event:o}){if(!Array.isArray(t))return{error:wI};let{appliedPolicies:i}=yt({tournamentRecord:e,drawDefinition:r,structure:n,event:o}),s={};for(let a of t){let c=i?.[a];c&&(s[a]=c)}return Object.keys(s).length?{policyDefinitions:s}:{info:Fc.message}}var Jh="WALKOVER",kU="RETIRED",Zm="COMPETITIVE",ac="ROUTINE",cc="DECISIVE",td="winRatio";var nk={[hi]:{policyName:"Competitive Bands Default",profileBands:{[cc]:20,[ac]:50}}},ed=nk;function qn({policyDefinitions:t,tournamentRecord:e,contextProfile:r,drawDefinition:n,event:o}){let i={policies:{}};if(!r)return i;let s=vo({tournamentRecord:e,drawDefinition:n,event:o}).policyDefinitions;if(r.withCompetitiveness){let a=t?.[hi]??s?.[hi]??ed[hi];i.policies[hi]=a}return i}function ei({tournamentRecord:t,drawDefinition:e,policyType:r,structure:n,event:o}){if(!t)return{error:Y};let{appliedPolicies:i}=yt({tournamentRecord:t,drawDefinition:e,structure:n,event:o});return i?.[r]?{policy:i[r]}:{info:Fc?.message}}function ya({tournamentRecord:t,categoryName:e,categoryType:r,event:n}){e=e??n?.category?.categoryName??n?.category?.ageCategoryCode,r=r??n?.category?.categoryType??n?.category?.subType;let{policy:o}=ei({policyType:No,tournamentRecord:t,event:n}),s=(t?dt({element:t,name:Vo}).extension:void 0)?.value,c=(n&&dt({name:Vo,element:n}).extension)?.value;return{scheduleTiming:{tournamentScheduling:s,eventScheduling:c,categoryName:e,categoryType:r,policy:o}}}function qf({drawDefinition:t,attributes:e}){let{extension:r}=dt({element:t,name:jm}),n=r?.value||{};return e.forEach(o=>{Object.keys(o).forEach(i=>{n[i]?Object.assign(n[i],o[i]):n[i]=o[i]})}),r={name:jm,value:n},fp({drawDefinition:t,extension:r}),{entryProfile:n}}function lu({drawDefinition:t}){let{extension:e}=dt({element:t,name:jm});return{entryProfile:e?.value||{}}}var nn="ALTERNATE",$f="CONFIRMED",kr="DIRECT_ACCEPTANCE",rd="FEED_IN",Kf="JUNIOR_EXEMPT",cs="LUCKY_LOSER",zf="ORGANISER_ACCEPTANCE",nd="QUALIFIER",ok="REGISTERED",Qf="SPECIAL_EXEMPT",Gr="UNGROUPED",Ei="UNPAIRED",fu="WILDCARD",io="WITHDRAWN",Xf=[$f,kr,Kf,zf,Qf],GU=[rd,cs,nd],ri=[$f,kr,rd,Kf,zf,Qf,fu],Qr=[$f,kr,Kf,cs,nd,zf,Qf,fu],VU=[nn,$f,kr,rd,Kf,cs,zf,nd,ok,Qf,Gr,Ei,fu,io],Ub={ALTERNATE:nn,CONFIRMED:$f,DIRECT_ACCEPTANCE:kr,DIRECT_ENTRY_STATUSES:ri,DRAW_SPECIFIC_STATUSES:GU,EQUIVALENT_ACCEPTANCE_STATUSES:Xf,FEED_IN:rd,JUNIOR_EXEMPT:Kf,LUCKY_LOSER:cs,ORGANISER_ACCEPTANCE:zf,QUALIFIER:nd,SPECIAL_EXEMPT:Qf,STRUCTURE_SELECTED_STATUSES:Qr,UNGROUPED:Gr,UNPAIRED:Ei,VALID_ENTRY_STATUSES:VU,WILDCARD:fu,WITHDRAWN:io};function Jf({stage:t,drawDefinition:e}){let{entryProfile:r}=lu({drawDefinition:e}),n=Object.keys(r).includes(t);if(!n&&$c.includes(t)){let o=[{[t]:{drawSize:void 0,alternates:!0}}];return qf({drawDefinition:e,attributes:o}),!0}return n}function Pb({stage:t,drawDefinition:e}){let{entryProfile:r}=lu({drawDefinition:e});return r[t]?.alternates||0}function Db({stage:t,drawDefinition:e}){let{entryProfile:r}=lu({drawDefinition:e});return r[t]?.wildcardsCount||0}function Zh({stage:t,drawDefinition:e,entryStatus:r}){return e.entries.reduce((n,o)=>o.entryStage===t&&o.entryStatus===r?n+1:n,0)}function Ui({provisionalPositioning:t,placementGroup:e,drawDefinition:r,stageSequence:n,entryStatuses:o,structureId:i,roundTarget:s,stages:a,stage:c}){let u=r.entries?.reduce((p,m)=>{let d=dt({name:Mn,element:m})?.extension?.value,l=c&&m.entryStage===c||a?.length&&m.entryStage&&a.includes(m.entryStage),f=!o||m.entryStatus&&o.includes(m.entryStatus),g=m.entryStageSequence??1;return l&&(!n||g===n)&&f&&(!s||!d||s===d)?p.concat(m):p},[])??[];if(i&&c===de){let{playoffEntries:p,error:m}=ik({provisionalPositioning:t,drawDefinition:r,structureId:i});return m&&console.log("playoff entries error"),(p?.length?p:u).filter(d=>!e||d.placementGroup===e)}return u}function ik({provisionalPositioning:t,drawDefinition:e,structureId:r}){let n=[],o=(e.links??[]).find(i=>i.linkType===to&&i.target.structureId===r);if(o){let{finishingPositions:i,structureId:s}=o.source,{structure:a}=at({drawDefinition:e,structureId:s});a?.structureType===Ge&&(a.structures??[]).forEach(u=>{let p=u.positionAssignments??[],{structureId:m}=u,d=m,l=Object.assign({},...p.map(h=>{let{participantId:S}=h,T=dt({element:h,name:Jo}).extension?.value;return T&&S?{[S]:T}:void 0}).filter(Boolean)),g=Object.keys(l).reduce((h,S)=>{let T=l[S],y=T.groupOrder||t&&T.provisionalOrder;return h.includes(y)||h.push(y),h},[]).length===Object.keys(l).length,I=Object.keys(l).filter(h=>{let S=l[h],T=S.groupOrder||t&&S.provisionalOrder;return i?.includes(T)});(!t||g)&&I.forEach(h=>{let S=l[h],{groupOrder:T,provisionalOrder:y,GEMscore:P}=S,U=T||t&&y,E=[...i??[]].sort(me).indexOf(U)+1;n.push({entryStage:de,entryStatus:rd,placementGroup:E,groupingValue:d,participantId:h,GEMscore:P})})})}return{playoffEntries:n}}function Nb({stage:t,drawDefinition:e}){return ri.reduce((r,n)=>(Zh({drawDefinition:e,entryStatus:n,stage:t})||0)+r,0)}function on({provisionalPositioning:t,returnAllProxies:e,drawDefinition:r,structureId:n,structure:o}){let i,s=[];o||({structure:o,error:i}=at({drawDefinition:r,structureId:n}));let a=bt({structure:o}).positionAssignments;if(i||!o)return{seedAssignments:[],error:kt};n||(n=o.structureId);let{stage:c,stageSequence:u}=o,m=c===de&&r&&Ui({provisionalPositioning:t,drawDefinition:r,stageSequence:u,structureId:n,stage:c}),d=m?m.filter(g=>g.placementGroup===1).sort((g,I)=>g.GEMscore<I.GEMscore&&1||g.GEMscore>I.GEMscore&&-1||0).map((g,I)=>{let h=I+1;return{participantId:g.participantId,seedValue:h,seedProxy:!0,seedNumber:h}}):[],l=d?.slice(0,e?d.length:a.length/2);l.length?s=l:o.seedAssignments?s=o.seedAssignments:i=FA;let f=o.seedLimit??o?.positionAssignments?.length;return{seedAssignments:s,stageSequence:u,seedLimit:f,stage:c,error:i}}function ni(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 Tp({item:t,drawDefinition:e,structure:r,event:n}){if(t){if(t.tieFormat)return t.tieFormat;if(t.tieFormatId){if(e.tieFormat)return e.tieFormat;let o=e.tieFormats?.find(i=>t.tieFormatId===i.tieFormatId);return o||(n.tieFormat?n.tieFormat:n.tieFormats?.find(i=>t.tieFormatId===i.tieFormatId))}if(r.tieFormat)return r.tieFormat;if(r.tieFormatId){let o=e.tieFormats?.find(i=>r.tieFormatId===i.tieFormatId);if(o)return o}}}function We({drawDefinition:t,structure:e,matchUp:r,event:n}){return{tieFormat:Tp({item:r,drawDefinition:t,structure:e,event:n})||Tp({item:e,drawDefinition:t,structure:e,event:n})||ni(t)||ni(n)}}function Mb({matchUps:t}){let e=t.reduce((n,o)=>!o.collectionPosition||n.includes(o.collectionPosition)?n:n.concat(o.collectionPosition),[]).map(n=>({[n]:t.filter(o=>o.collectionPosition===n)}));return{collectionPositionMatchUps:Object.assign({},...e)}}function Ne({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 oi({mappedMatchUps:t,matchUpsMap:e,structureId:r,inContext:n}){t=e?.mappedMatchUps??t;let o=t[r],i=(o?.itemStructureIds||[]).map(s=>{let{matchUps:a,structureName:c}=t[s];return n?a.map(u=>Object.assign(J(u,!0,!0),{containerStructureId:r,structureId:s,structureName:c})):a}).flat();return(o?.matchUps||[]).concat(...i)}function tS({groupedOrder:t,roundPositionsCount:e}){if(!t||t?.length<=e)return t;let n=ye(t,t.length/e).map(i=>i.reduce((s,a)=>s+a)),o=n.slice().sort(me);return n.map(i=>o.indexOf(i)+1)}function Zf(t){if(!ht(t))return!1;let{matchUpId:e,drawPositions:r}=t,n=typeof e=="string",o=!r||Array.isArray(r)&&r.length<=2&&r.every(i=>It(i)||i===void 0||i===null);return n&&o}function Vr(t){return Array.isArray(t)?t.every(Zf):!1}function Ke({matchUps:t=[],interpolate:e}){if(!Vr(t))return{roundMatchUps:[],error:G};let r=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?pt(l.roundNumber):l.roundNumber;return!l.roundNumber||d.includes(f)?d:d.concat(f)},[]).sort(me).map(d=>{let l=t.filter(h=>h.roundNumber===d),g=l.find(({matchUpType:h})=>h===jt)?l.filter(({matchUpType:h})=>h===jt):l,I=h=>h.sort((S,T)=>me(S.roundPosition,T.roundPosition));return{[d]:I(g)}}),n=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?pt(l.roundNumber):l.roundNumber;return d[f]||(d[f]=ot({abbreviatedRoundName:l.abbreviatedRoundName,finishingRound:l.finishingRound,roundName:l.roundName})),d},{}),o=Object.assign({},...r);if(e){let d=Math.max(...Object.keys(o).map(f=>pt(f)).filter(f=>!isNaN(f))),l=o[d]?.length;if(l>1&&vn(l)){let f=d+1,g=f+l/2;et(f,g).forEach((h,S)=>{o[h]=et(0,l/(2+S*2)).map(()=>({}))})}}let i=0,s=Object.assign({},...Object.keys(o).map(d=>{let l=o[d]?.length,f=o[d]?.filter(I=>!ce.includes(I.matchUpStatus)&&!I.score?.scoreStringSide1)?.length,g=l&&l===f;return i=Math.max(i,l),{[d]:{matchUpsCount:l,inactiveCount:f,inactiveRound:g}}})),a=0,c=0,u=Object.keys(o).map(d=>pt(d)).filter(d=>!isNaN(d));u.forEach(d=>{let l=o[d].sort((g,I)=>g.roundPosition-I.roundPosition),f=l.map(g=>g?.drawPositions||[]).flat();if(s[d].roundNumber=d,s[d].roundFactor=s[d].matchUpsCount?i/s[d].matchUpsCount:1,s[d].finishingRound=n[d]?.finishingRound,s[d].roundName=n[d]?.roundName,s[d].abbreviatedRoundName=n[d]?.abbreviatedRoundName,s[d].finishingPositionRange=o[d]?.[0]?.finishingPositionRange,d===1||!s[d-1]){let g=f.sort(me),I=ye(g,2);s[d].drawPositions=g,s[d].pairedDrawPositions=I}else{let g=s[d-1],I=g.drawPositions,h=g.matchUpsCount/s[d].matchUpsCount,S=ye(I,h),T=l.map(y=>{let{roundPosition:P}=y,U=[...y.drawPositions||[],void 0,void 0].slice(0,2);if(!P)return U;let E=U?.filter(Boolean)||[];if(!E?.length)return[void 0,void 0];if(d<3&&E?.length===2)return U?.slice().sort(me);let A=Yt(I,E).length!==E?.length;if(E?.length&&A)return E?.length===1?[E[0],void 0]:U?.slice().sort(me);let N=(P-1)*2;return S.slice(N,N+2).map(M=>E?.find(R=>M.includes(R)))});s[d].drawPositions=T?.flat(),s[d].pairedDrawPositions=T}s[d+1]&&s[d+1].matchUpsCount===s[d].matchUpsCount&&(s[d+1].feedRound=!0,s[d+1].feedRoundIndex=c,s[d].preFeedRound=!0,c+=1),s[d]&&!s[d].feedRound&&(s[d].roundIndex=a,a+=1)});let p=!!Object.values(s).find(({matchUpsCount:d})=>!vn(d));return{hasNoRoundPositions:t.some(d=>!d.roundPosition),roundsNotPowerOf2:p,maxMatchUpsCount:i,roundMatchUps:o,roundNumbers:u,roundProfile:s,...C}}function od(t){if(!Array.isArray(t))return"";let e=t.filter(Zt);return e.length?ut([Math.min(...e),Math.max(...e)]).join("-"):""}function Rb({drawDefinition:t,structureId:e,matchUpsMap:r}){if(!t)return{error:Z};if(!e)return{error:Er};let{structure:n}=at({drawDefinition:t,structureId:e});if(n?.stage!==qe)return{error:Oi,info:"Structure is not CONSOLATION stage"};let{links:o}=t,i=o?.filter(m=>m.target.structureId===e)||[],s=i?.reduce((m,d)=>{let{structureId:l}=d.source;return m.includes(l)?m:m.concat(l)},[])||[],a=Object.assign({},...s.map(m=>{let d=oi({structureId:m,matchUpsMap:r}),f=Ke({matchUps:d}).roundProfile;return{[m]:f}})),c=oi({matchUpsMap:r,structureId:e}),{roundProfile:u}=Ke({matchUps:c}),p={};return i?.forEach(m=>{let{structureId:d,roundNumber:l}=m.source,{feedProfile:f,groupedOrder:g,positionInterleave:I,roundNumber:h}=m.target,S=a[d],T=S[1]?.drawPositions,P=S[l]?.matchUpsCount;if(!P)return;let U=P?T.length/P:0,E=T.length/U,A=T.slice(),N=tS({roundPositionsCount:E,groupedOrder:g}),D=N?.length||1;if(D<=E){let v=T.length/D,O=ye(A,v);f===di&&O.forEach(x=>x.reverse()),A=N?.length&&N?.map(x=>O[x-1]).flat()||A}let M=ye(A,U);if(I){let v=et(0,I.interleave).map(()=>{}),O=et(0,I.offset).map(()=>{});M=M.map(F=>[F,...v]),M.unshift(O),M=M.flat(1);let x=M.length-I.offset;M=M.slice(0,x)}p[h]||(p[h]={});let b=u?.[h]?.feedRound?2:1;M.forEach((v,O)=>{let x=1+O*b;p[h][x]||(p[h][x]=od(v))})}),{sourceDrawPositionRanges:p}}function eS({drawDefinition:t}){if(typeof t!="object")return{error:ua};let e={},{structures:r=[],links:n=[]}=t||{},o=r.reduce((s,a)=>{let{stage:c}=a;return s[c]?s[c].push(a):s[c]=[a],s},{});for(let s of Object.keys(o)){let a=o[s].find(({stageSequence:p})=>p===1);if(!a)continue;let{structureId:c}=a;i({aggregator:{},targetRound:0,exitProfiles:e,exitProfile:"0",structureId:c,stage:s})}return{exitProfiles:e};function i({exitProfiles:s,exitProfile:a,structureId:c,targetRound:u,aggregator:p,stage:m}){s[c]||(s[c]=[]),a==="0"&&[qe,de].includes(m)||s[c].push(a);let d=n.filter(l=>l.source.structureId===c&&l.source.roundNumber>=u);for(let l of d){let f=l.source.roundNumber,g=l.target.roundNumber,I=l.target.structureId,h=r.find(T=>T.structureId===I).stage,S=[h,I,g,f].join("|");if(p[S])return;p[S]=!0,i({exitProfile:`${a}-${f}`,structureId:I,exitProfiles:s,targetRound:g,aggregator:p,stage:h})}}}function Cb({drawDefinition:t,roundProfile:e,structureId:r,matchUpsMap:n}){if(!t)return{error:Z};if(!r)return{error:Er};if(!e){let c=oi({matchUpsMap:n,structureId:r});if({roundProfile:e}=Ke({matchUps:c}),!e)return{error:st}}let i=(Math.min(...e?.[1]?.drawPositions??[])||1)-1,s=Object.keys(e);return{drawPositionsRanges:Object.assign({},...(s||[]).map(c=>{let u=e?.[c]?.matchUpsCount,p=e?.[1]?.drawPositions??[],m=ye(p,p.length/u),d=m.map(od),l=m.map(S=>S.map(T=>T-i)).map(od),f=s.map(S=>{if(S>c)return;let T=e?.[S]?.drawPositions??[];return ye(T,T.length/u)}).filter(Boolean),g=et(0,u).map(S=>f.map(T=>T[S]).flat().filter(Boolean).sort(me)).map(S=>ut(S)),I=g.map(S=>lC(S).map(od).join(", ")),h=Object.assign({},...et(0,u).map(S=>({[S+1]:{firstRoundDrawPositionsRange:d[S],firstRoundOffsetDrawPositionsRange:l[S],possibleDrawPositions:g[S],drawPositionsRange:I[S]}})));return{[c]:h}}))}}function id({roundsNotPowerOf2:t,drawDefinition:e,structure:r,matchUps:n}){if(!r)return!1;n=n??r.matchUps??[],t=t??Ke({matchUps:n}).roundsNotPowerOf2;let o=!!r.positionAssignments?.find(({drawPosition:i})=>i)||!!n?.find(({drawPositions:i})=>i?.length);return(!e?.drawType||e.drawType!==ki)&&!r?.structures&&t&&o}function cr({structure:t}){if(!t)return!1;let e=t.matchUps||t.roundMatchUps&&Object.values(t.roundMatchUps).flat(),r=!!e?.find(o=>o?.roundPosition),n=!!e?.find(o=>o?.drawPositions?.length);return!t?.structures&&t?.stage!==$e&&(!e.length||!r&&!n)}var tg={[fa]:{policyName:"Round Naming Default",namingConventions:{round:"Round",pre:"Pre"},qualifyingFinishMap:{1:"Final"},abbreviatedRoundNamingMap:{1:"F",2:"SF",4:"QF"},roundNamingMap:{1:"Final",2:"Semifinal",4:"Quarterfinal"},affixes:{roundNumber:"R",preFeedRound:"Q",preQualifying:"P"},stageConstants:{[nt]:"",[de]:"P",[ct]:"Q",[qe]:"C"}}},bb=tg;function vb({roundNamingPolicy:t,drawDefinition:e,structure:r,matchUps:n}){let{roundProfile:o,roundMatchUps:i}=Ke({matchUps:n}),{structureAbbreviation:s,stage:a}=r,c=cr({structure:r}),u=id({structure:r}),p=r.structures,m={},d=tg[fa],l=r.stage===ct,f=l?Math.max(...(e?.structures??[]).filter(b=>b.stage===ct).map(({stageSequence:b})=>b??1),0):0,g=(r.stageSequence??1)<f?r.stageSequence??1:"",I=g&&(t?.affixes?.preQualifying||d.affixes.preQualifying)||"",h=t?.roundNamingMap||d.roundNamingMap||{},S=t?.abbreviatedRoundNamingMap||d.abbreviatedRoundNamingMap||{},T=t?.affixes?.preFeedRound||d.affixes.preFeedRound,y=t?.affixes?.roundNumber||d.affixes.roundNumber,U=(t?.namingConventions||d.namingConventions).round,E=a&&a!==nt?a[0]:"",A=t?.stageConstants||d.stageConstants,N=a&&A?.[a]||E,D=`${I}${N}${g}`,M=o?Object.keys(o):[],R=l&&A?.[ct]?`${A?.[ct]}-`:"";if(p||c||u)Object.assign(m,...M.map(b=>{let v=`${R}${U} ${b}`,O=`${y}${b}`;return{[b]:{roundName:v,abbreviatedRoundName:O}}}));else{let b=l&&(t?.qualifyingFinishMap||d?.qualifyingFinishMap||{});Object.assign(m,...M.map(v=>{if(!o?.[v])return;let{matchUpsCount:O,preFeedRound:x}=o[v],F=O*2,L=b?.[o?.[v].finishingRound]||b&&`${y}${F}`||h[O]||`${y}${F}`,w=x?`-${T}`:"",V=`${L}${w}`,k=[D,s,V].filter(Boolean).join("-"),H=`${S[O]||`${y}${F}`}${w}`,K=[D,s,H].filter(Boolean).join("-");return{[v]:{abbreviatedRoundName:K,roundName:k}}}))}return{roundNamingProfile:m,roundProfile:o,roundMatchUps:i}}var sk=(t,e)=>(t||0)+(e||0);function rS(t,e){let r=Array.isArray(t)?t[0]:t;return isNaN(r)&&Jh||r<=e[cc]&&cc||r<=e[ac]&&ac||Zm}function nS({score:t}){let e=t?.sets||[],r=e.reduce((o,i)=>(o[0]+=i.side1Score||0,o[1]+=i.side2Score||0,o),[0,0]),n=e.reduce((o,i)=>(o[0]+=i.side1TiebreakScore||0,o[1]+=i.side2TiebreakScore||0,o),[0,0]);return n.reduce(sk)&&(r[n[0]>n[1]?0:1]+=1),{sets:e,games:r,score:t}}function ak(t){let e=Math.min(...t.games),r=Math.max(...t.games);return Math.round(e/r*100)}function oS(t){return t.map(ak).sort().map(e=>parseFloat(e.toFixed(2)))}function gu({tournamentRecord:t,profileBands:e,matchUp:r}){if(!r)return{error:hr};let{score:n,winningSide:o}=r;if(!o)return{error:G};let i=!e&&t&&ei({policyType:hi,tournamentRecord:t}).policy,s=e||i?.profileBands||ed[hi].profileBands,a=nS({score:n}),c=oS([a]),u=rS(c,s),p=Array.isArray(c)?c[0]:c;return{...C,competitiveness:u,pctSpread:p}}function iS({matchUp:t}){if(!t)return{error:hr};if(t&&!t.sides)return{error:dr};if(t&&!t.hasContext)return{error:Gc};let e=(t.sides??[])?.map(a=>a?.participantId).filter(Boolean),r=t.sides?.filter(a=>a.participant?.participantType===Tt).map(a=>a.participantId).filter(Boolean)??[],o=((t.sides??[])?.map(a=>a.participant?.individualParticipants).filter(Boolean)??[]).map(a=>(a??[]).map(c=>c?.participantId).filter(Boolean)),i=[...r,...o.flat()].filter(Boolean)??[],s=ut(i.concat(e)).filter(Boolean)??[];return{nestedIndividualParticipantIds:o,allRelevantParticipantIds:s,individualParticipantIds:i,sideParticipantIds:e,...C}}var sd="CHECK_IN",ad="CHECK_OUT",ck="SCHEDULE",Hi="SCHEDULE.ASSIGNMENT.VENUE",so="SCHEDULE.ALLOCATION.COURTS",Bo="SCHEDULE.ASSIGNMENT.COURT",yp="SCHEDULE.COURT.ORDER",Wi="SCHEDULE.DATE",uk="COMPLETED.DATE",cd="HOME_PARTICIPANT_ID",eg="SCHEDULE.ASSIGN.OFFICIAL",ji="SCHEDULE.TIME.SCHEDULED",Oo="SCHEDULE.TIME.START",Yi="SCHEDULE.TIME.STOP",Pi="SCHEDULE.TIME.RESUME",Di="SCHEDULE.TIME.END",Ap="SCHEDULE.TIME.MODIFIERS",Ob="TO_BE_ANNOUNCED",_b="NEXT_AVAILABLE",xb="FOLLOWED_BY",wb="AFTER_REST",Lb="RAIN_DELAY",pk="NOT_BEFORE",sS=[Ob,_b,xb,wb,Lb],mk="ELIGIBILITY",dk="REGISTRATION",lk="SUSPENSION",fk="MEDICAL",gk="PENALTY",BU="SCALE",HU="RATING",WU="RANKING",rg="SEEDING",_o="PUBLISH",Nr="PUBLIC",xo="STATUS",Ik="MODIFICATION",hk="RETRIEVAL",Sk="other",Fb={MUTUALLY_EXCLUSIVE_TIME_MODIFIERS:sS,AFTER_REST:wb,ALLOCATE_COURTS:so,ASSIGN_COURT:Bo,ASSIGN_OFFICIAL:eg,ASSIGN_VENUE:Hi,CHECK_IN:sd,CHECK_OUT:ad,COMPLETED_DATE:uk,COURT_ORDER:yp,ELIGIBILITY:mk,END_TIME:Di,FOLLOWED_BY:xb,MEDICAL:fk,MODIFICATION:Ik,NEXT_AVAILABLE:_b,NOT_BEFORE:pk,OTHER:Sk,PENALTY:gk,PUBLIC:Nr,PUBLISH:_o,RANKING:WU,RATING:HU,RAIN_DELAY:Lb,REGISTRATION:dk,RESUME_TIME:Pi,RETRIEVAL:hk,SCALE:BU,SCHEDULE:ck,SCHEDULED_DATE:Wi,SCHEDULED_TIME:ji,SEEDING:rg,START_TIME:Oo,STATUS:xo,STOP_TIME:Yi,SUSPENSION:lk,TIME_MODIFIERS:Ap,TO_BE_ANNOUNCED:Ob};function us({matchUp:t}){if(!t)return{error:hr};if(!t.hasContext)return{error:Gc};if(!t.sides||t.sides.filter(Boolean).length!==2)return{error:dr};let{nestedIndividualParticipantIds:e,allRelevantParticipantIds:r,sideParticipantIds:n}=iS({matchUp:t}),i=(t.timeItems??[]).filter(u=>u?.itemType&&[sd,ad].includes(u.itemType)).sort((u,p)=>(u.createdAt?new Date(u.createdAt).getTime():0)-(p.createdAt?new Date(p.createdAt).getTime():0)),a=i.map(u=>u.itemValue).filter(u=>i.filter(p=>p?.itemValue===u).reverse()[0].itemType===sd);e?.forEach((u,p)=>{let m=n?.[p],d=u?.length&&u.every(l=>a.includes(l));m&&d&&!a.includes(m)&&a.push(m)}),n?.forEach((u,p)=>{a.includes(u)&&(e?.[p]??[]).forEach(m=>{m&&!a.includes(m)&&a.push(m)})});let c=n?.reduce((u,p)=>a.includes(p)&&u,!0);return{allRelevantParticipantIds:r,allParticipantsCheckedIn:c,checkedInParticipantIds:a,...C}}var ue=t=>e=>{let r=ht(e)&&e?.matchUpType||Vt(e)&&e;return r&&EI[t].includes(r)};function Ep(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 Up(t){let{matchUpRecoveryTimes:e,averageMinutes:r,matchUpFormat:n}=t||{};return e?.find(({matchUpFormatCodes:o,averageTimes:i,recoveryTimes:s})=>{if(i&&r){let{greaterThan:a=0,lessThan:c=360}=i;if(r>a&&r<c)return!0}return o?.find(a=>a===n)&&s})?.recoveryTimes}function aS({timesBlockArray:t,categoryName:e,categoryType:r}){return t.filter(n=>Array.isArray(n)).map(n=>n.sort((o,i)=>(i.categoryNames?.length||0)-(o.categoryNames?.length||0)).find(({categoryTypes:o,categoryNames:i})=>!i?.length&&!o?.length||i?.includes(e)||o?.includes(r))).find(Boolean)}function kb({tournamentScheduling:t,eventScheduling:e,averageMinutes:r,defaultTiming:n,matchUpFormat:o,categoryName:i,categoryType:s,policy:a}){let c=e?.matchUpRecoveryTimes&&Up({...e,averageMinutes:r,matchUpFormat:o}),u=t?.matchUpRecoveryTimes&&Up({...t,averageMinutes:r,matchUpFormat:o}),p=a?.matchUpRecoveryTimes&&Up({...a,averageMinutes:r,matchUpFormat:o}),m=[c,u,p,a?.defaultTimes?.recoveryTimes,n?.recoveryTimes];return aS({categoryName:i,categoryType:s,timesBlockArray:m})}function Gb({matchUpFormat:t,categoryName:e,categoryType:r,defaultTiming:n,tournamentScheduling:o,eventScheduling:i,policy:s}){let a=i?.matchUpAverageTimes&&Ep({...i,matchUpFormat:t}),c=o?.matchUpAverageTimes&&Ep({...o,matchUpFormat:t}),u=s?.matchUpAverageTimes&&Ep({...s,matchUpFormat:t}),p=[a,c,u,s?.defaultTimes?.averageTimes,n?.averageTimes];return aS({categoryName:e,categoryType:r,timesBlockArray:p})}var jU="DOUBLES_SINGLES",YU="SINGLES_DOUBLES",ao="total",cS="participantConflict",Aa="matchUpConflict",qU="ISSUE_IDS",uc="CONFLICT",pc="WARNING",uS="ERROR",pS="ISSUE",ng="STATE",Vb={SINGLES_DOUBLES:YU,DOUBLES_SINGLES:jU,TOTAL:ao,CONFLICT_MATCHUP_ORDER:Aa,CONFLICT_PARTICIPANTS:cS,SCHEDULE_ISSUE_IDS:qU,SCHEDULE_CONFLICT:uc,SCHEDULE_WARNING:pc,SCHEDULE_ERROR:uS,SCHEDULE_ISSUE:pS,SCHEDULE_STATE:ng};function Iu({defaultAverageMinutes:t=90,defaultRecoveryMinutes:e=0,tournamentRecord:r,matchUpFormat:n,categoryName:o,categoryType:i,eventType:s,event:a}){if(!r)return{error:Y};s=s??a?.eventType??Fs;let c={averageTimes:[{minutes:{default:t}}],recoveryTimes:[{minutes:{default:e}}]},{scheduleTiming:u}=ya({tournamentRecord:r,categoryName:o,categoryType:i,event:a}),p={...u,matchUpFormat:n,categoryType:i,defaultTiming:c};return Pp({eventType:s,timingDetails:p})}function Pp({timingDetails:t,eventType:e}){let r=Gb(t),n=Object.keys(r?.minutes||{}),o=r?.minutes&&(n?.includes(e)&&r.minutes[e]||r.minutes.default),i=kb({...t,averageMinutes:o}),s=Object.keys(i?.minutes||{}),a=i?.minutes&&(s?.includes(e)&&i.minutes[e]||i.minutes.default),c=ue(Fs)(e)?YU:jU,u=i?.minutes&&(s?.includes(c)&&i.minutes[c]||a);return{averageMinutes:o,recoveryMinutes:a,typeChangeRecoveryMinutes:u}}function $U(t){return t.createdAt?new Date(t.createdAt).getTime():0}function Ho({timeItems:t,itemType:e}){let r=t.filter(o=>o&&o.itemType===e).sort((o,i)=>$U(o)-$U(i)).pop(),n=r&&$U(r);return{itemValue:r?.itemValue,timeStamp:n}}function mS({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Ho({timeItems:r?.timeItems||[],itemType:ji});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{scheduledTime:n}:e}function Hs({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Ho({timeItems:r?.timeItems||[],itemType:Wi});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{scheduledDate:n}:e}function Dp(t){if($I.test(t)){let e=If();return new Date(`${e}T${t}`)}else return new Date(t)}function Bb({matchUp:t}){if(!t)return{error:hr};if(!t.timeItems)return{error:tf};let e=t.timeItems.filter(n=>[Oo,Yi,Pi,Di].includes(n?.itemType)).sort((n,o)=>Dp(n.itemValue).getTime()-Dp(o.itemValue).getTime()),r=e.reduce((n,o)=>{let i,s=o?.itemType?.split("."),c=`SCHEDULE.TIME.${o?.itemType?.startsWith("SCHEDULE.TIME")&&s[2]}`;switch(c){case Oo:i=0;break;case Di:if(n.lastValue&&[Oo,Pi].includes(n.lastType)){let u=Dp(o.itemValue).getTime()-Dp(n.lastValue).getTime();i=n.milliseconds+u}else i=n.milliseconds;break;case Yi:if([Oo,"SCHECULE.TIME.RESUME"].includes(n.lastType)){let u=Dp(o.itemValue).getTime()-Dp(n.lastValue).getTime();i=n.milliseconds+u}else i=n.milliseconds;break;default:i=n.milliseconds;break}return{milliseconds:i,lastType:c,lastValue:o.itemValue}},{milliseconds:0,lastType:void 0,lastValue:void 0});if([Oo,Pi].includes(r.lastType)){let n=new Date().getTime()-Dp(r.lastValue).getTime();r.milliseconds+=n}return{milliseconds:r.milliseconds,time:Tk(r.milliseconds),relevantTimeItems:e}}function Tk(t){let e=(r,n=2)=>("00"+r).slice(-n);return e(t/36e5|0)+":"+e(t%36e5/6e4|0)+":"+e(t%6e4/1e3|0)}function Hb({matchUp:t}){let e=t?.timeItems||[],r=i=>i.createdAt?new Date(i.createdAt).getTime():0;return{startTime:e.reduce((i,s)=>{let a=s.itemType===Oo&&s;return a&&(!i||r(a)<r(i))?a:i},void 0)?.itemValue}}function mc(t){let{disableNotice:e,venue:r,context:n}=t;if(typeof r!="object")return{error:G};let o=Dr(t);r.venueId||(r.venueId=Dt());let i;for(let s of Object.values(o)){let a=yk({disableNotice:!0,tournamentRecord:s,context:n,venue:r});if(a?.error)return a;i=a.venue}return e||mt({topic:Hh,payload:{venue:r}}),ot({...C,venue:i})}function yk({tournamentRecord:t,disableNotice:e,context:r,venue:n}){return t?n?(t.venues||(t.venues=[]),n.venueId||(n.venueId=Dt()),t.venues.reduce((i,s)=>i||s.venueId===n.venueId,void 0)?{error:SE}:(r&&At({element:n,extension:{value:r,name:SU}}),t.venues.push(n),e||mt({payload:{venue:n,tournamentId:t.tournamentId},topic:Hh}),{...C,venue:J(n)})):{error:st,info:"missing venue"}:{error:Y}}function Wo({tournamentRecords:t,tournamentRecord:e,venueId:r}){if(!e)return{error:Y};if(!r)return{error:Xo};let o=(e.venues??[]).reduce((i,s)=>s.venueId===r?s:i,void 0);if(!o&&t){let s=(iu({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let a of s){let c=t[a],u=Wo({tournamentRecord:c,venueId:r});if(u.success&&u.venue)return mc({tournamentRecord:e,venue:u.venue}),{...C,venue:o}}}return o?{...C,venue:o}:{error:Li}}function dS({convertExtensions:t,...e}){let{tournamentRecords:r,tournamentRecord:n,venueId:o}=e,i=Wo({tournamentRecords:r,tournamentRecord:n,venueId:o});return J(i,t,!0)}function ps({tournamentRecords:t,tournamentRecord:e,courtId:r}){if(!e)return{error:Y};if(!r)return{error:_i};let n="findCourt",o,i;if((e.venues??[]).forEach(s=>{(s.courts??[]).forEach(a=>{a.courtId===r&&(o=a,i=s)})}),o)return{...C,court:o,venue:i};if(t){let a=(iu({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let c of a){let u=t[c],p=ps({tournamentRecord:u,courtId:r});if(p.success)return p.venue&&mc({tournamentRecord:e,venue:p.venue}),{...C,court:o,venue:i}}}return _({result:{error:Os},stack:n})}function lS(t){return J(ps(t),!1,!0)}function ud({tournamentRecord:t,internalUse:e,courtId:r}){if(!t)return{error:Y};if(!r)return{error:_i};let n=ps({tournamentRecord:t,courtId:r});if(n.error)return n;let o=n.court&&(({altitude:i,courtId:s,courtName:a,courtDimensions:c,latitude:u,longitude:p,surfaceCategory:m,surfaceType:d,surfacedDate:l,pace:f,notes:g})=>({altitude:i,courtId:s,courtName:a,courtDimensions:c,latitude:u,longitude:p,surfaceCategory:m,surfaceType:d,surfacedDate:l,pace:f,notes:g}))(n.court);return{...C,courtInfo:J(o,!1,e)}}function dc(t){let e=rt(t,[{[ie]:!0},{venueId:!0,[fn]:Xo}]);if(e.error)return e;let{tournamentRecord:r,venueId:n}=t,o=Wo({tournamentRecord:r,venueId:n});if(o.error)return o;let s=(o.venue?.courts??[]).map(u=>(({courtInfo:p})=>({...p}))(ud({courtId:u.courtId,internalUse:!0,tournamentRecord:r}))),a=o.venue&&(({venueId:u,venueName:p,venueAbbreviation:m})=>({venueAbbreviation:m,venueName:p,venueId:u}))(o.venue),c=a&&{...a,courtsInfo:s};return{...C,venueData:J(c,!1,!0)}}function Wb({matchUp:t}){let e=t?.timeItems||[],r=i=>i.createdAt?new Date(i.createdAt).getTime():0;return{endTime:e.reduce((i,s)=>{let a=s.itemType===Di&&s;return a&&(!i||r(a)>r(i))?a:i},void 0)?.itemValue}}function Ht({event:t,eventId:e}){if(!t)return{error:vt};let n=dt({name:un,element:t})?.extension,o=e?J(n?.value,!1,!0):n?.value;return e&&t.drawDefinitions?.forEach(i=>{o?.flights?.forEach(s=>{s.drawId===i.drawId&&Object.assign(s,{drawDefinition:i})})}),{flightProfile:o}}function ze(t){let{tournamentRecord:e,eventId:r,drawId:n}=t,o="findEvent",i={},s=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},a=Object.values(s).map(({events:u,tournamentId:p})=>(u&&u.forEach(m=>{i[m.eventId]={tournamentId:p}}),u??[])).flat(),c;if(n){let u,p=a.find(m=>{let l=(m?.drawDefinitions??[]).find(f=>f.drawId===n);if(l)u=l,c=i[m.eventId].tournamentId;else{let g=(m&&Ht({event:m})?.flightProfile)?.flights?.find(I=>I.drawId===n);if(g)return c=i[m.eventId].tournamentId,{entries:g.drawEntries,drawName:g.drawName,tournamentId:c,drawId:n}}return l});if(p)return{event:p,drawDefinition:u,tournamentId:c}}if(r){let u=a.find(p=>p?.eventId===r);if(u)c=i[u.eventId].tournamentId;else return{event:void 0,drawDefinition:void 0,..._({result:{error:jr},stack:o})};return{event:u,drawDefinition:void 0,tournamentId:c}}return{event:void 0,drawDefinition:void 0,..._({result:{error:Mr},context:{drawId:n,eventId:r},stack:o})}}function pd(t){let e=t.event,r=t.matchUpType,{scheduleVisibilityFilters:n,afterRecoveryTimes:o,tournamentRecord:i,usePublishState:s,scheduleTiming:a,matchUpFormat:c,publishStatus:u,matchUp:p}=t;if(!p)return{error:hr};if(o&&!p.matchUpType&&!t.matchUpType&&(e||i)&&p.drawId){let U=t.drawDefinition||e?.drawDefinitions?.find(A=>A.drawId===p.drawId);!U&&i&&({drawDefinition:U,event:e}=ze({drawId:p.drawId,tournamentRecord:i}));let E=p.structureId&&U?.structures?.find(({structureId:A})=>A===p.structureId);r=t.matchUpType||E?.matchUpType||U?.matchUpType||e?.eventType!==_e&&e?.eventType}let{milliseconds:m,time:d}=Bb({matchUp:p}),{startTime:l}=Hb({matchUp:p}),{endTime:f}=Wb({matchUp:p}),g,{eventIds:I,drawIds:h}=n??{};if((!I||I.includes(p.eventId))&&(!h||h.includes(p.drawId))){let U=X=>X.createdAt?new Date(X.createdAt).getTime():0,E=new Map,A=p.timeItems?.toSorted((X,lt)=>U(X)-U(lt))??[];for(let X of A)E.set(X.itemType,X.itemValue);let N=E.get(cd),D=E.get(so),M=E.get(ji),R=E.get(Ap),b=E.get(Wi),v=E.get(eg),O=E.get(yp),x=E.get(Hi),F=E.get(Bo),L,w,V,k,W,H=p.matchUpType??r;if(a&&M&&o&&H){let X={matchUpFormat:p.matchUpFormat??c,...a};({averageMinutes:w=0,recoveryMinutes:V=0,typeChangeRecoveryMinutes:k=0}=Pp({timingDetails:X,eventType:H})),(w||V)&&(L=f?Yr(Kt(f),V):Yr(M,w+V)),k&&(W=f?Yr(Kt(f),k):Yr(M,w+k))}!b&&M&&(b=Et(M));let K=bm({scheduledDate:b,scheduledTime:M}),q={},B=(i&&x&&dc({tournamentRecord:i,venueId:x}))?.venueData||{};x&&(q[x]=B);let{venueName:$,venueAbbreviation:z,courtsInfo:j}=B,Q=(F&&j?.find(X=>X.courtId===F))?.courtName;for(let X of D||[]){if(!i)break;X.venueId&&!q[X.venueid]&&(q[X.venueId]=dc({venueId:X.venueId,tournamentRecord:i})?.venueData);let lt=q[X.venueId];X.venueName=lt?.venueName;let it=lt?.courtsInfo?.find(Rt=>Rt.courtId===X.courtId);X.courtName=it?.courtName}g=ot({typeChangeTimeAfterRecovery:W,timeAfterRecovery:L,scheduledDate:b,scheduledTime:M,isoDateString:K,homeParticipantId:N,venueAbbreviation:z,allocatedCourts:D,timeModifiers:R,venueName:$,venueId:x,courtOrder:O,courtName:Q,courtId:F,official:v,typeChangeRecoveryMinutes:k,recoveryMinutes:V,averageMinutes:w,milliseconds:m,startTime:l,endTime:f,time:d})}else g=ot({milliseconds:m,startTime:l,endTime:f,time:d});let{scheduledDate:S}=Hs({matchUp:p}),{scheduledTime:T}=mS({matchUp:p});if(s&&u?.displaySettings?.draws){let U=u.displaySettings.draws,E=(U?.[p.drawId]??U?.default)?.scheduleDetails;if(E){let A=(E.find(N=>S&&N.dates?.includes(S))??E.find(N=>!N.dates?.length))?.attributes;if(A){let N=Object.assign({},...Object.keys(g).map(D=>({[D]:!0})),A);g=Vi({source:g,template:N})}}}let P=p.matchUpStatus&&ce.includes(p.matchUpStatus)&&(Et(f)||Et(S)||Et(T))||void 0;return{schedule:g,endDate:P}}function jb({drawPositions:t,roundProfile:e,roundNumber:r}){let n=[void 0,void 0];if(NI(t))return{orderedDrawPositions:n,displayOrder:n};let o=e?.[r],s=o?.pairedDrawPositions?.find(c=>Fe(c||[],t.filter(Boolean)))??n,a=o?.feedRound;if(DI(t)){let c=[...t].sort(me);return{orderedDrawPositions:c.length===2?c:s,displayOrder:a?c:s}}if(a){let u=[t.find(p=>!isNaN(pt(p))),void 0];return{orderedDrawPositions:u,displayOrder:u}}return{orderedDrawPositions:s,displayOrder:s}}function Np({collectionPosition:t,collectionId:e,lineUp:r}){let n=[],o=[];if(r){let i=a=>a===void 0?-1:a,s=r.map(a=>{let{collectionAssignments:c,participantId:u}=a,p=c?.find(m=>m.collectionPosition===t&&m.collectionId===e);return p&&{participantId:u,...p}}).filter(Boolean).sort((a,c)=>i(a.substitutionOrder)-i(c.substitutionOrder));for(let a of s){let{participantId:c,previousParticipantId:u,substitutionOrder:p}=a;n.includes(c)||(u&&o.push({previousParticipantId:u,substitutionOrder:p,participantId:c}),n=n.filter(m=>m!==u),n.push(c))}}return{assignedParticipantIds:n,substitutions:o}}function In({tournamentParticipants:t,tournamentRecord:e,participantIds:r}){let n="getPairedParticipant";if(!t&&!e)return{error:Y};if(!Array.isArray(r)||r.length>2)return{error:wr};if(!r.length)return _({result:{error:Uo},stack:n});t=t??e?.participants??[];let o=t.filter(a=>a.participantType===ft&&Yt(r,a.individualParticipantIds).length===r.length&&a.individualParticipantIds.length===r.length),i=o[0];if(!i)return _({result:{error:te},stack:n});let s=J(o.slice(1),!1,!0);return{participant:J(i),duplicatedPairParticipants:s,...C}}function ms({drawDefinition:t,participantId:e}){if(typeof t!="object")return{error:Z};if(typeof e!="string")return{error:oe};let{extension:r}=dt({element:t,name:Ro});return{lineUp:(r?.value||{})[e]}}function Yb({tournamentParticipants:t,positionAssignments:e,collectionPosition:r,drawPositions:n=[],participantMap:o,drawDefinition:i,collectionId:s,sideLineUps:a,matchUpType:c}){if(!s||!r)return{};let u=({attribute:m,lineUp:d,teamParticipant:l})=>{let{assignedParticipantIds:f,substitutions:g}=Np({collectionPosition:r,collectionId:s,lineUp:d});if(c===_t){if(f?.length<=2){let I=o?.[f[0]]?.pairIdMap?.[f[1]],T=(I&&o[I]?.participant||In({participantIds:f,tournamentParticipants:t}).participant)?.participantId;return{[m]:{participantId:T,teamParticipant:l,substitutions:g}}}else if(f?.length>2)return{[m]:{teamParticipant:l,substitutions:g}}}else{let I=f?.[0];return I&&{[m]:{participantId:I,teamParticipant:l,substitutions:g}}}};if(!n?.length){let m=a?.map(d=>{let{teamParticipant:l,sideNumber:f}=d,g=d.lineUp||ms({participantId:l.teamParticipantId,drawDefinition:i})?.lineUp;return u({attribute:f,lineUp:g,teamParticipant:l})}).filter(Boolean)||{};return{sideNumberCollectionAssignment:Object.assign({},...m)}}let p=n?.map(m=>{let d=e.find(I=>I.drawPosition===m)?.participantId,l=a?.find(I=>I?.drawPosition===m),f=l?.teamParticipant||d&&o?.[d]?.participant||t?.find(({participantId:I})=>I===d),g=l?.lineUp||ms({participantId:d,drawDefinition:i})?.lineUp;return u({attribute:m,lineUp:g,teamParticipant:f})}).filter(Boolean)||{};return{drawPositionCollectionAssignment:Object.assign({},...p)}}function md(t){let e=rt(t,[{[_n]:!0}]);if(e.error)return e;let r=t?.matchUp,n=r?.matchUpType;if(!n&&r?.sides?.length){let s=r.sides.find(({participant:a})=>a)?.participant?.participantType;n=s===Tt&&xt||s===ft&&_t||s===Lt&&Lt||void 0}return{matchUpType:n}}function qb({drawPositionCollectionAssignment:t,sideNumberCollectionAssignment:e,positionAssignments:r,displaySideNumber:n,seedAssignments:o,drawPosition:i,isFeedRound:s,sideNumber:a}){let c=r.find(l=>l.drawPosition&&l.drawPosition===i),u=i&&t,p=a&&e,m=u?u[i]?.participantId:c?.participantId,d=c?Ak({displaySideNumber:n,seedAssignments:o,participantId:m,assignment:c,sideNumber:a}):{...p?.[a]};if(s&&(a===1?Object.assign(d,{participantFed:!0}):Object.assign(d,{participantAdvanced:!0})),i&&u){let l=u[i]?.teamParticipant,f=u[i]?.participant,g=u[i]?.substitutions;f&&(d.participant=f),g&&(d.substitutions=g),l&&(d.teamParticipant=l)}return d}function Ak({displaySideNumber:t,seedAssignments:e,participantId:r,assignment:n,sideNumber:o}){let i={drawPosition:n.drawPosition,displaySideNumber:t,sideNumber:o};if(r){let s=Ek({seedAssignments:e,participantId:r});Object.assign(i,s,{participantId:r}),s?.seedNumber&&s?.seedValue===""&&(i.seedValue="~")}else n.bye&&Object.assign(i,{bye:!0});return n.qualifier&&Object.assign(i,{qualifier:!0}),i}function Ek({seedAssignments:t,participantId:e}){return t?.find(r=>!r.seedProxy&&r.participantId===e)}function KU({scheduleVisibilityFilters:t,sourceDrawPositionRanges:e,tournamentParticipants:r,positionAssignments:n,drawPositionsRanges:o,hydrateParticipants:i,afterRecoveryTimes:s,initialRoundOfPlay:a,additionalContext:c,roundNamingProfile:u,tournamentRecord:p,tieDrawPositions:m,appliedPolicies:d,isCollectionBye:l,seedAssignments:f,usePublishState:g,participantMap:I,contextContent:h,scheduleTiming:S,contextProfile:T,drawDefinition:y,publishStatus:P,scoringActive:U,matchUpTieId:E,isRoundRobin:A,roundProfile:N,sideLineUps:D,structure:M,context:R,matchUp:b,event:v}){c=c??{};let O=We({drawDefinition:y,structure:M,matchUp:b,event:v})?.tieFormat,{roundOffset:x,structureId:F,structureName:L,stage:w,stageSequence:V}=M,{drawId:k,drawName:W,drawType:H}=y??{},K=O?.collectionDefinitions,q=b.collectionId&&K?.find(Pe=>Pe.collectionId===b.collectionId),B=b.collectionId?q?.matchUpFormat:b.matchUpFormat??M?.matchUpFormat??y?.matchUpFormat??v?.matchUpFormat,$=b.matchUpType||q?.matchUpType||M?.matchUpType||y?.matchUpType||!ue(_e)(v?.eventType)&&v?.eventType,z=l?Nt:b.matchUpStatus,{schedule:j,endDate:tt}=pd({scheduleVisibilityFilters:t,afterRecoveryTimes:s,tournamentRecord:p,usePublishState:g,scheduleTiming:S,drawDefinition:y,matchUpFormat:B,publishStatus:P,matchUpType:$,matchUp:b,event:v}),Q=m??b.drawPositions??[],{collectionPosition:X,collectionId:lt,roundPosition:it}=b,Rt=b.roundNumber??c.roundNumber,Ft=lt?Yb({tournamentParticipants:r,positionAssignments:n,collectionPosition:X,participantMap:I,drawDefinition:y,drawPositions:Q,collectionId:lt,sideLineUps:D,matchUpType:$}):void 0,Ue=u?.[Rt]?.roundName||c.roundName,fe=u?.[Rt]?.abbreviatedRoundName||c.abbreviatedRoundName,Me=N?.[Rt]?.feedRound,vr=N?.[Rt]?.preFeedRound,Zr=N?.[Rt]?.roundFactor,lr=o?.[Rt],Xe=it?lr?.[it]:void 0,ee=e?.[Rt],Pt=q?.category?{...R?.category||{},...q.category}:R?.category??v?.category,ae=b.processCodes?.length&&b.processCodes||q?.processCodes?.length&&q?.processCodes||M?.processCodes?.length&&M?.processCodes||y?.processCodes?.length&&y?.processCodes||v?.processCodes?.length&&v?.processCodes||p?.processCodes,re=T?.withCompetitiveness&&gu({...h,matchUp:b}),pr=b.finishingPositionRange??c.finishingPositionRange,Jt=Pe=>ot(Pe,void 0,!0),Wt={...Jt(R),...Jt({matchUpFormat:b.matchUpType===_e?void 0:B,tieFormat:b.matchUpType!==_e?void 0:O,gender:q?.gender??v?.gender,roundOfPlay:w!==ct&&It(a)&&a+(Rt||0),endDate:b.endDate??tt,discipline:v?.discipline,category:Pt,finishingPositionRange:pr,abbreviatedRoundName:fe,drawPositionsRange:Xe,competitiveProfile:re,structureName:L,stageSequence:V,drawPositions:Q,matchUpStatus:z,processCodes:ae,isRoundRobin:A,matchUpTieId:E,preFeedRound:vr,matchUpType:$,roundFactor:Zr,roundOffset:x,structureId:F,roundNumber:Rt,feedRound:Me,roundName:Ue,drawName:W,drawType:H,schedule:j,drawId:k,stage:w}),...J(Jt(b),!0,!0)};if(B&&b.score?.scoreStringSide1){let Pe=Ye(B),{bestOf:Or,finalSetFormat:Je,setFormat:De}=Pe??{};(Je?.tiebreakSet||De?.tiebreakSet||De?.timed)&&(Wt.score.sets=Wt.score.sets.sort((Ee,ge)=>Ee.setNumber-ge.setNumber).map((Ee,ge)=>(ge+1===Or?(Je?.tiebreakSet||Je?.timed)&&(Ee.tiebreakSet=!0):(De?.tiebreakSet||De?.timed)&&(Ee.tiebreakSet=!0),Ee)))}if(Array.isArray(Q)){let{orderedDrawPositions:Pe,displayOrder:Or}=jb({drawPositions:Q,roundProfile:N,roundNumber:Rt}),Je=N?.[Rt]?.feedRound,De=Or[0]!==Pe[0],ge=Pe.concat(void 0,void 0).slice(0,2).map((_r,fr)=>{let uo=fr+1,be=De?3-uo:uo,Ar=qb({...Ft,positionAssignments:n,displaySideNumber:be,seedAssignments:f,drawPosition:_r,isFeedRound:Je,sideNumber:uo}),Zi=b.sides?.find(ju=>ju.sideNumber===uo),Tn=it?(it-1)*2+fr+1:void 0,ts=Tn?ee?.[Tn]:void 0;return Jt({sourceDrawPositionRange:ts,...Zi,...Ar})});Object.assign(Wt,J({sides:ge},!0,!0))}if(r&&Wt.sides&&i!==!1){let Pe=d?.[Vs],Or=De=>{let Ee=I?.[De]?.participant;return Ee&&Vi({template:Pe?.participant,source:Ee})};if(Wt.sides.filter(Boolean).forEach(De=>{if(De.participantId){let Ee=J(Or(De.participantId)||(r?Go({policyDefinitions:d,participantId:De.participantId,tournamentParticipants:r,internalUse:!0,contextProfile:T}):void 0),void 0,!0);if(Ee){if(y?.entries){let ge=y.entries.find(fr=>fr.participantId===De.participantId),_r=v?.entries?.find(fr=>fr.participantId===De.participantId);Ee.entryStatus=ge?.entryStatus||_r?.entryStatus,ge?.entryStage&&(Ee.entryStage=ge.entryStage)}Object.assign(De,{participant:Ee})}}if(De?.participant?.individualParticipantIds?.length&&!De.participant.individualParticipants?.length){let Ee=De.participant.individualParticipantIds.map(ge=>Or(ge)||(r?Go({policyDefinitions:d,tournamentParticipants:r,internalUse:!0,contextProfile:T,participantId:ge}):void 0));Object.assign(De.participant,{individualParticipants:Ee})}}),!Wt.matchUpType){let{matchUpType:De}=md({matchUp:Wt});De&&Object.assign(Wt,{matchUpType:De})}if(T?.inferGender&&(!Wt.gender||Wt.gender===Tr)&&Wt.sides?.length===2&&Wt.matchUpType!==_e){let De=Wt.sides.map(Ee=>{if(ue(xt)(Wt.matchUpType))return Ee.participant?.person?.sex;if(Ee.participant?.individualParticipants?.length===2){let ge=ut(Ee.participant.individualParticipants.map(_r=>_r.person?.sex)).filter(Boolean);if(ge.length===1)return ge[0]}});if(De.filter(Boolean).length===2&&ut(De).length===1){let Ee=De[0];Wt.inferredGender=Ee}}}if(Wt.tieMatchUps){let Pe=Wt.matchUpStatus===Nt,Or=Wt.sides?.map(({participant:Je,drawPosition:De,sideNumber:Ee,lineUp:ge})=>{let _r=Je?.participantType===_e&&Je;return{teamParticipant:_r&&ot({participantRoleResponsibilities:_r.participantRoleResponsibilities,participantOtherName:_r.participanOthertName,participantName:_r.participantName,participantId:_r.participantId,teamId:_r.teamId}),drawPosition:De,sideNumber:Ee,lineUp:ge}});Wt.tieMatchUps=Wt.tieMatchUps.map(Je=>{let De=Wt.matchUpId,ge={finishingPositionRange:Wt.finishingPositionRange,abbreviatedRoundName:fe,roundNumber:Rt,roundName:Ue};return KU({tieDrawPositions:Q,scheduleVisibilityFilters:t,sourceDrawPositionRanges:e,sideLineUps:Or,drawPositionsRanges:o,initialRoundOfPlay:a,roundNamingProfile:u,additionalContext:ge,appliedPolicies:d,isCollectionBye:Pe,usePublishState:g,publishStatus:P,matchUpTieId:De,isRoundRobin:A,roundProfile:N,matchUp:Je,event:v,tournamentParticipants:r,positionAssignments:n,tournamentRecord:p,seedAssignments:f,participantMap:I,contextContent:h,scheduleTiming:S,contextProfile:T,drawDefinition:y,scoringActive:U,structure:M,context:R})})}let mr=Wt.sides&&Wt.sides.filter(Pe=>Pe?.participantId).length===2,zt=!Wt.winningSide;if(Object.assign(Wt,{readyToScore:U&&mr&&zt,hasContext:!0}),mr){let{allParticipantsCheckedIn:Pe,checkedInParticipantIds:Or}=us({matchUp:Wt});Object.assign(Wt,{allParticipantsCheckedIn:Pe,checkedInParticipantIds:Or})}return Array.isArray(T?.exclude)&&T?.exclude.forEach(Pe=>delete Wt[Pe]),Wt}function $b({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Ho({timeItems:r?.timeItems||[],itemType:so});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{allocatedCourts:J(n,!1,!0)}:e}function Kb({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Ho({timeItems:r?.timeItems||[],itemType:Bo});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{courtId:n}:e}function zb({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Ho({timeItems:r?.timeItems||[],itemType:Hi});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{venueId:n}:e}function Ni(t){if(!Array.isArray(t.matchUps))return[];let{matchUps:e,excludeMatchUpStatuses:r,hasParticipantsCount:n,isCollectionMatchUp:o,matchUpStatuses:i,hasWinningSide:s,matchUpFormats:a,roundPositions:c,matchUpFormat:u,collectionIds:p,isMatchUpTie:m,roundNumbers:d,matchUpIds:l,roundNames:f,filterMatchUpTypes:g=!0,filterMatchUpIds:I=!0,stageSequences:h,scheduledDates:S,scheduledDate:T,participantIds:y,processContext:P,tournamentIds:U,matchUpTypes:E,structureIds:A,readyToScore:N,courtIds:D,eventIds:M,venueIds:R,drawIds:b,stages:v}=t,O=Array.isArray(y)?y.filter(Boolean):[],x=Array.isArray(i)?i.filter(Boolean):[],F=Array.isArray(r)?r.filter(Boolean):[],L=Array.isArray(v)?v.filter(Boolean):[],w=Array.isArray(h)?h.filter(Boolean):[],V=Array.isArray(p)?p.filter(Boolean):[],k=Array.isArray(f)?f.filter(Boolean):[],W=Array.isArray(d)?d.filter(Boolean):[],H=Array.isArray(c)?c.filter(Boolean):[],K=Array.isArray(l)&&I?l.filter(Boolean):[],q=Array.isArray(E)&&g?E.filter(Boolean):[],B=Array.isArray(D)?D.filter(Boolean):[],$=Array.isArray(R)?R.filter(Boolean):[],z=Array.isArray(a)&&a.filter(Boolean)||typeof u=="string"&&[u]||[],j=Array.isArray(S)&&S.filter(Boolean)||typeof T=="string"&&T.length&&[T]||[],tt=Array.isArray(U)?U.filter(Boolean):[],Q=Array.isArray(M)?M.filter(Boolean):[],X=Array.isArray(b)?b.filter(Boolean):[],lt=Array.isArray(A)?A.filter(Boolean):[];return e.filter(it=>{if(N&&!ue(xr)(it)&&!it.readyToScore||it.winningSide&&s&&![1,2].includes(it.winningSide)||m!==void 0&&(m&&!it.tieMatchUps||!m&&it.tieMatchUps)||o!==void 0&&(o&&!it.collectionId||!o&&it.collectionId)||L.length&&!L.includes(it.stage)||w.length&&!w.includes(it.stageSequence)||V.length&&(!it.collectionId||!V.includes(it.collectionId))||k.length&&(!it.roundName||!k.includes(it.roundName))||W.length&&(!it.roundNumber||!W.includes(it.roundNumber))||H.length&&(!it.roundPosition||!H.includes(it.roundPosition))||x.length&&(!it.matchUpStatus||!x.includes(it.matchUpStatus))||F.length&&it.matchUpStatus&&F.includes(it.matchUpStatus)||K.length&&!K.includes(it.matchUpId)||q.length&&(!it.matchUpType||!Lc(q,it.matchUpType))||z.length&&(!it.matchUpFormat||!z.includes(it.matchUpFormat)))return!1;if(j?.length){let{scheduledTime:Rt}=mS({matchUp:it}),{scheduledDate:Ft}=Hs({matchUp:it}),fe=Et(Rt)||Ft;if(!j.find(Me=>Wn(Me,fe)))return!1}if(B.length){let{courtId:Rt}=Kb({matchUp:it}),{allocatedCourts:Ft}=$b({matchUp:it}),Ue=Ft?.map(({courtId:fe})=>fe);if(!B.filter(Boolean).includes(Rt)||Ue?.includes(Rt))return!1}if($.length){let{venueId:Rt}=zb({matchUp:it});if(!$.filter(Boolean).includes(Rt))return!1}if(P){if(tt.length&&!tt.includes(it.tournamentId)||Q.length&&!Q.includes(it.eventId)||X.length&&!X.includes(it.drawId)||lt.length&&!lt.includes(it.structureId))return!1;let Rt=it.sides?.map(({participantId:Ft})=>Ft).filter(Boolean)??[];if(n&&Rt.length<n||O.length&&!O.some(Ue=>Rt.includes(Ue)))return!1}return!0})}function Ut(t){let{provisionalPositioning:e,tournamentRecord:r,contextFilters:n,matchUpFilters:o,contextProfile:i,drawDefinition:s,context:a={},structure:c,inContext:u,event:p}=t,{seedAssignments:m,contextContent:d,exitProfiles:l,matchUpsMap:f}=t,g={},I={};if(!c)return{collectionPositionMatchUps:g,error:pi,roundMatchUps:I,matchUps:[]};let h=Array.isArray(o?.eventIds)?o?.eventIds.filter(Boolean):[],S=Array.isArray(o?.structureIds)?o?.structureIds.filter(Boolean):[],T=Array.isArray(o?.drawIds)?o?.drawIds.filter(Boolean):[],y=!a?.eventId||!h?.length&&!n?.eventIds?.filter(Boolean).length||h?.includes(a.eventId)||n?.eventIds?.includes(a.eventId),P=!S?.length||S.includes(c.structureId),U=!s||!T?.length||T.includes(s.drawId);if(!y||!P||!U)return{collectionPositionMatchUps:g,roundMatchUps:I,matchUps:[]};i&&!d&&(d=qn({tournamentRecord:r,contextProfile:i,drawDefinition:s}));let{appliedPolicies:E}=yt({drawDefinition:s}),A={...t.tournamentAppliedPolicies,...E,...t.policyDefinitions},N=A?.scoring?.structures,D=c.stage&&N?.stage?.[c.stage],M=c.stageSequence&&D?.stageSequence?.[c.stageSequence],R=A?.scoring?.requireAllPositionsAssigned||D?.requireAllPositionsAssigned||M?.requireAllPositionsAssigned;f||(f=Ne({drawDefinition:s,structure:c}));let{positionAssignments:b,allPositionsAssigned:v}=Se({structure:c}),O=!R||v,{seedAssignments:x}=on({provisionalPositioning:e,drawDefinition:s,structure:c});m=m??x;let{structureId:F}=c;l=l||s&&eS({drawDefinition:s}).exitProfiles;let L=l?.[F],w=L?.length&&(L[0].split("-").map(B=>parseInt(B)).reduce((B,$)=>B+$)||0),V=!!c.structures,k=oi({matchUpsMap:f,structureId:F,inContext:u}),W=A?.[fa],H=vb({roundNamingPolicy:W,drawDefinition:s,structure:c,matchUps:k}),{roundNamingProfile:K,roundProfile:q}=H;if(I=H?.roundMatchUps??[],o&&(k=Ni({matchUps:k,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1})),u){let{sourceDrawPositionRanges:B}=Rb({drawDefinition:s,matchUpsMap:f,structureId:F}),$=s?Cb({drawDefinition:s,roundProfile:q,matchUpsMap:f,structureId:F}).drawPositionsRanges:void 0;k=k.map(j=>KU({tournamentParticipants:t.tournamentParticipants??r?.participants,scheduleVisibilityFilters:t.scheduleVisibilityFilters,hydrateParticipants:t.hydrateParticipants,afterRecoveryTimes:t.afterRecoveryTimes,usePublishState:t.usePublishState,participantMap:t.participantMap,scheduleTiming:t.scheduleTiming,publishStatus:t.publishStatus,sourceDrawPositionRanges:B,positionAssignments:b,drawPositionsRanges:$,initialRoundOfPlay:w,roundNamingProfile:K,tournamentRecord:r,appliedPolicies:A,seedAssignments:m,contextContent:d,contextProfile:i,drawDefinition:s,scoringActive:O,isRoundRobin:V,roundProfile:q,structure:c,context:a,matchUp:j,event:p})),(k?.filter(j=>Array.isArray(j.tieMatchUps))).forEach(j=>{let tt=j.tieMatchUps;k=k.concat(...tt)}),n&&(k=Ni({processContext:!0,...n,matchUps:k}))}else(k?.filter($=>Array.isArray($.tieMatchUps))).forEach($=>{let z=$.tieMatchUps;k=k.concat(...z)});return o&&(k=Ni({matchUps:k,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1})),(o?.matchUpTypes||o?.matchUpIds)&&(k=Ni({matchUpTypes:o.matchUpTypes,matchUpIds:o.matchUpIds,matchUps:k})),(o?.matchUpTypes||o?.matchUpIds||u)&&(I=Ke({matchUps:k}).roundMatchUps??[]),We({drawDefinition:s,structure:c,event:p})?.tieFormat&&({collectionPositionMatchUps:g}=Mb({matchUps:k})),{collectionPositionMatchUps:g,roundMatchUps:I,isRoundRobin:V,roundProfile:q,matchUpsMap:f,matchUps:k}}function ds({matchUp:t}){return t?ce.includes(t?.matchUpStatus)||t?.winningSide:!1}function hu({requireParticipants:t=!0,scheduleVisibilityFilters:e,tournamentAppliedPolicies:r,tournamentParticipants:n,hydrateParticipants:o,afterRecoveryTimes:i,policyDefinitions:s,tournamentRecord:a,usePublishState:c,matchUpFilters:u,contextFilters:p,contextContent:m,participantMap:d,scheduleTiming:l,publishStatus:f,contextProfile:g,drawDefinition:I,exitProfiles:h,matchUpsMap:S,structureId:T,inContext:y,structure:P,context:U,event:E}){!P&&T&&({structure:P}=at({drawDefinition:I,structureId:T}));let A=Ut({tournamentAppliedPolicies:r,scheduleVisibilityFilters:e,tournamentParticipants:n,hydrateParticipants:o,afterRecoveryTimes:i,policyDefinitions:s,tournamentRecord:a,usePublishState:c,matchUpFilters:u,contextFilters:p,contextContent:m,participantMap:d,scheduleTiming:l,publishStatus:f,contextProfile:g,drawDefinition:I,exitProfiles:h,matchUpsMap:S,structure:P,inContext:y,context:U,event:E}),N=[],D=[],M=[],R=[],b=[];if(A.error)return A;let{matchUps:v}=A,{assignedPositions:O}=Se({structure:P}),x=O?.filter(L=>L.participantId).map(L=>L.drawPosition),F;return v.filter(L=>{let w=u?.matchUpTypes?.length===1&&u.matchUpTypes[0]===jt;return!(L.matchUpType!==jt&&w)}).forEach(L=>{if(L.matchUpStatus===br){N.push(L);return}L.matchUpType===jt&&(F=!0);let w=L.collectionId,V=w&&L.sides?.every($=>$.participantId),k=!w&&L.drawPositions?.filter(Boolean).length===2,W=!w&&L.drawPositions?.every($=>x?.includes($)),H=O?.filter($=>$.bye).map($=>$.drawPosition),K=!w&&L.drawPositions?.find($=>H?.includes($)),B=Gh.includes(L.matchUpStatus)&&(V||k&&(!t||W));return K?b.push(L):ds({matchUp:L})?D.push(L):B?M.push(L):R.push(L)}),{includesTeamMatchUps:F,abandonedMatchUps:N,completedMatchUps:D,upcomingMatchUps:M,pendingMatchUps:R,byeMatchUps:b,structure:P}}function Qb({drawDefinition:t,roundNumber:e,structureId:r}){if(!t)return{error:Z};if(!r)return{error:Er};let{links:n}=Ws({drawDefinition:t,structureId:r}),o=n.source.reduce((s,a)=>!a.source.roundNumber||a.source.roundNumber===e?s.concat(a):s,[]),i=n.target.reduce((s,a)=>!a.target.roundNumber||a.target.roundNumber===e?s.concat(a):s,[]);return{links:{source:o,target:i}}}function fS({finishingPositions:t,linkCondition:e,linkType:r,source:n}){let o=n.find(i=>{let s=!i.source?.finishingPositions||!t||Fe(t,i.source?.finishingPositions);return e===i.linkCondition&&s&&i.linkType===r});return[fo,eo].includes(o?.linkType)&&!o?.source?.roundNumber?_({result:{error:G},stack:"getTargetLink",context:o}):o}function Ws({drawDefinition:t,structureId:e,roundNumber:r}){return t?e?{links:(t.links||[]).filter(Boolean).reduce((i,s)=>(s.source?.structureId===e&&(!r||s.source.roundNumber===r)&&(i.source=i.source.concat(s)),s.target?.structureId===e&&(!r||s.target.roundNumber===r)&&(i.target=i.target.concat(s)),i),{source:[],target:[]})}:{error:Er}:{error:Z}}function Xb({structureMatchUps:t,matchUp:e}){let{roundNumber:r,roundPosition:n}=e,o=t.filter(s=>s.roundNumber===r&&!s.matchUpTieId),i=t.filter(s=>s.roundNumber===r+1&&!s.matchUpTieId);if(i.length){let s;return i.length===o.length?s=i.find(a=>a.roundPosition===n):i.length===o.length/2&&(s=i.find(a=>a.roundPosition===Math.ceil(n/2))),{matchUp:s}}return{message:"no progression found"}}function gS({sourceRoundMatchUpCount:t,inContextDrawMatchUps:e,sourceRoundPosition:r,drawDefinition:n,targetLink:o}){if(!o)return{error:kl};let{target:{structureId:i,feedProfile:s,groupedOrder:a,roundNumber:c,positionInterleave:u}}=o,{structure:p}=at({drawDefinition:n,structureId:i}),{positionAssignments:m}=bt({structure:p}),l=(e?.filter(D=>D.structureId===p?.structureId)).filter(D=>D.roundNumber===c&&!D.matchUpTieId),f=l.length,g=et(1,f+1),I=f/t,h=Math.ceil(I*r),S=1-r%2;if(u?.interleave&&I!==.5){let D=u.offset+(r-1)*u.interleave,M=r+D;h=Math.ceil(M/2),S=1-M%2}let T=g,y=g[h-1],P=tS({roundPositionsCount:g.length,groupedOrder:a}),U=P?.length||1;if(U<=g.length){let D=f/U,M=ye(g,D);s===di&&M.forEach(R=>R.reverse()),T=P?.length&&P?.map(R=>M[R-1]).flat()||T}s===En?y=T[h-1]:s===di?((!P?.length||U>g.length)&&(h=l.length+1-h),y=T[h-1]):s===cp&&Ur()&&console.log(Zu,{feedProfile:s});let E=y&&l.reduce((D,M)=>M.roundPosition===y?M:D,void 0),A;E?.feedRound?(S=0,A=Math.min(...(E.drawPositions||[]).filter(Boolean))):A=E?.drawPositions?.length===2&&E?.drawPositions[S];let N=m?.find(({drawPosition:D})=>D===A);if(N){let{extension:D}=dt({element:N,name:Hm});if(D?.value)return{disabledDrawPosition:A}}return{matchUp:E,targetDrawPosition:A,matchUpDrawPositionIndex:S}}function ur({inContextDrawMatchUps:t=[],useTargetMatchUpIds:e,inContextMatchUp:r,drawDefinition:n,matchUpId:o}){let i=r;t.length&&!i&&(i=t.find(c=>c.matchUpId===o));let{structure:s}=at({structureId:i?.structureId,drawDefinition:n});return s?.finishingPosition===Gi?Uk({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:n,structure:s,matchUp:i}):Pk({matchUp:i})}function Uk({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:r,structure:n,matchUp:o}){let{winnerMatchUpId:i,loserMatchUpId:s}=o,{links:a}=Qb({roundNumber:o.roundNumber,structureId:n.structureId,drawDefinition:r}),c=a?.source,u=fS({source:c,linkType:fo}),p=fS({linkCondition:On,linkType:eo,source:c}),m=fS({source:c,linkType:eo}),d=p&&m;m||(m=p);let l=u?.target?.feedProfile,f=m?.target?.feedProfile,g=p?.target?.feedProfile,I,h,S,T,y,P,U,E,A,N;if(e&&(i||s)&&(U=i&&l!==dn&&t.find(({matchUpId:R})=>R===i),T=s&&f!==dn&&t.find(({matchUpId:R})=>R===s),U||T))return{matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u},targetMatchUps:{loserMatchUp:T,winnerMatchUp:U}};let{roundPosition:D}=o;N=N||t.filter(R=>R.structureId===n.structureId);let M=N.reduce((R,b)=>b.roundNumber===o.roundNumber&&!b.matchUpTieId?R+1:R,0);return m&&!T&&f!==dn&&({matchUpDrawPositionIndex:P,targetDrawPosition:y,matchUp:T}=gS({targetLink:m,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),d&&g!==dn&&({matchUpDrawPositionIndex:S,targetDrawPosition:h,matchUp:I}=gS({targetLink:p,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),u&&!U&&l!==dn&&({matchUpDrawPositionIndex:A,targetDrawPosition:E,matchUp:U}=gS({targetLink:u,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),U||(N=N||t.filter(R=>R.structureId===n.structureId),{matchUp:U}=Xb({structureMatchUps:N,matchUp:o})),ot({matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u,byeTargetLink:p},targetMatchUps:{winnerMatchUpDrawPositionIndex:A,loserMatchUpDrawPositionIndex:P,byeMatchUpDrawPositionIndex:S,winnerTargetDrawPosition:E,loserTargetDrawPosition:y,byeTargetDrawPosition:h,winnerMatchUp:U,loserMatchUp:T,byeMatchUp:I},targetMatchUpIds:!!(i||s)})}function Pk({matchUp:t}){return{targetLinks:{loserTargetLink:void 0,winnerTargetLink:void 0},targetMatchUps:{loserMatchUp:void 0,winnerMatchUp:void 0},matchUp:t}}function Jb({drawDefinition:t,inContextDrawMatchUps:e}){let r={};return e.forEach(n=>{let{matchUpId:o,structureId:i,drawPositions:s=[]}=n,{structure:a}=at({drawDefinition:t,structureId:i});if(a?.finishingPosition===li){let{roundNumber:c}=n,u=c&&pt(c)+1,p=a.matchUps??[],{roundMatchUps:m}=Ke({matchUps:p});if(u&&m?.[u]){let d=[...s].sort(me).map((l,f)=>{let g=m[u].find(I=>I.drawPositions?.includes(l));return{matchUpId:g?.matchUpId,roundNumber:u,schedule:g?.schedule,sideNumber:f+1,structureName:a.structureName}});Object.assign(n,{sidesTo:d})}}else{let c=ur({useTargetMatchUpIds:!0,inContextDrawMatchUps:e,inContextMatchUp:n,drawDefinition:t,matchUpId:o}),{winnerMatchUp:u}=c.targetMatchUps,{loserMatchUp:p}=c.targetMatchUps;!n.winnerMatchUpId&&u&&(n.winnerMatchUpId=u.matchUpId),!n.loserMatchUpId&&p&&(n.loserMatchUpId=p.matchUpId);let m=zU({upcomingMatchUp:u}),d=zU({upcomingMatchUp:p});if(n.matchUpStatus!==Nt&&p?.matchUpStatus===Nt){let{matchUp:f}=Zb({matchUp:p,drawDefinition:t,inContextDrawMatchUps:e})||{};d=f&&zU({upcomingMatchUp:f})||d}let l=n.schedule?.timeAfterRecovery;if(l&&(m?.schedule?.scheduledTime&&qt(m.schedule.scheduledTime)<qt(l)&&(r[m.matchUpId]=n.matchUpId,m.schedule.scheduleConflict=n.matchUpId),d?.schedule?.scheduledTime&&qt(d.schedule.scheduledTime)<qt(l)&&(r[d.matchUpId]=n.matchUpId,d.schedule.scheduleConflict=n.matchUpId)),Object.assign(n,{winnerTo:m,loserTo:d}),n.drawPositions?.filter(Boolean).length){let g=c.targetLinks?.loserTargetLink?.linkCondition===On,I=Dk(n);if(I.length){let h=vf(u?.sides),S=vf(p?.sides),y=I.find(({participantId:E})=>h.includes(E))?[]:I,U=I.find(({participantId:E})=>S.includes(E))?[]:I;p&&g&&U.length<2&&U.push({bye:!0,tbd:!0}),y?.length&&u&&(!c.targetMatchUpIds&&u&&(u=e.find(({matchUpId:E})=>E===u.matchUpId)),u.potentialParticipants||(u.potentialParticipants=[]),u.potentialParticipants.push(y)),U?.length&&p&&(c.targetMatchUpIds||(u=e.find(({matchUpId:E})=>E===p.matchUpId)),p.potentialParticipants||(p.potentialParticipants=[]),p.potentialParticipants.push(U))}}}}),Object.keys(r).length&&e.forEach(n=>{Object.keys(r).includes(n.matchUpId)&&(n.schedule.scheduleConflict=r[n.matchUpId])}),{scheduleConflictMatchUpIds:r}}function Dk(t){return t?.sides?.map(({participant:e,participantId:r,qualifier:n})=>e||r&&{participantId:r}||n&&{qualifier:n}).filter(Boolean)||[]}function Zb({matchUp:t,drawDefinition:e,inContextDrawMatchUps:r}){let{matchUpId:n,matchUpStatus:o,structureId:i}=t||{};if(!t||!i||t?.matchUpStatus===Qt)return{matchUp:t};if(o===Nt){let s;return t.winnerMatchUpId?s=r.find(({matchUpId:a})=>a===t.winnerMatchUpId):{winnerMatchUp:s}=ur({inContextDrawMatchUps:r,drawDefinition:e,matchUpId:n})?.targetMatchUps||{},Zb({matchUp:s,drawDefinition:e,inContextDrawMatchUps:r})}return{matchUp:void 0}}function zU(t){if(t?.upcomingMatchUp)return(({matchUpId:e,structureId:r,schedule:n,roundNumber:o,roundPosition:i,structureName:s})=>({matchUpId:e,structureId:r,schedule:n,roundNumber:o,roundPosition:i,structureName:s}))(t.upcomingMatchUp)}function se(t){let e="getAllDrawMatchUps";Object.assign(t,{requireParticipants:!1});let r=js(t);if(r.error)return _({result:r,stack:e});let{abandonedMatchUps:n,completedMatchUps:o,upcomingMatchUps:i,pendingMatchUps:s,byeMatchUps:a,matchUpsMap:c}=r;return{matchUps:(n??[]).concat(...o??[],...i??[],...s??[],...a??[]),matchUpsMap:c}}function js(t){if(!t?.drawDefinition)return{error:Z};let{tournamentParticipants:e,contextContent:r,matchUpsMap:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,requireParticipants:s,participantsProfile:a,afterRecoveryTimes:c,policyDefinitions:u,tournamentRecord:p,usePublishState:m,contextFilters:d,matchUpFilters:l,scheduleTiming:f,participantMap:g,publishStatus:I,contextProfile:h,drawDefinition:S,nextMatchUps:T,inContext:y,context:P,event:U}=t,E=[],A=[],N=[],D=[],M=[];h&&!r&&(r=qn({policyDefinitions:u,tournamentRecord:p,contextProfile:h,event:U}));let R;!e?.length&&p&&(e=p?.participants,(y||a?.withGroupings)&&e?.length&&({participantsWithGroupings:e,groupInfo:R}=Xm({participants:e,participantsProfile:a})));let{structures:b}=gn({drawDefinition:S});if(!b)return{error:kt};n||(n=Ne({drawDefinition:S}));let v=S&&eS({drawDefinition:S}).exitProfiles;b.forEach(F=>{let{byeMatchUps:L=[],pendingMatchUps:w=[],upcomingMatchUps:V=[],completedMatchUps:k=[],abandonedMatchUps:W=[]}=hu({matchUpFilters:T?void 0:l,contextFilters:T?void 0:d,inContext:y||T||d,hydrateParticipants:t.hydrateParticipants,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,tournamentParticipants:e,requireParticipants:s,afterRecoveryTimes:c,policyDefinitions:u,tournamentRecord:p,usePublishState:m,contextContent:r,participantMap:g,scheduleTiming:f,publishStatus:I,contextProfile:h,drawDefinition:S,exitProfiles:v,matchUpsMap:n,structure:F,context:P,event:U});E=E.concat(...W),A=A.concat(...k),N=N.concat(...V),D=D.concat(...w),M=M.concat(...L)});let O=F=>(!l&&!T&&!d||(l&&(F=Ni({matchUps:F,...l})),d&&(F=Ni({matchUps:F,...d,processContext:!0}))),F),x={abandonedMatchUps:O(E),completedMatchUps:O(A),upcomingMatchUps:O(N),pendingMatchUps:O(D),byeMatchUps:O(M),matchUpsMap:n,...C,groupInfo:R};if(T){let F=typeof T=="object"||{abandoned:!0,completed:!0,upcoming:!0,pending:!0,bye:!0},{abandoned:L,completed:w,upcoming:V,pending:k,bye:W}=F,H=[].concat(...L&&E||[],...w&&A||[],...V&&N||[],...k&&D||[],...W&&M||[]);Jb({inContextDrawMatchUps:H,drawDefinition:S})}return x}function $n(t){let{participants:e=[],contextContent:r,participantMap:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,contextFilters:m,contextProfile:d,matchUpFilters:l,nextMatchUps:f,inContext:g,context:I,event:h}=t;if(!h)return{error:vt};let{eventId:S,eventName:T,endDate:y,eventType:P,category:U,gender:E,matchUpFormat:A}=h??{},N={...I,...ot({indoorOutDoor:h.indoorOutdoor??p?.indoorOutdoor,surfaceCategory:h.surfaceCategory??p?.surfaceCategory,endDate:h.endDate??p?.endDate,tournamentId:p?.tournamentId,matchUpFormat:A,eventName:T,eventType:P,category:U,eventId:S,gender:E})};y&&(N.endDate=y),d&&!r&&(r=qn({policyDefinitions:c,tournamentRecord:p,contextProfile:d,event:h}));let D;if(!e?.length&&!n&&p){let v=Ai({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:d,inContext:g});n=v.participantMap,e=v.participants??[],D=v.groupInfo}let M=h.drawDefinitions??[],R=ya({tournamentRecord:p,event:h}).scheduleTiming;return{matchUps:M.flatMap(v=>{let{matchUps:O}=se({tournamentParticipants:e,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,context:N,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,contextFilters:m,contextProfile:d,drawDefinition:v,contextContent:r,matchUpFilters:l,participantMap:n,scheduleTiming:R,nextMatchUps:f,inContext:g,event:h});return O??[]}),groupInfo:D}}function Te(t){let e=rt(t,[{tournamentRecord:!0}]);if(e.error)return e;if(!t?.tournamentRecord)return{error:Y};let{participantMap:r,participants:n}=t,{scheduleVisibilityFilters:o,participantsProfile:i,afterRecoveryTimes:s,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,inContext:p=!0,contextProfile:m,matchUpFilters:d,contextFilters:l,nextMatchUps:f,context:g}=t,I=t.tournamentId??u.tournamentId,h=u?.events??[];n||({participants:n,participantMap:r}=Ai({participantsProfile:i,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,contextProfile:m,inContext:p}));let{appliedPolicies:S}=yt({tournamentRecord:u}),T={...g,tournamentId:I,indoorOutDoor:u.indoorOutdoor,surfaceCategory:u.surfaceCategory,endDate:u.endDate},y=qn({policyDefinitions:c,tournamentRecord:u,contextProfile:m});return{matchUps:h.flatMap(U=>(T.eventDrawsCount=U.drawDefinitions?.length??0,$n({context:T,scheduleVisibilityFilters:o,tournamentAppliedPolicies:S,participantsProfile:i,afterRecoveryTimes:s,policyDefinitions:c,tournamentRecord:u,contextContent:y,contextFilters:l,contextProfile:m,matchUpFilters:d,participantMap:r,nextMatchUps:f,participants:n,inContext:p,event:U}).matchUps??[])).concat(...u.matchUps??[])}}function Un({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,tournamentRecords:n,policyDefinitions:o,matchUpFilters:i,contextFilters:s,nextMatchUps:a,inContext:c}){if(typeof n!="object"||!Object.keys(n).length)return{error:wt};let p=Object.keys(n).map(m=>{let d=n[m];return Te({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,policyDefinitions:o,tournamentRecord:d,matchUpFilters:i,contextFilters:s,nextMatchUps:a,inContext:c}).matchUps??[]}).flat();return{...C,matchUps:p}}function Mi(t,e){return Nk(t,e)||(t?.stageSequence||0)-(e?.stageSequence||0)||t?.roundNumber&&e.roundNumber&&t?.roundNumber-e?.roundNumber||(t?.roundPosition??0)-(e?.roundPosition??0)}function Nk(t,e){return(ks[t?.stage]||0)-(ks[e?.stage]||0)}function or(t){let{participants:e,participantMap:r,contextContent:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,matchUpFilters:m,contextFilters:d,contextProfile:l,drawDefinition:f,nextMatchUps:g,inContext:I,context:h,event:S}=t,{eventId:T,eventName:y,endDate:P,eventType:U,category:E,gender:A,matchUpFormat:N}=S??{},D={...h,surfaceCategory:S?.surfaceCategory??p?.surfaceCategory,indoorOutDoor:S?.indoorOutdoor??p?.indoorOutdoor,matchUpFormat:N,eventType:U,eventName:y,category:E,eventId:T,endDate:P,gender:A},M;return!e?.length&&!r&&p&&({participants:e=[],participantMap:r,groupInfo:M}=Ai({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:l,inContext:I})),l&&!n&&(n=qn({policyDefinitions:c,tournamentRecord:p,contextProfile:l,drawDefinition:f,event:S})),{...se({context:D,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,tournamentParticipants:e,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,drawDefinition:f,contextContent:n,contextFilters:d,contextProfile:l,matchUpFilters:m,participantMap:r,nextMatchUps:g,inContext:I,event:S}),groupInfo:M}}function ls({element:t,accessor:e}){if(typeof e!="string")return{values:[]};let r=J(t),n=e.split("."),o=[],i;a({targetElement:r,attributes:n});let s={value:i};return o.length&&(s.values=o),s;function a({targetElement:c,attributes:u=[],significantCharacters:p}){for(let[d,l]of u.entries())if(c?.[l]){let f=u.slice(d+1);f.length?Array.isArray(c[l])?c[l].forEach(I=>a({targetElement:I,attributes:f})):(c=c[l],m({targetElement:c,index:d})):(i||(i=c[l]),o.includes(c[l])||o.push(c[l]))}function m({targetElement:d,index:l}){if(d&&l===u.length-1&&["string","number"].includes(typeof d)){let f=p?d.slice(0,p):d;i?o.includes(f)||o.push(f):(i=f,o.push(f))}}}}var QU=t=>e=>!t||typeof e!="object"?void 0:Array.isArray(t)&&t.map(r=>({[r]:ls({element:e,accessor:r})?.value}))||typeof t=="object"&&Object.keys(t).map(r=>({[r]:ls({element:e,accessor:r})?.value}))||(typeof t=="string"&&ls({element:e,accessor:t}))?.value,Br=QU;function Ea({finishingPositionOffset:t=0,finishingPositionLimit:e,positionsFed:r,roundsCount:n,roundLimit:o,matchUps:i,lucky:s,fmlc:a}){if(!Vr(i))return[];let{roundProfile:c,roundNumbers:u=[]}=Ke({interpolate:!0,matchUps:i});n=n??Math.max(...u,0);let p=o?n-o:0,m=p&&c?.[n-p]?.matchUpsCount,d=c&&Object.values(c).map(Br("matchUpsCount")),l=(I,h)=>{let S=Math.min(...I);m&&h&&S===1&&(S=m);let T=Math.max(...I);return e&&T>e&&(T=e),[S,T]},f=c&&Object.assign({},...u.map(I=>{let h=(n??0)+1-I-p,S=c[I].matchUpsCount,T={finishingPositionRange:{},finishingRound:h},y=d?.slice(I-1).reduce((R,b)=>R+(b||0),0),P=a&&I!==1,U=1+t+(P?r??0:0),E=1,A=et(U,s?U+S*2:y+U+E),N=y+E-S,D=l(A.slice(N)),M=l(A.slice(0,N),!0);return T.finishingPositionRange={loser:D,winner:M},{[I]:T}})),g=Ur({finishingRound:!0});return i.filter(Boolean).forEach(I=>{let h=I.roundNumber&&f[I.roundNumber];g&&!h&&console.log({roundFinishingData:f,matchUp:I}),I.finishingRound=h?.finishingRound,I.finishingPositionRange=h?.finishingPositionRange}),i}function qi({inContextDrawMatchUps:t,drawDefinition:e,matchUpsMap:r}){if(!e)return{error:Z};let n={loserMatchUpIds:{},winnerMatchUpIds:{}};if(t||({matchUps:t,matchUpsMap:r}=se({inContext:!0,drawDefinition:e,matchUpsMap:r})),!r?.drawMatchUps.some(i=>i.finishingPositionRange)&&e?.structures?.length===1&&!e?.structures[0].structures){let i=r?.drawMatchUps??[];Ea({matchUps:i})}return(t??[]).filter(({collectionId:i})=>!i).forEach(i=>{let{matchUpId:s,structureId:a}=i,c=ur({inContextDrawMatchUps:t,drawDefinition:e,matchUpId:s}),{winnerMatchUp:u,loserMatchUp:p}=c.targetMatchUps,m=u?.matchUpId,d=p?.matchUpId,f=oi({matchUpsMap:r,structureId:a}).find(g=>g.matchUpId===s);if(f&&(m&&(n.winnerMatchUpIds[f.matchUpId]=m,Object.assign(f,{winnerMatchUpId:m}),Object.assign(i,{winnerMatchUpId:m})),d&&(n.loserMatchUpIds[f.matchUpId]=d,i.loserMatchUpId=d,f.loserMatchUpId=d,i.finishingPositionRange))){let g=p.finishingPositionRange&&[...i.finishingPositionRange.loser,...p.finishingPositionRange.loser],I=g&&[Math.min(...g),Math.max(...g)];i.finishingPositionRange.loser=I,f.finishingPositionRange.loser=I}}),{inContextDrawMatchUps:t,goesToMap:n}}function sn(t){let e=Dr(t),r=t.matchUps??[],n=t.drawIds??[],{includeParticipantDependencies:o,tournamentRecord:i,drawDefinition:s}=t;if(!Array.isArray(r))return{error:Xn};if(!Array.isArray(n))return{error:an};let a=t.matchUpIds?.length?t.matchUpIds:r.map(T=>T.matchUpId);if(!Array.isArray(a))return{error:rs};let c={},u={},p={},m={};i&&!Object.keys(e).length&&(e={[i.tournamentId]:i});let d=Object.values(e),f=d.reduce((T,y)=>T.concat(y.events??[]).map(P=>(P.drawDefinitions||[]).map(U=>U.links||[])).flat(1/0),[]).filter(({linkType:T})=>T===to),g=r;if(f.length){g=Un({nextMatchUps:!0,tournamentRecords:e}).matchUps;let T=f.reduce((y,P)=>{let U=P.source?.structureId,E=P.target?.structureId;return U&&E&&(p[E]=U),U&&!y.includes(U)&&y.push(U),y},[]);for(let y of T)c[y]=[];for(let y of g??[]){let P=y.containerStructureId||y.structureId;T.includes(P)&&c[P].push(y.matchUpId)}}let I=T=>{u[T]||(u[T]={dependentMatchUpIds:[],participantIds:[],matchUpIds:[],sources:[]},m[T]=[])},h=(T,y)=>{u[T].matchUpIds.forEach(U=>{u[y].matchUpIds.push(U)}),u[y].matchUpIds.push(T),u[T].dependentMatchUpIds.push(y),o&&u[T].participantIds.forEach(U=>u[y].participantIds.push(U))},S=T=>{let y=Object.keys(c).length;for(let P of T||[]){let{matchUpId:U,winnerMatchUpId:E,loserMatchUpId:A}=P;if(!a.length||a.includes(U)){if(I(U),o){let{individualParticipantIds:M}=uu(P);u[U].participantIds=M}E&&(I(E),h(U,E),m[E].push(U)),A&&(I(A),h(U,A),m[A].push(U)),u[U].sources.push(m[U]);let N=m[U].map(M=>u[M].sources[0]).flat(),D=m[U].map(M=>u[M].sources[1]).flat();if(u[U].sources.push(N,D),y){let M=P.containerStructureId||P.structureId,R=p[M];if(c[R])for(let b of c[R])I(b),h(b,U),m[b].push(U)}}}};if(s)qi({drawDefinition:s}),g?.length||(g=or({drawDefinition:s}).matchUps),S(g);else{if(g?.length||(g=Un({nextMatchUps:!0,tournamentRecords:e}).matchUps),!n.length){let T=d?.length?d.map(({events:y=[]})=>y.map(({drawDefinitions:P=[]})=>P.map(({drawId:U})=>U))).flat(1/0):[];T&&(n=T)}for(let T of n){let y=g?.filter(U=>U.drawId===T).sort(Mi);if(!y?.find(({roundPosition:U})=>!U)){let U=y?.find(({tournamentId:A})=>A),{drawDefinition:E}=ze({tournamentRecord:e[U?.tournamentId],drawId:T});E&&qi({drawDefinition:E})}S(y)}}return{positionDependencies:c,matchUpDependencies:u,sourceMatchUpIds:m,matchUps:g,...C}}function Ie(t){let e=t?.matchUp,r=t?.score||e?.score,n=r?.sets?.[0],{side1Score:o,side2Score:i,side1TiebreakScore:s,side2TiebreakScore:a,side1PointScore:c,side2PointScore:u}=n||{},p=o||i||s||a||c||u;return!!(r?.sets?.length>1||p)}function Ua({matchUpStatus:t}){return Fh.includes(t)}function tv({matchUpStatus:t}){return Km.includes(t)}function og({matchUpStatus:t}){return kh.includes(t)}function ig({matchUpStatus:t,winningSide:e,tieMatchUps:r,sides:n,score:o}){let i=n?.find(({participantId:c})=>c),s=r?.filter(ig)?.length;return Ie({score:o})||s||e&&i||t&&tv({matchUpStatus:t})&&![Mt,Ct,Ln].includes(t)}function Pa(t){let{drawDefinition:e,findContainer:r,structureId:n,event:o}=t,i=t.structure,s={isCollectionMatchUp:!1},{containedStructures:a}=as({drawDefinition:e}),c=n?a[n]||[]:[];if(!i){let E=at({drawDefinition:e,structureId:n});if(E.error)return E;i=r?E.containingStructure??E.structure:E.structure}if(cr({structure:i}))return{structure:i,isAdHoc:!0,error:Rs};let{matchUps:u}=se({inContext:!0,matchUpFilters:s,drawDefinition:e,event:o}),p=u?.filter(E=>E.structureId===n||c.includes(E.structureId)),{matchUpDependencies:m}=sn({drawIds:[e.drawId],matchUps:u,drawDefinition:e}),d=[],l=[],f={},g=[];for(let E of u??[]){if(E.structureId===n||c.includes(E.structureId)){l.push(...E.drawPositions??[]);let A=E.roundNumber;for(let N of(E.drawPositions??[]).filter(Boolean))(!f[N]||A&&f[N]>A)&&(f[N]=A)}ig(E)&&(g.push(E),d.push(E.matchUpId,...m?.[E?.matchUpId]?.matchUpIds||[]))}let I=ut(l.filter(Boolean)).sort(me),h=ut(d),S=ut(p?.map(({matchUpId:E,drawPositions:A})=>h.includes(E)?A:[]).flat().filter(Boolean)).sort(me),{positionAssignments:T}=bt({drawDefinition:e,structure:i}),y=T?.filter(E=>E.bye).map(E=>E.drawPosition),P=T?.filter(E=>E.qualifier).map(E=>E.drawPosition),U=I?.filter(E=>!S.includes(E))||[];return{allDrawPositions:I,inContextStructureMatchUps:p,drawPositionInitialRounds:f,activeDependentMatchUpIds:h,qualifyingDrawPositions:P,inactiveDrawPositions:U,positionAssignments:T,activeDrawPositions:S,byeDrawPositions:y,activeMatchUps:g,structure:i}}function fs({drawPosition:t,matchUps:e=[]}){return{initialRoundNumber:e.filter(({drawPositions:n})=>t&&n?.includes(t)).map(({roundNumber:n})=>n).sort(me)[0]}}var Da={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",brightred:"\x1B[91m",green:"\x1B[32m",brightgreen:"\x1B[92m",yellow:"\x1B[33m",brightyellow:"\x1B[93m",blue:"\x1B[34m",brightblue:"\x1B[94m",lightblue:"\x1B[105m",magenta:"\x1B[35m",brightmagenta:"\x1B[95m",cyan:"\x1B[36m",brightcyan:"\x1B[96m",white:"\x1B[37m",brightwhite:"\x1B[97m"};var IS=[];function Rn(t,e){Vt(t)&&(t={method:t}),(e||Ur())&&IS.push(t)}function Mk(t){let e=IS.slice();return t&&(IS.length=0),e}function ev(t){let r=Mk(t).map(n=>{let{color:o,keyColors:i,method:s,newline:a}=n,c=Object.keys(Da).includes(o)?Da[o]:Da.cyan,p=Object.keys(n).filter(d=>!["color","keyColors","method","newline"].includes(d)).map(d=>{let l=i&&Object.keys(i).includes(d)&&Da[i[d]]?Da[i[d]]:Da.brightwhite;return`${Da.white}${d}: ${l}${n[d]}`}).join(", "),m=s?.length<15?" ":" ";return[a?`
|
|
1
|
+
var oL=Object.defineProperty;var Xt=(t,e)=>{for(var r in e)oL(t,r,{get:e[r],enumerable:!0})};function Va(){return"2.1.30"}var hA={};Xt(hA,{competitionGovernor:()=>DU,drawsGovernor:()=>MN,entriesGovernor:()=>xN,eventGovernor:()=>$N,generationGovernor:()=>ZN,matchUpFormatGovernor:()=>Oy,matchUpGovernor:()=>yM,mocksGovernor:()=>fI,participantGovernor:()=>QM,policyGovernor:()=>nN,publishingGovernor:()=>iR,queryGovernor:()=>DN,reportGovernor:()=>sR,scheduleGovernor:()=>SR,scoreGovernor:()=>Hg,tieFormatGovernor:()=>RR,tournamentGovernor:()=>VR,venueGovernor:()=>QR});var DU={};Xt(DU,{getLinkedTournamentIds:()=>iu,getTournamentIds:()=>Ip,linkTournaments:()=>yU,mutate:()=>UU,query:()=>PU,unlinkTournament:()=>EU,unlinkTournaments:()=>AU});var UU={};Xt(UU,{linkTournaments:()=>yU,unlinkTournament:()=>EU,unlinkTournaments:()=>AU});var aa="SINGLES",xt="SINGLES",vi="DOUBLES",_t="DOUBLES",xr="TEAM",jt="TEAM",sC={SINGLES_MATCHUP:aa,SINGLES:xt,DOUBLES_MATCHUP:vi,DOUBLES:_t,TEAM_MATCHUP:xr,TEAM:jt};var EI={[xt]:[xt,"S"],[_t]:[_t,"D"],[jt]:[jt,"T"],S:[xt,"S"],D:[_t,"D"],T:[jt,"T"]};function me(t,e){return(t??0)-(e??0)}function pt(t){return typeof t=="number"?parseInt(t.toString()):typeof t=="string"?parseInt(t):0}function vn(t){return isNaN(t)?!1:t&&(t&t-1)===0}function AA(t){if(!t.length)return;let e=[...t].sort(me),r=Math.floor(e.length/2);return e.length%2?e[r]:(e[r-1]+e[r])/2}function aC(t){if(!vn(t))return!1;let e=t,r=1;for(;e!==2;)r+=1,e=e/2;return r}function hm(t){return isNaN(t)?0:t%2&&t+1||t}function Sm(t){return Math.pow(2,Math.round(Math.log(t)/Math.log(2)))}function Zt(t){return!isNaN(parseFloat(t))}function UI(t){let e=pt(t);if(!isNaN(e))return e===0?!1:(e&-e)===1}function es(t){if(isNaN(t))return!1;for(;!vn(t);)t++;return t}function po(t,e){return t=Math.ceil(t),e=Math.floor(e),Math.floor(Math.random()*(e-t+1))+t}function It(t){return Number.isSafeInteger(typeof t=="string"?+t:t)}function cC(t=1,e=3,r=!0){let n=0;for(let o=0;o<e;o++)n+=Math.random()*(t/e);return r&&t>1?Math.round(n):n}function iL(t,e){e||(e=1);let r=1/e;return Math.round(t*r)/r}function EA(t,e,r,n,o=2){let i=1-Math.random(),s=1-Math.random(),a=Math.sqrt(-2*Math.log(i))*Math.cos(2*Math.PI*s);return a=a/10+.5,a>1||a<0?a=EA(t,e,r):(a=Math.pow(a,r),a*=e-t,a+=t),n&&(a=iL(a,n)),parseFloat(a.toFixed(o))}function _l(t,e=2){return parseFloat(Number(Math.round(t*1e3)/1e3).toFixed(e))}function ut(t){return Array.isArray(t)?t?.filter((e,r,n)=>n.lastIndexOf(e)===r):[]}function uC(t){return Array.isArray(t)?t?.map(e=>e===null?void 0:e):t}function Ir(t){return Array.isArray(t)?t.map(e=>[Math.random(),e]).sort((e,r)=>e[0]-r[0]).map(e=>e[1]):[]}function Ba(t){return It(t)?t:1/0}function Sr(t){return Array.isArray(t)?t.reduce((e,r)=>(e[r]||(e[r]=0),e[r]++,e),{}):{}}function pC(t){return UA(Sr(t))}function UA(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return e[n]?e[n].push(r):e[n]=[r],e},{})}function sL(t,e,r){return r.indexOf(t)===e}function PI(t){return t.filter(sL)}function tn(t){return Array.isArray(t)&&t.length?t.splice(Math.floor(Math.random()*t.length),1)[0]:void 0}function yn(t){let e=Math.floor(Math.random()*t.length);return t[e]}function et(t,e){return Array.from({length:e-t},(r,n)=>n+t)}function mo(t,e){return e.reduce((r,n,o)=>(n===t&&r.push(o),r),[])}function Yt(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(r=>e.indexOf(r)!==-1).filter((r,n,o)=>o.indexOf(r)===n)}function PA(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(r=>!e.includes(r))}function Fe(t,e){return!Array.isArray(t)||!Array.isArray(e)?!1:t.some(r=>e.includes(r))}function mC(t,e){return Array.isArray(e)&&e.reduce((r,n)=>(r[n]=1+r[n]||1,r),{})[t]||0}function dC(t,e,r,n){return Array.isArray(t)?[].concat(...t.slice(0,e),...t.slice(e,e+r).sort(n),...t.slice(e+r,t.length)):[]}function ye(t,e){return Array.isArray(t)?t.reduce((r,n,o)=>{let i=Math.floor(o/e);return r[i]=[].concat(r[i]||[],n),r},[]):[]}function DA(t,[e,...r]){return t.length?[t.slice(0,e),...DA(t.slice(e),[...r,e])]:[]}function lC(t){return t.reduce((e,r)=>{let n=e[e.length-1];return(!n||n[n.length-1]!==r-1)&&e.push([]),e[e.length-1].push(r),e},[])}function DI(t){return Array.isArray(t)?t.reduce((e,r)=>!isNaN(parseInt(r))&&e,!0):!1}function NI(t){return Array.isArray(t)?t.reduce((e,r)=>isNaN(parseInt(r))&&e,!0):!1}function xl(t,e,r){return Array.isArray(t)?t.reduce((n,o,i)=>{let s=r?!!(Math.floor(i/e)%2):!1,a=i%e,c=s?e-1-a:a;return n[c]||(n[c]=[]),n[c].push(o),n},[]):[]}function fC(t,e=1){if(!Array.isArray(t)||!t.every(It))return[];let r=Math.min(...t,e),n=Math.max(...t);return et(r,n+1).filter(o=>!t.includes(o))}function Wr(t){return typeof t=="function"}function Vt(t){return typeof t=="string"}function ht(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function gC(t,e){if(!ht(t)||!ht(e))return!1;let r=Object.keys(t),n=Object.keys(e);if(r.length!==n.length)return!1;for(let o of r)if(t[o]!==e[o])return!1;return!0}function RI(t,e){return Array.isArray(t)?Object.assign({},...(t??[]).filter(ht).map(r=>r[e]&&{[r[e]]:r}).filter(Boolean)):{}}var IC=t=>e=>Object.keys(t).every(r=>e[r]===t[r]);function MI(t,e){if(t===void 0)return null;if(!ht(t)||t===null)return t;let r=Object.keys(t),n=o=>o===void 0?null:o;return Object.assign({},...r.map(o=>Array.isArray(t[o])?{[o]:e?t[o]:t[o].map(i=>MI(i))}:{[o]:e?n(t[o]):MI(t[o])}))}function NA(t){return Array.isArray(t)?t.length+t.map(NA).reduce((e,r)=>e+r,0):ht(t)&&t!==null?Object.keys(t).length+Object.keys(t).map(e=>NA(t[e])).reduce((e,r)=>e+r,0):0}function hC(t){if(t===null||typeof t!="object")return;let e=JSON.stringify(t),r=NA(t),n=e.split("").reduce((o,i)=>o+i.charCodeAt(0),0);return[e.length,r,n].map(o=>o.toString(36)).join("")}function Lc(t,e){return!Array.isArray(t)||!Vt(e)?!1:Yt(t,EI[e]).length}var C={success:!0},MA="error",SC={SUCCESS:C,ERROR:MA};function CI({collectionValueProfiles:t,matchUpCount:e}){let r=[];if(!Array.isArray(t))return r.push(`collectionValueProfiles is not an array: ${t}`),{errors:r};if(t.length&&t.length!==e)return r.push("collectionValueProfiles do not align with matchUpsCount"),{errors:r};for(let o of t){if(typeof o!="object")return r.push(`valueProfile is not type object: ${o}`),{errors:r};let{matchUpValue:i,collectionPosition:s}=o;if(typeof i!="number"||typeof s!="number"||s>e||s<1)return r.push("Invalid value profile: value and collectionPosition must be numeric. collectionPosition cannot be greater than matchUpCount"),{errors:r}}let n=t.map(o=>o.collectionPosition);return n.length!==ut(n).length?(r.push("collectionPositions are not unique"),{errors:r}):{...C}}var bC={};Xt(bC,{addNotice:()=>mt,callListener:()=>Pm,createInstanceState:()=>wE,cycleMutationStatus:()=>cf,deepCopyEnabled:()=>af,deleteNotice:()=>YI,deleteNotices:()=>Fi,disableNotifications:()=>LE,enableNotifications:()=>sf,getDevContext:()=>Ur,getMethods:()=>uf,getNotices:()=>jI,getProvider:()=>qI,getTopics:()=>Lr,getTournamentId:()=>ns,getTournamentRecord:()=>pf,getTournamentRecords:()=>Fo,globalLog:()=>GE,handleCaughtError:()=>op,hasTopic:()=>rp,removeTournamentRecord:()=>kE,setDeepCopy:()=>Hc,setDevContext:()=>Bc,setGlobalLog:()=>MC,setGlobalMethods:()=>RC,setGlobalSubscriptions:()=>LL,setMethods:()=>CC,setStateMethods:()=>VE,setStateProvider:()=>xL,setSubscriptions:()=>FL,setTournamentId:()=>np,setTournamentRecord:()=>FE,setTournamentRecords:()=>Dm,timeKeeper:()=>wL});var bI={message:"Chronological error; time violation.",code:"ANACHRONISM"},Tm={message:"Duplicate entry",code:"DUPLICATE_ENTRY"},RA={message:"Cannot remove main structure",code:"ERR_CANNOT_REMOVE_MAIN_STRUCTURE"},vI={message:"records must be an object with tournamentId keys",code:"ERR_INVALID_TOURNAMENTS"},wt={message:"Missing tournamentRecords",code:"ERR_MISSING_TOURNAMENTS"},Y={message:"Missing tournamentRecord",code:"ERR_MISSING_TOURNAMENT"},Ha={message:"Invalid tournamentRecord",code:"ERR_INVALID_TOURNAMENT"},ca={message:"Missing tournamentId",code:"ERR_MISSING_TOURNAMENT_ID"},ua={message:"Invalid drawDefinition",code:"ERR_INVALID_DRAWDEF"},Z={message:"Missing drawDefinition",code:"ERR_MISSING_DRAWDEF"},CA={message:"Existing drawDefinition(s)",code:"ERR_EXISTING_DRAWDEFS"},Mr={message:"drawDefinition not found",code:"ERR_NOT_FOUND_DRAWDEF"},Qo={message:"Invalid structure",code:"ERR_INVALID_STRUCTURE"},wl={message:"Incomplete source structure",code:"ERR_INCOMPLETE_STRUCTURE"},Ll={message:"Invalid drawPosition for seedAssignment",code:"ERR_INVALID_SEEDING_POSITION"},Wa={message:"drawPosition already assigned",code:"ERR_EXISTING_POSITION_ASSIGNMENT"},bA={message:"Schedule not cleared",code:"ERR_UNCHANGED_SCHEDULE_NOT_CLEARED"},vA={message:"drawPosition not cleared",code:"ERR_FAILURE_POSITION_NOT_CLEARED"},aL={message:"drawPosition not found",code:"ERR_NOT_FOUND_DRAW_POSITION"},Fl={message:"Unrecognized drawType",code:"ERR_UNRECOGNIZED_DRAW_TYPE"},ja={message:"Missing drawPositions",code:"ERR_MISSING_DRAW_POSITIONS"},Yu={message:"drawPosition is active",code:"ERR_ACTIVE_DRAW_POSITION"},TC={message:"drawPosition is occupied",code:"ERR_OCCUPIED_DRAW_POSITION"},Rs={message:"Invlid drawPosition",code:"ERR_INVALID_DRAW_POSITION"},Cs={message:"Missing drawPosition",code:"ERR_MISSING_DRAW_POSITION"},ym={message:"Invalid drawType",code:"ERR_INVALID_DRAW_TYPE"},qu={message:"Invalid drawSize",code:"ERR_INVALID_DRAW_SIZE"},OI={message:"Cannot set drawSize to be less than existing entries",code:"ERR_INVALID_DRAW_SIZE_MISMATCH"},Ya={message:"Missing drawSize",code:"ERR_MISSING_DRAW_SIZE"},an={message:"Missing drawId",code:"ERR_MISSING_DRAW_ID"},OA={message:"drawId exists",code:"ERR_EXISTING_DRAW_ID"},_A={message:"participantId cannot be assigned to multiple seedNumbers",code:"INVALID_PARTICIPANT_SEEDING"},xA={message:"seedsCount greater than drawSize",code:"ERR_INVALID_SEED_COUNT"},wA={message:"Missing seedCountThresholds",code:"ERR_MISSING_SEED_COUNT_THRESHOLD"},LA={message:"Invalid action",code:"ERR_INVALID_ACTION"},_I={message:"Invalid assignment",code:"ERR_INVALID_ASSIGNMENT"},FA={message:"Missing seedAssignments",code:"ERR_MISSING_SEED_ASSIGNMENTS"},kA={message:"Invalid seedNumber",code:"ERR_INVALID_SEED_NUMBER"},GA={message:"Invalid seedPosition",code:"ERR_INVALID_SEED_POSITION"},kl={message:"Missing targetLink",code:"ERR_MISSING_LINK_TARGET"},VA={message:"Existing round",code:"ERR_EXISTING_ROUND"},cL={message:"Missing roundNumber",code:"ERR_MISSING_ROUND_NUMBER"},Er={message:"Missing structureId",code:"ERR_MISSING_STRUCTURE_ID"},kt={message:"structure not found",code:"ERR_NOT_FOUND_STRUCTURE"},Gl={message:"Missing structures",code:"ERR_MISSING_STRUCTURES"},pi={message:"Missing structure",code:"ERR_MISSING_STRUCTURE"},BA={message:"drawDefinition contains unlinked structures",code:"ERR_MISSING_STRUCTURE_LINKS"},Bn={message:"Invalid eventType",code:"ERR_INVALID_EVENT_TYPE"};var vt={message:"Missing event / eventId",code:"ERR_MISSING_EVENT_ID"},jr={message:"Event not found",code:"ERR_NOT_FOUND_EVENT"},HA={message:"Event exists",code:"ERR_EXISTING_EVENT"},WA={message:"Missing entries",code:"ERR_MISSING_ENTRIES"},jA={message:"Invalid entries",code:"ERR_INVALID_ENTRIES"},Vl={message:"Missing assignments",code:"ERR_MISSING_ASSIGNMENTS"},YA={message:"Missing stage",code:"ERR_MISSING_STAGE"},Oi={message:"Invalid stage",code:"ERR_INVALID_STAGE"},qA={message:"stageSequence limit",code:"ERR_LIMIT_STAGE_SEQUENCE"},$A={message:"Missing positionAssignments",code:"ERR_MISSING_POSITION_ASSIGNMENTS"},KA={message:"Cannot Assign BYE status if no assignment: { bye: true }",code:"ERR_UNCHANGED_CANNOT_ASSIGN_BYE"},xI={message:"Unrecognized matchUpStatus",code:"ERR_UNRECOGNIZED_MATCHUP_STATUS"},qa={message:"Unrecognized matchUpFormat",code:"ERR_UNRECOGNIZED_MATCHUP_FORMAT"},Bl={message:"Incompatible matchUpStatus",code:"ERR_INCOMPATIBLE_MATCHUP_STATUS"},pa={message:"Invalid matchUpStatus",code:"ERR_INVALID_MATCHUP_STATUS"},Lo={message:"Invalid tieFormat",code:"ERR_INVALID_TIE_FORMAT"},Hl={message:"Invalid matchUpFormat",code:"ERR_INVALID_MATCHUP_FORMAT"},Wl={message:"Missing matchUpFormat",code:"ERR_MISSING_MATCHUP_FORMAT"},zA={message:"Missing collectionDefinition",code:"ERR_MISSING_COLLECTION_DEFINITION"},bs={message:"Missing tieFormat",code:"ERR_MISSING_TIE_FORMAT"},sr={message:"Missing matchUpId",code:"ERR_MISSING_MATCHUP_ID"},rs={message:"Missing matchUpIds",code:"ERR_MISSING_MATCHUP_IDS"},Le={message:"matchUp not found",code:"ERR_NOT_FOUND_MATCHUP"},Xn={message:"Missing matchUps",code:"ERR_MISSING_MATCHUPS"},hr={message:"Missing matchUp",code:"ERR_MISSING_MATCHUP"},dr={message:"Invalid matchUp",code:"ERR_INVALID_MATCHUP"},wI={message:"Missing policyType",code:"ERR_MISSING_POLICY_TYPE"},$u={message:"Missing policyDefinitions",code:"ERR_MISSING_POLICY_DEFINITIONS"},uL={message:"Missing seeding policy",code:"ERR_MISSING_POLICY_SEEDING"},QA={message:"Missing avoidance policy",code:"ERR_MISSING_POLICY_AVOIDANCE"},LI={message:"Missing policy attributes",code:"ERR_MISSING_POLICY_ATTRIBUTES"},XA={message:"Invalid policyDefinitions",code:"ERR_INVALID_POLICY_DEFINITIONS"},FI={message:"existing policyType",code:"ERR_EXISTING_POLICY_TYPE"},pL={message:"Policy not attached",code:"ERR_FAILURE_POLICY_NOT_ATTACHED"},Fc={message:"Policy not found",code:"ERR_NOT_FOUND_POLICY"},mL={message:"Missing scoring policy / matchUpFormats",code:"ERR_MISSING_POLICY_SCORING_MATCHUP_FORMATS"},jl={message:"Invalid sideNumber",code:"ERR_INVALID_SIDE_NUMBER"},dL={message:"Invalid setNumber",code:"ERR_INVALID_SET_NUMBER"},Yl={message:"Missing setObject",code:"ERR_MISSING_SET_ATTRIBUTE"},lL={message:"Missing setNumber",code:"ERR_MISSING_SET_NUMBER"},fL={message:"Missing sideNumber",code:"ERR_MISSING_SIDE_NUMBER"},_i={message:"Missing courtId",code:"ERR_MISSING_COURT_ID"},st={message:"Missing value",code:"ERR_MISSING_VALUE"},JA={message:"Missing birthdate",code:"ERR_MISSING_BIRTH_DATE"},ZA={message:"Missing date",code:"ERR_MISSING_DATE"},tE={message:"No valid dates",code:"ERR_NO_VALID_DATES"},Am={message:"Invalid bookings",code:"ERR_INVALID_BOOKINGS"},ql={message:"Invalid dateAvailability",code:"ERR_INVALID_DATE_AVAILABILITY"},eE={message:"Missing dateAvailability",code:"ERR_MISSING_DATE_AVAILABILITY"},je={message:"Invalid Date",code:"ERR_INVALID_DATE"},Eo={message:"Invalid time",code:"ERR_INVALID_TIME"},rE={message:"Invalid tournament dates",code:"ERR_INVALID_DATES_TOURNAMENT"};var kI={message:"Invalid game scores",code:"ERR_INVALID_SCORES_GAME"},nE={message:"Invalid score",code:"ERR_INVALID_SCORE"},Em={message:"Invalid winningSide",code:"ERR_INVALID_WINNING_SIDE"};var yC={message:"No participants generated",code:"ERR_NO_PARTICIPANTS_GENERATED"},$l={message:"Cannot modify tieFormat",code:"ERR_UNCHANGED_CANNOT_MODIFY_TIEFORMAT"},oE={message:"Cannot modify participantType",code:"ERR_UNCHANGED_CANNOT_MODIFY_PARTICIPANT_TYPE"},Ku={message:"Cannot remove participants",code:"ERR_UNCHANGED_CANNOT_REMOVE_PARTICIPANTS"},GI={message:"Participant category mismatch",code:"ERR_CATEGORY_MISMATCH"},Um={message:"Cannot change winningSide",code:"ERR_UNCHANGED_CANNOT_CHANGE_WINNING_SIDE"},xi={message:"Invalid participant",code:"ERR_INVALID_PARTICIPANT"},mn={message:"Invalid participantId",code:"ERR_INVALID_PARTICIPANT_ID"},wr={message:"Invalid participantIds",code:"ERR_INVALID_PARTICIPANT_IDS"},iE={message:"Invalid participantRole",code:"ERR_INVALID_PARTICIPANT_ROLE"},An={message:"Invalid participantType",code:"ERR_INVALID_PARTICIPANT_TYPE"},sE={message:"Missing participantRole",code:"ERR_MISSING_PARTICIPANT_ROLE"},wi={message:"Missing participant",code:"ERR_MISSING_PARTICIPANT"},$a={message:"Missing participants",code:"ERR_MISSING_PARTICIPANTS"},oe={message:"Missing participantId",code:"ERR_MISSING_PARTICIPANT_ID"},te={message:"Participant Not Found",code:"ERR_NOT_FOUND_PARTICIPANT"},aE={message:"participantId exists",code:"ERR_EXISTING_PARTICIPANT_ID"},gL={message:"participant pair exists",code:"ERR_EXISTING_PARTICIPANT_PAIR"},cE={message:"No participant removed",code:"ERR_UNCHANGED_NO_PARTICIPANT_REMOVED"},Uo={message:"Missing participantIds",code:"ERR_MISSING_PARTICIPANT_IDS"},uE={message:"Missing participantsCount",code:"ERR_MISSING_PARTICIPANT_COUNT"},pE={message:"Participant not checked in",code:"ERR_UNCHANGED_PARTICIPANT_NOT_CHECKED_IN"},mE={message:"Missing person details",code:"ERR_MISSING_PERSON_DETAILS"},vs={message:"Existing participant drawPosition assignment",code:"ERR_EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT"},zu={message:"Existing participant",code:"ERR_EXISTING_PARTICIPANT"},Kl={message:"participantsCount exceeds drawSize",code:"ERR_INVALID_PARTICIPANT_COUNT"},zl={message:"Invalid entry status",code:"ERR_INVALID_ENTRY_STATUS"},VI={message:"Participant Entry Not Found",code:"ERR_NOT_FOUND_PARTICIPANT_ENTRY"},AC={message:"Participant not entered in stage",code:"ERR_UNCHANGED_PARTICIPANT_NOT_ENTERED"},EC={message:"Participant not found in stageSequence",code:"ERR_NOT_FOUND_PARTICIPANT_IN_STAGE"},dE={message:"entryStatus not allowed in stage",code:"ERR_INVALID_ENTRY_STATUS_IN_STAGE"},lE={message:"entryStatus not allowed for event",code:"ERR_INVALID_ENTRY_STATUS_IN_EVENT"},BI={message:"No stage space available for entryStatus",code:"ERR_UNCHANGED_NO_AVAILABLE_STAGE_SPACE"},fE={message:"Insufficient drawPositions to accommodate qualifiers",code:"ERR_UNCHANGED_NO_DRAW_POSITIONS_FOR_QUALIFIERS"},Ql={message:"Insufficient drawPositions to accommodate entries",code:"ERR_INSUFFICIENT_DRAW_POSITIONS"},gE={message:"Missing penaltyType",code:"ERR_MISSING_PENALTY_TYPE"},Xl={message:"Missing penaltyId",code:"ERR_MISSING_PENALTY_ID"},kc={message:"Penalty not found",code:"ERR_NOT_FOUND_PENALTY"},IE={message:"Missing courtsCount/courtNames",code:"ERR_MISSING_COURTS_INFO"},Os={message:"Court not found",code:"ERR_NOT_FOUND_COURT"},hE={message:"Court exists",code:"ERR_EXISTING_COURT"},SE={message:"Venue exists",code:"ERR_EXISTING_VENUE"},Li={message:"Venue not found",code:"ERR_NOT_FOUND_VENUE"},Xo={message:"Missing venueId",code:"ERR_MISSING_VENUE_ID"},TE={message:"Invalid endTime",code:"ERR_INVALID_END_TIME"},HI={message:"Existing endTime",code:"ERR_EXISTING_END_TIME"},yE={message:"Invalid stopTime",code:"ERR_INVALID_STOP_TIME"},AE={message:"Invalid startTime",code:"ERR_INVALID_START_TIME"},UC={message:"Invalid resumeTime",code:"ERR_INVALID_RESUME_TIME"},Jl={message:"Invalid timeItem",code:"ERR_INVALID_TIME_ITEMS"},EE={message:"Missing async state provider",code:"ERR_MISSING_ASYNC_STATE_PROVIDER"},Zl={message:"Missing timeItem",code:"ERR_MISSING_TIME_ITEM"},tf={message:"Missing timeItems",code:"ERR_MISSING_TIME_ITEMS"},Gc={message:"Missing context",code:"ERR_MISSING_CONTEXT"},UE={message:"Missing schedule",code:"ERR_MISSING_SCHEDULE"},Ka={message:"Invalid scaleItem",code:"ERR_INVALID_SCALE_ITEM"},PE={message:"Modifications failed",code:"ERR_FAILURE_MODIFICATIONS"},_s={message:"No modifications applied",code:"ERR_UNCHANGED_NO_MODIFICATIONS_APPLIED"},DE={message:"Unable to assign court",code:"ERR_UNCHANGED_COURT_NOT_ASSIGNED"},Qu={message:"No Candidates",code:"ERR_UNCHANGED_NO_CANDIDATES"},NE={message:"Invalid configuration",code:"ERR_INVALID_CONFIG"},ME={message:"Invalid collectionDefinition",code:"ERR_INVALID_COLLECTION_DEFINITION"},lo={message:"Invalid object",code:"ERR_INVALID_OBJECT"},Xu={message:"Invalid gender",code:"ERR_INVALID_GENDER"},Vc={message:"Invalid category",code:"ERR_INVALID_CATEGORY"},G={message:"Invalid values",code:"ERR_INVALID_VALUES"},RE={message:"Duplicate value",code:"ERR_DUPLICATE_VALUE"},ef={message:"Team not found",code:"ERR_NOT_FOUND_TEAM"},CE={message:"No valid actions",code:"ERR_NO_VALID_ACTIONS"},Ju={message:"No valid attributes",code:"ERR_NO_VALID_ATTRIBUTES"},rf={message:"Value unchanged",code:"ABORT_UNCHANGED"},ve={message:"Not found",code:"ERR_NOT_FOUND"},Zu={message:"Not implemented",code:"ERR_NOT_IMPLEMENTED"},bE={message:"Existing flight",code:"ERR_EXISTING_FLIGHT"},nf={message:"Existing flight profile",code:"ERR_EXISTING_FLIGHT_PROFILE"},vE={message:"Existing outcome",code:"ERR_EXISTING_OUTCOME"},OE={message:"Existing matchUpId",code:"ERR_EXISTING_MATCHUP_ID"},WI={message:"Existing stage",code:"ERR_EXISTING_STAGE"},of={message:"Existing structure",code:"ERR_EXISTING_STRUCTURE"},za={message:"Method not found",code:"ERR_NOT_FOUND_METHOD"},_E={message:"Scheduled matchUps",code:"ERR_SCHEDULED_MATCHUPS"},tp={message:"Scores present",code:"ERR_SCORES_PRESENT"},PC={ANACHRONISM:bI,CANNOT_CHANGE_WINNING_SIDE:Um,CANNOT_MODIFY_TIEFORMAT:$l,CANNOT_MODIFY_PARTICIPANT_TYPE:oE,CANNOT_REMOVE_MAIN_STRUCTURE:RA,CANNOT_REMOVE_PARTICIPANTS:Ku,CATEGORY_MISMATCH:GI,COURT_EXISTS:hE,COURT_NOT_FOUND:Os,DRAW_DEFINITION_NOT_FOUND:Mr,DRAW_ID_EXISTS:OA,DRAW_POSITION_ACTIVE:Yu,DRAW_POSITION_ASSIGNED:Wa,DRAW_POSITION_NOT_CLEARED:vA,DRAW_POSITION_NOT_FOUND:aL,DRAW_SIZE_MISMATCH:OI,DUPLICATE_ENTRY:Tm,DUPLICATE_VALUE:RE,ENTRY_STATUS_NOT_ALLOWED_FOR_EVENT:lE,ENTRY_STATUS_NOT_ALLOWED_IN_STAGE:dE,EVENT_EXISTS:HA,EVENT_NOT_FOUND:jr,EXISTING_DRAW_DEFINITIONS:CA,EXISTING_END_TIME:HI,EXISTING_FLIGHT:bE,EXISTING_MATCHUP_ID:OE,EXISTING_OUTCOME:vE,EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT:vs,EXISTING_PARTICIPANT:zu,EXISTING_POLICY_TYPE:FI,EXISTING_PROFILE:nf,EXISTING_ROUND:VA,EXISTING_STAGE:WI,EXISTING_STRUCTURE:of,INCOMPATIBLE_MATCHUP_STATUS:Bl,INCOMPLETE_SOURCE_STRUCTURE:wl,INSUFFICIENT_DRAW_POSITIONS:Ql,INVALID_ACTION:LA,INVALID_ASSIGNMENT:_I,INVALID_BOOKINGS:Am,INVALID_CATEGORY:Vc,INVALID_COLLECTION_DEFINITION:ME,INVALID_CONFIGURATION:NE,INVALID_DATE_AVAILABILITY:ql,INVALID_DATE:je,INVALID_DRAW_DEFINITION:ua,INVALID_DRAW_POSITION_FOR_SEEDING:Ll,INVALID_DRAW_POSITION:Rs,INVALID_DRAW_SIZE:qu,INVALID_END_TIME:TE,INVALID_ENTRIES:jA,INVALID_EVENT_TYPE:Bn,INVALID_GAME_SCORES:kI,INVALID_GENDER:Xu,INVALID_MATCHUP_FORMAT:Hl,INVALID_MATCHUP_STATUS:pa,INVALID_MATCHUP_STATUS_BYE:KA,INVALID_MATCHUP:dr,INVALID_OBJECT:lo,INVALID_PARTICIPANT_ID:mn,INVALID_PARTICIPANT_IDS:wr,INVALID_PARTICIPANT_ROLE:iE,INVALID_PARTICIPANT_SEEDING:_A,INVALID_PARTICIPANT_TYPE:An,INVALID_PARTICIPANT:xi,INVALID_POLICY_DEFINITION:XA,INVALID_RECORDS:vI,INVALID_SCALE_ITEM:Ka,INVALID_SEED_NUMBER:kA,INVALID_SEED_POSITION:GA,INVALID_SET_NUMBER:dL,INVALID_SIDE_NUMBER:jl,INVALID_SCORE:nE,INVALID_STAGE:Oi,INVALID_START_TIME:AE,INVALID_STRUCTURE:Qo,INVALID_STOP_TIME:yE,INVALID_TIE_FORMAT:Lo,INVALID_TIME:Eo,INVALID_TIME_ITEM:Jl,INVALID_TOURNAMENT_DATES:rE,INVALID_TOURNAMENT_RECORD:Ha,INVALID_VALUES:G,INVALID_WINNING_SIDE:Em,MATCHUP_NOT_FOUND:Le,METHOD_NOT_FOUND:za,MISSING_ASSIGNMENTS:Vl,MISSING_ASYNC_STATE_PROVIDER:EE,MISSING_AVOIDANCE_POLICY:QA,MISSING_BIRTH_DATE:JA,MISSING_COLLECTION_DEFINITION:zA,MISSING_COURT_ID:_i,MISSING_COURTS_INFO:IE,MISSING_DATE_AVAILABILITY:eE,MISSING_DATE:ZA,MISSING_DRAW_DEFINITION:Z,MISSING_DRAW_ID:an,MISSING_DRAW_POSITION:Cs,MISSING_DRAW_POSITIONS:ja,MISSING_DRAW_SIZE:Ya,MISSING_ENTRIES:WA,MISSING_EVENT:vt,MISSING_MATCHUP_FORMAT:Wl,MISSING_MATCHUP_ID:sr,MISSING_MATCHUP_IDS:rs,MISSING_MATCHUP:hr,MISSING_MATCHUPS:Xn,MISSING_PARTICIPANT_COUNT:uE,MISSING_PARTICIPANT_ID:oe,MISSING_PARTICIPANT_IDS:Uo,MISSING_PARTICIPANT_ROLE:sE,MISSING_PARTICIPANT:wi,MISSING_PARTICIPANTS:$a,MISSING_PENALTY_ID:Xl,MISSING_PENALTY_TYPE:gE,MISSING_PERSON_DETAILS:mE,MISSING_POLICY_ATTRIBUTES:LI,MISSING_POLICY_DEFINITION:$u,MISSING_POLICY_TYPE:wI,MISSING_POSITION_ASSIGNMENTS:$A,MISSING_ROUND_NUMBER:cL,MISSING_SCHEDULE:UE,MISSING_SCORING_POLICY:mL,MISSING_SEED_ASSIGNMENTS:FA,MISSING_SEEDCOUNT_THRESHOLDS:wA,MISSING_SEEDING_POLICY:uL,MISSING_SET_NUMBER:lL,MISSING_SET_OBJECT:Yl,MISSING_SIDE_NUMBER:fL,MISSING_STAGE:YA,MISSING_STRUCTURE_ID:Er,MISSING_STRUCTURE:pi,MISSING_STRUCTURES:Gl,MISSING_TARGET_LINK:kl,MISSING_TIE_FORMAT:bs,MISSING_TIME_ITEM:Zl,MISSING_TIME_ITEMS:tf,MISSING_TOURNAMENT_ID:ca,MISSING_TOURNAMENT_RECORD:Y,MISSING_TOURNAMENT_RECORDS:wt,MISSING_VALUE:st,MISSING_VENUE_ID:Xo,MODIFICATIONS_FAILED:PE,NO_CANDIDATES:Qu,NO_DRAW_POSITIONS_AVAILABLE_FOR_QUALIFIERS:fE,NO_MODIFICATIONS_APPLIED:_s,NO_STAGE_SPACE_AVAILABLE_FOR_ENTRY_STATUS:BI,NO_PARTICIPANT_REMOVED:cE,NO_VALID_ACTIONS:CE,NO_VALID_ATTRIBUTES:Ju,NO_VALID_DATES:tE,NOT_FOUND:ve,NOT_IMPLEMENTED:Zu,PARTICIPANT_COUNT_EXCEEDS_DRAW_SIZE:Kl,PARTICIPANT_ID_EXISTS:aE,PARTICIPANT_NOT_CHECKED_IN:pE,PARTICIPANT_NOT_FOUND:te,PARTICIPANT_PAIR_EXISTS:gL,PENALTY_NOT_FOUND:kc,POLICY_NOT_ATTACHED:pL,POLICY_NOT_FOUND:Fc,SCHEDULE_NOT_CLEARED:bA,SCHEDULED_MATCHUPS:_E,SCORES_PRESENT:tp,SEEDSCOUNT_GREATER_THAN_DRAW_SIZE:xA,STAGE_SEQUENCE_LIMIT:qA,STRUCTURE_NOT_FOUND:kt,TEAM_NOT_FOUND:ef,UNABLE_TO_ASSIGN_COURT:DE,UNLINKED_STRUCTURES:BA,UNRECOGNIZED_DRAW_TYPE:Fl,UNRECOGNIZED_MATCHUP_FORMAT:qa,UNRECOGNIZED_MATCHUP_STATUS:xI,VALUE_UNCHANGED:rf,VENUE_EXISTS:SE};var Ze={disableNotifications:!1,tournamentId:void 0,tournamentRecords:{},subscriptions:{},modified:!1,methods:{},notices:[]},xE={addNotice:ML,callListener:OL,cycleMutationStatus:NL,deleteNotice:bL,deleteNotices:CL,disableNotifications:IL,enableNotifications:hL,getMethods:ep,getNotices:RL,getTopics:vL,getTournamentId:DC,getTournamentRecord:SL,getTournamentRecords:TL,removeTournamentRecord:UL,setMethods:DL,setSubscriptions:PL,setTournamentId:AL,setTournamentRecord:yL,setTournamentRecords:EL,handleCaughtError:_L};function IL(){Ze.disableNotifications=!0}function hL(){Ze.disableNotifications=!1}function DC(){return Ze.tournamentId}function SL(t){return Ze.tournamentRecords[t]}function TL(){return Ze.tournamentRecords}function yL(t){let e=t?.tournamentId;return e?(Ze.tournamentRecords[e]=t,{success:!0}):{error:Ha}}function AL(t){return t?Ze.tournamentRecords[t]?(Ze.tournamentId=t,{success:!0}):{error:Y}:(Ze.tournamentId=void 0,{success:!0})}function EL(t){Ze.tournamentRecords=t;let e=Object.keys(t);e.length===1?Ze.tournamentId=e[0]:e.length||(Ze.tournamentId=void 0)}function UL(t){if(typeof t!="string")return{error:G};if(!Ze.tournamentRecords[t])return{error:ve};delete Ze.tournamentRecords[t];let e=Object.keys(Ze.tournamentRecords);return e.length===1?Ze.tournamentId=e[0]:e.length||(Ze.tournamentId=void 0),{success:!0}}function PL(t){return typeof t.subscriptions!="object"?{error:G}:(Object.keys(t.subscriptions).forEach(e=>{typeof t.subscriptions[e]=="function"?Ze.subscriptions[e]=t.subscriptions[e]:delete Ze.subscriptions[e]}),{...C})}function DL(t){return typeof t!="object"?{error:G}:(Object.keys(t).forEach(e=>{typeof t[e]=="function"&&(Ze.methods[e]=t[e])}),{...C})}function NL(){let t=Ze.modified;return Ze.modified=!1,t}function ML({topic:t,payload:e,key:r},n){if(!(typeof t!="string"||typeof e!="object")&&(Ze.disableNotifications||(Ze.modified=!0),!(Ze.disableNotifications||!Ze.subscriptions[t]&&!n)))return r&&(Ze.notices=Ze.notices.filter(o=>!(o.topic===t&&o.key===r))),Ze.notices.push({topic:t,payload:e,key:r}),{...C}}function ep(){return Ze.methods??{}}function RL({topic:t}){return Ze.notices.filter(e=>e.topic===t).map(e=>e.payload)}function CL(){Ze.notices=[]}function bL({topic:t,key:e}){Ze.notices=Ze.notices.filter(r=>(!t||r.topic===t)&&r.key!==e)}function vL(){return{topics:Object.keys(Ze.subscriptions)}}function OL({topic:t,notices:e},r){let n=Ze.subscriptions[t];n&&typeof n=="function"&&n(e);let o=r?.[t];o&&typeof o=="function"&&o(e)}function _L({engineName:t,methodName:e,params:r,err:n}){let o;return typeof n=="string"?o=n.toUpperCase():n instanceof Error&&(o=n.message),console.log("ERROR",{tournamentId:DC(),params:JSON.stringify(r),engine:t,methodName:e,error:o}),{error:o}}var Oe={timers:{default:{elapsedTime:0}},globalSubscriptions:{},deepCopyAttributes:{stringify:[],ignore:[],toJSON:[]},globalMethods:[],deepCopy:!0},cn=xE,NC=["addNotice","callListener","cycleMutationStatus","deleteNotice","deleteNotices","disableNotifications","enableNotifications","getMethods","getNotices","getTopics","getTournamentId","getTournamentRecord","getTournamentRecords","removeTournamentRecord","setSubscriptions","setTournamentId","setTournamentRecord","setTournamentRecords"];function xL(t){if(typeof t!="object")throw new Error("Global state provider can not be undefined or null");if(Yt(Object.keys(t),NC).length!==NC.length)throw new Error("Global state provider is missing required methods");return cn=t,{success:!0}}function wE(){if(cn.createInstanceState){try{cn.createInstanceState()}catch(t){return{error:t}}return{success:!0}}else return{error:EE}}function Ur(t){return!t||typeof t!="object"?Oe.devContext??!1:typeof Oe.devContext!="object"?!1:Object.keys(t).every(e=>Oe.devContext?.[e]===t[e])&&Oe.devContext}function wL(t="reset",e="default"){let r=Date.now();if(t==="report"){if(e==="allTimers")return Object.keys(Oe.timers).filter(o=>o!=="default"||Oe.timers[o].startTime).map(o=>{let i=Oe.timers[o],s=i.state==="stopped"?0:(r-(i?.startTime??0))/1e3,a=i.elapsedTime+s;return{state:Oe.timers[o].state,elapsedTime:a.toFixed(2),timer:o}});{let n=Oe.timers[e].state==="stopped"?0:(r-(Oe.timers[e]?.startTime??0))/1e3,o=Oe.timers[e].elapsedTime+n;return{state:Oe.timers[e].state,elapsedTime:o.toFixed(2),timer:e}}}if(!Oe.timers[e]||t==="reset"){if(e==="allTimers")return Oe.timers={default:{elapsedTime:0}},!0;Oe.timers[e]={startTime:r,state:"active",elapsedTime:0}}return Oe.timers[e].elapsedTime||(Oe.timers[e].elapsedTime=0),t==="stop"&&Oe.timers[e].state!=="stopped"&&(Oe.timers[e].state="stopped")&&(Oe.timers[e].elapsedTime+=(r-(Oe.timers[e]?.startTime??0))/1e3),t==="start"&&(Oe.timers[e].startTime=r)&&(Oe.timers[e].state="active"),Oe.timers[e]}function MC(t){Wr(t)?Oe.globalLog=t:delete Oe.globalLog}function Bc(t){Oe.devContext=t}function LE(){cn.disableNotifications()}function sf(){cn.enableNotifications()}function Hc(t,e){typeof t=="boolean"&&(Oe.deepCopy=t),typeof e=="object"&&(Array.isArray(e.ignore)&&(Oe.deepCopyAttributes.ignore=e.ignore),Array.isArray(e.toJSON)&&(Oe.deepCopyAttributes.toJSON=e.toJSON),Array.isArray(e.stringify)&&(Oe.deepCopyAttributes.stringify=e.stringify),e.threshold&&(Oe.deepCopyAttributes.threshold=e.threshold))}function af(){return{enabled:Oe.deepCopy,...Oe.deepCopyAttributes}}function LL(t){return t?.subscriptions?(Object.keys(t.subscriptions).forEach(e=>{Oe.globalSubscriptions[e]=t.subscriptions[e]}),{...C}):{error:st,info:"missing subscriptions"}}function FL(t){return t?.subscriptions?cn.setSubscriptions({subscriptions:t.subscriptions}):{error:st,info:"missing subscriptions"}}function RC(t){return t?typeof t!="object"?{error:G}:(Object.keys(t).forEach(e=>{Wr(t[e])&&(Oe.globalMethods[e]=t[e])}),{...C}):{error:st,info:"missing method declarations"}}function CC(t){return t?typeof t!="object"?{error:G}:cn.setMethods(t):{error:st,info:"missing method declarations"}}function cf(){return cn.cycleMutationStatus()}function mt(t){if(typeof t?.topic!="string")return;let e=Oe.globalSubscriptions[t.topic];return cn.addNotice(t,e)}function uf(){return{...Oe.globalMethods,...cn.getMethods()}}function jI(t){return cn.getNotices(t)}function YI({key:t,topic:e}){return cn.deleteNotice({key:t,topic:e})}function Fi(){return cn.deleteNotices()}function Lr(){return cn.getTopics()}function rp(t){return Lr()?.topics?.includes(t)}async function Pm(t){return cn.callListener(t,Oe.globalSubscriptions)}function ns(){return cn.getTournamentId()}function pf(t){return cn.getTournamentRecord(t)}function Fo(){return cn.getTournamentRecords()}function FE(t){return cn.setTournamentRecord(t)}function Dm(t){return cn.setTournamentRecords(t)}function np(t){return cn.setTournamentId(t)}function kE(t){return cn.removeTournamentRecord(t)}function qI(){return cn}function op({engineName:t,methodName:e,params:r,err:n}){let o=Wr(cn.handleCaughtError)&&cn.handleCaughtError||xE.handleCaughtError,{tournamentRecord:i,...s}=r;return o({params:s,engineName:t,methodName:e,err:n})}function GE(t,e){if(Oe.globalLog)try{Oe.globalLog({log:t,engine:e})}catch(r){console.log("globalLog error",r),console.log(e,t),MC()}else console.log(e,t)}function VE(t,e,r,n){if(!ht(t))return{error:G};Zt||(r=1);let o=Array.isArray(e)?e:[],i={},s=(a,c=0)=>{Object.keys(a).forEach(u=>{Wr(a[u])?i[u]=a[u]:ht(a[u])&&(e===!0||o?.includes(u))&&(r===void 0||c<r)&&s(a[u],c+1)})};return s(t),n?RC(i):CC(i),{methods:i}}function kL(t,e,r){return Object.keys(t).filter(n=>!e.includes(t[n])&&(!r||(Array.isArray(t[n])?t[n].length:!0)))}function ot(t,e,r,n){if(typeof t!="object"||t===null)return t;af()?.enabled||(n=!0);let i=["",void 0,null];e&&i.push(!1);let s=kL(t,i,r);return Object.assign({},...s.map(a=>Array.isArray(t[a])?{[a]:n?t[a]:t[a].map(c=>ot(c))}:{[a]:n?t[a]:ot(t[a])}))}function _({context:t,result:e,stack:r,info:n}){return e&&!Array.isArray(e?.stack)&&(e.stack=[]),e&&Array.isArray(e?.stack)&&typeof r=="string"&&e.stack.push(r),e&&n&&(e.info=n),e&&typeof t=="object"&&Object.keys(t).length&&Object.assign(e,ot(t)),e&&!e?.error&&!e?.success&&Object.assign(e,{...C}),e??{success:!0}}var Pn="ANY",$t="MALE",Tr="MIXED",os="OTHER",ne="FEMALE",Nm={ANY:Pn,MALE:$t,FEMALE:ne,MIXED:Tr,OTHER:os};var GL="MIXED events can not contain mixed singles or { gender: ANY } collections",VL="events with { gender: ANY } can not contain MIXED singles collections";function Mm(t){let e="tieFormatGenderValidityCheck",{referenceGender:r,matchUpType:n,gender:o}=t;return r&&o&&[$t,ne].includes(r)&&r!==o?_({result:{valid:!1,error:Xu},context:{gender:o},stack:e}):r===Tr&&(o===Pn||o===Tr&&n!==_t)?_({result:{error:Xu,valid:!1},info:GL,stack:e}):r===Pn&&o===Tr&&n!==_t?_({result:{error:Xu,valid:!1},info:VL,stack:e}):{valid:!0}}var BL="normal",BE="timed",HL="final",mf="NOAD",Rm="SET",vC={S:BL,F:HL};function ip(t,e){if(ht(t),(t?.bestOf||t?.exactly)&&t?.setFormat)return WL(t,e)}function df(t){return!isNaN(Number(t))&&Number(t)}function xC(t){let e=`T${t.minutes}`;return t.based&&(e+=t.based),t.modifier&&(e+=`@${t.modifier}`),e}function WL(t,e){let r=df(t.bestOf)||void 0,n=df(t.exactly)||void 0,o=r||n;if(t.setFormat?.timed&&t.simplified&&o===1)return xC(t.setFormat);let i=o&&`${Rm}${o}`||"",s=OC(t.setFormat,e),a=s&&`S:${s}`||"",c=OC(t.finalSetFormat,e),u=o&&o>1&&c&&s!==c&&`F:${c}`||"";if(i&&s)return[i,a,u].filter(m=>m).join("-")}function OC(t,e){if(typeof t=="object"&&Object.keys(t).length){if(t.timed)return xC(t);if(t.tiebreakSet)return _C(t.tiebreakSet);let r=df(t.setTo);if(r){let n=t.NoAD&&mf||"",o=_C(t.tiebreakFormat),i=o&&`/${o}`||"",s=df(t.tiebreakAt),a=s&&(s!==r||e)&&`@${s}`||"";if(o!==!1)return`${r}${n}${i}${a}`}}}function _C(t){if(t){if(typeof t=="object"&&!t.tiebreakTo)return"";if(typeof t=="object"&&df(t.tiebreakTo)){let e=`TB${t.tiebreakTo}${t.NoAD?mf:""}`;return t.modifier&&(e+=`@${t.modifier}`),e}else return!1}}function Ye(t){if(Vt(t)){let e=t.startsWith("T")&&BE||t.startsWith(Rm)&&Rm||"";if(e===BE){let r=kC(t),n={simplified:!0,setFormat:r,bestOf:1};if(r)return n}if(e===Rm)return jL(t)}}function jL(t){let e=t.split("-"),r=lf(e[0].slice(3)),n=r===1||r%2!==0?r:void 0,o=r!==1&&r%2===0?r:void 0,i=e&&wC(e[1]),s=e&&wC(e[2]),a=i&&i.timed||s&&s.timed,c=n&&n<6||a&&o,u=!e[2]||s,p=i,m=ot({setFormat:i,exactly:o,bestOf:n});if(s&&(m.finalSetFormat=s),c&&p&&u)return m}function wC(t){if(t?.[1]===":"){let e=t.split(":"),r=vC[e[0]],n=e[1];if(r&&n){if(n.startsWith("TB")){let I=LC(n);return I===!1?!1:typeof I=="object"?{tiebreakSet:I}:void 0}if(n.startsWith("T"))return kC(n);let s=t.match(/^[FS]:(\d+)([A-Za-z]*)/),a=s&&GC(s[2])||!1,c=!s?.[2]||a,u=s?lf(s[1]):void 0,p=FC(n),m=p!==!1,d=m&&p||u,l=LC(n.split("/")[1]),f=l!==!1,g={setTo:u};return a&&(g.NoAD=!0),l?(g.tiebreakFormat=l,g.tiebreakAt=d):g.noTiebreak=!0,u&&c&&f&&m&&g||!1}}}function FC(t,e=!0){let r=t?.indexOf("@")>0&&t.split("@");if(r)return(e?lf(r[1]):r[1])||!1}function LC(t){if(t)if(t.startsWith("TB")){let e=FC(t,!1),r=t.match(/^TB(\d+)([A-Za-z]*)/),n=r?.[1],o=r&&GC(r[2]),i=!r?.[2]||o,s=lf(n);if(s&&i){let a={tiebreakTo:s};return e&&typeof e=="string"&&!It(e)&&(a.modifier=e),o&&(a.NoAD=!0),a}else return!1}else return!1}function kC(t){let e=t.slice(1),r=e.match(/^(\d+)(@?[A-Za-z]*)/),n=lf(r?.[1]);if(!n)return;let o={timed:!0,minutes:n},i=r?.[2],s=[void 0,"P","G"].includes(i);if(i&&!s){let a=e.match(/^(\d+)(@)([A-Za-z]+)$/)?.[3];return a?(o.modifier=a,o):void 0}return i&&(o.based=r[2]),o}function GC(t){return t&&t.indexOf(mf)>=0}function lf(t){return isNaN(Number(t))?0:Number(t)}function Pr({matchUpFormat:t}){if(!Vt(t)||t==="")return!1;let e=Ye(t),r=t.match(/-S:([1-9])+\/TB([0-9]{1,2})@?([1-9]?)*/),n=r?.[1],o=r?.[2],i=r?.[3],s=t.match(/-F:([1-9])+\/TB([0-9]{1,2})@?([1-9]?)*/),a=s?.[1],c=s?.[2],u=s?.[3];return ip(e,!!(r&&o&&n===i||s&&c&&a===u))===t}var Cm=/^[\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1])$/,$I=/^((0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)([.,][0-9]{3})?$/,Po=/^([\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1]))([ T](0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)?([.,][\d]{3})?Z?$/,xs=/^([\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1]))?([ T]?(0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)?([.,][\d]{3})?Z?$/;function bm(t){let{scheduledDate:e}=t;if(!e&&t.scheduledTime&&(e=Et(t.scheduledTime)),!e)return;let r=Kt(t.scheduledTime),n=Et(e);return n&&r&&(n+=`T${r}`),n}function VC(t){return typeof t!="object"||Array.isArray(t)?!1:Object.prototype.toString.call(t)==="[object Date]"}function Wc(t){let e=typeof t=="string"?t?.split(" "):[];return t&&e?.length>1&&!["AM","PM"].includes(e[1].toUpperCase())?!1:!!(!t||xs.test(Xa(t,!0,!0)))}function Rr(t){return Qa(t)||Cm.test(t)}function YL(t){let e=new Date(t),r=e.getSeconds()+60*e.getMinutes()+60*60*e.getHours();return qL(r,{displaySeconds:!1})}function qL(t,e){let r=parseInt(t,10),n=Math.floor(r/3600),o=Math.floor((r-n*3600)/60),i=r-n*3600-o*60;return(!e||e?.displaySeconds?n+":"+o+":"+i:n+":"+o).split(":").map(Jn).join(":")}var If=t=>{let e=ff(t)||Qa(t)?new Date(t):new Date,r=e.getUTCMonth()+1,n=r<10?`0${r}`:`${r}`;return`${e.getUTCFullYear()}-${Jn(n)}-${Jn(e.getUTCDate())}`};function $L(t){let e=ff(t)||Qa(t)?new Date(t):new Date;return Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())}function Hn(t,e="-",r="YMD"){if(!t)return"";typeof t=="string"&&t.indexOf("T")<0&&(t=t+"T00:00");let n=new Date(t),o=""+(n.getMonth()+1),i=""+n.getDate(),s=n.getFullYear();return o.length<2&&(o="0"+o),i.length<2&&(i="0"+i),r==="DMY"?[i,o,s].join(e):r==="MDY"?[o,i,s].join(e):r==="YDM"?[s,i,o].join(e):r==="DYM"?[i,s,o].join(e):r==="MYD"?[o,s,i].join(e):[s,o,i].join(e)}function KI(t){let e=t?new Date(t):new Date,r=e.getTimezoneOffset();return new Date(e.getTime()-r*60*1e3)}function KL(t){return KI(t).getTime()}function ff(t){if(typeof t=="boolean")return!1;let e=t instanceof Date&&t||!isNaN(t)&&new Date(t)||!1;return e&&!isNaN(e.valueOf())}function ws(t,e){if(!Rr(t)||!Rr(e))return[];let r=Et(t)+"T00:00",n=Et(e)+"T00:00",o=new Date(r),i=new Date(n),s=ff(i)&&ff(o)&&u(o,i),a=[],c=0;if(s){let p=o,m=p.getTime();for(;m<=i.getTime()&&c<300;)c+=1,a.push(new Date(p)),m=p.setDate(p.getDate()+1)}return a.map(p=>Hn(p));function u(p,m){return p<=m}}var zL=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;function Qa(t){return typeof t!="string"?!1:zL.test(t)}function QI(t){if(typeof t!="string")return!1;let r=t.split("Z")[0].split(":"),n=r.every(i=>!isNaN(parseInt(i)));return!(r.length<2||!n||parseInt(r[0])>23||parseInt(r[1])>60)}function qt(t){let e=Kt(t);if(!e)return 0;let[r,n]=e.split(":").map(o=>parseInt(o));return r*60+n}function BC(t){let e=Math.floor(t/60),r=t-e*60;return e>23&&(e=e%24),[Jn(e),Jn(r)].join(":")}function gf(t){return QI(t)?t.split(":").slice(0,2).map(Jn).join(":"):void 0}function Kt(t){return Qa(t)&&t.indexOf("T")>0?gf(t.split("T").reverse()[0]):gf(t)}function Et(t){return Qa(t)||Po.test(t)?t.split("T")[0]:void 0}function sp(t,e){let r=new Date(t);return r.setDate(r.getDate()+e),Et(r.toISOString())}function zI(t){t=typeof t!="string"?"00:00":t;let e={},r={};return{0:e.time,1:e.ampm}=t.split(" ")||[],{0:r.hours,1:r.minutes}=e.time.split(":")||[],r.ampm=e.ampm,isNaN(r.hours)||isNaN(r.minutes)||r.ampm&&!["AM","PM"].includes(r.ampm.toUpperCase())?{}:r}function QL(t){let e=zI(t);return e.ampm&&e.hours&&(e.ampm.toLowerCase()==="pm"&&parseInt(e.hours)<12&&(e.hours=(e.hours&&parseInt(e.hours)||0)+12),e.ampm.toLowerCase()==="am"&&e.hours==="12"&&(e.hours="00")),`${e.hours||"12"}:${e.minutes||"00"}`.split(":").map(Jn).join(":")}function XL(t){let e=zI(t);if(!(typeof e=="object"&&!Object.keys(e).length))return e.ampm?t:(e.hours>12?(e.hours-=12,e.ampm="PM"):e.hours==="12"?e.ampm="PM":(e.hours==="00"&&(e.hours="12"),e.ampm="AM"),e.hours?.[0]==="0"&&(e.hours=e.hours.slice(1)),`${e.hours||"12"}:${e.minutes||"00"} ${e.ampm}`)}function Xa(t,e,r){let n=Et(t),o=Kt(t),i=n?o:t;return t?e&&(n&&r&&t||QL(i))||XL(i):void 0}function XI(t,e){let r=zI(t),n=zI(e);if(parseInt(r.hours)<parseInt(n.hours))return-1;if(parseInt(r.hours)>parseInt(n.hours))return 1;if(r.hours===n.hours){if(parseInt(r.minutes)<parseInt(n.minutes))return-1;if(parseInt(r.minutes)>parseInt(n.minutes))return 1}return 0}function JI(t,e=7){let r=Et(t)+"T00:00",n=new Date(r),o=new Date(n.setDate(n.getDate()+e));return Hn(o)}function JL(t){return JI(t)}function ZL(t,e,r,n=!1){let o=new Date(e,0,1+(t-1)*7),i=n?0:1;return o.setDate(o.getDate()+(i-o.getDay())),Hn(o,r)}function HC(t,e,r){let n=new Date(t,0);return Hn(new Date(n.setDate(e)),r)}function ke(t,e=void 0){let[r,n]=(t||"00:00").split(":").map(Jn),o=KI(e).setHours(r,n,0,0);return KI(o)}function ma(t,e,r=!0){let n=new Date(t),i=(new Date(e).getTime()-n.getTime())/1e3/60;return r?Math.abs(Math.round(i)):Math.round(i)}function Yr(t,e){let r=Kt(t);if(!r)return"00:00";let n=isNaN(e)?0:e;return Kt(hf(ke(r),n).toISOString())}function hf(t,e){let r=new Date(t);return new Date(r.getTime()+e*6e4)}function Jn(t){return t.toString()[1]?t:"0"+t}function Wn(t,e){let r=new Date(t),n=new Date(e);return r.getFullYear()===n.getFullYear()&&r.getMonth()===n.getMonth()&&r.getDate()===n.getDate()}var ZI={addDays:JI,addWeek:JL,addMinutesToTimeString:Yr,convertTime:Xa,getIsoDateString:bm,getUTCdateString:If,DateHHMM:YL,extractDate:Et,extractTime:Kt,formatDate:Hn,getDateByWeek:ZL,isISODateString:Qa,isDate:ff,isTimeString:QI,offsetDate:KI,offsetTime:KL,sameDay:Wn,timeStringMinutes:qt,timeToDate:ke,timeUTC:$L,validTimeValue:Wc,validDateString:Cm,timeValidation:xs,dateValidation:Po};var tF=(t,e)=>t.filter(Boolean).every(r=>typeof r===e),eF=t=>t.filter(Boolean).every(Zt);function Ls(t){let e=t.category;if(typeof e!="object")return{error:Vc};let{ageCategoryCode:r,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s}=e,a=e.categoryName,c;if(!tF([r,n,o,a],"string")||!eF([i,s]))return{error:Vc};let u=t.consideredDate??Et(new Date().toLocaleDateString("sv"));if(!Rr(u))return{error:je};let[p]=u.split("-").slice(0,3).map(w=>parseInt(w)),m=sp(u,-1),[d,l]=m.split("-").slice(1,3).map(w=>parseInt(w)),f=`${Jn(d)}-${Jn(l)}`,g=sp(u,1),[I,h]=g.split("-").slice(1,3).map(w=>parseInt(w)),S=`${Jn(I)}-${Jn(h)}`,T=s&&sp(u,-1*365*s),y=i&&sp(u,-1*365*i),P=[],U=w=>!P.includes(w)&&P.push(w);r=r??a;let E=/^([UO]?)(\d{1,2})([UO]?)$/,A=/^C(\d{1,2})-(\d{1,2})$/,N=r?.includes("-"),D=N&&r?.match(A),M=r?.match(E),R=(w,V)=>`${w}-${V}`,b=w=>{let V=p-w,k=R(V,S);e.ageMinDate&&e.ageMinDate!==k&&U(`Invalid submitted ageMinDate: ${o}`),o=k,r&&(e.ageMax&&e.ageMax!==w-1&&(U(`Invalid submitted ageMax: ${i}`),y=void 0),i=w-1)},v=w=>{let V=p-w-1,k=R(V,S);e.ageMin&&e.ageMin>w&&U(`Invalid submitted ageMin: ${s}`),e.ageMax&&e.ageMax>w&&U(`Invalid submitted ageMax: ${i}`),e.ageMinDate&&e.ageMinDate!==k&&U(`Invalid submitted ageMinDate: ${o}`),o=k,r&&(e.ageMax&&e.ageMax!==w&&(U(`Invalid submitted ageMax: ${i}`),T=void 0),i=w)},O=w=>{let V=p-w,k=R(V,f);e.ageMaxDate&&e.ageMaxDate!==k&&U(`Invalid submitted ageMaxDate: ${n}`),n=k,r&&(e.ageMin&&e.ageMin!==w+1&&(U(`Invalid submitted ageMin: ${s}`),T=void 0),s=w+1)},x=w=>{let V=p-w-1,k=R(V,f);e.ageMaxDate&&e.ageMaxDate!==k&&U(`Invalid submitted ageMaxDate: ${n}`),n=k,r&&(e.ageMin&&e.ageMin!==w&&(U(`Invalid submitted ageMin: ${s}`),T=void 0),s=w)},F=w=>{let[V,k,W]=(w.match(E)||[]).slice(1),H=parseInt(k);V==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&U(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),b(H)):V==="O"&&O(H),W==="U"?(e.ageMaxDate&&e.ageMaxDate!==n&&U(`Invalid submitted ageMaxDate: ${e.ageMaxDate}`),v(H)):W==="O"&&x(H),n=n??T,o=o??y};if(D){if(n=void 0,o=void 0,i=void 0,s=void 0,e.ageMin){let k=p-e.ageMin;n=R(k,f)}if(e.ageMax){let k=p-e.ageMax-1;o=R(k,S)}let[w,V]=(r?.match(A)??[]).slice(1).map(k=>parseInt(k));w<=V?(s=w,i=V,c=!0):U(`Invalid combined age range ${r}`)}else N?r?.split("-").forEach(F):M?F(r):(s&&O(s),i&&v(i));i&&e.ageMin&&e.ageMin>i&&(U(`Invalid submitted ageMin: ${e.ageMin}`),s=void 0);let L=ot({consideredDate:u,combinedAge:c,ageMaxDate:n,ageMinDate:o,ageMax:i,ageMin:s});return P.length&&(L.errors=P),L}function jc({category:t}){if(!ht(t))return{error:G};let e=Ls({category:t});if(e.error)return{error:e};let{ratingMax:r,ratingMin:n}=t;return r&&!Zt(r)?_({result:{error:G},context:{ratingMax:r}}):n&&!Zt(n)?_({result:{error:G},context:{ratingMin:n}}):{...e}}function Yc({childCategory:t,withDetails:e,category:r}){let n=jc({category:r}),o=jc({category:t}),i=o.ageMin&&(n.ageMin&&o.ageMin<n.ageMin||n.ageMax&&o.ageMin>n.ageMax),s=o.ageMax&&(n.ageMax&&o.ageMax>n.ageMax||n.ageMin&&o.ageMax<n.ageMin),a=o.ageMinDate&&n.ageMaxDate&&new Date(o.ageMinDate)>new Date(n.ageMaxDate),c=o.ageMaxDate&&n.ageMinDate&&new Date(o.ageMaxDate)<new Date(n.ageMinDate),p=r?.ratingType&&t?.ratingType&&r.ratingType===t.ratingType&&(r.ratingMin&&t.ratingMin&&t.ratingMin<r.ratingMin||r.ratingMax&&t.ratingMax&&t.ratingMax>r.ratingMax||r.ratingMin&&t.ratingMax&&t.ratingMax<r.ratingMin||r.ratingMax&&t.ratingMin&&t.ratingMin>r.ratingMax),m=r?.ballType&&t?.ballType&&r.ballType!==t.ballType,f=ot({invalidRatingRange:p,invalidAgeMinDate:a,invalidAgeMaxDate:c,invalidBallType:m,invalidAgeMax:s,invalidAgeMin:i,valid:!p&&!a&&!c&&!m&&!s&&!i},!0);return e&&Object.assign(f,{categoryDetails:n,childCategoryDetails:o}),f}function qc({checkCategory:t=!0,collectionDefinition:e,checkCollectionIds:r,checkGender:n=!0,referenceCategory:o,referenceGender:i,event:s}){i=i??s?.gender;let a="validateCollectionDefinition",c=[];if(typeof e!="object")return c.push(`collectionDefinition must be an object: ${e}`),_({result:{errors:c,error:lo},stack:a});let{collectionValueProfiles:u,collectionGroupNumber:p,collectionValue:m,collectionId:d,matchUpCount:l,matchUpFormat:f,matchUpValue:g,matchUpType:I,scoreValue:h,setValue:S,category:T,gender:y}=e;if(r&&typeof d!="string"&&c.push(`collectionId is not type string: ${d}`),typeof l!="number"&&c.push(`matchUpCount is not type number: ${l}`),I&&!Lc([xt,_t],I)&&c.push(`matchUpType must be SINGLES or DOUBLES: ${I}`),[!!u?.length].concat([g,m,h,S].map(It)).filter(Boolean).length!==1&&c.push("Missing value definition for matchUps: matchUpValue, collectionValue, or collectionValueProfiles"),g&&typeof g!="number"&&c.push(`matchUpValue is not type number: ${g}`),m&&typeof m!="number"&&c.push(`collectionValue is not type number: ${m}`),u&&l){let U=CI({collectionValueProfiles:u,matchUpCount:l});U.errors&&c.push(...U.errors)}if(p&&typeof p!="number"&&c.push(`collectionGroupNumber is not type number: ${m}`),f&&!Pr({matchUpFormat:f})&&c.push(`Invalid matchUpFormat: ${f}`),n){let U=Mm({referenceGender:i,matchUpType:I,gender:y});if(U.error)return _({context:{referenceGender:i,gender:y},result:U,stack:a})}if(t&&o&&T){let U=Yc({category:o,childCategory:T});if(!U.valid)return _({result:{error:Vc},context:U,stack:a})}return c.length?_({result:{errors:c,error:ME},stack:a}):{valid:!0}}function ar(t){let e=!!(t?.enforceCategory!==!1&&t?.category),r=!!(t?.enforceGender!==!1&&t?.gender),n=t?.checkCollectionIds,o=t?.tieFormat,i=t?.event,s="validateTieFormat",a=[],c=rF({...t,stack:s});if(c?.error)return c;let u,p=o.collectionDefinitions.every(I=>{let{setValue:h,scoreValue:S,collectionValue:T}=I;(h||S)&&!T&&(u=!0);let{valid:y,errors:P}=qc({referenceCategory:t.category,referenceGender:t.gender,collectionDefinition:I,checkCollectionIds:n,checkCategory:e,checkGender:r,event:i});return y?!0:(Array.isArray(P)&&a.push(...P),!1)}),m=typeof o.winCriteria?.valueGoal=="number"&&o.winCriteria?.valueGoal>0&&!u||o.winCriteria?.aggregateValue;if(!(m||o.winCriteria?.aggregateValue))return u?a.push("aggregateValue is required"):a.push("Either non-zero valueGoal, or { aggregateValue: true } must be specified in winCriteria"),_({context:{tieFormat:o,errors:a,aggregateValueImperative:u},result:{error:Lo},stack:s});let d=o.collectionDefinitions.map(({collectionId:I})=>I),l=!n||d.length===ut(d).length,f=p&&m&&l,g={valid:f,errors:a};return f?g:_({result:{error:Lo},context:{tieFormat:o,errors:a},stack:s})}function rF(t){let{tieFormat:e,stack:r}=t;return!t||!e||!ht(e)?_({result:{error:Lo},context:{tieFormat:e,message:"tieformat must be an object"},stack:r}):ht(e.winCriteria)?Array.isArray(e.collectionDefinitions)?{...C}:_({result:{error:Lo},context:{tieFormat:e,message:"collectionDefinitions must be an array"},stack:r}):_({result:{error:Lo},context:{tieFormat:e,message:"tieformat.winCritiera must be an object"},stack:r})}var Ja="resourceSubType",Za="resourceType",tc="identifier",WC={RESOURCE_SUB_TYPE:Ja,RESOURCE_TYPE:Za,IDENTIFIER:tc};function J(t,e,r,n,o=0){if(qI().makeDeepCopy)return qI().makeDeepCopy(t,e,r,n);let i=af(),{stringify:s,toJSON:a,ignore:c,modulate:u}=i||{};if(!i?.enabled&&!r||typeof t!="object"||Wr(t)||t===null||typeof i?.threshold=="number"&&o>=i.threshold)return t;let p=Array.isArray(t)?[]:{},m=Object.keys(t).filter(l=>!r||!c||Array.isArray(c)&&!c.includes(l)||Wr(c)&&!c(l)),d=(l,f)=>{p[l]=Wr(f?.toString)?f.toString():JSON.stringify(f)};for(let l of m){let f=t[l],g=Wr(u)?u(f):void 0;if(g!==void 0)p[l]=g;else if(e&&l==="extensions"&&Array.isArray(f)){let I=Sf(f);Object.assign(p,...I)}else n&&l==="extensions"?p[l]=[]:Array.isArray(s)&&s.includes(l)?d(l,f):Array.isArray(a)&&a.includes(l)&&Wr(f?.toJSON)?p[l]=f.toJSON():f===null?p[l]=void 0:VC(f)?p[l]=new Date(f).toISOString():p[l]=J(f,e,r,n,o+1)}return p}function Sf(t){return t?.map(e=>{let{name:r,value:n}=e;return r&&n&&{[`_${r}`]:n}}).filter(Boolean)}function th(t=1,e){return et(0,t).map(()=>Dt(e))}function Dt(t){let e=[];for(let a=0;a<256;a++)e[a]=(a<16?"0":"")+a.toString(16);let r=Math.random()*4294967295|0,n=Math.random()*4294967295|0,o=Math.random()*4294967295|0,i=Math.random()*4294967295|0,s=e[r&255]+e[r>>8&255]+e[r>>16&255]+e[r>>24&255]+"-"+e[n&255]+e[n>>8&255]+"-"+e[n>>16&15|64]+e[n>>24&255]+"-"+e[o&63|128]+e[o>>8&255]+"-"+e[o>>16&255]+e[o>>24&255]+e[i&255]+e[i>>8&255]+e[i>>16&255]+e[i>>24&255];return typeof t=="string"?`${t}_${s.replace(/-/g,"")}`:s}var eh={collectionDefinitions:[{collectionName:"Male Singles",matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpCount:4,matchUpValue:1,gender:"MALE"},{collectionName:"Female Singles",matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",gender:"FEMALE",matchUpCount:4,matchUpValue:1},{collectionName:"Male Doubles",matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",matchUpCount:2,matchUpValue:1,gender:"MALE"},{collectionName:"Female Doubles",matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",gender:"FEMALE",matchUpCount:2,matchUpValue:1},{collectionName:"Mixed Doubles",matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",matchUpCount:4,matchUpValue:1,gender:"MIXED"}],tieFormatName:"USTA_GOLD_TEAM_CHALLENGE",winCriteria:{valueGoal:9}};var rh={collectionDefinitions:[{collectionName:"Round 1",matchUpCount:3,matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Round 2",matchUpCount:3,matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Round 3",matchUpCount:3,matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"Doubles Shuffle",unrestrictedSelections:!0,winCriteria:{aggregateValue:!0}};var nh={collectionDefinitions:[{collectionName:"Male Singles",gender:"MALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Mixed Doubles",gender:"MIXED",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],tieFormatName:"USTA_SOUTHERN_LEVEL_5",winCriteria:{valueGoal:8}};var oh={collectionDefinitions:[{category:{ageCategoryCode:"16U"},collectionName:"16U Singles",matchUpCount:4,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Singles",matchUpCount:4,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Doubles",matchUpCount:2,matchUpFormat:"SET1-S:6/TB7",matchUpType:"DOUBLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Doubles",matchUpCount:2,matchUpFormat:"SET1-S:6/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Tiebreak Doubles",matchUpCount:1,matchUpFormat:"SET1-S:TB10",matchUpType:"DOUBLES",matchUpValue:1,processCodes:["RANKING.IGNORE"]}],tieFormatName:"USTA_SECTION_BATTLE",winCriteria:{valueGoal:9}};var ih={collectionDefinitions:[{collectionName:"Male Singles",gender:"MALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Mixed Doubles",gender:"MIXED",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],tieFormatName:"USTA_INTERSECTIONAL",winCriteria:{valueGoal:8}};var sh={collectionDefinitions:[{scoreValue:1,matchUpType:"SINGLES",collectionName:"Men's Singles",matchUpFormat:"SET1-S:T60",gender:"MALE",matchUpCount:1},{scoreValue:1,matchUpType:"SINGLES",collectionName:"Women's Singles",matchUpFormat:"SET1-S:T60",gender:"FEMALE",matchUpCount:1},{matchUpValue:1,matchUpType:"DOUBLES",collectionName:"Mixed Doubles",matchUpFormat:"SET1-S:T60",gender:"MIXED",matchUpCount:1}],tieFormatName:"Time Tennis Pro Circuit",winCriteria:{aggregateValue:!0}};var ah={collectionDefinitions:[{collectionName:"Mixed Doubles",gender:"MIXED",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Male Singles",matchUpCount:1,gender:"MALE",matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"DOMINANT_DUO_MIXED",winCriteria:{valueGoal:2}};var ch={collectionDefinitions:[{scoreValue:1,matchUpType:"SINGLES",collectionName:"Men's Singles",matchUpFormat:"SET1-S:T60",gender:"MALE",matchUpCount:3},{scoreValue:1,matchUpType:"SINGLES",collectionName:"Women's Singles",matchUpFormat:"SET1-S:T60",gender:"FEMALE",matchUpCount:3},{scoreValue:1,matchUpType:"DOUBLES",collectionName:"Men's Doubles",matchUpFormat:"SET1-S:T60",gender:"MALE",matchUpCount:1},{matchUpValue:1,matchUpType:"DOUBLES",collectionName:"Women's Doubles",matchUpFormat:"SET1-S:T60",gender:"FEMALE",matchUpCount:1},{matchUpValue:1,matchUpType:"DOUBLES",collectionName:"Mixed Doubles",matchUpFormat:"SET1-S:T60",gender:"MIXED",matchUpCount:1}],tieFormatName:"Time Tennis Dual",winCriteria:{aggregateValue:!0}};var uh={collectionDefinitions:[{category:{ageCategoryCode:"14U"},collectionName:"14U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{category:{ageCategoryCode:"14U"},collectionName:"14U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Doubles",collectionGroupNumber:1,matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],collectionGroups:[{groupNumber:1,groupName:"Doubles",groupValue:1,winCriteria:{valueGoal:2}}],tieFormatName:"USTA_BREWER_CUP",winCriteria:{valueGoal:4}};var ph={winCriteria:{valueGoal:23},tieFormatName:"USTA_OZAKI_CUP",collectionDefinitions:[{category:{ageCategoryCode:"18U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"18U Boys Singles",matchUpType:"SINGLES",matchUpCount:3,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"18U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"18U Girls Singles",matchUpType:"SINGLES",gender:"FEMALE",matchUpCount:3,matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Boys Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",matchUpCount:1,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"18U"},collectionName:"18U Girls Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"FEMALE",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"18U"},collectionName:"18U Mixed Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"MIXED",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"16U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"16U Boys Singles",matchUpType:"SINGLES",matchUpCount:3,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"16U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"16U Girls Singles",matchUpType:"SINGLES",gender:"FEMALE",matchUpCount:3,matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Boys Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",matchUpCount:1,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"16U"},collectionName:"16U Girls Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"FEMALE",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"16U"},collectionName:"16U Mixed Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"MIXED",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"14U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"14U Boys Singles",matchUpType:"SINGLES",matchUpCount:3,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"14U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"14U Girls Singles",matchUpType:"SINGLES",gender:"FEMALE",matchUpCount:3,matchUpValue:1},{category:{ageCategoryCode:"14U"},collectionName:"14U Boys Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",matchUpCount:1,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"14U"},collectionName:"14U Girls Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"FEMALE",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"14U"},collectionName:"14U Mixed Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"MIXED",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"12U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"12U Boys Singles",matchUpType:"SINGLES",matchUpCount:3,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"12U"},matchUpFormat:"SET3-S:6/TB7-F:TB10",collectionName:"12U Girls Singles",matchUpType:"SINGLES",gender:"FEMALE",matchUpCount:3,matchUpValue:1},{category:{ageCategoryCode:"12U"},collectionName:"12U Boys Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",matchUpCount:1,matchUpValue:1,gender:"MALE"},{category:{ageCategoryCode:"12U"},collectionName:"12U Girls Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"FEMALE",matchUpCount:1,matchUpValue:1},{category:{ageCategoryCode:"12U"},collectionName:"12U Mixed Doubles",matchUpFormat:"SET1-S:8/TB8",matchUpType:"DOUBLES",gender:"MIXED",matchUpCount:1,matchUpValue:1}]};var Dn="SET3-S:6/TB7",lF="SET3-S:6NOAD",HE="SET3-S:6/TB7-F:TB10",fF="SET3-S:4/TB7",gF="SET3-S:4/TB5@3",IF="SET1-S:T20",hF="SET1-S:8/TB7",SF="SET1-S:8/TB7@7",jC={FORMAT_STANDARD:Dn,FORMAT_STANDARD_NOAD:lF,FORMAT_ATP_DOUBLES:HE,FORMAT_SHORT_SETS:fF,FORMAT_FAST4:gF,FORMAT_PRO_SET:hF,FORMAT_COLLEGE_PRO_SET:SF,TIMED20:IF};var mh={collectionDefinitions:[{collectionName:"Doubles",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Singles",matchUpCount:2,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"DOMINANT_DUO",winCriteria:{valueGoal:2}};var dh={collectionDefinitions:[{collectionName:"Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7@7",matchUpType:"DOUBLES",collectionValue:1},{collectionName:"Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1}],tieFormatName:"USTA_COLLEGE",winCriteria:{valueGoal:4}};var lh={collectionDefinitions:[{collectionName:"Male Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Female Singles",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Male Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Female Doubles",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],tieFormatName:"USTA_LEVEL_1",winCriteria:{valueGoal:10}};var fh={collectionDefinitions:[{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Male Singles",matchUpCount:1,gender:"MALE",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Overtime",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"USTA_WTT_ITT",winCriteria:{aggregateValue:!0}};var gh={collectionDefinitions:[{collectionName:"Male Singles",gender:"MALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:6,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpType:"SINGLES",matchUpValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:3,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1},{collectionName:"Mixed Doubles",gender:"MIXED",matchUpCount:1,matchUpFormat:"SET1-S:8/TB7",matchUpType:"DOUBLES",matchUpValue:1}],tieFormatName:"USTA_ZONAL",winCriteria:{valueGoal:10}};var Ih={collectionDefinitions:[{collectionGroupNumber:1,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:1},{collectionGroupNumber:1,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:1},{collectionGroupNumber:2,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:2},{collectionGroupNumber:2,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:2},{collectionGroupNumber:3,matchUpType:"DOUBLES",matchUpCount:1,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:3},{collectionGroupNumber:3,matchUpType:"SINGLES",matchUpCount:3,matchUpFormat:"SET3-S:6/TB7-F:TB10",matchUpValue:3}],collectionGroups:[{groupNumber:1,groupName:"Day 1"},{groupNumber:2,groupName:"Day 2"},{groupNumber:3,groupName:"Day 3"}],tieFormatName:"LAVER_CUP",winCriteria:{valueGoal:13}};var hh={collectionDefinitions:[{collectionName:"Female Doubles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Male Doubles",gender:"MALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Female Singles",gender:"FEMALE",matchUpCount:1,matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Male Singles",matchUpCount:1,gender:"MALE",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"SINGLES",scoreValue:1},{collectionName:"Mixed Doubles",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:6/TB5NOAD@5",matchUpType:"DOUBLES",scoreValue:1},{collectionName:"Overtime",matchUpCount:1,gender:"MIXED",matchUpFormat:"SET1-S:T20",matchUpType:"DOUBLES",scoreValue:1}],tieFormatName:"USTA_TOC",winCriteria:{aggregateValue:!0}};var vm="COLLEGE_DEFAULT",Sh="COLLEGE_JUCO",Th="COLLEGE_D3",WE="DOMINANT_DUO",jE="DOMINANT_DUO_MIXED",YE="LAVER_CUP",qE="TEAM_DOUBLES_3_AGGREGATION",$E="TIME_TENNIS_DUAL",KE="TIME_TENNIS_PRO_CIRCUIT",zE="USTA_BREWER_CUP",QE="USTA_OZAKI_CUP",XE="USTA_COLLEGE",JE="USTA_GOLD_TEAM_CHALLENGE",ZE="USTA_LEVEL_1",tU="USTA_INTERSECTIONAL",eU="USTA_SECTION_BATTLE",rU="USTA_SOUTHERN_LEVEL_5",nU="USTA_TOC",oU="USTA_WTT_ITT",iU="USTA_ZONAL",YC={COLLEGE_D3:Th,COLLEGE_DEFAULT:vm,COLLEGE_JUCO:Sh,DOMINANT_DUO:WE,DOMINANT_DUO_MIXED:jE,LAVER_CUP:YE,TEAM_DOUBLES_3_AGGREGATION:qE,TIME_TENNIS_DUAL:$E,TIME_TENNIS_PRO_CIRCUIT:KE,USTA_BREWER_CUP:zE,USTA_OZAKI_CUP:QE,USTA_COLLEGE:XE,USTA_GOLD_TEAM_CHALLENGE:JE,USTA_INTERSECTIONAL:tU,USTA_LEVEL_1:ZE,USTA_SECTION_BATTLE:eU,USTA_SOUTHERN_LEVEL_5:rU,USTA_TOC:nU,USTA_WTT_ITT:oU,USTA_ZONAL:iU};var $C="STANDARD",qC={[$C]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1},singles:{matchUpCount:6,matchUpValue:1},valueGoal:5},[Th]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7@7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:Dn,matchUpCount:6,matchUpValue:1},tieFormatName:Th,valueGoal:5},[vm]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:6/TB7",collectionValue:1,matchUpCount:3},singles:{matchUpFormat:Dn,matchUpCount:6,matchUpValue:1},tieFormatName:vm,valueGoal:4},[Sh]:{hydrate:!0,doubles:{matchUpFormat:"SET1-S:8/TB7",matchUpCount:3,matchUpValue:1},singles:{matchUpFormat:Dn,matchUpCount:6,matchUpValue:1},tieFormatName:Sh,valueGoal:5},[YE]:Ih,[WE]:mh,[jE]:ah,[qE]:rh,[$E]:ch,[KE]:sh,[zE]:uh,[QE]:ph,[XE]:dh,[JE]:eh,[tU]:ih,[ZE]:lh,[eU]:oh,[rU]:nh,[oU]:fh,[nU]:hh,[iU]:gh},NF=t=>{let e=t?.namedFormat&&Object.keys(qC).includes(t.namedFormat)?t.namedFormat:$C,r=Array.isArray(t?.uuids)?t?.uuids:[],n,{category:o,gender:i}=t?.event??{},s=J(qC[e],!1,!0),a=c=>{if(!t?.isMock&&!t?.event?.isMock||!t.event)return r?.pop()??Dt();let u=t?.event?.eventId;return r.pop()??`${u}-COL-${c+1}`};return s.hydrate?(n={winCriteria:{valueGoal:s.valueGoal},collectionDefinitions:[{collectionId:a(0),matchUpFormat:HE,collectionName:"Doubles",matchUpType:_t,...s.doubles},{collectionId:a(1),matchUpFormat:Dn,collectionName:"Singles",matchUpType:xt,...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},Zn=NF;var jn="SINGLES",Fs="SINGLES",qr="DOUBLES",ko="DOUBLES",_e="TEAM",Cr="TEAM",MF="AGE",RF="RATING",CF="BOTH",KC={AGE:MF,BOTH:CF,DOUBLES:qr,DOUBLES_EVENT:ko,RATING:RF,SINGLES:jn,SINGLES_EVENT:Fs,TEAM_EVENT:Cr,TEAM:_e};var nt="MAIN",ct="QUALIFYING",qe="CONSOLATION",$e="VOLUNTARY_CONSOLATION",de="PLAY_OFF",$c=[nt,ct,qe,de,$e],ks={[ct]:1,[nt]:2,[de]:3,[qe]:3,[$e]:4},sU="finishingPositions",aU="aggregateEventStructures",cU={[nt]:1,[de]:2,[qe]:3,[ct]:4,[$e]:5},zC={[de]:1,[nt]:2,[qe]:3,[ct]:4,[$e]:5},Kc="CLUSTER",QC="SEPARATE",mi="WATERFALL",ap="ITEM",Ge="CONTAINER",dn="DRAW",cp="RANDOM",En="TOP_DOWN",di="BOTTOM_UP",to="POSITION",fo="WINNER",eo="LOSER",On="FIRST_MATCHUP",$r="AD_HOC",bF="AD_HOC",da="FEED_IN",zc="COMPASS",Qc="OLYMPIC",vF="SINGLE_ELIMINATION";var go="SINGLE_ELIMINATION",Xc="DOUBLE_ELIMINATION",Jc="FIRST_MATCH_LOSER_CONSOLATION",up="FIRST_ROUND_LOSER_CONSOLATION",ki="LUCKY_DRAW",Tf="CURTIS_CONSOLATION",XC="CURTIS_CONSOLATION",yh="FEED_IN_CHAMPIONSHIP_TO_SF",Om="FEED_IN_CHAMPIONSHIP_TO_SF",Ah="FEED_IN_CHAMPIONSHIP_TO_QF",_m="FEED_IN_CHAMPIONSHIP_TO_QF",Eh="FEED_IN_CHAMPIONSHIP_TO_R16",xm="FEED_IN_CHAMPIONSHIP_TO_R16",uU="MODIFIED_FEED_IN_CHAMPIONSHIP",wm="MODIFIED_FEED_IN_CHAMPIONSHIP",pp="FEED_IN_CHAMPIONSHIP",JC="DOUBLE_ROUND_ROBIN",Nn="ROUND_ROBIN",Io="ROUND_ROBIN_WITH_PLAYOFF",pU="DECIDER",mU="BACKDRAW",yf={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-3":{name:"Northeast",abbreviation:"NE"},"0-1-1":{name:"South",abbreviation:"S"},"0-1-2":{name:"Southwest",abbreviation:"SW"},"0-2-1":{name:"Northwest",abbreviation:"NW"},"0-1-1-1":{name:"Southeast",abbreviation:"SE"}},Af={0:{name:"East",abbreviation:"E"},"0-1":{name:"West",abbreviation:"W"},"0-2":{name:"North",abbreviation:"N"},"0-1-1":{name:"South",abbreviation:"S"}},li="WIN_RATIO",Gi="ROUND_OUTCOME",dU=[zc,Tf,_m,xm,Om,pp,Ah,Eh,yh,Jc,up,ki,wm,Qc,de,Io],OF=[$r,zc,Tf,Xc,_m,xm,Om,pp,da,Jc,up,ki,wm,Qc,de,Nn,Io,go],lU={MAIN:nt,QUALIFYING:ct,CONSOLATION:qe,ITEM:ap,CONTAINER:Ge,FIRST_MATCHUP:On,WINNER:fo,LOSER:eo,AD_HOC:$r,FEED_IN:da,FLEX_ROUNDS:bF,COMPASS:zc,PLAY_OFF:de,OLYMPIC:Qc,KNOCKOUT:vF,SINGLE_ELIMINATION:go,DOUBLE_ELIMINATION:Xc,CURTIS:Tf,FICSF:yh,FICQF:Ah,FICR16:Eh,MFIC:uU,VOLUNTARY_CONSOLATION:$e,FIRST_MATCH_LOSER_CONSOLATION:Jc,FIRST_ROUND_LOSER_CONSOLATION:up,MODIFIED_FEED_IN_CHAMPIONSHIP:wm,FEED_IN_CHAMPIONSHIP_TO_R16:xm,FEED_IN_CHAMPIONSHIP_TO_QF:_m,FEED_IN_CHAMPIONSHIP_TO_SF:Om,FEED_IN_CHAMPIONSHIP:pp,LUCKY_DRAW:ki,ROUND_ROBIN_WITH_PLAYOFF:Io,ROUND_ROBIN:Nn,DECIDER:pU,BACKDRAW:mU,COMPASS_ATTRIBUTES:yf,OLYMPIC_ATTRIBUTES:Af,DRAW:dn,RANDOM:cp,TOP_DOWN:En,BOTTOM_UP:di,WATERFALL:mi,WIN_RATIO:li,ROUND_OUTCOME:Gi,MULTI_STRUCTURE_DRAWS:dU,generatedDrawTypes:OF,stageOrder:ks,finishOrder:cU,AGGREGATE_EVENT_STRUCTURES:aU,FINISHING_POSITIONS:sU},ZC=lU;var Re="tournamentRecords",Ef="policyDefinitions",ie="tournamentRecord",Uh="onlineResource",Ve="drawDefinition",Ph="tieFormatName",Lm="matchUpFormat",ro="participantId",Dh="scheduleDates",tb="tournamentId",eb="scheduleDate",rb="roundNumber",Zc="structureId",Uf="participant",ec="matchUpIds",Nh="entryStage",nb="policyType",fU="structures",Pf="eventType",ln="matchUpId",Fm="tieFormat",tu="inContext",mp="structure",dp="courtIds",ob="personId",lp="venueIds",Df="matchUps",Mh="courtId",Rh="eventId",_n="matchUp",Ch="drawId",fn="error",Do="event",is="param",Nf="uuids",ib="averageMatchUpMinutes",sb="recoveryMinutes",ab="periodLength",cb="number";var Kr="object",Be="array";var tr="_validate",bh="_message",Fr="_invalid",He="_ofType",km="_anyOf",Gs="_oneOf";var ub={[Uh]:t=>Yt(Object.keys(t),[Ja,Za,tc]).length===3,[Ph]:t=>t&&Zn({namedFormat:t}),[Nf]:t=>!t||Array.isArray(t)&&t.every(Vt),[Fm]:t=>!ar({tieFormat:t}).error,[Pf]:t=>[jn,qr,_e].includes(t),[Nh]:t=>$c.includes(t)},_F={[Re]:wt,[ie]:Y,[Ef]:$u,[Ve]:Z,[ro]:oe,[Lm]:Wl,[tb]:ca,[Zc]:Er,[ec]:rs,[Uf]:wi,[Uh]:lo,[Pf]:Bn,[fU]:Gl,[ln]:sr,[Fm]:Lo,[mp]:pi,[Mh]:_i,[Df]:Xn,[Rh]:jr,[_n]:hr,[dp]:st,[lp]:st,[Ch]:an,[Do]:vt},xF={[Re]:Kr,[Ef]:Kr,[ie]:Kr,[Ve]:Kr,[Uh]:Kr,[Dh]:Be,[Uf]:Kr,[ec]:Be,[fU]:Be,[Fm]:Kr,[mp]:Kr,[dp]:Be,[lp]:Be,[Df]:Be,[_n]:Kr,[Do]:Kr,[Nf]:Be};function rt(t,e,r){if(!t&&!ht(t))return{error:G};if(!e?.length||t?._bypassParamCheck)return{valid:!0};if(!Array.isArray(e))return{error:G};let{paramError:n,errorParam:o}=FF(t,e);if(!n)return{valid:!0};let i=n[tr]&&(n[fn]||n[Fr])||t?.[o]===void 0&&(n[fn]||n[Fr]||_F[o]||G)||G,s=o??(n[Gs]&&Object.keys(n[Gs]).join(", "));return _({info:{param:s,message:n[bh]},result:{error:i},stack:r})}function pb(t,e){let r=Object.keys(t),n=Object.keys(e);return Yt(r,n)}function wF(t,e){if(!e)return;let r=pb(t,e);return r.length!==1?{error:G}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function LF(t,e){if(!e)return;let r=pb(t,e).filter(n=>t[n]);return r.length<1?{error:G}:r.reduce((n,o)=>({...n,[o]:!0}),{})}function FF(t,e){let r,n;return{paramError:e.find(({_ofType:i,_oneOf:s,_anyOf:a,_validate:c,_info:u,...p})=>{let m=s&&wF(t,s);if(m?.error)return m.error;m&&Object.assign(p,m);let d=a&&LF(t,a);if(d?.error)return d.error;d&&Object.assign(p,d);let l=Object.keys(p).filter(g=>typeof p[g]=="boolean"),f=l.find(g=>{let I=c&&!Wr(c),h=t[g]!==void 0&&!c&&kF(t,g,i),S=p[g]&&[void 0,null].includes(t[g]),y=I||h||S||c&&t[g]!==void 0&&!GF(t[g],c)||ub[g]&&!ub[g](t[g]);return y&&(r=g,n=u),y});return!l.length||f}),errorParam:r,paramInfo:n}}function kF(t,e,r){return r=r||xF[e]||"string",r==="array"?!Array.isArray(t[e]):typeof t[e]!==r}function GF(t,e){return Wr(e)?e(t):!0}var Gm="DYNAMIC",fi="RANKING",gi="RATING",Ii="SCALE",ho="SEEDING",mb={RANKING:fi,RATING:gi,SCALE:Ii,SEEDING:ho};function la(t){let e=rt(t,[{[Uf]:!0}]);if(e.error)return e;let r=t.participant.timeItems?.filter(({itemType:o})=>o?.startsWith(Ii)&&[fi,gi,ho].includes(o.split(".")[1])),n={ratings:{},rankings:{},seedings:{}};if(r?.length){let o=s=>r.filter(a=>a?.itemType===s).sort((a,c)=>new Date(a.createdAt||void 0).getTime()-new Date(c.createdAt||void 0).getTime()).pop(),i=ut(r.map(({itemType:s})=>s));for(let s of i){let a=o(s);if(a){let[,c,u,p,m]=a.itemType.split("."),d=m?`${p}.${m}`:p,l=c===ho&&"seedings"||c===fi&&"rankings"||"ratings";n[l][u]||(n[l][u]=[]),n[l][u].push({scaleValue:a.itemValue,scaleDate:a.itemDate,scaleName:d})}}}return{...C,...n}}function Vi(t){if(t===null)return{};let{source:e,template:r}=t||{};if(!r)return e;let n={};return o(e,r,n),n;function o(i,s,a){if(!i||!s)return;let c=Object.keys(i),u=Object.keys(s),p=Object.assign({},...u.filter(l=>l.indexOf("||")).map(l=>l.split("||").map(f=>({[f]:l}))).flat()),m=u.concat(...Object.keys(p)),d=m.includes("*");for(let l of c)if(m.indexOf(l)>=0||d){let f=p[l]||l,g=s[f]||d,I=i[l];if(typeof g=="object"&&typeof I!="function"&&!Array.isArray(g))if(Array.isArray(I)){let h=I.map(S=>{let T={};return o(S,g,T)!==!1?T:void 0}).filter(Boolean);a[l]=h}else I&&(a[l]={},o(I,g,a[l]));else{let h=i[l];if(Array.isArray(g)&&!g.includes(h))return!1;(s[l]||d&&s[l]!==!1)&&(a[l]=h)}}}}var vh="voluntaryConsolation",hi="competitiveBands",Mf="roundRobinTally",So="positionActions",er="matchUpActions",Rf="rankingPoints",fa="roundNaming",Vs="participant",eu="progression",No="scheduling",ru="avoidance",VF="participant",BF="display",en="scoring",xn="seeding",rc="feedIn",HF="audit",Vm="draws",db={POLICY_TYPE_VOLUNTARY_CONSOLATION:vh,POLICY_TYPE_COMPETITIVE_BANDS:hi,POLICY_TYPE_ROUND_ROBIN_TALLY:Mf,POLICY_TYPE_POSITION_ACTIONS:So,POLICY_TYPE_MATCHUP_ACTIONS:er,POLICY_TYPE_RANKING_POINTS:Rf,POLICY_TYPE_ROUND_NAMING:fa,POLICY_TYPE_PARTICIPANT:Vs,POLICY_TYPE_PROGRESSION:eu,POLICY_TYPE_SCHEDULING:No,POLICY_TYPE_AVOIDANCE:ru,POLICY_TYPE_DISPLAY:BF,POLICY_TYPE_PRIVACY:VF,POLICY_TYPE_FEED_IN:rc,POLICY_TYPE_SCORING:en,POLICY_TYPE_SEEDING:xn,POLICY_TYPE_AUDIT:HF,POLICY_TYPE_DRAWS:Vm};function Go({tournamentParticipants:t=[],policyDefinitions:e={},contextProfile:r,participantId:n,internalUse:o,personId:i}){let s=t.find(c=>n&&c.participantId===n||i&&c.person&&c.person.personId===i),a=J(s,!1,o);if(a){let c=e?.[Vs];if(r?.withScaleValues){let{ratings:u,rankings:p}=la({participant:a});a.rankings=p,a.ratings=u}if(c?.participant)return Vi({template:c.participant,source:a})}return a}var lb="element required",fb="missing name";function gr(t){if(!t||typeof t!="object")return{error:st};if(t.element&&typeof t?.element!="object")return{error:G};if(!t?.name)return{error:st,info:fb};if(!t?.element){if(t.discover&&t.tournamentRecords){for(let e of Object.keys(t.tournamentRecords)){let r=t.tournamentRecords[e],n=gr({element:r,name:t.name});if(n.error)return _({result:n,stack:"removeExtension"})}return{...C}}return{error:st,info:lb}}return t?.element.extensions?(t.element.extensions=t.element.extensions.filter(e=>e?.name!==t.name),{...C}):{...C,info:ve}}function wn({requiredAttributes:t=["name","value"],extension:e}){if(!e||typeof e!="object"||typeof e.name!="string")return!1;let r=Object.keys(e);return t.filter(n=>r.includes(n)).length===t.length}function At(t){if(typeof t!="object")return{error:st};let e="addExtension";if(t?.element&&typeof t.element!="object")return _({result:{error:G},stack:e});if(!wn({extension:t.extension}))return _({result:{error:G,info:"invalid extension"},stack:e});if(!t.element)if(t.discover&&!t.tournamentId&&t.tournamentRecords){for(let o of Object.values(t.tournamentRecords)){let i=At({extension:t.extension,element:o});if(i.error)return _({result:i,stack:e})}return{...C}}else return _({result:{error:st},stack:e});if(t.element.extensions||(t.element.extensions=[]),t?.creationTime??!0){let o=new Date().toISOString();Object.assign(t.extension,{createdAt:o})}let n=t.element.extensions.find(({name:o})=>o===t.extension.name);return n?n.value=t.extension.value:t.extension.value&&t.element.extensions.push(t.extension),{...C}}function Cf(t){return!t||typeof t!="object"?{error:st}:t.tournamentRecord?At({creationTime:t.creationTime,element:t.tournamentRecord,extension:t.extension}):{error:Y}}function fp(t){return!t||typeof t!="object"?{error:st}:t.drawDefinition?At({creationTime:t.creationTime,element:t.drawDefinition,extension:t.extension}):{error:Mr}}function Mo(t){return!t||typeof t!="object"?{error:st}:t.event?At({creationTime:t.creationTime,extension:t.extension,element:t.event}):{error:jr}}function gU(t){if(!t||typeof t!="object")return{error:st};if(!t.participantId)return{error:oe};let e=t.tournamentRecord?.participants||[],r=Go({participantId:t.participantId,tournamentParticipants:e});return r?At({creationTime:t.creationTime,extension:t.extension,element:r}):{error:te}}function bf(t){return!t||typeof t!="object"?{error:st}:t.tournamentRecord?gr({element:t.tournamentRecord,name:t.name}):{error:Y}}function IU(t){return!t||typeof t!="object"?{error:st}:t.drawDefinition?gr({element:t.drawDefinition,name:t.name}):{error:Mr}}function gp(t){return!t||typeof t!="object"?{error:st}:t?.event?gr({element:t.event,name:t.name}):{error:jr}}function hU(t){if(!t||typeof t!="object")return{error:st};if(!t.participantId)return{error:oe};let e=t.tournamentRecord?.participants||[],r=Go({participantId:t.participantId,tournamentParticipants:e});return r?gr({element:r,name:t.name}):{error:te}}function Ip({tournamentRecords:t}){return{tournamentIds:ht(t)?Object.keys(t):[],...C}}var WF="extensionQueries";function dt({discover:t,element:e,name:r,...n}){if(!e||!r){if(t&&n){let s=Object.keys(n).filter(p=>typeof t=="boolean"||Array.isArray(t)&&t.includes(p)).find(p=>Array.isArray(n[p]?.extensions)?n[p].extensions.find(m=>m?.name===r):!1),a=s&&n[s];!a&&n.tournamentRecords&&(a=Object.values(n.tournamentRecords).find(p=>p.extensions?.length));let c=a?.extensions?.find(p=>p?.name===r);return{extension:c,info:c?void 0:ve}}return _({result:{error:st},stack:WF})}if(!Array.isArray(e.extensions))return{info:"no extensions"};let o=e.extensions.find(s=>s?.name===r);return{extension:o,info:o?void 0:ve}}var jF="activeSuspension",nu="appliedPolicies",SU="context",Bm="delegatedOutcome",no="disabled",ga="disableAutoCalc",Hm="disableLinks",Wm="display",Ia="drawDeletions",YF="drawProfile",jm="entryProfile",qF="eventProfile",$F="eventWithdrawalRequests",KF="factory",un="flightProfile",Oh="groupingAttribute",Ro="lineUps",Bs="linkedTournamentsIds",Ym="matchUpHistory",_h="participantRepresentatives",ha="personRequests",nc="positionActions",zF="rankingPoints",QF="registration",Mn="roundTarget",ou="scheduleLimits",Vo="scheduleTiming",Sa="schedulingProfile",XF="statusDetail",oc="subOrder",Jo="tally",qm="tieFormatModification",xh={ACTIVE_SUSPENSION:jF,APPLIED_POLICIES:nu,CONTEXT:SU,DELEGATED_OUTCOME:Bm,DISABLED:no,DISABLE_LINKS:Hm,DISABLE_AUTO_CALC:ga,DISPLAY:Wm,DRAW_DELETIONS:Ia,DRAW_PROFILE:YF,ENTRY_PROFILE:jm,EVENT_PROFILE:qF,EVENT_WITHDRAWAL_REQUESTS:$F,FLIGHT_PROFILE:un,GROUPING_ATTRIBUTE:Oh,LINEUPS:Ro,LINKED_TOURNAMENTS:Bs,MATCHUP_HISTORY:Ym,PARTICIPANT_REPRESENTATIVES:_h,PERSON_REQUESTS:ha,POSITION_ACTIONS:nc,RANKING_POINTS:zF,REGISTRATION:QF,ROUND_TARGET:Mn,SCHEDULE_LIMITS:ou,SCHEDULE_TIMING:Vo,SCHEDULING_PROFILE:Sa,STATUS_DETAIL:XF,SUB_ORDER:oc,TALLY:Jo,TIE_FORMAT_MODIFICATIONS:qm,FACTORY:KF},TU=[Bm,no,ga,Hm,un,Ro,Bs,Ym,_h,ha,Mn,ou,Vo,Sa,oc,Jo,qm];function yU({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:wt};let e=Ip({tournamentRecords:t}),{tournamentIds:r}=e;return r?.length>1?At({tournamentRecords:t,discover:!0,extension:{name:Bs,value:{tournamentIds:r}}}):{...C}}function AU({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:wt};let e=gr({name:Bs,tournamentRecords:t,discover:!0});return _({result:e,stack:"unlinkTournaments"})}function EU({tournamentRecords:t,tournamentId:e}){if(typeof t!="object")return{error:G};if(!e)return{error:ca};let r=Ip({tournamentRecords:t}),{tournamentIds:n}=r;if(!n.includes(e))return{error:ca};let o;return n.every(i=>{let s=t[i],{extension:a}=dt({element:s,name:Bs});if(!a)return!0;let c=a?.value?.tournamentIds||[];if(!c?.length||c.length===1&&c.includes(e)||i===e){let m=bf({name:Bs,tournamentRecord:s});return m.error&&(o=m.error),m.success}let u=c.filter(m=>m!==e);a.value={tournamentIds:u};let p=Cf({tournamentRecord:s,extension:a});return p.error&&(o=p.error),p.success}),o?{error:o}:{...C}}var PU={};Xt(PU,{getLinkedTournamentIds:()=>iu,getTournamentIds:()=>Ip});function iu({tournamentRecords:t}){return typeof t!="object"||!Object.keys(t).length?{error:wt}:{linkedTournamentIds:Object.assign({},...Object.keys(t).map(r=>{let n=t[r],o=n?.tournamentId,{extension:i}=dt({element:n,name:Bs}),s=(i?.value?.tournamentIds||[]).filter(a=>a!==o);return{[r]:s}}))}}var MN={};Xt(MN,{adHocPositionSwap:()=>wP,addAdHocMatchUps:()=>bd,addDrawDefinitionTimeItem:()=>Tg,addFinishingRounds:()=>Ea,addGoesTo:()=>qi,addPlayoffStructures:()=>kp,addQualifyingStructure:()=>xP,addVoluntaryConsolationStage:()=>CP,addVoluntaryConsolationStructure:()=>pg,allPlayoffPositionsFilled:()=>OS,alternateDrawPositionAssignment:()=>SP,assignDrawPosition:()=>zP,assignDrawPositionBye:()=>Hr,attachConsolationStructures:()=>YP,attachPlayoffStructures:()=>Cg,attachQualifyingStructure:()=>Sg,attachStructures:()=>bg,autoSeeding:()=>X_,automatedPlayoffPositioning:()=>Ks,automatedPositioning:()=>Sc,checkValidEntries:()=>_d,deleteAdHocMatchUps:()=>QP,drawMatic:()=>qd,findDrawDefinition:()=>oT,generateAdHocMatchUps:()=>Ou,generateAdHocRounds:()=>Yd,generateAndPopulatePlayoffStructures:()=>Cd,generateDrawDefinition:()=>xa,generateDrawMaticRound:()=>Fd,generateDrawStructuresAndLinks:()=>xd,generateDrawTypeAndModifyDrawDefinition:()=>wd,generateQualifyingStructure:()=>Pd,generateVoluntaryConsolation:()=>PT,getAssignedParticipantIds:()=>Ri,getAvailableMatchUpsCount:()=>vd,getAvailablePlayoffProfiles:()=>Pu,getDrawDefinitionTimeItem:()=>zh,getDrawParticipantRepresentativeIds:()=>rT,getDrawStructures:()=>gn,getDrawTypeCoercion:()=>bu,getEligibleVoluntaryConsolationParticipants:()=>eT,getMatchUpsMap:()=>Ne,getParticipantIdFinishingPositions:()=>nT,getPositionAssignments:()=>Gp,getPositionsPlayedOff:()=>yc,getSeedingThresholds:()=>ES,getSeedsCount:()=>vu,getStructureSeedAssignments:()=>on,getTeamLineUp:()=>ms,getValidGroupSizes:()=>Cp,isAdHoc:()=>cr,isCompletedStructure:()=>si,isValidForQualifying:()=>hT,luckyLoserDrawPositionAssignment:()=>lP,modifyDrawDefinition:()=>qP,modifyDrawName:()=>vg,modifySeedAssignment:()=>TP,mutate:()=>ZP,positionActions:()=>IT,pruneDrawDefinition:()=>KP,qualifierDrawPositionAssignment:()=>hP,query:()=>pD,removeDrawPositionAssignment:()=>Au,removeRoundMatchUps:()=>XP,removeSeededParticipant:()=>_P,removeStructure:()=>RP,renameStructures:()=>MP,resetDrawDefinition:()=>$P,resetVoluntaryConsolationStructure:()=>wU,setDrawParticipantRepresentativeIds:()=>MU,setPositionAssignments:()=>gP,setStructureOrder:()=>NP,setSubOrder:()=>JP,shiftAdHocRounds:()=>fP,swapAdHocRounds:()=>IP,swapDrawPositionAssignments:()=>OP,updateTeamLineUp:()=>Ki,withdrawParticipantAtDrawPosition:()=>mP});var ZP={};Xt(ZP,{adHocPositionSwap:()=>wP,addAdHocMatchUps:()=>bd,addDrawDefinitionTimeItem:()=>Tg,addPlayoffStructures:()=>kp,addQualifyingStructure:()=>xP,addVoluntaryConsolationStage:()=>CP,addVoluntaryConsolationStructure:()=>pg,alternateDrawPositionAssignment:()=>SP,assignDrawPosition:()=>zP,assignDrawPositionBye:()=>Hr,attachConsolationStructures:()=>YP,attachPlayoffStructures:()=>Cg,attachQualifyingStructure:()=>Sg,attachStructures:()=>bg,automatedPlayoffPositioning:()=>Ks,automatedPositioning:()=>Sc,deleteAdHocMatchUps:()=>QP,luckyLoserDrawPositionAssignment:()=>lP,modifyDrawDefinition:()=>qP,modifyDrawName:()=>vg,modifySeedAssignment:()=>TP,pruneDrawDefinition:()=>KP,qualifierDrawPositionAssignment:()=>hP,removeDrawPositionAssignment:()=>Au,removeRoundMatchUps:()=>XP,removeSeededParticipant:()=>_P,removeStructure:()=>RP,renameStructures:()=>MP,resetDrawDefinition:()=>$P,resetVoluntaryConsolationStructure:()=>wU,setDrawParticipantRepresentativeIds:()=>MU,setPositionAssignments:()=>gP,setStructureOrder:()=>NP,setSubOrder:()=>JP,shiftAdHocRounds:()=>fP,swapAdHocRounds:()=>IP,swapDrawPositionAssignments:()=>OP,updateTeamLineUp:()=>Ki,withdrawParticipantAtDrawPosition:()=>mP});var NU=t=>e=>t[e],$m=(t=[])=>t.map(Ae).filter(Boolean),vf=(t=[])=>t.map(St).filter(Boolean),St=(t={})=>NU(t)("participantId");var Ae=(t={})=>NU(t)("matchUpId"),su=(t={})=>NU(t)("drawId");function MU({representativeParticipantIds:t,drawDefinition:e}){if(!e)return{error:Mr};if(!Array.isArray(t))return{error:G};let r=vf(e?.entries||[]);return t.length&&Yt(t,r).length<t.length?{error:G}:fp({drawDefinition:e,extension:{name:_h,value:t}})}var br="ABANDONED",ic="AWAITING_RESULT",Nt="BYE",oo="CANCELLED",le="COMPLETED",au="DEAD_RUBBER",Mt="DEFAULTED",Ce="DOUBLE_DEFAULT",he="DOUBLE_WALKOVER",Ln="IN_PROGRESS",pn="INCOMPLETE",RU="NOT_PLAYED",rr="RETIRED",ss="SUSPENDED",Qt="TO_BE_PLAYED",Ct="WALKOVER",gb=[ic,le,Mt,Ln,pn,rr,ss],wh=[ic,le,Mt,he,Ce,Ln,pn,rr,ss,Ct],Lh=[br,ic,Nt,oo,le,au,Mt,he,Ce,Ln,pn,RU,rr,ss,Qt,Ct],Fh=[Nt,he,Ce,le,Mt,rr,Ct],kh=[br,ic,oo,au,Ln,pn,RU,ss,Qt,void 0],ce=[oo,br,le,au,Mt,he,Ce,rr,Ct],Km=[br,le,Mt,he,Ce,Ln,rr,Ct],Gh=[Ln,pn,ss,Qt],Vh={ABANDONED:br,AWAITING_RESULT:ic,BYE:Nt,CANCELLED:oo,COMPLETED:le,DEAD_RUBBER:au,DEFAULTED:Mt,DOUBLE_WALKOVER:he,DOUBLE_DEFAULT:Ce,IN_PROGRESS:Ln,INCOMPLETE:pn,NOT_PLAYED:RU,RETIRED:rr,SUSPENDED:ss,TO_BE_PLAYED:Qt,WALKOVER:Ct};function Si(t,e,r){let n=m=>dt({element:m,name:Mn})?.extension?.value,o=r?.deprioritizeCompleted,i=r?.mode===aU&&zC,s=r?.mode===sU&&cU,a=s||i||ks,c=m=>m?.stage===nt&&m?.stageSequence===1,u=m=>c(m)?-1:a[m?.stage],p=m=>m?.matchUps.every(({matchUpStatus:d})=>ce.includes(d)?1:-1);return o&&p(t)-p(e)||i&&u(t)-u(e)||(t?.stage&&a[t.stage]||0)-(e?.stage&&a[e.stage]||0)||(n(t)||0)-(n(e)||0)||!s&&!i&&(e?.positionAssignments?.length??1/0)-(t?.positionAssignments?.length??1/0)||(t?.stageSequence??0)-(e?.stageSequence??0)||(Of(t)||0)-(Of(e)||0)}function Of(t){return(t?.matchUps||[]).reduce((e,r)=>{let n=(r.finishingPositionRange?.winner||[]).reduce((o,i)=>o+i,0);return!e||n<e?n:e},void 0)}function at(t){let e=rt(t,[{[Ve]:!0,[Zc]:!0}]);if(e.error)return e;let{drawDefinition:r,structureId:n}=t,{structures:o}=gn({drawDefinition:r}),i=o?.map(c=>c.structures?[...c.structures].concat(c):c).flat(),s=i?.find(c=>c.structureId===n);if(!s)return{error:kt};let a=s.structureType===ap?i?.find(c=>c.structures?.some(u=>u.structureId===n)):void 0;return{structure:s,containingStructure:a}}function gn({withStageGrouping:t,drawDefinition:e,stageSequences:r,stageSequence:n,roundTarget:o,sortConfig:i,stages:s,stage:a}){let c=!e&&Z||!e?.structures&&Gl||void 0;if(c)return{error:c,structures:[],stageStructures:{}};let u=f=>{let g=dt({element:f,name:Mn})?.extension?.value;return!o||o===g},p=e?.structures?.filter(d).filter(l).filter(u).sort((f,g)=>Si(f,g,i))??[],m=t?Object.assign({},...$c.map(f=>{let g=p?.filter(I=>I.stage===f);return g?.length&&{[f]:g}}).filter(Boolean)):{};return{structures:p,stageStructures:m};function d(f){return!a&&!Array.isArray(s)||a&&f.stage===a||Array.isArray(s)&&s.includes(f.stage)}function l(f){return!n&&!Array.isArray(r)||n&&f.stageSequence===n||Array.isArray(r)&&r.includes(f.stageSequence)}}function Bh({drawDefinition:t}){if(!t)return{error:Z};let e={};return{allPositionedParticipantIds:(t.structures||[]).map(n=>{let o=n.stage;e[o]||(e[o]=[]);let{positionAssignments:i}=bt({structure:n}),s=i?.map(St).filter(Boolean)??[];return e[o].push(...s),s}).flat(),stagePositionedParticipantIds:e}}function bt({drawDefinition:t,structureId:e,structure:r}){let n,o=[];if(!r){if(!t)return{positionAssignments:o,error:Z};if({structure:r,error:n}=at({drawDefinition:t,structureId:e}),n)return{positionAssignments:o,error:n}}return r.structures?o=[].concat(...r.structures.map(i=>bt({structure:i}).positionAssignments)):r.positionAssignments?o=r.positionAssignments:n=$A,{positionAssignments:o,error:n}}function Se({drawDefinition:t,structureId:e,structure:r}){let n=bt({drawDefinition:t,structureId:e,structure:r})?.positionAssignments||[],o=n?.filter(u=>u.participantId??u.bye??u.qualifier),i=n&&n?.length===o?.length,s=n?.filter(u=>!u.participantId&&!u.bye&&!u.qualifier),a=n?.filter(u=>!u.participantId&&u.bye),c=n?.filter(u=>!u.participantId&&u.qualifier);return{allPositionsAssigned:i,positionAssignments:n,unassignedPositions:s,assignedPositions:o,qualifierPositions:c,byePositions:a}}var _f="addDrawDefinition",hp="addMatchUps",Zo="addParticipants",xf="addScaleItems",CU="addEvent",Hh="addVenue",Ti="audit",Wh="dataIssue",wf="deleteParticipants",Lf="deleteVenue",Ff="deletedDrawIds",kf="deletedMatchUpIds",Gf="modifyDrawDefinition",bU="modifyDrawEntries",vU="modifyEventEntries",Vf="modifyMatchUp",nr="modifyParticipants",Bf="modifyPositionAssignments",Hf="modifySeedAssignments",Bi="modifyTournamentDetail",yi="modifyVenue",zm="mutations",jh="publishEvent",OU="publishEventSeeding",_U="publishOrderOfPlay",xU="publishParticipants",Wf="unPublishEvent",jf="unPublishEventSeeding",Yf="unPublishOrderOfPlay",Ib="unPublishParticipants",Sp="updateInContextMatchUp",hb={ADD_DRAW_DEFINITION:_f,ADD_MATCHUPS:hp,ADD_PARTICIPANTS:Zo,ADD_SCALE_ITEMS:xf,ADD_EVENT:CU,ADD_VENUE:Hh,AUDIT:Ti,DATA_ISSUE:Wh,DELETE_PARTICIPANTS:wf,DELETE_VENUE:Lf,DELETED_DRAW_IDS:Ff,DELETED_MATCHUP_IDS:kf,MODIFY_DRAW_DEFINITION:Gf,MODIFY_DRAW_ENTRIES:bU,MODIFY_EVENT_ENTRIES:vU,MODIFY_MATCHUP:Vf,MODIFY_PARTICIPANTS:nr,MODIFY_POSITION_ASSIGNMENTS:Bf,MODIFY_SEED_ASSIGNMENTS:Hf,MODIFY_TOURNAMENT_DETAIL:Bi,MODIFY_VENUE:yi,MUTATIONS:zm,PUBLISH_EVENT_SEEDING:OU,PUBLISH_EVENT:jh,PUBLISH_ORDER_OF_PLAY:_U,PUBLISH_PARTICIPANTS:xU,UNPUBLISH_EVENT_SEEDING:jf,UNPUBLISH_EVENT:Wf,UNPUBLISH_ORDER_OF_PLAY:Yf,UPDATE_INCONTEXT_MATCHUP:Sp};function Yh(t,e){if(!t)return{error:Z};let r=Date.now();t.updatedAt&&r===new Date(t.updatedAt).getTime()&&(r+=1);let n=new Date(r).toISOString(),o=e?.filter(Boolean);return t.updatedAt=n,t.structures?.filter(Boolean).forEach(i=>{(!o?.length||o?.includes(i.structureId))&&(i.updatedAt=n)}),{...C}}function Co({drawDefinition:t,tournamentId:e,matchUps:r,eventId:n}){return t&&Yh(t),mt({payload:{matchUps:r,tournamentId:e,eventId:n},topic:hp}),{...C}}function Yn({drawDefinition:t,tournamentId:e,matchUpIds:r,eventId:n,action:o}){t&&Yh(t),mt({topic:kf,payload:{tournamentId:e,matchUpIds:r,eventId:n,action:o}});for(let i of r)YI({key:i});return{...C}}function gt({drawDefinition:t,tournamentId:e,structureId:r,context:n,eventId:o,matchUp:i}){return i?(t&&Ot({drawDefinition:t,structureIds:r?[r]:void 0,tournamentId:e,eventId:o}),mt({topic:Vf,payload:{matchUp:i,tournamentId:e,context:n},key:i.matchUpId}),{...C}):(console.log(hr),{error:hr})}function Sb({tournamentId:t,inContextMatchUp:e}){return e?(mt({payload:{inContextMatchUp:e,tournamentId:t},topic:Sp,key:e.matchUpId}),{...C}):{error:hr}}function Ta({tournamentId:t,eventId:e,drawDefinition:r}){return r?(Yh(r),mt({payload:{drawDefinition:r,tournamentId:t,eventId:e},topic:_f,key:r.drawId}),{...C}):(console.log(Z),{error:Z})}function Tb({tournamentId:t,eventId:e,drawId:r}){return mt({payload:{drawId:r,tournamentId:t,eventId:e},topic:Ff,key:r}),YI({key:r}),{...C}}function Ot({drawDefinition:t,tournamentId:e,structureIds:r,eventId:n}){return t?(Yh(t,r),mt({payload:{tournamentId:e,eventId:n,drawDefinition:t},topic:Gf,key:t.drawId}),{...C}):{error:Z}}function qh({drawDefinition:t,tournamentId:e,structure:r,eventId:n}){if(!t)return{error:Z};if(!r)return{error:pi};let o=r.seedAssignments,i=r.structureId,s=t.drawId;return mt({payload:{tournamentId:e,eventId:n,drawId:s,structureId:i,seedAssignments:o},topic:Hf,key:t.drawId}),Ot({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:n}),{...C}}function bo({drawDefinition:t,tournamentId:e,structure:r,event:n}){if(!t)return{error:Z};if(!r)return{error:pi};let o=bt({structure:r}),i=r.structureId,s=t.drawId,a=n?.eventId;return mt({topic:Bf,payload:{positionAssignments:o,tournamentId:e,structureId:i,eventId:a,drawId:s},key:i}),Ot({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:a}),{...C}}function wU({tournamentRecord:t,drawDefinition:e,resetEntries:r,event:n}){if(!e)return{error:Z};let o=e.structures?.find(s=>s.stage===$e);if(!o)return{error:kt};let i=o.matchUps?.map(({matchUpId:s})=>s)||[];return o.positionAssignments=[],o.seedAssignments=[],o.matchUps=[],Yn({tournamentId:t?.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:i,drawDefinition:e}),r&&(e.entries=e.entries.filter(s=>s.entryStage!==$e)),Ot({tournamentId:t?.tournamentId,eventId:n?.eventId,drawDefinition:e,structureIds:[o.structureId]}),{...C}}function Qm({drawPositions:t,structure:e}){if([ct,nt].includes(e.stage)&&e.stageSequence===1)return;let{positionAssignments:r}=bt({structure:e});r?.filter(({drawPosition:o})=>t?.includes(o))?.forEach(o=>{At({element:o,extension:{name:Hm,value:!0}})})}function cu(t){let{appliedPolicies:e,positionAction:r,drawDefinition:n}=t;if(e?.audit?.[nc]===!1)return;let{extension:o}=dt({name:nc,element:n}),i=Array.isArray(o?.value)?o?.value??[]:[];if(!i?.length){let a=n.structures.find(c=>c.stage===nt);if(a){let c=bt({structure:a}).positionAssignments?.map(({drawPosition:u,participantId:p,bye:m,qualifier:d})=>({drawPosition:u,participantId:p,qualifier:d,bye:m}));i.push({name:"initialMainAssignments",initialAssignments:c})}}let s={value:i.concat(r),name:nc};At({element:n,extension:s})}function as({tournamentRecord:t,drawDefinition:e,event:r}){let o=(t?.events||r&&[r])?.map(c=>c?.drawDefinitions).flat().filter(Boolean)||e&&[e]||[],i={},s={},a=o.map(c=>c?.structures?.filter(u=>u?.structures)).flat().filter(Boolean);for(let c of a){let{structures:u,structureId:p}=c??{};u&&p&&(i[p]=u?.map(m=>m.structureId))&&u.forEach(m=>s[m.structureId]=c?.structureId)}return{containedStructures:i,containerStructures:s}}function uu(t){let{sides:e,matchUpType:r}=t||{},n=t.potentialParticipants?.length?t.potentialParticipants.flat().map(s=>r===_t?s?.individualParticipantIds||[]:s.participantId).flat():[],o=(e||[]).map(s=>r===_t&&(s?.participant?.individualParticipantIds||[])||s?.participantId&&[s.participantId]||[]).flat();return{individualParticipantIds:o.concat(n).flat(),enteredIndividualParticipantIds:o,potentialIndividualParticipantIds:n}}function Dr(t){return t?.tournamentRecords??(t?.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord})??{}}var sc="SIGN_IN_STATUS",LU="SIGNED_OUT",pu="SIGNED_IN",yr="TEAM",Tt="INDIVIDUAL",zr="GROUP",ft="PAIR",Lt="TEAM",mu={TEAM_PARTICIPANT:yr,INDIVIDUAL:Tt,GROUP:zr,TEAM:Lt,PAIR:ft},yb={INDIVIDUAL:Tt,GROUP:zr,PAIR:ft,TEAM:Lt,SIGN_IN_STATUS:sc,SIGNED_OUT:LU,SIGNED_IN:pu};function Xm({participantsProfile:t,participants:e=[],deepCopy:r}){let n=new Map,o=r!==!1?J(e,t?.convertExtensions,!0):e,i=o.filter(c=>c.participantType===Lt),s=o.filter(c=>c.participantType===zr),a=o.filter(c=>c.participantType===ft);return o.forEach(c=>{if(c.participantType===Tt){let{participantId:u}=c;c.groupParticipantIds=[],c.teamParticipantIds=[],c.pairParticipantIds=[],c.groups=[],c.teams=[],i.forEach(p=>{(p?.individualParticipantIds||[]).forEach(m=>{m===u&&!c.teamParticipantIds?.includes(p.participantId)&&(c.teamParticipantIds.push(p.participantId),n.get(p.participantId)||n.set(p.participantId,{participantName:p.participantName,participantId:p.participantId}),c.teams.push({participantRoleResponsibilities:p.participantRoleResponsibilities,participantOtherName:p.participantOtherName,participantName:p.participantName,participantId:p.participantId,teamId:p.teamId}))})}),a.forEach(p=>{(p?.individualParticipantIds||[]).forEach(m=>{m===u&&!c.pairParticipantIds.includes(p.participantId)&&c.pairParticipantIds.push(p.participantId)})}),s.forEach(p=>{(p?.individualParticipantIds||[]).forEach(m=>{m===u&&!c.groupParticipantIds.includes(p.participantId)&&(c.groupParticipantIds.push(p.participantId),c.groups.push({participantRoleResponsibilities:p.participantRoleResponsibilities,participantOtherName:p.participantOtherName,participantName:p.participantName,participantId:p.participantId}))})})}}),{participantsWithGroupings:o,groupInfo:Object.fromEntries(n)}}function FU(t){return t&&typeof String.fromCodePoint<"u"?t.toUpperCase().replace(/./g,e=>String.fromCodePoint(e.charCodeAt(0)+127397)):t}function Ab(t){let e=Object.assign({},...ti.filter(r=>r.ioc).map(r=>({[r.ioc]:r.iso})));return FU(e[t])}var ti=[{ioc:"",iso2:"",iso:"",label:"NONE",phone:""},{ioc:"AND",iso2:"AD",iso:"AND",label:"Andorra",phone:"376"},{ioc:"UAE",iso2:"AE",iso:"ARE",label:"United Arab Emirates",phone:"971"},{ioc:"AFG",iso2:"AF",iso:"AFG",label:"Afghanistan",phone:"93"},{ioc:"ANT",iso2:"AG",iso:"ATG",label:"Antigua and Barbuda",phone:"1-268"},{ioc:"AIA",iso2:"AI",iso:"AIA",label:"Anguilla",phone:"1-264"},{ioc:"ALB",iso2:"AL",iso:"ALB",label:"Albania",phone:"355"},{ioc:"ARM",iso2:"AM",iso:"ARM",label:"Armenia",phone:"374"},{ioc:"ANG",iso2:"AO",iso:"AGO",label:"Angola",phone:"244"},{ioc:"",iso2:"AQ",iso:"ATA",label:"Antarctica",phone:"672"},{ioc:"ARG",iso2:"AR",iso:"ARG",label:"Argentina",phone:"54"},{ioc:"ASA",iso2:"AS",iso:"ASM",label:"American Samoa",phone:"1-684"},{ioc:"AUT",iso2:"AT",iso:"AUT",label:"Austria",phone:"43"},{ioc:"AUS",iso2:"AU",iso:"AUS",label:"Australia",phone:"61",suggested:!0},{ioc:"ARU",iso2:"AW",iso:"ABW",label:"Aruba",phone:"297"},{ioc:"AZE",iso2:"AZ",iso:"AZE",label:"Azerbaijan",phone:"994"},{ioc:"BIH",iso2:"BA",iso:"BIH",label:"Bosnia and Herzegovina",phone:"387"},{ioc:"BAR",iso2:"BB",iso:"BRB",label:"Barbados",phone:"1-246"},{ioc:"BAN",iso2:"BD",iso:"BGD",label:"Bangladesh",phone:"880"},{ioc:"BEL",iso2:"BE",iso:"BEL",label:"Belgium",phone:"32"},{ioc:"BUR",iso2:"BF",iso:"BFA",label:"Burkina Faso",phone:"226"},{ioc:"BUL",iso2:"BG",iso:"BGR",label:"Bulgaria",phone:"359"},{ioc:"BRN",iso2:"BH",iso:"BHR",label:"Bahrain",phone:"973"},{ioc:"BDI",iso2:"BI",iso:"BDI",label:"Burundi",phone:"257"},{ioc:"BEN",iso2:"BJ",iso:"BEN",label:"Benin",phone:"229"},{ioc:"",iso2:"BL",iso:"BLM",label:"Saint Barthelemy",phone:"590"},{ioc:"BER",iso2:"BM",iso:"BMU",label:"Bermuda",phone:"1-441"},{ioc:"BRU",iso2:"BN",iso:"BRN",label:"Brunei Darussalam",phone:"673"},{ioc:"BOL",iso2:"BO",iso:"BOL",label:"Bolivia",phone:"591"},{ioc:"BRA",iso2:"BR",iso:"BRA",label:"Brazil",phone:"55"},{ioc:"BAH",iso2:"BS",iso:"BHS",label:"Bahamas",phone:"1-242"},{ioc:"BHU",iso2:"BT",iso:"BTN",label:"Bhutan",phone:"975"},{ioc:"",iso2:"BV",iso:"BVT",label:"Bouvet Island",phone:"47"},{ioc:"BOT",iso2:"BW",iso:"BWA",label:"Botswana",phone:"267"},{ioc:"BLR",iso2:"BY",iso:"BLR",label:"Belarus",phone:"375"},{ioc:"BIZ",iso2:"BZ",iso:"BLZ",label:"Belize",phone:"501"},{ioc:"CAN",iso2:"CA",iso:"CAN",label:"Canada",phone:"1",suggested:!0},{ioc:"",iso2:"CC",iso:"CCK",label:"Cocos (Keeling) Islands",phone:"61"},{ioc:"CGO",iso2:"CD",iso:"COG",label:"Congo, Republic of the",phone:"242"},{ioc:"CAF",iso2:"CF",iso:"CAF",label:"Central African Republic",phone:"236"},{ioc:"COD",iso2:"CG",iso:"CGD",label:"Congo, Democratic Republic of the",phone:"243"},{ioc:"SUI",iso2:"CH",iso:"CHE",label:"Switzerland",phone:"41"},{ioc:"CIV",iso2:"CI",iso:"CIV",label:"Cote d'Ivoire",phone:"225"},{ioc:"COK",iso2:"CK",iso:"COK",label:"Cook Islands",phone:"682"},{ioc:"CHI",iso2:"CL",iso:"CHL",label:"Chile",phone:"56"},{ioc:"CMR",iso2:"CM",iso:"CMR",label:"Cameroon",phone:"237"},{ioc:"CHN",iso2:"CN",iso:"CHN",label:"China",phone:"86"},{ioc:"COL",iso2:"CO",iso:"COL",label:"Colombia",phone:"57"},{ioc:"CRC",iso2:"CR",iso:"CRI",label:"Costa Rica",phone:"506"},{ioc:"CUB",iso2:"CU",iso:"CUB",label:"Cuba",phone:"53"},{ioc:"CPV",iso2:"CV",iso:"CPV",label:"Cape Verde",phone:"238"},{ioc:"CUW",iso2:"CW",iso:"CUW",label:"Curacao",phone:"599"},{ioc:"CXR",iso2:"CX",iso:"CXR",label:"Christmas Island",phone:"61"},{ioc:"CYP",iso2:"CY",iso:"CYP",label:"Cyprus",phone:"357"},{ioc:"CZE",iso2:"CZ",iso:"CZE",label:"Czech Republic",phone:"420"},{ioc:"GER",iso2:"DE",iso:"DEU",label:"Germany",phone:"49",suggested:!0},{ioc:"DJI",iso2:"DJ",iso:"DJI",label:"Djibouti",phone:"253"},{ioc:"DEN",iso2:"DK",iso:"DNK",label:"Denmark",phone:"45"},{ioc:"DMA",iso2:"DM",iso:"DMA",label:"Dominica",phone:"1-767"},{ioc:"DOM",iso2:"DO",iso:"DOM",label:"Dominican Republic",phone:"1-809"},{ioc:"ALG",iso2:"DZ",iso:"DZA",label:"Algeria",phone:"213"},{ioc:"ECU",iso2:"EC",iso:"ECU",label:"Ecuador",phone:"593"},{ioc:"EST",iso2:"EE",iso:"ESE",label:"Estonia",phone:"372"},{ioc:"EGY",iso2:"EG",iso:"EGY",label:"Egypt",phone:"20"},{ioc:"",iso2:"EH",iso:"ESH",label:"Western Sahara",phone:"212"},{ioc:"ERI",iso2:"ER",iso:"ERI",label:"Eritrea",phone:"291"},{ioc:"ESP",iso2:"ES",iso:"ESP",label:"Spain",phone:"34"},{ioc:"ETH",iso2:"ET",iso:"ETH",label:"Ethiopia",phone:"251"},{ioc:"FIN",iso2:"FI",iso:"FIN",label:"Finland",phone:"358"},{ioc:"FIJ",iso2:"FJ",iso:"FJI",label:"Fiji",phone:"679"},{ioc:"FLK",iso2:"FK",iso:"FLK",label:"Falkland Islands (Malvinas)",phone:"500"},{ioc:"FSM",iso2:"FM",iso:"FSM",label:"Micronesia, Federated States of",phone:"691"},{ioc:"FAR",iso2:"FO",iso:"FRO",label:"Faroe Islands",phone:"298"},{ioc:"FRA",iso2:"FR",iso:"FRA",label:"France",phone:"33",suggested:!0},{ioc:"GAB",iso2:"GA",iso:"GAB",label:"Gabon",phone:"241"},{ioc:"GBR",iso2:"GB",iso:"GBR",label:"United Kingdom",phone:"44"},{ioc:"GRN",iso2:"GD",iso:"GRD",label:"Grenada",phone:"1-473"},{ioc:"GEO",iso2:"GE",iso:"GEO",label:"Georgia",phone:"995"},{ioc:"FGU",iso2:"GF",iso:"GUF",label:"French Guiana",phone:"594"},{ioc:"",iso2:"GG",iso:"GGY",label:"Guernsey",phone:"44"},{ioc:"",iso2:"GH",iso:"GHA",label:"Ghana",phone:"233"},{ioc:"GIB",iso2:"GI",iso:"GIB",label:"Gibraltar",phone:"350"},{ioc:"GRL",iso2:"GL",iso:"GRL",label:"Greenland",phone:"299"},{ioc:"GAM",iso2:"GM",iso:"GMB",label:"Gambia",phone:"220"},{ioc:"GUI",iso2:"GN",iso:"GIN",label:"Guinea",phone:"224"},{ioc:"GUD",iso2:"GP",iso:"GLP",label:"Guadeloupe",phone:"590"},{ioc:"GEQ",iso2:"GQ",iso:"GNQ",label:"Equatorial Guinea",phone:"240"},{ioc:"GRE",iso2:"GR",iso:"GRC",label:"Greece",phone:"30"},{ioc:"",iso2:"GS",iso:"SGS",label:"South Georgia and the South Sandwich Islands",phone:"500"},{ioc:"GUA",iso2:"GT",iso:"GTM",label:"Guatemala",phone:"502"},{ioc:"GUM",iso2:"GU",iso:"GUM",label:"Guam",phone:"1-671"},{ioc:"GBS",iso2:"GW",iso:"GNB",label:"Guinea-Bissau",phone:"245"},{ioc:"GUY",iso2:"GY",iso:"GUY",label:"Guyana",phone:"592"},{ioc:"HKG",iso2:"HK",iso:"HKG",label:"Hong Kong",phone:"852"},{ioc:"",iso2:"HM",iso:"HMD",label:"Heard Island and McDonald Islands",phone:"672"},{ioc:"HON",iso2:"HN",iso:"HND",label:"Honduras",phone:"504"},{ioc:"CRO",iso2:"HR",iso:"HRV",label:"Croatia",phone:"385"},{ioc:"HAI",iso2:"HT",iso:"HTI",label:"Haiti",phone:"509"},{ioc:"HUN",iso2:"HU",iso:"HUN",label:"Hungary",phone:"36"},{ioc:"INA",iso2:"ID",iso:"IDN",label:"Indonesia",phone:"62"},{ioc:"IRL",iso2:"IE",iso:"IRL",label:"Ireland",phone:"353"},{ioc:"ISR",iso2:"IL",iso:"ISR",label:"Israel",phone:"972"},{ioc:"",iso2:"IM",iso:"IMN",label:"Isle of Man",phone:"44"},{ioc:"IND",iso2:"IN",iso:"IND",label:"India",phone:"91"},{ioc:"",iso2:"IO",iso:"IOT",label:"British Indian Ocean Territory",phone:"246"},{ioc:"IRQ",iso2:"IQ",iso:"IRQ",label:"Iraq",phone:"964"},{ioc:"IRI",iso2:"IR",iso:"IRN",label:"Iran, Islamic Republic of",phone:"98"},{ioc:"ISL",iso2:"IS",iso:"ISL",label:"Iceland",phone:"354"},{ioc:"ITA",iso2:"IT",iso:"ITA",label:"Italy",phone:"39"},{ioc:"",iso2:"JE",iso:"JEY",label:"Jersey",phone:"44"},{ioc:"JAM",iso2:"JM",iso:"JAM",label:"Jamaica",phone:"1-876"},{ioc:"JOR",iso2:"JO",iso:"JOR",label:"Jordan",phone:"962"},{ioc:"JPN",iso2:"JP",iso:"JPN",label:"Japan",phone:"81",suggested:!0},{ioc:"KEN",iso2:"KE",iso:"KEN",label:"Kenya",phone:"254"},{ioc:"KGZ",iso2:"KG",iso:"KGZ",label:"Kyrgyzstan",phone:"996"},{ioc:"CAM",iso2:"KH",iso:"KHM",label:"Cambodia",phone:"855"},{ioc:"KIR",iso2:"KI",iso:"KIR",label:"Kiribati",phone:"686"},{ioc:"COM",iso2:"KM",iso:"COM",label:"Comoros",phone:"269"},{ioc:"SKN",iso2:"KN",iso:"KNA",label:"Saint Kitts and Nevis",phone:"1-869"},{ioc:"KOR",iso2:"KP",iso:"KOR",label:"Korea, Democratic People's Republic of",phone:"850"},{ioc:"PRK",iso2:"KR",iso:"PRK",label:"Korea, Republic of",phone:"82"},{ioc:"KUW",iso2:"KW",iso:"KWT",label:"Kuwait",phone:"965"},{ioc:"CAY",iso2:"KY",iso:"CYM",label:"Cayman Islands",phone:"1-345"},{ioc:"KAZ",iso2:"KZ",iso:"KAZ",label:"Kazakhstan",phone:"7"},{ioc:"LAO",iso2:"LA",iso:"LAO",label:"Lao People's Democratic Republic",phone:"856"},{ioc:"LIB",iso2:"LB",iso:"LBN",label:"Lebanon",phone:"961"},{ioc:"LCA",iso2:"LC",iso:"LCA",label:"Saint Lucia",phone:"1-758"},{ioc:"LIE",iso2:"LI",iso:"LIE",label:"Liechtenstein",phone:"423"},{ioc:"SRI",iso2:"LK",iso:"LKA",label:"Sri Lanka",phone:"94"},{ioc:"LBR",iso2:"LR",iso:"LBR",label:"Liberia",phone:"231"},{ioc:"LES",iso2:"LS",iso:"LSO",label:"Lesotho",phone:"266"},{ioc:"LTU",iso2:"LT",iso:"LTU",label:"Lithuania",phone:"370"},{ioc:"LUX",iso2:"LU",iso:"LUX",label:"Luxembourg",phone:"352"},{ioc:"LAT",iso2:"LV",iso:"LVA",label:"Latvia",phone:"371"},{ioc:"LBA",iso2:"LY",iso:"LBY",label:"Libya",phone:"218"},{ioc:"MAR",iso2:"MA",iso:"MAR",label:"Morocco",phone:"212"},{ioc:"MON",iso2:"MC",iso:"MCO",label:"Monaco",phone:"377"},{ioc:"MDA",iso2:"MD",iso:"MDA",label:"Moldova, Republic of",phone:"373"},{ioc:"MNE",iso2:"ME",iso:"MNE",label:"Montenegro",phone:"382"},{ioc:"",iso2:"MF",iso:"MAF",label:"Saint Martin (French part)",phone:"590"},{ioc:"MAD",iso2:"MG",iso:"MDG",label:"Madagascar",phone:"261"},{ioc:"MSH",iso2:"MH",iso:"MHL",label:"Marshall Islands",phone:"692"},{ioc:"MKD",iso2:"MK",iso:"MKD",label:"Macedonia, the Former Yugoslav Republic of",phone:"389"},{ioc:"MLI",iso2:"ML",iso:"MLI",label:"Mali",phone:"223"},{ioc:"MYA",iso2:"MM",iso:"MMR",label:"Myanmar",phone:"95"},{ioc:"MGL",iso2:"MN",iso:"MNG",label:"Mongolia",phone:"976"},{ioc:"MAC",iso2:"MO",iso:"MAC",label:"Macao",phone:"853"},{ioc:"NMA",iso2:"MP",iso:"NMP",label:"Northern Mariana Islands",phone:"1-670"},{ioc:"MRT",iso2:"MQ",iso:"MTQ",label:"Martinique",phone:"596"},{ioc:"MTN",iso2:"MR",iso:"MRT",label:"Mauritania",phone:"222"},{ioc:"MNT",iso2:"MS",iso:"MSR",label:"Montserrat",phone:"1-664"},{ioc:"MLT",iso2:"MT",iso:"MLT",label:"Malta",phone:"356"},{ioc:"MRI",iso2:"MU",iso:"MUS",label:"Mauritius",phone:"230"},{ioc:"MDV",iso2:"MV",iso:"MDV",label:"Maldives",phone:"960"},{ioc:"MAW",iso2:"MW",iso:"MWI",label:"Malawi",phone:"265"},{ioc:"MEX",iso2:"MX",iso:"MEX",label:"Mexico",phone:"52"},{ioc:"MAS",iso2:"MY",iso:"MYS",label:"Malaysia",phone:"60"},{ioc:"MOZ",iso2:"MZ",iso:"MOZ",label:"Mozambique",phone:"258"},{ioc:"NAM",iso2:"NA",iso:"NAM",label:"Namibia",phone:"264"},{ioc:"NCL",iso2:"NC",iso:"NCL",label:"New Caledonia",phone:"687"},{ioc:"NIG",iso2:"NE",iso:"NER",label:"Niger",phone:"227"},{ioc:"NFI",iso2:"NF",iso:"NFK",label:"Norfolk Island",phone:"672"},{ioc:"NGR",iso2:"NG",iso:"NGA",label:"Nigeria",phone:"234"},{ioc:"NCA",iso2:"NI",iso:"NIC",label:"Nicaragua",phone:"505"},{ioc:"NED",iso2:"NL",iso:"NLD",label:"Netherlands",phone:"31"},{ioc:"NOR",iso2:"NO",iso:"NOR",label:"Norway",phone:"47"},{ioc:"NEP",iso2:"NP",iso:"NPL",label:"Nepal",phone:"977"},{ioc:"NRU",iso2:"NR",iso:"NRU",label:"Nauru",phone:"674"},{ioc:"NIU",iso2:"NU",iso:"NIU",label:"Niue",phone:"683"},{ioc:"NZL",iso2:"NZ",iso:"NZL",label:"New Zealand",phone:"64"},{ioc:"OMA",iso2:"OM",iso:"OMN",label:"Oman",phone:"968"},{ioc:"PAN",iso2:"PA",iso:"PAN",label:"Panama",phone:"507"},{ioc:"PER",iso2:"PE",iso:"PER",label:"Peru",phone:"51"},{ioc:"FPO",iso2:"PF",iso:"PYF",label:"French Polynesia",phone:"689"},{ioc:"PNG",iso2:"PG",iso:"PNG",label:"Papua New Guinea",phone:"675"},{ioc:"PHI",iso2:"PH",iso:"PHL",label:"Philippines",phone:"63"},{ioc:"PAK",iso2:"PK",iso:"PAK",label:"Pakistan",phone:"92"},{ioc:"POL",iso2:"PL",iso:"POL",label:"Poland",phone:"48"},{ioc:"SPM",iso2:"PM",iso:"SPM",label:"Saint Pierre and Miquelon",phone:"508"},{ioc:"",iso2:"PN",iso:"PCN",label:"Pitcairn",phone:"870"},{ioc:"PUR",iso2:"PR",iso:"PRI",label:"Puerto Rico",phone:"1"},{ioc:"PLE",iso2:"PS",iso:"PSE",label:"Palestine, State of",phone:"970"},{ioc:"POR",iso2:"PT",iso:"PRT",label:"Portugal",phone:"351"},{ioc:"PLW",iso2:"PW",iso:"PLW",label:"Palau",phone:"680"},{ioc:"PAR",iso2:"PY",iso:"PRY",label:"Paraguay",phone:"595"},{ioc:"QAT",iso2:"QA",iso:"QAT",label:"Qatar",phone:"974"},{ioc:"REU",iso2:"RE",iso:"REU",label:"Reunion",phone:"262"},{ioc:"ROU",iso2:"RO",iso:"ROU",label:"Romania",phone:"40"},{ioc:"SRB",iso2:"RS",iso:"SRB",label:"Serbia",phone:"381"},{ioc:"RUS",iso2:"RU",iso:"RUS",label:"Russia",phone:"7"},{ioc:"RWA",iso2:"RW",iso:"RWA",label:"Rwanda",phone:"250"},{ioc:"KSA",iso2:"SA",iso:"SAU",label:"Saudi Arabia",phone:"966"},{ioc:"SOL",iso2:"SB",iso:"SLB",label:"Solomon Islands",phone:"677"},{ioc:"SEY",iso2:"SC",iso:"SYC",label:"Seychelles",phone:"248"},{ioc:"SUD",iso2:"SD",iso:"SDN",label:"Sudan",phone:"249"},{ioc:"SWE",iso2:"SE",iso:"SWE",label:"Sweden",phone:"46"},{ioc:"SIN",iso2:"SG",iso:"SGP",label:"Singapore",phone:"65"},{ioc:"HEL",iso2:"SH",iso:"SHN",label:"Saint Helena",phone:"290"},{ioc:"SLO",iso2:"SI",iso:"SVN",label:"Slovenia",phone:"386"},{ioc:"",iso2:"SJ",iso:"SJM",label:"Svalbard and Jan Mayen",phone:"47"},{ioc:"SVK",iso2:"SK",iso:"SVK",label:"Slovakia",phone:"421"},{ioc:"SLE",iso2:"SL",iso:"SLE",label:"Sierra Leone",phone:"232"},{ioc:"SMR",iso2:"SM",iso:"SMR",label:"San Marino",phone:"378"},{ioc:"SEN",iso2:"SN",iso:"SEN",label:"Senegal",phone:"221"},{ioc:"SOM",iso2:"SO",iso:"SOM",label:"Somalia",phone:"252"},{ioc:"SUR",iso2:"SR",iso:"SUR",label:"Suriname",phone:"597"},{ioc:"",iso2:"SS",iso:"SSD",label:"South Sudan",phone:"211"},{ioc:"STP",iso2:"ST",iso:"STP",label:"Sao Tome and Principe",phone:"239"},{ioc:"ESA",iso2:"SV",iso:"SLV",label:"El Salvador",phone:"503"},{ioc:"",iso2:"SX",iso:"SMX",label:"Sint Maarten",phone:"1-721"},{ioc:"SYR",iso2:"SY",iso:"SYR",label:"Syria",phone:"963"},{ioc:"",iso2:"SZ",iso:"SWZ",label:"Swaziland",phone:"268"},{ioc:"TKS",iso2:"TC",iso:"TCA",label:"Turks and Caicos Islands",phone:"1-649"},{ioc:"CHA",iso2:"TD",iso:"TCD",label:"Chad",phone:"235"},{ioc:"",iso2:"TF",iso:"ATF",label:"French Southern Territories",phone:"262"},{ioc:"TOG",iso2:"TG",iso:"TGO",label:"Togo",phone:"228"},{ioc:"THA",iso2:"TH",iso:"THA",label:"Thailand",phone:"66"},{ioc:"TJK",iso2:"TJ",iso:"TJK",label:"Tajikistan",phone:"992"},{ioc:"",iso2:"TK",iso:"TKL",label:"Tokelau",phone:"690"},{ioc:"TLS",iso2:"TL",iso:"TLS",label:"Timor-Leste",phone:"670"},{ioc:"TKM",iso2:"TM",iso:"TKM",label:"Turkmenistan",phone:"993"},{ioc:"TUN",iso2:"TN",iso:"TUN",label:"Tunisia",phone:"216"},{ioc:"TGA",iso2:"TO",iso:"TON",label:"Tonga",phone:"676"},{ioc:"TUR",iso2:"TR",iso:"TUR",label:"Turkey",phone:"90"},{ioc:"TTO",iso2:"TT",iso:"TTO",label:"Trinidad and Tobago",phone:"1-868"},{ioc:"TUV",iso2:"TV",iso:"TUV",label:"Tuvalu",phone:"688"},{ioc:"TPE",iso2:"TW",iso:"TWN",label:"Taiwan",phone:"886"},{ioc:"TAN",iso2:"TZ",iso:"TZA",label:"United Republic of Tanzania",phone:"255"},{ioc:"UKR",iso2:"UA",iso:"UKR",label:"Ukraine",phone:"380"},{ioc:"UGA",iso2:"UG",iso:"UGA",label:"Uganda",phone:"256"},{ioc:"USA",iso2:"US",label:"United States",phone:"1",suggested:!0,iso:"USA"},{ioc:"URU",iso2:"UY",iso:"URY",label:"Uruguay",phone:"598"},{ioc:"UZB",iso2:"UZ",iso:"UZB",label:"Uzbekistan",phone:"998"},{ioc:"",iso2:"VA",iso:"VAT",label:"Holy See (Vatican City State)",phone:"379"},{ioc:"VIN",iso2:"VC",iso:"VCT",label:"Saint Vincent and the Grenadines",phone:"1-784"},{ioc:"VEN",iso2:"VE",iso:"VEN",label:"Venezuela",phone:"58"},{ioc:"IVB",iso2:"VG",iso:"VGB",label:"British Virgin Islands",phone:"1-284"},{ioc:"ISV",iso2:"VI",iso:"VIR",label:"US Virgin Islands",phone:"1-340"},{ioc:"VIE",iso2:"VN",iso:"VNM",label:"Vietnam",phone:"84"},{ioc:"VAN",iso2:"VU",iso:"VUT",label:"Vanuatu",phone:"678"},{ioc:"WAF",iso2:"WF",iso:"WLF",label:"Wallis and Futuna",phone:"681"},{ioc:"SAM",iso2:"WS",iso:"WSM",label:"Samoa",phone:"685"},{ioc:"KOS",iso2:"XK",iso:"KOS",label:"Kosovo",phone:"383"},{ioc:"YEM",iso2:"YE",iso:"YEM",label:"Yemen",phone:"967"},{ioc:"MAY",iso2:"YT",iso:"MYT",label:"Mayotte",phone:"262"},{ioc:"RSA",iso2:"ZA",iso:"ZAF",label:"South Africa",phone:"27"},{ioc:"ZAM",iso2:"ZM",iso:"ZMB",label:"Zambia",phone:"260"},{ioc:"ZIM",iso2:"ZW",iso:"ZWE",label:"Zimbabwe",phone:"263"}];function $h({participant:t,withISO2:e,withIOC:r}){let{person:n,individualParticipants:o}=t,i=[n,o?.map(({person:a})=>a)].flat().filter(Boolean);function s(a){let{nationalityCode:c}=a||{};if(c){let u=ti.find(({iso:p})=>p===c);r&&u?.ioc&&!a.iocNationalityCode&&(a.iocNationalityCode=u.ioc),e&&u?.iso2&&!a.iso2NationalityCode&&(a.iso2NationalityCode=u.iso2),u?.label&&!a.countryName&&(a.countryName=u.label)}}i.forEach(s)}function Eb({participantMap:t,template:e}){let r=Object.values(t);for(let n of r){let o=n.participant;if(o.individualParticipantIds?.length){o.individualParticipants=[];for(let i of o.individualParticipantIds){let s=t[i].participant;o.individualParticipants.push(e?Vi({template:e,source:s}):s)}}}}function To(t){let{tournamentRecord:e,participantId:r}=t,n=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};for(let o of Object.values(n)){let i=o.participants?.find(s=>s.participantId===r);if(i)return{participant:i,tournamentId:o.tournamentId}}return{error:te}}function Kh(t){let{tournamentRecord:e,participantId:r}=t;if(r){let o=To({tournamentRecord:e,participantId:r});return o.participant??o}let n=t.element||t.drawDefinition||t.event||t.tournamentRecord;return n||{error:st}}function rn(t){let{returnPreviousValues:e,itemSubTypes:r,itemType:n}=t,o=Kh(t);if(o.error)return o;if(r&&!Array.isArray(r))return{error:G,context:{itemSubTypes:r}};if(!Array.isArray(o.timeItems))return{error:tf};let i=o.timeItems.filter(a=>a?.itemType===n).filter(a=>!r?.length||r.some(c=>a?.itemSubTypes?.includes(c))).sort((a,c)=>{let u=new Date(a.createdAt||void 0).getTime(),p=new Date(c.createdAt||void 0).getTime();return u-p}),s=J(i.pop(),!1,!0);if(s){let a={timeItem:s,...C};return e&&Object.assign(a,{previousItems:i}),a}else return{info:ve}}function zh({returnPreviousValues:t,drawDefinition:e,itemSubTypes:r,itemType:n}){if(!e)return{error:an};if(!e.timeItems)return{info:ve};let{timeItem:o,previousItems:i,info:s}=rn({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function du({returnPreviousValues:t,itemSubTypes:e,itemType:r,event:n}){if(!n)return{error:vt};if(!n.timeItems)return{info:ve};let{timeItem:o,previousItems:i,info:s}=rn({returnPreviousValues:t,element:n,itemSubTypes:e,itemType:r});return o&&{timeItem:o,previousItems:i}||{info:s}}function Jm({returnPreviousValues:t,tournamentRecord:e,itemSubTypes:r,itemType:n}){if(!e)return{error:Y};if(!e.timeItems)return{info:ve};let{timeItem:o,previousItems:i,info:s}=rn({element:e,returnPreviousValues:t,itemSubTypes:r,itemType:n});return o&&{timeItem:o,previousItems:i}||{info:s}}function Qh({returnPreviousValues:t,tournamentRecord:e,participantId:r,itemSubTypes:n,itemType:o}){if(!e)return{error:Y};if(!r)return{error:oe};let i=To({tournamentRecord:e,participantId:r});if(i.error)return i;let{participant:s}=i;if(!s?.timeItems)return{info:ve};let{timeItem:a,previousItems:c,info:u}=rn({element:i.participant,returnPreviousValues:t,itemSubTypes:n,itemType:o});return a&&{timeItem:a,previousItems:c}||{info:u}}var JF={[zr]:"groupParticipantIds",[ft]:"pairParticipantIds",[Lt]:"teamParticipantIds"},ZF={[zr]:"groups",[Lt]:"teams"};function Xh({withIndividualParticipants:t,convertExtensions:e,tournamentRecord:r,withSignInStatus:n,withScaleValues:o,internalUse:i,withISO2:s,withIOC:a}){let c=[],u={};for(let p of r.participants??[]){let m=p?.participantId;m&&rk({participantMap:u,participantId:m})}for(let p of r.participants??[]){let m=J(p,e,i),{participantId:d,individualParticipantIds:l,participantType:f}=m;if(!u[d]){c.push(d);continue}if(Object.assign(u[d].participant,m),l){let g=ek({individualParticipantIds:l,participantCopy:m,participantMap:u,participantType:f,participantId:d});g.missingParticipantIds.length&&c.push(...g.missingParticipantIds)}if(n&&(u[d].participant.signedIn=tk(m)),o){let{ratings:g,rankings:I,seedings:h}=la({participant:m});u[d].participant.seedings=h,u[d].participant.rankings=I,u[d].participant.ratings=g}(a||s)&&$h({participant:u[d].participant,withISO2:s,withIOC:a})}if(t){let p=ht(t)?t:void 0;Eb({participantMap:u,template:p})}return{missingParticipantIds:c,participantMap:u}}function tk(t){let{timeItem:e}=rn({itemType:sc,element:t});return e?.itemValue===pu}function ek({individualParticipantIds:t,participantCopy:e,participantMap:r,participantType:n,participantId:o}){let i=[];for(let s of t){let a=r[s]?.participant;if(!a){i.push(s);continue}if(a[JF[n]].push(o),[Lt,zr].includes(n)){let{participantRoleResponsibilities:c,participantOtherName:u,participantName:p,participantId:m,teamId:d}=e,l=ZF[n];a[l].push({participantRoleResponsibilities:c,participantOtherName:u,participantName:p,participantId:m,teamId:d})}if(n===ft){let c=t.find(u=>u!==s);r[s].pairIdMap[o]=c,r[s].pairIdMap[c]=o}}return{missingParticipantIds:i}}function rk({participantMap:t,participantId:e}){if(t[e])return;let r={walkoverWins:0,defaultWins:0,walkovers:0,defaults:0,losses:0,wins:0};t[e]={structureParticipation:{},potentialMatchUps:{},scheduleConflicts:{},scheduleItems:[],participant:{groupParticipantIds:[],pairParticipantIds:[],teamParticipantIds:[],seedings:{},rankings:{},ratings:{},groups:[],teams:[]},statistics:{},opponents:{},pairIdMap:{},matchUps:{},events:{},draws:{},counters:{[xt]:{...r},[_t]:{...r},[Lt]:{...r},...r}}}function Ai({participantsProfile:t,useParticipantMap:e,tournamentRecord:r,contextProfile:n,inContext:o}){if(e)return{participantMap:Xh({...t,...n,tournamentRecord:r})?.participantMap};let i=J(r.participants,!1,!0)||[];(t?.withIOC||t?.withISO2)&&i.forEach(a=>$h({participant:a,...t}));let s;if((o||t?.withGroupings)&&i?.length&&({participantsWithGroupings:i,groupInfo:s}=Xm({participantsProfile:t,deepCopy:!1,participants:i})),t?.withScaleValues&&i?.length)for(let a of i){let{ratings:c,rankings:u}=la({participant:a});a.rankings=u,a.ratings=c}return{participants:i,groupInfo:s}}function yt({onlySpecifiedPolicyTypes:t=!1,policyTypes:e=[],tournamentRecord:r,drawDefinition:n,structure:o,event:i}){if(!Array.isArray(e))return{error:wI};let s={};return r&&a(r),i&&a(i),n&&a(n),o&&a(o),{appliedPolicies:s,...C};function a(c){let p=c?.extensions?.find(m=>m.name===nu)?.value;if(p)for(let m of Object.keys(p))(t?e.includes(m):!e.length||e.includes(m))&&(s[m]=J(p[m],!1,!0))}}function vo({policyTypes:t=[],tournamentRecord:e,drawDefinition:r,structure:n,event:o}){if(!Array.isArray(t))return{error:wI};let{appliedPolicies:i}=yt({tournamentRecord:e,drawDefinition:r,structure:n,event:o}),s={};for(let a of t){let c=i?.[a];c&&(s[a]=c)}return Object.keys(s).length?{policyDefinitions:s}:{info:Fc.message}}var Jh="WALKOVER",kU="RETIRED",Zm="COMPETITIVE",ac="ROUTINE",cc="DECISIVE",td="winRatio";var nk={[hi]:{policyName:"Competitive Bands Default",profileBands:{[cc]:20,[ac]:50}}},ed=nk;function qn({policyDefinitions:t,tournamentRecord:e,contextProfile:r,drawDefinition:n,event:o}){let i={policies:{}};if(!r)return i;let s=vo({tournamentRecord:e,drawDefinition:n,event:o}).policyDefinitions;if(r.withCompetitiveness){let a=t?.[hi]??s?.[hi]??ed[hi];i.policies[hi]=a}return i}function ei({tournamentRecord:t,drawDefinition:e,policyType:r,structure:n,event:o}){if(!t)return{error:Y};let{appliedPolicies:i}=yt({tournamentRecord:t,drawDefinition:e,structure:n,event:o});return i?.[r]?{policy:i[r]}:{info:Fc?.message}}function ya({tournamentRecord:t,categoryName:e,categoryType:r,event:n}){e=e??n?.category?.categoryName??n?.category?.ageCategoryCode,r=r??n?.category?.categoryType??n?.category?.subType;let{policy:o}=ei({policyType:No,tournamentRecord:t,event:n}),s=(t?dt({element:t,name:Vo}).extension:void 0)?.value,c=(n&&dt({name:Vo,element:n}).extension)?.value;return{scheduleTiming:{tournamentScheduling:s,eventScheduling:c,categoryName:e,categoryType:r,policy:o}}}function qf({drawDefinition:t,attributes:e}){let{extension:r}=dt({element:t,name:jm}),n=r?.value||{};return e.forEach(o=>{Object.keys(o).forEach(i=>{n[i]?Object.assign(n[i],o[i]):n[i]=o[i]})}),r={name:jm,value:n},fp({drawDefinition:t,extension:r}),{entryProfile:n}}function lu({drawDefinition:t}){let{extension:e}=dt({element:t,name:jm});return{entryProfile:e?.value||{}}}var nn="ALTERNATE",$f="CONFIRMED",kr="DIRECT_ACCEPTANCE",rd="FEED_IN",Kf="JUNIOR_EXEMPT",cs="LUCKY_LOSER",zf="ORGANISER_ACCEPTANCE",nd="QUALIFIER",ok="REGISTERED",Qf="SPECIAL_EXEMPT",Gr="UNGROUPED",Ei="UNPAIRED",fu="WILDCARD",io="WITHDRAWN",Xf=[$f,kr,Kf,zf,Qf],GU=[rd,cs,nd],ri=[$f,kr,rd,Kf,zf,Qf,fu],Qr=[$f,kr,Kf,cs,nd,zf,Qf,fu],VU=[nn,$f,kr,rd,Kf,cs,zf,nd,ok,Qf,Gr,Ei,fu,io],Ub={ALTERNATE:nn,CONFIRMED:$f,DIRECT_ACCEPTANCE:kr,DIRECT_ENTRY_STATUSES:ri,DRAW_SPECIFIC_STATUSES:GU,EQUIVALENT_ACCEPTANCE_STATUSES:Xf,FEED_IN:rd,JUNIOR_EXEMPT:Kf,LUCKY_LOSER:cs,ORGANISER_ACCEPTANCE:zf,QUALIFIER:nd,SPECIAL_EXEMPT:Qf,STRUCTURE_SELECTED_STATUSES:Qr,UNGROUPED:Gr,UNPAIRED:Ei,VALID_ENTRY_STATUSES:VU,WILDCARD:fu,WITHDRAWN:io};function Jf({stage:t,drawDefinition:e}){let{entryProfile:r}=lu({drawDefinition:e}),n=Object.keys(r).includes(t);if(!n&&$c.includes(t)){let o=[{[t]:{drawSize:void 0,alternates:!0}}];return qf({drawDefinition:e,attributes:o}),!0}return n}function Pb({stage:t,drawDefinition:e}){let{entryProfile:r}=lu({drawDefinition:e});return r[t]?.alternates||0}function Db({stage:t,drawDefinition:e}){let{entryProfile:r}=lu({drawDefinition:e});return r[t]?.wildcardsCount||0}function Zh({stage:t,drawDefinition:e,entryStatus:r}){return e.entries.reduce((n,o)=>o.entryStage===t&&o.entryStatus===r?n+1:n,0)}function Ui({provisionalPositioning:t,placementGroup:e,drawDefinition:r,stageSequence:n,entryStatuses:o,structureId:i,roundTarget:s,stages:a,stage:c}){let u=r.entries?.reduce((p,m)=>{let d=dt({name:Mn,element:m})?.extension?.value,l=c&&m.entryStage===c||a?.length&&m.entryStage&&a.includes(m.entryStage),f=!o||m.entryStatus&&o.includes(m.entryStatus),g=m.entryStageSequence??1;return l&&(!n||g===n)&&f&&(!s||!d||s===d)?p.concat(m):p},[])??[];if(i&&c===de){let{playoffEntries:p,error:m}=ik({provisionalPositioning:t,drawDefinition:r,structureId:i});return m&&console.log("playoff entries error"),(p?.length?p:u).filter(d=>!e||d.placementGroup===e)}return u}function ik({provisionalPositioning:t,drawDefinition:e,structureId:r}){let n=[],o=(e.links??[]).find(i=>i.linkType===to&&i.target.structureId===r);if(o){let{finishingPositions:i,structureId:s}=o.source,{structure:a}=at({drawDefinition:e,structureId:s});a?.structureType===Ge&&(a.structures??[]).forEach(u=>{let p=u.positionAssignments??[],{structureId:m}=u,d=m,l=Object.assign({},...p.map(h=>{let{participantId:S}=h,T=dt({element:h,name:Jo}).extension?.value;return T&&S?{[S]:T}:void 0}).filter(Boolean)),g=Object.keys(l).reduce((h,S)=>{let T=l[S],y=T.groupOrder||t&&T.provisionalOrder;return h.includes(y)||h.push(y),h},[]).length===Object.keys(l).length,I=Object.keys(l).filter(h=>{let S=l[h],T=S.groupOrder||t&&S.provisionalOrder;return i?.includes(T)});(!t||g)&&I.forEach(h=>{let S=l[h],{groupOrder:T,provisionalOrder:y,GEMscore:P}=S,U=T||t&&y,E=[...i??[]].sort(me).indexOf(U)+1;n.push({entryStage:de,entryStatus:rd,placementGroup:E,groupingValue:d,participantId:h,GEMscore:P})})})}return{playoffEntries:n}}function Nb({stage:t,drawDefinition:e}){return ri.reduce((r,n)=>(Zh({drawDefinition:e,entryStatus:n,stage:t})||0)+r,0)}function on({provisionalPositioning:t,returnAllProxies:e,drawDefinition:r,structureId:n,structure:o}){let i,s=[];o||({structure:o,error:i}=at({drawDefinition:r,structureId:n}));let a=bt({structure:o}).positionAssignments;if(i||!o)return{seedAssignments:[],error:kt};n||(n=o.structureId);let{stage:c,stageSequence:u}=o,m=c===de&&r&&Ui({provisionalPositioning:t,drawDefinition:r,stageSequence:u,structureId:n,stage:c}),d=m?m.filter(g=>g.placementGroup===1).sort((g,I)=>g.GEMscore<I.GEMscore&&1||g.GEMscore>I.GEMscore&&-1||0).map((g,I)=>{let h=I+1;return{participantId:g.participantId,seedValue:h,seedProxy:!0,seedNumber:h}}):[],l=d?.slice(0,e?d.length:a.length/2);l.length?s=l:o.seedAssignments?s=o.seedAssignments:i=FA;let f=o.seedLimit??o?.positionAssignments?.length;return{seedAssignments:s,stageSequence:u,seedLimit:f,stage:c,error:i}}function ni(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 Tp({item:t,drawDefinition:e,structure:r,event:n}){if(t){if(t.tieFormat)return t.tieFormat;if(t.tieFormatId){if(e.tieFormat)return e.tieFormat;let o=e.tieFormats?.find(i=>t.tieFormatId===i.tieFormatId);return o||(n.tieFormat?n.tieFormat:n.tieFormats?.find(i=>t.tieFormatId===i.tieFormatId))}if(r.tieFormat)return r.tieFormat;if(r.tieFormatId){let o=e.tieFormats?.find(i=>r.tieFormatId===i.tieFormatId);if(o)return o}}}function We({drawDefinition:t,structure:e,matchUp:r,event:n}){return{tieFormat:Tp({item:r,drawDefinition:t,structure:e,event:n})||Tp({item:e,drawDefinition:t,structure:e,event:n})||ni(t)||ni(n)}}function Mb({matchUps:t}){let e=t.reduce((n,o)=>!o.collectionPosition||n.includes(o.collectionPosition)?n:n.concat(o.collectionPosition),[]).map(n=>({[n]:t.filter(o=>o.collectionPosition===n)}));return{collectionPositionMatchUps:Object.assign({},...e)}}function Ne({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 oi({mappedMatchUps:t,matchUpsMap:e,structureId:r,inContext:n}){t=e?.mappedMatchUps??t;let o=t[r],i=(o?.itemStructureIds||[]).map(s=>{let{matchUps:a,structureName:c}=t[s];return n?a.map(u=>Object.assign(J(u,!0,!0),{containerStructureId:r,structureId:s,structureName:c})):a}).flat();return(o?.matchUps||[]).concat(...i)}function tS({groupedOrder:t,roundPositionsCount:e}){if(!t||t?.length<=e)return t;let n=ye(t,t.length/e).map(i=>i.reduce((s,a)=>s+a)),o=n.slice().sort(me);return n.map(i=>o.indexOf(i)+1)}function Zf(t){if(!ht(t))return!1;let{matchUpId:e,drawPositions:r}=t,n=typeof e=="string",o=!r||Array.isArray(r)&&r.length<=2&&r.every(i=>It(i)||i===void 0||i===null);return n&&o}function Vr(t){return Array.isArray(t)?t.every(Zf):!1}function Ke({matchUps:t=[],interpolate:e}){if(!Vr(t))return{roundMatchUps:[],error:G};let r=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?pt(l.roundNumber):l.roundNumber;return!l.roundNumber||d.includes(f)?d:d.concat(f)},[]).sort(me).map(d=>{let l=t.filter(h=>h.roundNumber===d),g=l.find(({matchUpType:h})=>h===jt)?l.filter(({matchUpType:h})=>h===jt):l,I=h=>h.sort((S,T)=>me(S.roundPosition,T.roundPosition));return{[d]:I(g)}}),n=t.reduce((d,l)=>{let f=typeof l.roundNumber=="string"?pt(l.roundNumber):l.roundNumber;return d[f]||(d[f]=ot({abbreviatedRoundName:l.abbreviatedRoundName,finishingRound:l.finishingRound,roundName:l.roundName})),d},{}),o=Object.assign({},...r);if(e){let d=Math.max(...Object.keys(o).map(f=>pt(f)).filter(f=>!isNaN(f))),l=o[d]?.length;if(l>1&&vn(l)){let f=d+1,g=f+l/2;et(f,g).forEach((h,S)=>{o[h]=et(0,l/(2+S*2)).map(()=>({}))})}}let i=0,s=Object.assign({},...Object.keys(o).map(d=>{let l=o[d]?.length,f=o[d]?.filter(I=>!ce.includes(I.matchUpStatus)&&!I.score?.scoreStringSide1)?.length,g=l&&l===f;return i=Math.max(i,l),{[d]:{matchUpsCount:l,inactiveCount:f,inactiveRound:g}}})),a=0,c=0,u=Object.keys(o).map(d=>pt(d)).filter(d=>!isNaN(d));u.forEach(d=>{let l=o[d].sort((g,I)=>g.roundPosition-I.roundPosition),f=l.map(g=>g?.drawPositions||[]).flat();if(s[d].roundNumber=d,s[d].roundFactor=s[d].matchUpsCount?i/s[d].matchUpsCount:1,s[d].finishingRound=n[d]?.finishingRound,s[d].roundName=n[d]?.roundName,s[d].abbreviatedRoundName=n[d]?.abbreviatedRoundName,s[d].finishingPositionRange=o[d]?.[0]?.finishingPositionRange,d===1||!s[d-1]){let g=f.sort(me),I=ye(g,2);s[d].drawPositions=g,s[d].pairedDrawPositions=I}else{let g=s[d-1],I=g.drawPositions,h=g.matchUpsCount/s[d].matchUpsCount,S=ye(I,h),T=l.map(y=>{let{roundPosition:P}=y,U=[...y.drawPositions||[],void 0,void 0].slice(0,2);if(!P)return U;let E=U?.filter(Boolean)||[];if(!E?.length)return[void 0,void 0];if(d<3&&E?.length===2)return U?.slice().sort(me);let A=Yt(I,E).length!==E?.length;if(E?.length&&A)return E?.length===1?[E[0],void 0]:U?.slice().sort(me);let N=(P-1)*2;return S.slice(N,N+2).map(M=>E?.find(R=>M.includes(R)))});s[d].drawPositions=T?.flat(),s[d].pairedDrawPositions=T}s[d+1]&&s[d+1].matchUpsCount===s[d].matchUpsCount&&(s[d+1].feedRound=!0,s[d+1].feedRoundIndex=c,s[d].preFeedRound=!0,c+=1),s[d]&&!s[d].feedRound&&(s[d].roundIndex=a,a+=1)});let p=!!Object.values(s).find(({matchUpsCount:d})=>!vn(d));return{hasNoRoundPositions:t.some(d=>!d.roundPosition),roundsNotPowerOf2:p,maxMatchUpsCount:i,roundMatchUps:o,roundNumbers:u,roundProfile:s,...C}}function od(t){if(!Array.isArray(t))return"";let e=t.filter(Zt);return e.length?ut([Math.min(...e),Math.max(...e)]).join("-"):""}function Rb({drawDefinition:t,structureId:e,matchUpsMap:r}){if(!t)return{error:Z};if(!e)return{error:Er};let{structure:n}=at({drawDefinition:t,structureId:e});if(n?.stage!==qe)return{error:Oi,info:"Structure is not CONSOLATION stage"};let{links:o}=t,i=o?.filter(m=>m.target.structureId===e)||[],s=i?.reduce((m,d)=>{let{structureId:l}=d.source;return m.includes(l)?m:m.concat(l)},[])||[],a=Object.assign({},...s.map(m=>{let d=oi({structureId:m,matchUpsMap:r}),f=Ke({matchUps:d}).roundProfile;return{[m]:f}})),c=oi({matchUpsMap:r,structureId:e}),{roundProfile:u}=Ke({matchUps:c}),p={};return i?.forEach(m=>{let{structureId:d,roundNumber:l}=m.source,{feedProfile:f,groupedOrder:g,positionInterleave:I,roundNumber:h}=m.target,S=a[d],T=S[1]?.drawPositions,P=S[l]?.matchUpsCount;if(!P)return;let U=P?T.length/P:0,E=T.length/U,A=T.slice(),N=tS({roundPositionsCount:E,groupedOrder:g}),D=N?.length||1;if(D<=E){let v=T.length/D,O=ye(A,v);f===di&&O.forEach(x=>x.reverse()),A=N?.length&&N?.map(x=>O[x-1]).flat()||A}let M=ye(A,U);if(I){let v=et(0,I.interleave).map(()=>{}),O=et(0,I.offset).map(()=>{});M=M.map(F=>[F,...v]),M.unshift(O),M=M.flat(1);let x=M.length-I.offset;M=M.slice(0,x)}p[h]||(p[h]={});let b=u?.[h]?.feedRound?2:1;M.forEach((v,O)=>{let x=1+O*b;p[h][x]||(p[h][x]=od(v))})}),{sourceDrawPositionRanges:p}}function eS({drawDefinition:t}){if(typeof t!="object")return{error:ua};let e={},{structures:r=[],links:n=[]}=t||{},o=r.reduce((s,a)=>{let{stage:c}=a;return s[c]?s[c].push(a):s[c]=[a],s},{});for(let s of Object.keys(o)){let a=o[s].find(({stageSequence:p})=>p===1);if(!a)continue;let{structureId:c}=a;i({aggregator:{},targetRound:0,exitProfiles:e,exitProfile:"0",structureId:c,stage:s})}return{exitProfiles:e};function i({exitProfiles:s,exitProfile:a,structureId:c,targetRound:u,aggregator:p,stage:m}){s[c]||(s[c]=[]),a==="0"&&[qe,de].includes(m)||s[c].push(a);let d=n.filter(l=>l.source.structureId===c&&l.source.roundNumber>=u);for(let l of d){let f=l.source.roundNumber,g=l.target.roundNumber,I=l.target.structureId,h=r.find(T=>T.structureId===I).stage,S=[h,I,g,f].join("|");if(p[S])return;p[S]=!0,i({exitProfile:`${a}-${f}`,structureId:I,exitProfiles:s,targetRound:g,aggregator:p,stage:h})}}}function Cb({drawDefinition:t,roundProfile:e,structureId:r,matchUpsMap:n}){if(!t)return{error:Z};if(!r)return{error:Er};if(!e){let c=oi({matchUpsMap:n,structureId:r});if({roundProfile:e}=Ke({matchUps:c}),!e)return{error:st}}let i=(Math.min(...e?.[1]?.drawPositions??[])||1)-1,s=Object.keys(e);return{drawPositionsRanges:Object.assign({},...(s||[]).map(c=>{let u=e?.[c]?.matchUpsCount,p=e?.[1]?.drawPositions??[],m=ye(p,p.length/u),d=m.map(od),l=m.map(S=>S.map(T=>T-i)).map(od),f=s.map(S=>{if(S>c)return;let T=e?.[S]?.drawPositions??[];return ye(T,T.length/u)}).filter(Boolean),g=et(0,u).map(S=>f.map(T=>T[S]).flat().filter(Boolean).sort(me)).map(S=>ut(S)),I=g.map(S=>lC(S).map(od).join(", ")),h=Object.assign({},...et(0,u).map(S=>({[S+1]:{firstRoundDrawPositionsRange:d[S],firstRoundOffsetDrawPositionsRange:l[S],possibleDrawPositions:g[S],drawPositionsRange:I[S]}})));return{[c]:h}}))}}function id({roundsNotPowerOf2:t,drawDefinition:e,structure:r,matchUps:n}){if(!r)return!1;n=n??r.matchUps??[],t=t??Ke({matchUps:n}).roundsNotPowerOf2;let o=!!r.positionAssignments?.find(({drawPosition:i})=>i)||!!n?.find(({drawPositions:i})=>i?.length);return(!e?.drawType||e.drawType!==ki)&&!r?.structures&&t&&o}function cr({structure:t}){if(!t)return!1;let e=t.matchUps||t.roundMatchUps&&Object.values(t.roundMatchUps).flat(),r=!!e?.find(o=>o?.roundPosition),n=!!e?.find(o=>o?.drawPositions?.length);return!t?.structures&&t?.stage!==$e&&(!e.length||!r&&!n)}var tg={[fa]:{policyName:"Round Naming Default",namingConventions:{round:"Round",pre:"Pre"},qualifyingFinishMap:{1:"Final"},abbreviatedRoundNamingMap:{1:"F",2:"SF",4:"QF"},roundNamingMap:{1:"Final",2:"Semifinal",4:"Quarterfinal"},affixes:{roundNumber:"R",preFeedRound:"Q",preQualifying:"P"},stageConstants:{[nt]:"",[de]:"P",[ct]:"Q",[qe]:"C"}}},bb=tg;function vb({roundNamingPolicy:t,drawDefinition:e,structure:r,matchUps:n}){let{roundProfile:o,roundMatchUps:i}=Ke({matchUps:n}),{structureAbbreviation:s,stage:a}=r,c=cr({structure:r}),u=id({structure:r}),p=r.structures,m={},d=tg[fa],l=r.stage===ct,f=l?Math.max(...(e?.structures??[]).filter(b=>b.stage===ct).map(({stageSequence:b})=>b??1),0):0,g=(r.stageSequence??1)<f?r.stageSequence??1:"",I=g&&(t?.affixes?.preQualifying||d.affixes.preQualifying)||"",h=t?.roundNamingMap||d.roundNamingMap||{},S=t?.abbreviatedRoundNamingMap||d.abbreviatedRoundNamingMap||{},T=t?.affixes?.preFeedRound||d.affixes.preFeedRound,y=t?.affixes?.roundNumber||d.affixes.roundNumber,U=(t?.namingConventions||d.namingConventions).round,E=a&&a!==nt?a[0]:"",A=t?.stageConstants||d.stageConstants,N=a&&A?.[a]||E,D=`${I}${N}${g}`,M=o?Object.keys(o):[],R=l&&A?.[ct]?`${A?.[ct]}-`:"";if(p||c||u)Object.assign(m,...M.map(b=>{let v=`${R}${U} ${b}`,O=`${y}${b}`;return{[b]:{roundName:v,abbreviatedRoundName:O}}}));else{let b=l&&(t?.qualifyingFinishMap||d?.qualifyingFinishMap||{});Object.assign(m,...M.map(v=>{if(!o?.[v])return;let{matchUpsCount:O,preFeedRound:x}=o[v],F=O*2,L=b?.[o?.[v].finishingRound]||b&&`${y}${F}`||h[O]||`${y}${F}`,w=x?`-${T}`:"",V=`${L}${w}`,k=[D,s,V].filter(Boolean).join("-"),H=`${S[O]||`${y}${F}`}${w}`,K=[D,s,H].filter(Boolean).join("-");return{[v]:{abbreviatedRoundName:K,roundName:k}}}))}return{roundNamingProfile:m,roundProfile:o,roundMatchUps:i}}var sk=(t,e)=>(t||0)+(e||0);function rS(t,e){let r=Array.isArray(t)?t[0]:t;return isNaN(r)&&Jh||r<=e[cc]&&cc||r<=e[ac]&&ac||Zm}function nS({score:t}){let e=t?.sets||[],r=e.reduce((o,i)=>(o[0]+=i.side1Score||0,o[1]+=i.side2Score||0,o),[0,0]),n=e.reduce((o,i)=>(o[0]+=i.side1TiebreakScore||0,o[1]+=i.side2TiebreakScore||0,o),[0,0]);return n.reduce(sk)&&(r[n[0]>n[1]?0:1]+=1),{sets:e,games:r,score:t}}function ak(t){let e=Math.min(...t.games),r=Math.max(...t.games);return Math.round(e/r*100)}function oS(t){return t.map(ak).sort().map(e=>parseFloat(e.toFixed(2)))}function gu({tournamentRecord:t,profileBands:e,matchUp:r}){if(!r)return{error:hr};let{score:n,winningSide:o}=r;if(!o)return{error:G};let i=!e&&t&&ei({policyType:hi,tournamentRecord:t}).policy,s=e||i?.profileBands||ed[hi].profileBands,a=nS({score:n}),c=oS([a]),u=rS(c,s),p=Array.isArray(c)?c[0]:c;return{...C,competitiveness:u,pctSpread:p}}function iS({matchUp:t}){if(!t)return{error:hr};if(t&&!t.sides)return{error:dr};if(t&&!t.hasContext)return{error:Gc};let e=(t.sides??[])?.map(a=>a?.participantId).filter(Boolean),r=t.sides?.filter(a=>a.participant?.participantType===Tt).map(a=>a.participantId).filter(Boolean)??[],o=((t.sides??[])?.map(a=>a.participant?.individualParticipants).filter(Boolean)??[]).map(a=>(a??[]).map(c=>c?.participantId).filter(Boolean)),i=[...r,...o.flat()].filter(Boolean)??[],s=ut(i.concat(e)).filter(Boolean)??[];return{nestedIndividualParticipantIds:o,allRelevantParticipantIds:s,individualParticipantIds:i,sideParticipantIds:e,...C}}var sd="CHECK_IN",ad="CHECK_OUT",ck="SCHEDULE",Hi="SCHEDULE.ASSIGNMENT.VENUE",so="SCHEDULE.ALLOCATION.COURTS",Bo="SCHEDULE.ASSIGNMENT.COURT",yp="SCHEDULE.COURT.ORDER",Wi="SCHEDULE.DATE",uk="COMPLETED.DATE",cd="HOME_PARTICIPANT_ID",eg="SCHEDULE.ASSIGN.OFFICIAL",ji="SCHEDULE.TIME.SCHEDULED",Oo="SCHEDULE.TIME.START",Yi="SCHEDULE.TIME.STOP",Pi="SCHEDULE.TIME.RESUME",Di="SCHEDULE.TIME.END",Ap="SCHEDULE.TIME.MODIFIERS",Ob="TO_BE_ANNOUNCED",_b="NEXT_AVAILABLE",xb="FOLLOWED_BY",wb="AFTER_REST",Lb="RAIN_DELAY",pk="NOT_BEFORE",sS=[Ob,_b,xb,wb,Lb],mk="ELIGIBILITY",dk="REGISTRATION",lk="SUSPENSION",fk="MEDICAL",gk="PENALTY",BU="SCALE",HU="RATING",WU="RANKING",rg="SEEDING",_o="PUBLISH",Nr="PUBLIC",xo="STATUS",Ik="MODIFICATION",hk="RETRIEVAL",Sk="other",Fb={MUTUALLY_EXCLUSIVE_TIME_MODIFIERS:sS,AFTER_REST:wb,ALLOCATE_COURTS:so,ASSIGN_COURT:Bo,ASSIGN_OFFICIAL:eg,ASSIGN_VENUE:Hi,CHECK_IN:sd,CHECK_OUT:ad,COMPLETED_DATE:uk,COURT_ORDER:yp,ELIGIBILITY:mk,END_TIME:Di,FOLLOWED_BY:xb,MEDICAL:fk,MODIFICATION:Ik,NEXT_AVAILABLE:_b,NOT_BEFORE:pk,OTHER:Sk,PENALTY:gk,PUBLIC:Nr,PUBLISH:_o,RANKING:WU,RATING:HU,RAIN_DELAY:Lb,REGISTRATION:dk,RESUME_TIME:Pi,RETRIEVAL:hk,SCALE:BU,SCHEDULE:ck,SCHEDULED_DATE:Wi,SCHEDULED_TIME:ji,SEEDING:rg,START_TIME:Oo,STATUS:xo,STOP_TIME:Yi,SUSPENSION:lk,TIME_MODIFIERS:Ap,TO_BE_ANNOUNCED:Ob};function us({matchUp:t}){if(!t)return{error:hr};if(!t.hasContext)return{error:Gc};if(!t.sides||t.sides.filter(Boolean).length!==2)return{error:dr};let{nestedIndividualParticipantIds:e,allRelevantParticipantIds:r,sideParticipantIds:n}=iS({matchUp:t}),i=(t.timeItems??[]).filter(u=>u?.itemType&&[sd,ad].includes(u.itemType)).sort((u,p)=>(u.createdAt?new Date(u.createdAt).getTime():0)-(p.createdAt?new Date(p.createdAt).getTime():0)),a=i.map(u=>u.itemValue).filter(u=>i.filter(p=>p?.itemValue===u).reverse()[0].itemType===sd);e?.forEach((u,p)=>{let m=n?.[p],d=u?.length&&u.every(l=>a.includes(l));m&&d&&!a.includes(m)&&a.push(m)}),n?.forEach((u,p)=>{a.includes(u)&&(e?.[p]??[]).forEach(m=>{m&&!a.includes(m)&&a.push(m)})});let c=n?.reduce((u,p)=>a.includes(p)&&u,!0);return{allRelevantParticipantIds:r,allParticipantsCheckedIn:c,checkedInParticipantIds:a,...C}}var ue=t=>e=>{let r=ht(e)&&e?.matchUpType||Vt(e)&&e;return r&&EI[t].includes(r)};function Ep(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 Up(t){let{matchUpRecoveryTimes:e,averageMinutes:r,matchUpFormat:n}=t||{};return e?.find(({matchUpFormatCodes:o,averageTimes:i,recoveryTimes:s})=>{if(i&&r){let{greaterThan:a=0,lessThan:c=360}=i;if(r>a&&r<c)return!0}return o?.find(a=>a===n)&&s})?.recoveryTimes}function aS({timesBlockArray:t,categoryName:e,categoryType:r}){return t.filter(n=>Array.isArray(n)).map(n=>n.sort((o,i)=>(i.categoryNames?.length||0)-(o.categoryNames?.length||0)).find(({categoryTypes:o,categoryNames:i})=>!i?.length&&!o?.length||i?.includes(e)||o?.includes(r))).find(Boolean)}function kb({tournamentScheduling:t,eventScheduling:e,averageMinutes:r,defaultTiming:n,matchUpFormat:o,categoryName:i,categoryType:s,policy:a}){let c=e?.matchUpRecoveryTimes&&Up({...e,averageMinutes:r,matchUpFormat:o}),u=t?.matchUpRecoveryTimes&&Up({...t,averageMinutes:r,matchUpFormat:o}),p=a?.matchUpRecoveryTimes&&Up({...a,averageMinutes:r,matchUpFormat:o}),m=[c,u,p,a?.defaultTimes?.recoveryTimes,n?.recoveryTimes];return aS({categoryName:i,categoryType:s,timesBlockArray:m})}function Gb({matchUpFormat:t,categoryName:e,categoryType:r,defaultTiming:n,tournamentScheduling:o,eventScheduling:i,policy:s}){let a=i?.matchUpAverageTimes&&Ep({...i,matchUpFormat:t}),c=o?.matchUpAverageTimes&&Ep({...o,matchUpFormat:t}),u=s?.matchUpAverageTimes&&Ep({...s,matchUpFormat:t}),p=[a,c,u,s?.defaultTimes?.averageTimes,n?.averageTimes];return aS({categoryName:e,categoryType:r,timesBlockArray:p})}var jU="DOUBLES_SINGLES",YU="SINGLES_DOUBLES",ao="total",cS="participantConflict",Aa="matchUpConflict",qU="ISSUE_IDS",uc="CONFLICT",pc="WARNING",uS="ERROR",pS="ISSUE",ng="STATE",Vb={SINGLES_DOUBLES:YU,DOUBLES_SINGLES:jU,TOTAL:ao,CONFLICT_MATCHUP_ORDER:Aa,CONFLICT_PARTICIPANTS:cS,SCHEDULE_ISSUE_IDS:qU,SCHEDULE_CONFLICT:uc,SCHEDULE_WARNING:pc,SCHEDULE_ERROR:uS,SCHEDULE_ISSUE:pS,SCHEDULE_STATE:ng};function Iu({defaultAverageMinutes:t=90,defaultRecoveryMinutes:e=0,tournamentRecord:r,matchUpFormat:n,categoryName:o,categoryType:i,eventType:s,event:a}){if(!r)return{error:Y};s=s??a?.eventType??Fs;let c={averageTimes:[{minutes:{default:t}}],recoveryTimes:[{minutes:{default:e}}]},{scheduleTiming:u}=ya({tournamentRecord:r,categoryName:o,categoryType:i,event:a}),p={...u,matchUpFormat:n,categoryType:i,defaultTiming:c};return Pp({eventType:s,timingDetails:p})}function Pp({timingDetails:t,eventType:e}){let r=Gb(t),n=Object.keys(r?.minutes||{}),o=r?.minutes&&(n?.includes(e)&&r.minutes[e]||r.minutes.default),i=kb({...t,averageMinutes:o}),s=Object.keys(i?.minutes||{}),a=i?.minutes&&(s?.includes(e)&&i.minutes[e]||i.minutes.default),c=ue(Fs)(e)?YU:jU,u=i?.minutes&&(s?.includes(c)&&i.minutes[c]||a);return{averageMinutes:o,recoveryMinutes:a,typeChangeRecoveryMinutes:u}}function $U(t){return t.createdAt?new Date(t.createdAt).getTime():0}function Ho({timeItems:t,itemType:e}){let r=t.filter(o=>o&&o.itemType===e).sort((o,i)=>$U(o)-$U(i)).pop(),n=r&&$U(r);return{itemValue:r?.itemValue,timeStamp:n}}function mS({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Ho({timeItems:r?.timeItems||[],itemType:ji});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{scheduledTime:n}:e}function Hs({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Ho({timeItems:r?.timeItems||[],itemType:Wi});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{scheduledDate:n}:e}function Dp(t){if($I.test(t)){let e=If();return new Date(`${e}T${t}`)}else return new Date(t)}function Bb({matchUp:t}){if(!t)return{error:hr};if(!t.timeItems)return{error:tf};let e=t.timeItems.filter(n=>[Oo,Yi,Pi,Di].includes(n?.itemType)).sort((n,o)=>Dp(n.itemValue).getTime()-Dp(o.itemValue).getTime()),r=e.reduce((n,o)=>{let i,s=o?.itemType?.split("."),c=`SCHEDULE.TIME.${o?.itemType?.startsWith("SCHEDULE.TIME")&&s[2]}`;switch(c){case Oo:i=0;break;case Di:if(n.lastValue&&[Oo,Pi].includes(n.lastType)){let u=Dp(o.itemValue).getTime()-Dp(n.lastValue).getTime();i=n.milliseconds+u}else i=n.milliseconds;break;case Yi:if([Oo,"SCHECULE.TIME.RESUME"].includes(n.lastType)){let u=Dp(o.itemValue).getTime()-Dp(n.lastValue).getTime();i=n.milliseconds+u}else i=n.milliseconds;break;default:i=n.milliseconds;break}return{milliseconds:i,lastType:c,lastValue:o.itemValue}},{milliseconds:0,lastType:void 0,lastValue:void 0});if([Oo,Pi].includes(r.lastType)){let n=new Date().getTime()-Dp(r.lastValue).getTime();r.milliseconds+=n}return{milliseconds:r.milliseconds,time:Tk(r.milliseconds),relevantTimeItems:e}}function Tk(t){let e=(r,n=2)=>("00"+r).slice(-n);return e(t/36e5|0)+":"+e(t%36e5/6e4|0)+":"+e(t%6e4/1e3|0)}function Hb({matchUp:t}){let e=t?.timeItems||[],r=i=>i.createdAt?new Date(i.createdAt).getTime():0;return{startTime:e.reduce((i,s)=>{let a=s.itemType===Oo&&s;return a&&(!i||r(a)<r(i))?a:i},void 0)?.itemValue}}function mc(t){let{disableNotice:e,venue:r,context:n}=t;if(typeof r!="object")return{error:G};let o=Dr(t);r.venueId||(r.venueId=Dt());let i;for(let s of Object.values(o)){let a=yk({disableNotice:!0,tournamentRecord:s,context:n,venue:r});if(a?.error)return a;i=a.venue}return e||mt({topic:Hh,payload:{venue:r}}),ot({...C,venue:i})}function yk({tournamentRecord:t,disableNotice:e,context:r,venue:n}){return t?n?(t.venues||(t.venues=[]),n.venueId||(n.venueId=Dt()),t.venues.reduce((i,s)=>i||s.venueId===n.venueId,void 0)?{error:SE}:(r&&At({element:n,extension:{value:r,name:SU}}),t.venues.push(n),e||mt({payload:{venue:n,tournamentId:t.tournamentId},topic:Hh}),{...C,venue:J(n)})):{error:st,info:"missing venue"}:{error:Y}}function Wo({tournamentRecords:t,tournamentRecord:e,venueId:r}){if(!e)return{error:Y};if(!r)return{error:Xo};let o=(e.venues??[]).reduce((i,s)=>s.venueId===r?s:i,void 0);if(!o&&t){let s=(iu({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let a of s){let c=t[a],u=Wo({tournamentRecord:c,venueId:r});if(u.success&&u.venue)return mc({tournamentRecord:e,venue:u.venue}),{...C,venue:o}}}return o?{...C,venue:o}:{error:Li}}function dS({convertExtensions:t,...e}){let{tournamentRecords:r,tournamentRecord:n,venueId:o}=e,i=Wo({tournamentRecords:r,tournamentRecord:n,venueId:o});return J(i,t,!0)}function ps({tournamentRecords:t,tournamentRecord:e,courtId:r}){if(!e)return{error:Y};if(!r)return{error:_i};let n="findCourt",o,i;if((e.venues??[]).forEach(s=>{(s.courts??[]).forEach(a=>{a.courtId===r&&(o=a,i=s)})}),o)return{...C,court:o,venue:i};if(t){let a=(iu({tournamentRecords:t}).linkedTournamentIds??[])[e.tournamentId];for(let c of a){let u=t[c],p=ps({tournamentRecord:u,courtId:r});if(p.success)return p.venue&&mc({tournamentRecord:e,venue:p.venue}),{...C,court:o,venue:i}}}return _({result:{error:Os},stack:n})}function lS(t){return J(ps(t),!1,!0)}function ud({tournamentRecord:t,internalUse:e,courtId:r}){if(!t)return{error:Y};if(!r)return{error:_i};let n=ps({tournamentRecord:t,courtId:r});if(n.error)return n;let o=n.court&&(({altitude:i,courtId:s,courtName:a,courtDimensions:c,latitude:u,longitude:p,surfaceCategory:m,surfaceType:d,surfacedDate:l,pace:f,notes:g})=>({altitude:i,courtId:s,courtName:a,courtDimensions:c,latitude:u,longitude:p,surfaceCategory:m,surfaceType:d,surfacedDate:l,pace:f,notes:g}))(n.court);return{...C,courtInfo:J(o,!1,e)}}function dc(t){let e=rt(t,[{[ie]:!0},{venueId:!0,[fn]:Xo}]);if(e.error)return e;let{tournamentRecord:r,venueId:n}=t,o=Wo({tournamentRecord:r,venueId:n});if(o.error)return o;let s=(o.venue?.courts??[]).map(u=>(({courtInfo:p})=>({...p}))(ud({courtId:u.courtId,internalUse:!0,tournamentRecord:r}))),a=o.venue&&(({venueId:u,venueName:p,venueAbbreviation:m})=>({venueAbbreviation:m,venueName:p,venueId:u}))(o.venue),c=a&&{...a,courtsInfo:s};return{...C,venueData:J(c,!1,!0)}}function Wb({matchUp:t}){let e=t?.timeItems||[],r=i=>i.createdAt?new Date(i.createdAt).getTime():0;return{endTime:e.reduce((i,s)=>{let a=s.itemType===Di&&s;return a&&(!i||r(a)>r(i))?a:i},void 0)?.itemValue}}function Ht({event:t,eventId:e}){if(!t)return{error:vt};let n=dt({name:un,element:t})?.extension,o=e?J(n?.value,!1,!0):n?.value;return e&&t.drawDefinitions?.forEach(i=>{o?.flights?.forEach(s=>{s.drawId===i.drawId&&Object.assign(s,{drawDefinition:i})})}),{flightProfile:o}}function ze(t){let{tournamentRecord:e,eventId:r,drawId:n}=t,o="findEvent",i={},s=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},a=Object.values(s).map(({events:u,tournamentId:p})=>(u&&u.forEach(m=>{i[m.eventId]={tournamentId:p}}),u??[])).flat(),c;if(n){let u,p=a.find(m=>{let l=(m?.drawDefinitions??[]).find(f=>f.drawId===n);if(l)u=l,c=i[m.eventId].tournamentId;else{let g=(m&&Ht({event:m})?.flightProfile)?.flights?.find(I=>I.drawId===n);if(g)return c=i[m.eventId].tournamentId,{entries:g.drawEntries,drawName:g.drawName,tournamentId:c,drawId:n}}return l});if(p)return{event:p,drawDefinition:u,tournamentId:c}}if(r){let u=a.find(p=>p?.eventId===r);if(u)c=i[u.eventId].tournamentId;else return{event:void 0,drawDefinition:void 0,..._({result:{error:jr},stack:o})};return{event:u,drawDefinition:void 0,tournamentId:c}}return{event:void 0,drawDefinition:void 0,..._({result:{error:Mr},context:{drawId:n,eventId:r},stack:o})}}function pd(t){let e=t.event,r=t.matchUpType,{scheduleVisibilityFilters:n,afterRecoveryTimes:o,tournamentRecord:i,usePublishState:s,scheduleTiming:a,matchUpFormat:c,publishStatus:u,matchUp:p}=t;if(!p)return{error:hr};if(o&&!p.matchUpType&&!t.matchUpType&&(e||i)&&p.drawId){let U=t.drawDefinition||e?.drawDefinitions?.find(A=>A.drawId===p.drawId);!U&&i&&({drawDefinition:U,event:e}=ze({drawId:p.drawId,tournamentRecord:i}));let E=p.structureId&&U?.structures?.find(({structureId:A})=>A===p.structureId);r=t.matchUpType||E?.matchUpType||U?.matchUpType||e?.eventType!==_e&&e?.eventType}let{milliseconds:m,time:d}=Bb({matchUp:p}),{startTime:l}=Hb({matchUp:p}),{endTime:f}=Wb({matchUp:p}),g,{eventIds:I,drawIds:h}=n??{};if((!I||I.includes(p.eventId))&&(!h||h.includes(p.drawId))){let U=X=>X.createdAt?new Date(X.createdAt).getTime():0,E=new Map,A=p.timeItems?.toSorted((X,lt)=>U(X)-U(lt))??[];for(let X of A)E.set(X.itemType,X.itemValue);let N=E.get(cd),D=E.get(so),M=E.get(ji),R=E.get(Ap),b=E.get(Wi),v=E.get(eg),O=E.get(yp),x=E.get(Hi),F=E.get(Bo),L,w,V,k,W,H=p.matchUpType??r;if(a&&M&&o&&H){let X={matchUpFormat:p.matchUpFormat??c,...a};({averageMinutes:w=0,recoveryMinutes:V=0,typeChangeRecoveryMinutes:k=0}=Pp({timingDetails:X,eventType:H})),(w||V)&&(L=f?Yr(Kt(f),V):Yr(M,w+V)),k&&(W=f?Yr(Kt(f),k):Yr(M,w+k))}!b&&M&&(b=Et(M));let K=bm({scheduledDate:b,scheduledTime:M}),q={},B=(i&&x&&dc({tournamentRecord:i,venueId:x}))?.venueData||{};x&&(q[x]=B);let{venueName:$,venueAbbreviation:z,courtsInfo:j}=B,Q=(F&&j?.find(X=>X.courtId===F))?.courtName;for(let X of D||[]){if(!i)break;X.venueId&&!q[X.venueid]&&(q[X.venueId]=dc({venueId:X.venueId,tournamentRecord:i})?.venueData);let lt=q[X.venueId];X.venueName=lt?.venueName;let it=lt?.courtsInfo?.find(Rt=>Rt.courtId===X.courtId);X.courtName=it?.courtName}g=ot({typeChangeTimeAfterRecovery:W,timeAfterRecovery:L,scheduledDate:b,scheduledTime:M,isoDateString:K,homeParticipantId:N,venueAbbreviation:z,allocatedCourts:D,timeModifiers:R,venueName:$,venueId:x,courtOrder:O,courtName:Q,courtId:F,official:v,typeChangeRecoveryMinutes:k,recoveryMinutes:V,averageMinutes:w,milliseconds:m,startTime:l,endTime:f,time:d})}else g=ot({milliseconds:m,startTime:l,endTime:f,time:d});let{scheduledDate:S}=Hs({matchUp:p}),{scheduledTime:T}=mS({matchUp:p});if(s&&u?.displaySettings?.draws){let U=u.displaySettings.draws,E=(U?.[p.drawId]??U?.default)?.scheduleDetails;if(E){let A=(E.find(N=>S&&N.dates?.includes(S))??E.find(N=>!N.dates?.length))?.attributes;if(A){let N=Object.assign({},...Object.keys(g).map(D=>({[D]:!0})),A);g=Vi({source:g,template:N})}}}let P=p.matchUpStatus&&ce.includes(p.matchUpStatus)&&(Et(f)||Et(S)||Et(T))||void 0;return{schedule:g,endDate:P}}function jb({drawPositions:t,roundProfile:e,roundNumber:r}){let n=[void 0,void 0];if(NI(t))return{orderedDrawPositions:n,displayOrder:n};let o=e?.[r],s=o?.pairedDrawPositions?.find(c=>Fe(c||[],t.filter(Boolean)))??n,a=o?.feedRound;if(DI(t)){let c=[...t].sort(me);return{orderedDrawPositions:c.length===2?c:s,displayOrder:a?c:s}}if(a){let u=[t.find(p=>!isNaN(pt(p))),void 0];return{orderedDrawPositions:u,displayOrder:u}}return{orderedDrawPositions:s,displayOrder:s}}function Np({collectionPosition:t,collectionId:e,lineUp:r}){let n=[],o=[];if(r){let i=a=>a===void 0?-1:a,s=r.map(a=>{let{collectionAssignments:c,participantId:u}=a,p=c?.find(m=>m.collectionPosition===t&&m.collectionId===e);return p&&{participantId:u,...p}}).filter(Boolean).sort((a,c)=>i(a.substitutionOrder)-i(c.substitutionOrder));for(let a of s){let{participantId:c,previousParticipantId:u,substitutionOrder:p}=a;n.includes(c)||(u&&o.push({previousParticipantId:u,substitutionOrder:p,participantId:c}),n=n.filter(m=>m!==u),n.push(c))}}return{assignedParticipantIds:n,substitutions:o}}function In({tournamentParticipants:t,tournamentRecord:e,participantIds:r}){let n="getPairedParticipant";if(!t&&!e)return{error:Y};if(!Array.isArray(r)||r.length>2)return{error:wr};if(!r.length)return _({result:{error:Uo},stack:n});t=t??e?.participants??[];let o=t.filter(a=>a.participantType===ft&&Yt(r,a.individualParticipantIds).length===r.length&&a.individualParticipantIds.length===r.length),i=o[0];if(!i)return _({result:{error:te},stack:n});let s=J(o.slice(1),!1,!0);return{participant:J(i),duplicatedPairParticipants:s,...C}}function ms({drawDefinition:t,participantId:e}){if(typeof t!="object")return{error:Z};if(typeof e!="string")return{error:oe};let{extension:r}=dt({element:t,name:Ro});return{lineUp:(r?.value||{})[e]}}function Yb({tournamentParticipants:t,positionAssignments:e,collectionPosition:r,drawPositions:n=[],participantMap:o,drawDefinition:i,collectionId:s,sideLineUps:a,matchUpType:c}){if(!s||!r)return{};let u=({attribute:m,lineUp:d,teamParticipant:l})=>{let{assignedParticipantIds:f,substitutions:g}=Np({collectionPosition:r,collectionId:s,lineUp:d});if(c===_t){if(f?.length<=2){let I=o?.[f[0]]?.pairIdMap?.[f[1]],T=(I&&o[I]?.participant||In({participantIds:f,tournamentParticipants:t}).participant)?.participantId;return{[m]:{participantId:T,teamParticipant:l,substitutions:g}}}else if(f?.length>2)return{[m]:{teamParticipant:l,substitutions:g}}}else{let I=f?.[0];return I&&{[m]:{participantId:I,teamParticipant:l,substitutions:g}}}};if(!n?.length){let m=a?.map(d=>{let{teamParticipant:l,sideNumber:f}=d,g=d.lineUp||ms({participantId:l.teamParticipantId,drawDefinition:i})?.lineUp;return u({attribute:f,lineUp:g,teamParticipant:l})}).filter(Boolean)||{};return{sideNumberCollectionAssignment:Object.assign({},...m)}}let p=n?.map(m=>{let d=e.find(I=>I.drawPosition===m)?.participantId,l=a?.find(I=>I?.drawPosition===m),f=l?.teamParticipant||d&&o?.[d]?.participant||t?.find(({participantId:I})=>I===d),g=l?.lineUp||ms({participantId:d,drawDefinition:i})?.lineUp;return u({attribute:m,lineUp:g,teamParticipant:f})}).filter(Boolean)||{};return{drawPositionCollectionAssignment:Object.assign({},...p)}}function md(t){let e=rt(t,[{[_n]:!0}]);if(e.error)return e;let r=t?.matchUp,n=r?.matchUpType;if(!n&&r?.sides?.length){let s=r.sides.find(({participant:a})=>a)?.participant?.participantType;n=s===Tt&&xt||s===ft&&_t||s===Lt&&Lt||void 0}return{matchUpType:n}}function qb({drawPositionCollectionAssignment:t,sideNumberCollectionAssignment:e,positionAssignments:r,displaySideNumber:n,seedAssignments:o,drawPosition:i,isFeedRound:s,sideNumber:a}){let c=r.find(l=>l.drawPosition&&l.drawPosition===i),u=i&&t,p=a&&e,m=u?u[i]?.participantId:c?.participantId,d=c?Ak({displaySideNumber:n,seedAssignments:o,participantId:m,assignment:c,sideNumber:a}):{...p?.[a]};if(s&&(a===1?Object.assign(d,{participantFed:!0}):Object.assign(d,{participantAdvanced:!0})),i&&u){let l=u[i]?.teamParticipant,f=u[i]?.participant,g=u[i]?.substitutions;f&&(d.participant=f),g&&(d.substitutions=g),l&&(d.teamParticipant=l)}return d}function Ak({displaySideNumber:t,seedAssignments:e,participantId:r,assignment:n,sideNumber:o}){let i={drawPosition:n.drawPosition,displaySideNumber:t,sideNumber:o};if(r){let s=Ek({seedAssignments:e,participantId:r});Object.assign(i,s,{participantId:r}),s?.seedNumber&&s?.seedValue===""&&(i.seedValue="~")}else n.bye&&Object.assign(i,{bye:!0});return n.qualifier&&Object.assign(i,{qualifier:!0}),i}function Ek({seedAssignments:t,participantId:e}){return t?.find(r=>!r.seedProxy&&r.participantId===e)}function KU({scheduleVisibilityFilters:t,sourceDrawPositionRanges:e,tournamentParticipants:r,positionAssignments:n,drawPositionsRanges:o,hydrateParticipants:i,afterRecoveryTimes:s,initialRoundOfPlay:a,additionalContext:c,roundNamingProfile:u,tournamentRecord:p,tieDrawPositions:m,appliedPolicies:d,isCollectionBye:l,seedAssignments:f,usePublishState:g,participantMap:I,contextContent:h,scheduleTiming:S,contextProfile:T,drawDefinition:y,publishStatus:P,scoringActive:U,matchUpTieId:E,isRoundRobin:A,roundProfile:N,sideLineUps:D,structure:M,context:R,matchUp:b,event:v}){c=c??{};let O=We({drawDefinition:y,structure:M,matchUp:b,event:v})?.tieFormat,{roundOffset:x,structureId:F,structureName:L,stage:w,stageSequence:V}=M,{drawId:k,drawName:W,drawType:H}=y??{},K=O?.collectionDefinitions,q=b.collectionId&&K?.find(Pe=>Pe.collectionId===b.collectionId),B=b.collectionId?q?.matchUpFormat:b.matchUpFormat??M?.matchUpFormat??y?.matchUpFormat??v?.matchUpFormat,$=b.matchUpType||q?.matchUpType||M?.matchUpType||y?.matchUpType||!ue(_e)(v?.eventType)&&v?.eventType,z=l?Nt:b.matchUpStatus,{schedule:j,endDate:tt}=pd({scheduleVisibilityFilters:t,afterRecoveryTimes:s,tournamentRecord:p,usePublishState:g,scheduleTiming:S,drawDefinition:y,matchUpFormat:B,publishStatus:P,matchUpType:$,matchUp:b,event:v}),Q=m??b.drawPositions??[],{collectionPosition:X,collectionId:lt,roundPosition:it}=b,Rt=b.roundNumber??c.roundNumber,Ft=lt?Yb({tournamentParticipants:r,positionAssignments:n,collectionPosition:X,participantMap:I,drawDefinition:y,drawPositions:Q,collectionId:lt,sideLineUps:D,matchUpType:$}):void 0,Ue=u?.[Rt]?.roundName||c.roundName,fe=u?.[Rt]?.abbreviatedRoundName||c.abbreviatedRoundName,Me=N?.[Rt]?.feedRound,vr=N?.[Rt]?.preFeedRound,Zr=N?.[Rt]?.roundFactor,lr=o?.[Rt],Xe=it?lr?.[it]:void 0,ee=e?.[Rt],Pt=q?.category?{...R?.category||{},...q.category}:R?.category??v?.category,ae=b.processCodes?.length&&b.processCodes||q?.processCodes?.length&&q?.processCodes||M?.processCodes?.length&&M?.processCodes||y?.processCodes?.length&&y?.processCodes||v?.processCodes?.length&&v?.processCodes||p?.processCodes,re=T?.withCompetitiveness&&gu({...h,matchUp:b}),pr=b.finishingPositionRange??c.finishingPositionRange,Jt=Pe=>ot(Pe,void 0,!0),Wt={...Jt(R),...Jt({matchUpFormat:b.matchUpType===_e?void 0:B,tieFormat:b.matchUpType!==_e?void 0:O,gender:q?.gender??v?.gender,roundOfPlay:w!==ct&&It(a)&&a+(Rt||0),endDate:b.endDate??tt,discipline:v?.discipline,category:Pt,finishingPositionRange:pr,abbreviatedRoundName:fe,drawPositionsRange:Xe,competitiveProfile:re,structureName:L,stageSequence:V,drawPositions:Q,matchUpStatus:z,processCodes:ae,isRoundRobin:A,matchUpTieId:E,preFeedRound:vr,matchUpType:$,roundFactor:Zr,roundOffset:x,structureId:F,roundNumber:Rt,feedRound:Me,roundName:Ue,drawName:W,drawType:H,schedule:j,drawId:k,stage:w}),...J(Jt(b),!0,!0)};if(B&&b.score?.scoreStringSide1){let Pe=Ye(B),{bestOf:Or,finalSetFormat:Je,setFormat:De}=Pe??{};(Je?.tiebreakSet||De?.tiebreakSet||De?.timed)&&(Wt.score.sets=Wt.score.sets.sort((Ee,ge)=>Ee.setNumber-ge.setNumber).map((Ee,ge)=>(ge+1===Or?(Je?.tiebreakSet||Je?.timed)&&(Ee.tiebreakSet=!0):(De?.tiebreakSet||De?.timed)&&(Ee.tiebreakSet=!0),Ee)))}if(Array.isArray(Q)){let{orderedDrawPositions:Pe,displayOrder:Or}=jb({drawPositions:Q,roundProfile:N,roundNumber:Rt}),Je=N?.[Rt]?.feedRound,De=Or[0]!==Pe[0],ge=Pe.concat(void 0,void 0).slice(0,2).map((_r,fr)=>{let uo=fr+1,be=De?3-uo:uo,Ar=qb({...Ft,positionAssignments:n,displaySideNumber:be,seedAssignments:f,drawPosition:_r,isFeedRound:Je,sideNumber:uo}),Zi=b.sides?.find(ju=>ju.sideNumber===uo),Tn=it?(it-1)*2+fr+1:void 0,ts=Tn?ee?.[Tn]:void 0;return Jt({sourceDrawPositionRange:ts,...Zi,...Ar})});Object.assign(Wt,J({sides:ge},!0,!0))}if(r&&Wt.sides&&i!==!1){let Pe=d?.[Vs],Or=De=>{let Ee=I?.[De]?.participant;return Ee&&Vi({template:Pe?.participant,source:Ee})};if(Wt.sides.filter(Boolean).forEach(De=>{if(De.participantId){let Ee=J(Or(De.participantId)||(r?Go({policyDefinitions:d,participantId:De.participantId,tournamentParticipants:r,internalUse:!0,contextProfile:T}):void 0),void 0,!0);if(Ee){if(y?.entries){let ge=y.entries.find(fr=>fr.participantId===De.participantId),_r=v?.entries?.find(fr=>fr.participantId===De.participantId);Ee.entryStatus=ge?.entryStatus||_r?.entryStatus,ge?.entryStage&&(Ee.entryStage=ge.entryStage)}Object.assign(De,{participant:Ee})}}if(De?.participant?.individualParticipantIds?.length&&!De.participant.individualParticipants?.length){let Ee=De.participant.individualParticipantIds.map(ge=>Or(ge)||(r?Go({policyDefinitions:d,tournamentParticipants:r,internalUse:!0,contextProfile:T,participantId:ge}):void 0));Object.assign(De.participant,{individualParticipants:Ee})}}),!Wt.matchUpType){let{matchUpType:De}=md({matchUp:Wt});De&&Object.assign(Wt,{matchUpType:De})}if(T?.inferGender&&(!Wt.gender||Wt.gender===Tr)&&Wt.sides?.length===2&&Wt.matchUpType!==_e){let De=Wt.sides.map(Ee=>{if(ue(xt)(Wt.matchUpType))return Ee.participant?.person?.sex;if(Ee.participant?.individualParticipants?.length===2){let ge=ut(Ee.participant.individualParticipants.map(_r=>_r.person?.sex)).filter(Boolean);if(ge.length===1)return ge[0]}});if(De.filter(Boolean).length===2&&ut(De).length===1){let Ee=De[0];Wt.inferredGender=Ee}}}if(Wt.tieMatchUps){let Pe=Wt.matchUpStatus===Nt,Or=Wt.sides?.map(({participant:Je,drawPosition:De,sideNumber:Ee,lineUp:ge})=>{let _r=Je?.participantType===_e&&Je;return{teamParticipant:_r&&ot({participantRoleResponsibilities:_r.participantRoleResponsibilities,participantOtherName:_r.participanOthertName,participantName:_r.participantName,participantId:_r.participantId,teamId:_r.teamId}),drawPosition:De,sideNumber:Ee,lineUp:ge}});Wt.tieMatchUps=Wt.tieMatchUps.map(Je=>{let De=Wt.matchUpId,ge={finishingPositionRange:Wt.finishingPositionRange,abbreviatedRoundName:fe,roundNumber:Rt,roundName:Ue};return KU({tieDrawPositions:Q,scheduleVisibilityFilters:t,sourceDrawPositionRanges:e,sideLineUps:Or,drawPositionsRanges:o,initialRoundOfPlay:a,roundNamingProfile:u,additionalContext:ge,appliedPolicies:d,isCollectionBye:Pe,usePublishState:g,publishStatus:P,matchUpTieId:De,isRoundRobin:A,roundProfile:N,matchUp:Je,event:v,tournamentParticipants:r,positionAssignments:n,tournamentRecord:p,seedAssignments:f,participantMap:I,contextContent:h,scheduleTiming:S,contextProfile:T,drawDefinition:y,scoringActive:U,structure:M,context:R})})}let mr=Wt.sides&&Wt.sides.filter(Pe=>Pe?.participantId).length===2,zt=!Wt.winningSide;if(Object.assign(Wt,{readyToScore:U&&mr&&zt,hasContext:!0}),mr){let{allParticipantsCheckedIn:Pe,checkedInParticipantIds:Or}=us({matchUp:Wt});Object.assign(Wt,{allParticipantsCheckedIn:Pe,checkedInParticipantIds:Or})}return Array.isArray(T?.exclude)&&T?.exclude.forEach(Pe=>delete Wt[Pe]),Wt}function $b({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Ho({timeItems:r?.timeItems||[],itemType:so});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{allocatedCourts:J(n,!1,!0)}:e}function Kb({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Ho({timeItems:r?.timeItems||[],itemType:Bo});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{courtId:n}:e}function zb({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Ho({timeItems:r?.timeItems||[],itemType:Hi});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{venueId:n}:e}function Ni(t){if(!Array.isArray(t.matchUps))return[];let{matchUps:e,excludeMatchUpStatuses:r,hasParticipantsCount:n,isCollectionMatchUp:o,matchUpStatuses:i,hasWinningSide:s,matchUpFormats:a,roundPositions:c,matchUpFormat:u,collectionIds:p,isMatchUpTie:m,roundNumbers:d,matchUpIds:l,roundNames:f,filterMatchUpTypes:g=!0,filterMatchUpIds:I=!0,stageSequences:h,scheduledDates:S,scheduledDate:T,participantIds:y,processContext:P,tournamentIds:U,matchUpTypes:E,structureIds:A,readyToScore:N,courtIds:D,eventIds:M,venueIds:R,drawIds:b,stages:v}=t,O=Array.isArray(y)?y.filter(Boolean):[],x=Array.isArray(i)?i.filter(Boolean):[],F=Array.isArray(r)?r.filter(Boolean):[],L=Array.isArray(v)?v.filter(Boolean):[],w=Array.isArray(h)?h.filter(Boolean):[],V=Array.isArray(p)?p.filter(Boolean):[],k=Array.isArray(f)?f.filter(Boolean):[],W=Array.isArray(d)?d.filter(Boolean):[],H=Array.isArray(c)?c.filter(Boolean):[],K=Array.isArray(l)&&I?l.filter(Boolean):[],q=Array.isArray(E)&&g?E.filter(Boolean):[],B=Array.isArray(D)?D.filter(Boolean):[],$=Array.isArray(R)?R.filter(Boolean):[],z=Array.isArray(a)&&a.filter(Boolean)||typeof u=="string"&&[u]||[],j=Array.isArray(S)&&S.filter(Boolean)||typeof T=="string"&&T.length&&[T]||[],tt=Array.isArray(U)?U.filter(Boolean):[],Q=Array.isArray(M)?M.filter(Boolean):[],X=Array.isArray(b)?b.filter(Boolean):[],lt=Array.isArray(A)?A.filter(Boolean):[];return e.filter(it=>{if(N&&!ue(xr)(it)&&!it.readyToScore||it.winningSide&&s&&![1,2].includes(it.winningSide)||m!==void 0&&(m&&!it.tieMatchUps||!m&&it.tieMatchUps)||o!==void 0&&(o&&!it.collectionId||!o&&it.collectionId)||L.length&&!L.includes(it.stage)||w.length&&!w.includes(it.stageSequence)||V.length&&(!it.collectionId||!V.includes(it.collectionId))||k.length&&(!it.roundName||!k.includes(it.roundName))||W.length&&(!it.roundNumber||!W.includes(it.roundNumber))||H.length&&(!it.roundPosition||!H.includes(it.roundPosition))||x.length&&(!it.matchUpStatus||!x.includes(it.matchUpStatus))||F.length&&it.matchUpStatus&&F.includes(it.matchUpStatus)||K.length&&!K.includes(it.matchUpId)||q.length&&(!it.matchUpType||!Lc(q,it.matchUpType))||z.length&&(!it.matchUpFormat||!z.includes(it.matchUpFormat)))return!1;if(j?.length){let{scheduledTime:Rt}=mS({matchUp:it}),{scheduledDate:Ft}=Hs({matchUp:it}),fe=Et(Rt)||Ft;if(!j.find(Me=>Wn(Me,fe)))return!1}if(B.length){let{courtId:Rt}=Kb({matchUp:it}),{allocatedCourts:Ft}=$b({matchUp:it}),Ue=Ft?.map(({courtId:fe})=>fe);if(!B.filter(Boolean).includes(Rt)||Ue?.includes(Rt))return!1}if($.length){let{venueId:Rt}=zb({matchUp:it});if(!$.filter(Boolean).includes(Rt))return!1}if(P){if(tt.length&&!tt.includes(it.tournamentId)||Q.length&&!Q.includes(it.eventId)||X.length&&!X.includes(it.drawId)||lt.length&&!lt.includes(it.structureId))return!1;let Rt=it.sides?.map(({participantId:Ft})=>Ft).filter(Boolean)??[];if(n&&Rt.length<n||O.length&&!O.some(Ue=>Rt.includes(Ue)))return!1}return!0})}function Ut(t){let{provisionalPositioning:e,tournamentRecord:r,contextFilters:n,matchUpFilters:o,contextProfile:i,drawDefinition:s,context:a={},structure:c,inContext:u,event:p}=t,{seedAssignments:m,contextContent:d,exitProfiles:l,matchUpsMap:f}=t,g={},I={};if(!c)return{collectionPositionMatchUps:g,error:pi,roundMatchUps:I,matchUps:[]};let h=Array.isArray(o?.eventIds)?o?.eventIds.filter(Boolean):[],S=Array.isArray(o?.structureIds)?o?.structureIds.filter(Boolean):[],T=Array.isArray(o?.drawIds)?o?.drawIds.filter(Boolean):[],y=!a?.eventId||!h?.length&&!n?.eventIds?.filter(Boolean).length||h?.includes(a.eventId)||n?.eventIds?.includes(a.eventId),P=!S?.length||S.includes(c.structureId),U=!s||!T?.length||T.includes(s.drawId);if(!y||!P||!U)return{collectionPositionMatchUps:g,roundMatchUps:I,matchUps:[]};i&&!d&&(d=qn({tournamentRecord:r,contextProfile:i,drawDefinition:s}));let{appliedPolicies:E}=yt({drawDefinition:s}),A={...t.tournamentAppliedPolicies,...E,...t.policyDefinitions},N=A?.scoring?.structures,D=c.stage&&N?.stage?.[c.stage],M=c.stageSequence&&D?.stageSequence?.[c.stageSequence],R=A?.scoring?.requireAllPositionsAssigned||D?.requireAllPositionsAssigned||M?.requireAllPositionsAssigned;f||(f=Ne({drawDefinition:s,structure:c}));let{positionAssignments:b,allPositionsAssigned:v}=Se({structure:c}),O=!R||v,{seedAssignments:x}=on({provisionalPositioning:e,drawDefinition:s,structure:c});m=m??x;let{structureId:F}=c;l=l||s&&eS({drawDefinition:s}).exitProfiles;let L=l?.[F],w=L?.length&&(L[0].split("-").map(B=>parseInt(B)).reduce((B,$)=>B+$)||0),V=!!c.structures,k=oi({matchUpsMap:f,structureId:F,inContext:u}),W=A?.[fa],H=vb({roundNamingPolicy:W,drawDefinition:s,structure:c,matchUps:k}),{roundNamingProfile:K,roundProfile:q}=H;if(I=H?.roundMatchUps??[],o&&(k=Ni({matchUps:k,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1})),u){let{sourceDrawPositionRanges:B}=Rb({drawDefinition:s,matchUpsMap:f,structureId:F}),$=s?Cb({drawDefinition:s,roundProfile:q,matchUpsMap:f,structureId:F}).drawPositionsRanges:void 0;k=k.map(j=>KU({tournamentParticipants:t.tournamentParticipants??r?.participants,scheduleVisibilityFilters:t.scheduleVisibilityFilters,hydrateParticipants:t.hydrateParticipants,afterRecoveryTimes:t.afterRecoveryTimes,usePublishState:t.usePublishState,participantMap:t.participantMap,scheduleTiming:t.scheduleTiming,publishStatus:t.publishStatus,sourceDrawPositionRanges:B,positionAssignments:b,drawPositionsRanges:$,initialRoundOfPlay:w,roundNamingProfile:K,tournamentRecord:r,appliedPolicies:A,seedAssignments:m,contextContent:d,contextProfile:i,drawDefinition:s,scoringActive:O,isRoundRobin:V,roundProfile:q,structure:c,context:a,matchUp:j,event:p})),(k?.filter(j=>Array.isArray(j.tieMatchUps))).forEach(j=>{let tt=j.tieMatchUps;k=k.concat(...tt)}),n&&(k=Ni({processContext:!0,...n,matchUps:k}))}else(k?.filter($=>Array.isArray($.tieMatchUps))).forEach($=>{let z=$.tieMatchUps;k=k.concat(...z)});return o&&(k=Ni({matchUps:k,...o,filterMatchUpTypes:!1,filterMatchUpIds:!1})),(o?.matchUpTypes||o?.matchUpIds)&&(k=Ni({matchUpTypes:o.matchUpTypes,matchUpIds:o.matchUpIds,matchUps:k})),(o?.matchUpTypes||o?.matchUpIds||u)&&(I=Ke({matchUps:k}).roundMatchUps??[]),We({drawDefinition:s,structure:c,event:p})?.tieFormat&&({collectionPositionMatchUps:g}=Mb({matchUps:k})),{collectionPositionMatchUps:g,roundMatchUps:I,isRoundRobin:V,roundProfile:q,matchUpsMap:f,matchUps:k}}function ds({matchUp:t}){return t?ce.includes(t?.matchUpStatus)||t?.winningSide:!1}function hu({requireParticipants:t=!0,scheduleVisibilityFilters:e,tournamentAppliedPolicies:r,tournamentParticipants:n,hydrateParticipants:o,afterRecoveryTimes:i,policyDefinitions:s,tournamentRecord:a,usePublishState:c,matchUpFilters:u,contextFilters:p,contextContent:m,participantMap:d,scheduleTiming:l,publishStatus:f,contextProfile:g,drawDefinition:I,exitProfiles:h,matchUpsMap:S,structureId:T,inContext:y,structure:P,context:U,event:E}){!P&&T&&({structure:P}=at({drawDefinition:I,structureId:T}));let A=Ut({tournamentAppliedPolicies:r,scheduleVisibilityFilters:e,tournamentParticipants:n,hydrateParticipants:o,afterRecoveryTimes:i,policyDefinitions:s,tournamentRecord:a,usePublishState:c,matchUpFilters:u,contextFilters:p,contextContent:m,participantMap:d,scheduleTiming:l,publishStatus:f,contextProfile:g,drawDefinition:I,exitProfiles:h,matchUpsMap:S,structure:P,inContext:y,context:U,event:E}),N=[],D=[],M=[],R=[],b=[];if(A.error)return A;let{matchUps:v}=A,{assignedPositions:O}=Se({structure:P}),x=O?.filter(L=>L.participantId).map(L=>L.drawPosition),F;return v.filter(L=>{let w=u?.matchUpTypes?.length===1&&u.matchUpTypes[0]===jt;return!(L.matchUpType!==jt&&w)}).forEach(L=>{if(L.matchUpStatus===br){N.push(L);return}L.matchUpType===jt&&(F=!0);let w=L.collectionId,V=w&&L.sides?.every($=>$.participantId),k=!w&&L.drawPositions?.filter(Boolean).length===2,W=!w&&L.drawPositions?.every($=>x?.includes($)),H=O?.filter($=>$.bye).map($=>$.drawPosition),K=!w&&L.drawPositions?.find($=>H?.includes($)),B=Gh.includes(L.matchUpStatus)&&(V||k&&(!t||W));return K?b.push(L):ds({matchUp:L})?D.push(L):B?M.push(L):R.push(L)}),{includesTeamMatchUps:F,abandonedMatchUps:N,completedMatchUps:D,upcomingMatchUps:M,pendingMatchUps:R,byeMatchUps:b,structure:P}}function Qb({drawDefinition:t,roundNumber:e,structureId:r}){if(!t)return{error:Z};if(!r)return{error:Er};let{links:n}=Ws({drawDefinition:t,structureId:r}),o=n.source.reduce((s,a)=>!a.source.roundNumber||a.source.roundNumber===e?s.concat(a):s,[]),i=n.target.reduce((s,a)=>!a.target.roundNumber||a.target.roundNumber===e?s.concat(a):s,[]);return{links:{source:o,target:i}}}function fS({finishingPositions:t,linkCondition:e,linkType:r,source:n}){let o=n.find(i=>{let s=!i.source?.finishingPositions||!t||Fe(t,i.source?.finishingPositions);return e===i.linkCondition&&s&&i.linkType===r});return[fo,eo].includes(o?.linkType)&&!o?.source?.roundNumber?_({result:{error:G},stack:"getTargetLink",context:o}):o}function Ws({drawDefinition:t,structureId:e,roundNumber:r}){return t?e?{links:(t.links||[]).filter(Boolean).reduce((i,s)=>(s.source?.structureId===e&&(!r||s.source.roundNumber===r)&&(i.source=i.source.concat(s)),s.target?.structureId===e&&(!r||s.target.roundNumber===r)&&(i.target=i.target.concat(s)),i),{source:[],target:[]})}:{error:Er}:{error:Z}}function Xb({structureMatchUps:t,matchUp:e}){let{roundNumber:r,roundPosition:n}=e,o=t.filter(s=>s.roundNumber===r&&!s.matchUpTieId),i=t.filter(s=>s.roundNumber===r+1&&!s.matchUpTieId);if(i.length){let s;return i.length===o.length?s=i.find(a=>a.roundPosition===n):i.length===o.length/2&&(s=i.find(a=>a.roundPosition===Math.ceil(n/2))),{matchUp:s}}return{message:"no progression found"}}function gS({sourceRoundMatchUpCount:t,inContextDrawMatchUps:e,sourceRoundPosition:r,drawDefinition:n,targetLink:o}){if(!o)return{error:kl};let{target:{structureId:i,feedProfile:s,groupedOrder:a,roundNumber:c,positionInterleave:u}}=o,{structure:p}=at({drawDefinition:n,structureId:i}),{positionAssignments:m}=bt({structure:p}),l=(e?.filter(D=>D.structureId===p?.structureId)).filter(D=>D.roundNumber===c&&!D.matchUpTieId),f=l.length,g=et(1,f+1),I=f/t,h=Math.ceil(I*r),S=1-r%2;if(u?.interleave&&I!==.5){let D=u.offset+(r-1)*u.interleave,M=r+D;h=Math.ceil(M/2),S=1-M%2}let T=g,y=g[h-1],P=tS({roundPositionsCount:g.length,groupedOrder:a}),U=P?.length||1;if(U<=g.length){let D=f/U,M=ye(g,D);s===di&&M.forEach(R=>R.reverse()),T=P?.length&&P?.map(R=>M[R-1]).flat()||T}s===En?y=T[h-1]:s===di?((!P?.length||U>g.length)&&(h=l.length+1-h),y=T[h-1]):s===cp&&Ur()&&console.log(Zu,{feedProfile:s});let E=y&&l.reduce((D,M)=>M.roundPosition===y?M:D,void 0),A;E?.feedRound?(S=0,A=Math.min(...(E.drawPositions||[]).filter(Boolean))):A=E?.drawPositions?.length===2&&E?.drawPositions[S];let N=m?.find(({drawPosition:D})=>D===A);if(N){let{extension:D}=dt({element:N,name:Hm});if(D?.value)return{disabledDrawPosition:A}}return{matchUp:E,targetDrawPosition:A,matchUpDrawPositionIndex:S}}function ur({inContextDrawMatchUps:t=[],useTargetMatchUpIds:e,inContextMatchUp:r,drawDefinition:n,matchUpId:o}){let i=r;t.length&&!i&&(i=t.find(c=>c.matchUpId===o));let{structure:s}=at({structureId:i?.structureId,drawDefinition:n});return s?.finishingPosition===Gi?Uk({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:n,structure:s,matchUp:i}):Pk({matchUp:i})}function Uk({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:r,structure:n,matchUp:o}){let{winnerMatchUpId:i,loserMatchUpId:s}=o,{links:a}=Qb({roundNumber:o.roundNumber,structureId:n.structureId,drawDefinition:r}),c=a?.source,u=fS({source:c,linkType:fo}),p=fS({linkCondition:On,linkType:eo,source:c}),m=fS({source:c,linkType:eo}),d=p&&m;m||(m=p);let l=u?.target?.feedProfile,f=m?.target?.feedProfile,g=p?.target?.feedProfile,I,h,S,T,y,P,U,E,A,N;if(e&&(i||s)&&(U=i&&l!==dn&&t.find(({matchUpId:R})=>R===i),T=s&&f!==dn&&t.find(({matchUpId:R})=>R===s),U||T))return{matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u},targetMatchUps:{loserMatchUp:T,winnerMatchUp:U}};let{roundPosition:D}=o;N=N||t.filter(R=>R.structureId===n.structureId);let M=N.reduce((R,b)=>b.roundNumber===o.roundNumber&&!b.matchUpTieId?R+1:R,0);return m&&!T&&f!==dn&&({matchUpDrawPositionIndex:P,targetDrawPosition:y,matchUp:T}=gS({targetLink:m,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),d&&g!==dn&&({matchUpDrawPositionIndex:S,targetDrawPosition:h,matchUp:I}=gS({targetLink:p,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),u&&!U&&l!==dn&&({matchUpDrawPositionIndex:A,targetDrawPosition:E,matchUp:U}=gS({targetLink:u,sourceRoundMatchUpCount:M,inContextDrawMatchUps:t,sourceRoundPosition:D,drawDefinition:r})),U||(N=N||t.filter(R=>R.structureId===n.structureId),{matchUp:U}=Xb({structureMatchUps:N,matchUp:o})),ot({matchUp:o,targetLinks:{loserTargetLink:m,winnerTargetLink:u,byeTargetLink:p},targetMatchUps:{winnerMatchUpDrawPositionIndex:A,loserMatchUpDrawPositionIndex:P,byeMatchUpDrawPositionIndex:S,winnerTargetDrawPosition:E,loserTargetDrawPosition:y,byeTargetDrawPosition:h,winnerMatchUp:U,loserMatchUp:T,byeMatchUp:I},targetMatchUpIds:!!(i||s)})}function Pk({matchUp:t}){return{targetLinks:{loserTargetLink:void 0,winnerTargetLink:void 0},targetMatchUps:{loserMatchUp:void 0,winnerMatchUp:void 0},matchUp:t}}function Jb({drawDefinition:t,inContextDrawMatchUps:e}){let r={};return e.forEach(n=>{let{matchUpId:o,structureId:i,drawPositions:s=[]}=n,{structure:a}=at({drawDefinition:t,structureId:i});if(a?.finishingPosition===li){let{roundNumber:c}=n,u=c&&pt(c)+1,p=a.matchUps??[],{roundMatchUps:m}=Ke({matchUps:p});if(u&&m?.[u]){let d=[...s].sort(me).map((l,f)=>{let g=m[u].find(I=>I.drawPositions?.includes(l));return{matchUpId:g?.matchUpId,roundNumber:u,schedule:g?.schedule,sideNumber:f+1,structureName:a.structureName}});Object.assign(n,{sidesTo:d})}}else{let c=ur({useTargetMatchUpIds:!0,inContextDrawMatchUps:e,inContextMatchUp:n,drawDefinition:t,matchUpId:o}),{winnerMatchUp:u}=c.targetMatchUps,{loserMatchUp:p}=c.targetMatchUps;!n.winnerMatchUpId&&u&&(n.winnerMatchUpId=u.matchUpId),!n.loserMatchUpId&&p&&(n.loserMatchUpId=p.matchUpId);let m=zU({upcomingMatchUp:u}),d=zU({upcomingMatchUp:p});if(n.matchUpStatus!==Nt&&p?.matchUpStatus===Nt){let{matchUp:f}=Zb({matchUp:p,drawDefinition:t,inContextDrawMatchUps:e})||{};d=f&&zU({upcomingMatchUp:f})||d}let l=n.schedule?.timeAfterRecovery;if(l&&(m?.schedule?.scheduledTime&&qt(m.schedule.scheduledTime)<qt(l)&&(r[m.matchUpId]=n.matchUpId,m.schedule.scheduleConflict=n.matchUpId),d?.schedule?.scheduledTime&&qt(d.schedule.scheduledTime)<qt(l)&&(r[d.matchUpId]=n.matchUpId,d.schedule.scheduleConflict=n.matchUpId)),Object.assign(n,{winnerTo:m,loserTo:d}),n.drawPositions?.filter(Boolean).length){let g=c.targetLinks?.loserTargetLink?.linkCondition===On,I=Dk(n);if(I.length){let h=vf(u?.sides),S=vf(p?.sides),y=I.find(({participantId:E})=>h.includes(E))?[]:I,U=I.find(({participantId:E})=>S.includes(E))?[]:I;p&&g&&U.length<2&&U.push({bye:!0,tbd:!0}),y?.length&&u&&(!c.targetMatchUpIds&&u&&(u=e.find(({matchUpId:E})=>E===u.matchUpId)),u.potentialParticipants||(u.potentialParticipants=[]),u.potentialParticipants.push(y)),U?.length&&p&&(c.targetMatchUpIds||(u=e.find(({matchUpId:E})=>E===p.matchUpId)),p.potentialParticipants||(p.potentialParticipants=[]),p.potentialParticipants.push(U))}}}}),Object.keys(r).length&&e.forEach(n=>{Object.keys(r).includes(n.matchUpId)&&(n.schedule.scheduleConflict=r[n.matchUpId])}),{scheduleConflictMatchUpIds:r}}function Dk(t){return t?.sides?.map(({participant:e,participantId:r,qualifier:n})=>e||r&&{participantId:r}||n&&{qualifier:n}).filter(Boolean)||[]}function Zb({matchUp:t,drawDefinition:e,inContextDrawMatchUps:r}){let{matchUpId:n,matchUpStatus:o,structureId:i}=t||{};if(!t||!i||t?.matchUpStatus===Qt)return{matchUp:t};if(o===Nt){let s;return t.winnerMatchUpId?s=r.find(({matchUpId:a})=>a===t.winnerMatchUpId):{winnerMatchUp:s}=ur({inContextDrawMatchUps:r,drawDefinition:e,matchUpId:n})?.targetMatchUps||{},Zb({matchUp:s,drawDefinition:e,inContextDrawMatchUps:r})}return{matchUp:void 0}}function zU(t){if(t?.upcomingMatchUp)return(({matchUpId:e,structureId:r,schedule:n,roundNumber:o,roundPosition:i,structureName:s})=>({matchUpId:e,structureId:r,schedule:n,roundNumber:o,roundPosition:i,structureName:s}))(t.upcomingMatchUp)}function se(t){let e="getAllDrawMatchUps";Object.assign(t,{requireParticipants:!1});let r=js(t);if(r.error)return _({result:r,stack:e});let{abandonedMatchUps:n,completedMatchUps:o,upcomingMatchUps:i,pendingMatchUps:s,byeMatchUps:a,matchUpsMap:c}=r;return{matchUps:(n??[]).concat(...o??[],...i??[],...s??[],...a??[]),matchUpsMap:c}}function js(t){if(!t?.drawDefinition)return{error:Z};let{tournamentParticipants:e,contextContent:r,matchUpsMap:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,requireParticipants:s,participantsProfile:a,afterRecoveryTimes:c,policyDefinitions:u,tournamentRecord:p,usePublishState:m,contextFilters:d,matchUpFilters:l,scheduleTiming:f,participantMap:g,publishStatus:I,contextProfile:h,drawDefinition:S,nextMatchUps:T,inContext:y,context:P,event:U}=t,E=[],A=[],N=[],D=[],M=[];h&&!r&&(r=qn({policyDefinitions:u,tournamentRecord:p,contextProfile:h,event:U}));let R;!e?.length&&p&&(e=p?.participants,(y||a?.withGroupings)&&e?.length&&({participantsWithGroupings:e,groupInfo:R}=Xm({participants:e,participantsProfile:a})));let{structures:b}=gn({drawDefinition:S});if(!b)return{error:kt};n||(n=Ne({drawDefinition:S}));let v=S&&eS({drawDefinition:S}).exitProfiles;b.forEach(F=>{let{byeMatchUps:L=[],pendingMatchUps:w=[],upcomingMatchUps:V=[],completedMatchUps:k=[],abandonedMatchUps:W=[]}=hu({matchUpFilters:T?void 0:l,contextFilters:T?void 0:d,inContext:y||T||d,hydrateParticipants:t.hydrateParticipants,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,tournamentParticipants:e,requireParticipants:s,afterRecoveryTimes:c,policyDefinitions:u,tournamentRecord:p,usePublishState:m,contextContent:r,participantMap:g,scheduleTiming:f,publishStatus:I,contextProfile:h,drawDefinition:S,exitProfiles:v,matchUpsMap:n,structure:F,context:P,event:U});E=E.concat(...W),A=A.concat(...k),N=N.concat(...V),D=D.concat(...w),M=M.concat(...L)});let O=F=>(!l&&!T&&!d||(l&&(F=Ni({matchUps:F,...l})),d&&(F=Ni({matchUps:F,...d,processContext:!0}))),F),x={abandonedMatchUps:O(E),completedMatchUps:O(A),upcomingMatchUps:O(N),pendingMatchUps:O(D),byeMatchUps:O(M),matchUpsMap:n,...C,groupInfo:R};if(T){let F=typeof T=="object"||{abandoned:!0,completed:!0,upcoming:!0,pending:!0,bye:!0},{abandoned:L,completed:w,upcoming:V,pending:k,bye:W}=F,H=[].concat(...L&&E||[],...w&&A||[],...V&&N||[],...k&&D||[],...W&&M||[]);Jb({inContextDrawMatchUps:H,drawDefinition:S})}return x}function $n(t){let{participants:e=[],contextContent:r,participantMap:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,contextFilters:m,contextProfile:d,matchUpFilters:l,nextMatchUps:f,inContext:g,context:I,event:h}=t;if(!h)return{error:vt};let{eventId:S,eventName:T,endDate:y,eventType:P,category:U,gender:E,matchUpFormat:A}=h??{},N={...I,...ot({indoorOutDoor:h.indoorOutdoor??p?.indoorOutdoor,surfaceCategory:h.surfaceCategory??p?.surfaceCategory,endDate:h.endDate??p?.endDate,tournamentId:p?.tournamentId,matchUpFormat:A,eventName:T,eventType:P,category:U,eventId:S,gender:E})};y&&(N.endDate=y),d&&!r&&(r=qn({policyDefinitions:c,tournamentRecord:p,contextProfile:d,event:h}));let D;if(!e?.length&&!n&&p){let v=Ai({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:d,inContext:g});n=v.participantMap,e=v.participants??[],D=v.groupInfo}let M=h.drawDefinitions??[],R=ya({tournamentRecord:p,event:h}).scheduleTiming;return{matchUps:M.flatMap(v=>{let{matchUps:O}=se({tournamentParticipants:e,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,context:N,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,contextFilters:m,contextProfile:d,drawDefinition:v,contextContent:r,matchUpFilters:l,participantMap:n,scheduleTiming:R,nextMatchUps:f,inContext:g,event:h});return O??[]}),groupInfo:D}}function Te(t){let e=rt(t,[{tournamentRecord:!0}]);if(e.error)return e;if(!t?.tournamentRecord)return{error:Y};let{participantMap:r,participants:n}=t,{scheduleVisibilityFilters:o,participantsProfile:i,afterRecoveryTimes:s,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,inContext:p=!0,contextProfile:m,matchUpFilters:d,contextFilters:l,nextMatchUps:f,context:g}=t,I=t.tournamentId??u.tournamentId,h=u?.events??[];n||({participants:n,participantMap:r}=Ai({participantsProfile:i,useParticipantMap:a,policyDefinitions:c,tournamentRecord:u,contextProfile:m,inContext:p}));let{appliedPolicies:S}=yt({tournamentRecord:u}),T={...g,tournamentId:I,indoorOutDoor:u.indoorOutdoor,surfaceCategory:u.surfaceCategory,endDate:u.endDate},y=qn({policyDefinitions:c,tournamentRecord:u,contextProfile:m});return{matchUps:h.flatMap(U=>(T.eventDrawsCount=U.drawDefinitions?.length??0,$n({context:T,scheduleVisibilityFilters:o,tournamentAppliedPolicies:S,participantsProfile:i,afterRecoveryTimes:s,policyDefinitions:c,tournamentRecord:u,contextContent:y,contextFilters:l,contextProfile:m,matchUpFilters:d,participantMap:r,nextMatchUps:f,participants:n,inContext:p,event:U}).matchUps??[])).concat(...u.matchUps??[])}}function Un({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,tournamentRecords:n,policyDefinitions:o,matchUpFilters:i,contextFilters:s,nextMatchUps:a,inContext:c}){if(typeof n!="object"||!Object.keys(n).length)return{error:wt};let p=Object.keys(n).map(m=>{let d=n[m];return Te({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:r,policyDefinitions:o,tournamentRecord:d,matchUpFilters:i,contextFilters:s,nextMatchUps:a,inContext:c}).matchUps??[]}).flat();return{...C,matchUps:p}}function Mi(t,e){return Nk(t,e)||(t?.stageSequence||0)-(e?.stageSequence||0)||t?.roundNumber&&e.roundNumber&&t?.roundNumber-e?.roundNumber||(t?.roundPosition??0)-(e?.roundPosition??0)}function Nk(t,e){return(ks[t?.stage]||0)-(ks[e?.stage]||0)}function or(t){let{participants:e,participantMap:r,contextContent:n}=t,{scheduleVisibilityFilters:o,tournamentAppliedPolicies:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,matchUpFilters:m,contextFilters:d,contextProfile:l,drawDefinition:f,nextMatchUps:g,inContext:I,context:h,event:S}=t,{eventId:T,eventName:y,endDate:P,eventType:U,category:E,gender:A,matchUpFormat:N}=S??{},D={...h,surfaceCategory:S?.surfaceCategory??p?.surfaceCategory,indoorOutDoor:S?.indoorOutdoor??p?.indoorOutdoor,matchUpFormat:N,eventType:U,eventName:y,category:E,eventId:T,endDate:P,gender:A},M;return!e?.length&&!r&&p&&({participants:e=[],participantMap:r,groupInfo:M}=Ai({participantsProfile:s,useParticipantMap:u,policyDefinitions:c,tournamentRecord:p,contextProfile:l,inContext:I})),l&&!n&&(n=qn({policyDefinitions:c,tournamentRecord:p,contextProfile:l,drawDefinition:f,event:S})),{...se({context:D,tournamentAppliedPolicies:i,scheduleVisibilityFilters:o,tournamentParticipants:e,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,drawDefinition:f,contextContent:n,contextFilters:d,contextProfile:l,matchUpFilters:m,participantMap:r,nextMatchUps:g,inContext:I,event:S}),groupInfo:M}}function ls({element:t,accessor:e}){if(typeof e!="string")return{values:[]};let r=J(t),n=e.split("."),o=[],i;a({targetElement:r,attributes:n});let s={value:i};return o.length&&(s.values=o),s;function a({targetElement:c,attributes:u=[],significantCharacters:p}){for(let[d,l]of u.entries())if(c?.[l]){let f=u.slice(d+1);f.length?Array.isArray(c[l])?c[l].forEach(I=>a({targetElement:I,attributes:f})):(c=c[l],m({targetElement:c,index:d})):(i||(i=c[l]),o.includes(c[l])||o.push(c[l]))}function m({targetElement:d,index:l}){if(d&&l===u.length-1&&["string","number"].includes(typeof d)){let f=p?d.slice(0,p):d;i?o.includes(f)||o.push(f):(i=f,o.push(f))}}}}var QU=t=>e=>!t||typeof e!="object"?void 0:Array.isArray(t)&&t.map(r=>({[r]:ls({element:e,accessor:r})?.value}))||typeof t=="object"&&Object.keys(t).map(r=>({[r]:ls({element:e,accessor:r})?.value}))||(typeof t=="string"&&ls({element:e,accessor:t}))?.value,Br=QU;function Ea({finishingPositionOffset:t=0,finishingPositionLimit:e,positionsFed:r,roundsCount:n,roundLimit:o,matchUps:i,lucky:s,fmlc:a}){if(!Vr(i))return[];let{roundProfile:c,roundNumbers:u=[]}=Ke({interpolate:!0,matchUps:i});n=n??Math.max(...u,0);let p=o?n-o:0,m=p&&c?.[n-p]?.matchUpsCount,d=c&&Object.values(c).map(Br("matchUpsCount")),l=(I,h)=>{let S=Math.min(...I);m&&h&&S===1&&(S=m);let T=Math.max(...I);return e&&T>e&&(T=e),[S,T]},f=c&&Object.assign({},...u.map(I=>{let h=(n??0)+1-I-p,S=c[I].matchUpsCount,T={finishingPositionRange:{},finishingRound:h},y=d?.slice(I-1).reduce((R,b)=>R+(b||0),0),P=a&&I!==1,U=1+t+(P?r??0:0),E=1,A=et(U,s?U+S*2:y+U+E),N=y+E-S,D=l(A.slice(N)),M=l(A.slice(0,N),!0);return T.finishingPositionRange={loser:D,winner:M},{[I]:T}})),g=Ur({finishingRound:!0});return i.filter(Boolean).forEach(I=>{let h=I.roundNumber&&f[I.roundNumber];g&&!h&&console.log({roundFinishingData:f,matchUp:I}),I.finishingRound=h?.finishingRound,I.finishingPositionRange=h?.finishingPositionRange}),i}function qi({inContextDrawMatchUps:t,drawDefinition:e,matchUpsMap:r}){if(!e)return{error:Z};let n={loserMatchUpIds:{},winnerMatchUpIds:{}};if(t||({matchUps:t,matchUpsMap:r}=se({inContext:!0,drawDefinition:e,matchUpsMap:r})),!r?.drawMatchUps.some(i=>i.finishingPositionRange)&&e?.structures?.length===1&&!e?.structures[0].structures){let i=r?.drawMatchUps??[];Ea({matchUps:i})}return(t??[]).filter(({collectionId:i})=>!i).forEach(i=>{let{matchUpId:s,structureId:a}=i,c=ur({inContextDrawMatchUps:t,drawDefinition:e,matchUpId:s}),{winnerMatchUp:u,loserMatchUp:p}=c.targetMatchUps,m=u?.matchUpId,d=p?.matchUpId,f=oi({matchUpsMap:r,structureId:a}).find(g=>g.matchUpId===s);if(f&&(m&&(n.winnerMatchUpIds[f.matchUpId]=m,Object.assign(f,{winnerMatchUpId:m}),Object.assign(i,{winnerMatchUpId:m})),d&&(n.loserMatchUpIds[f.matchUpId]=d,i.loserMatchUpId=d,f.loserMatchUpId=d,i.finishingPositionRange))){let g=p.finishingPositionRange&&[...i.finishingPositionRange.loser,...p.finishingPositionRange.loser],I=g&&[Math.min(...g),Math.max(...g)];i.finishingPositionRange.loser=I,f.finishingPositionRange.loser=I}}),{inContextDrawMatchUps:t,goesToMap:n}}function sn(t){let e=Dr(t),r=t.matchUps??[],n=t.drawIds??[],{includeParticipantDependencies:o,tournamentRecord:i,drawDefinition:s}=t;if(!Array.isArray(r))return{error:Xn};if(!Array.isArray(n))return{error:an};let a=t.matchUpIds?.length?t.matchUpIds:r.map(T=>T.matchUpId);if(!Array.isArray(a))return{error:rs};let c={},u={},p={},m={};i&&!Object.keys(e).length&&(e={[i.tournamentId]:i});let d=Object.values(e),f=d.reduce((T,y)=>T.concat(y.events??[]).map(P=>(P.drawDefinitions||[]).map(U=>U.links||[])).flat(1/0),[]).filter(({linkType:T})=>T===to),g=r;if(f.length){g=Un({nextMatchUps:!0,tournamentRecords:e}).matchUps;let T=f.reduce((y,P)=>{let U=P.source?.structureId,E=P.target?.structureId;return U&&E&&(p[E]=U),U&&!y.includes(U)&&y.push(U),y},[]);for(let y of T)c[y]=[];for(let y of g??[]){let P=y.containerStructureId||y.structureId;T.includes(P)&&c[P].push(y.matchUpId)}}let I=T=>{u[T]||(u[T]={dependentMatchUpIds:[],participantIds:[],matchUpIds:[],sources:[]},m[T]=[])},h=(T,y)=>{u[T].matchUpIds.forEach(U=>{u[y].matchUpIds.push(U)}),u[y].matchUpIds.push(T),u[T].dependentMatchUpIds.push(y),o&&u[T].participantIds.forEach(U=>u[y].participantIds.push(U))},S=T=>{let y=Object.keys(c).length;for(let P of T||[]){let{matchUpId:U,winnerMatchUpId:E,loserMatchUpId:A}=P;if(!a.length||a.includes(U)){if(I(U),o){let{individualParticipantIds:M}=uu(P);u[U].participantIds=M}E&&(I(E),h(U,E),m[E].push(U)),A&&(I(A),h(U,A),m[A].push(U)),u[U].sources.push(m[U]);let N=m[U].map(M=>u[M].sources[0]).flat(),D=m[U].map(M=>u[M].sources[1]).flat();if(u[U].sources.push(N,D),y){let M=P.containerStructureId||P.structureId,R=p[M];if(c[R])for(let b of c[R])I(b),h(b,U),m[b].push(U)}}}};if(s)qi({drawDefinition:s}),g?.length||(g=or({drawDefinition:s}).matchUps),S(g);else{if(g?.length||(g=Un({nextMatchUps:!0,tournamentRecords:e}).matchUps),!n.length){let T=d?.length?d.map(({events:y=[]})=>y.map(({drawDefinitions:P=[]})=>P.map(({drawId:U})=>U))).flat(1/0):[];T&&(n=T)}for(let T of n){let y=g?.filter(U=>U.drawId===T).sort(Mi);if(!y?.find(({roundPosition:U})=>!U)){let U=y?.find(({tournamentId:A})=>A),{drawDefinition:E}=ze({tournamentRecord:e[U?.tournamentId],drawId:T});E&&qi({drawDefinition:E})}S(y)}}return{positionDependencies:c,matchUpDependencies:u,sourceMatchUpIds:m,matchUps:g,...C}}function Ie(t){let e=t?.matchUp,r=t?.score||e?.score,n=r?.sets?.[0],{side1Score:o,side2Score:i,side1TiebreakScore:s,side2TiebreakScore:a,side1PointScore:c,side2PointScore:u}=n||{},p=o||i||s||a||c||u;return!!(r?.sets?.length>1||p)}function Ua({matchUpStatus:t}){return Fh.includes(t)}function tv({matchUpStatus:t}){return Km.includes(t)}function og({matchUpStatus:t}){return kh.includes(t)}function ig({matchUpStatus:t,winningSide:e,tieMatchUps:r,sides:n,score:o}){let i=n?.find(({participantId:c})=>c),s=r?.filter(ig)?.length;return Ie({score:o})||s||e&&i||t&&tv({matchUpStatus:t})&&![Mt,Ct,Ln].includes(t)}function Pa(t){let{drawDefinition:e,findContainer:r,structureId:n,event:o}=t,i=t.structure,s={isCollectionMatchUp:!1},{containedStructures:a}=as({drawDefinition:e}),c=n?a[n]||[]:[];if(!i){let E=at({drawDefinition:e,structureId:n});if(E.error)return E;i=r?E.containingStructure??E.structure:E.structure}if(cr({structure:i}))return{structure:i,isAdHoc:!0,error:Rs};let{matchUps:u}=se({inContext:!0,matchUpFilters:s,drawDefinition:e,event:o}),p=u?.filter(E=>E.structureId===n||c.includes(E.structureId)),{matchUpDependencies:m}=sn({drawIds:[e.drawId],matchUps:u,drawDefinition:e}),d=[],l=[],f={},g=[];for(let E of u??[]){if(E.structureId===n||c.includes(E.structureId)){l.push(...E.drawPositions??[]);let A=E.roundNumber;for(let N of(E.drawPositions??[]).filter(Boolean))(!f[N]||A&&f[N]>A)&&(f[N]=A)}ig(E)&&(g.push(E),d.push(E.matchUpId,...m?.[E?.matchUpId]?.matchUpIds||[]))}let I=ut(l.filter(Boolean)).sort(me),h=ut(d),S=ut(p?.map(({matchUpId:E,drawPositions:A})=>h.includes(E)?A:[]).flat().filter(Boolean)).sort(me),{positionAssignments:T}=bt({drawDefinition:e,structure:i}),y=T?.filter(E=>E.bye).map(E=>E.drawPosition),P=T?.filter(E=>E.qualifier).map(E=>E.drawPosition),U=I?.filter(E=>!S.includes(E))||[];return{allDrawPositions:I,inContextStructureMatchUps:p,drawPositionInitialRounds:f,activeDependentMatchUpIds:h,qualifyingDrawPositions:P,inactiveDrawPositions:U,positionAssignments:T,activeDrawPositions:S,byeDrawPositions:y,activeMatchUps:g,structure:i}}function fs({drawPosition:t,matchUps:e=[]}){return{initialRoundNumber:e.filter(({drawPositions:n})=>t&&n?.includes(t)).map(({roundNumber:n})=>n).sort(me)[0]}}var Da={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",brightred:"\x1B[91m",green:"\x1B[32m",brightgreen:"\x1B[92m",yellow:"\x1B[33m",brightyellow:"\x1B[93m",blue:"\x1B[34m",brightblue:"\x1B[94m",lightblue:"\x1B[105m",magenta:"\x1B[35m",brightmagenta:"\x1B[95m",cyan:"\x1B[36m",brightcyan:"\x1B[96m",white:"\x1B[37m",brightwhite:"\x1B[97m"};var IS=[];function Rn(t,e){Vt(t)&&(t={method:t}),(e||Ur())&&IS.push(t)}function Mk(t){let e=IS.slice();return t&&(IS.length=0),e}function ev(t){let r=Mk(t).map(n=>{let{color:o,keyColors:i,method:s,newline:a}=n,c=Object.keys(Da).includes(o)?Da[o]:Da.cyan,p=Object.keys(n).filter(d=>!["color","keyColors","method","newline"].includes(d)).map(d=>{let l=i&&Object.keys(i).includes(d)&&Da[i[d]]?Da[i[d]]:Da.brightwhite;return`${Da.white}${d}: ${l}${n[d]}`}).join(", "),m=s?.length<15?" ":" ";return[a?`
|
|
2
2
|
`:"",c,s,m,Da.white,p,Da.reset,`
|
|
3
3
|
`].join("")});r?.length&&console.log(...r)}function rv(){IS.length=0}function Hr({provisionalPositioning:t,isPositionAction:e,tournamentRecord:r,drawDefinition:n,drawPosition:o,matchUpsMap:i,structureId:s,structure:a,event:c}){if(!n)return{error:Z};if(a||({structure:a}=at({drawDefinition:n,structureId:s})),!a)return{error:kt};s||({structureId:s}=a);let u="assignDrawPositionBye";Rn({method:u,color:"cyan",drawPosition:o}),i||(i=Ne({drawDefinition:n}));let{positionAssignments:p}=bt({structure:a}),{activeDrawPositions:m}=Pa({drawDefinition:n,structureId:s});if(p?.find(R=>R.drawPosition===o)?.bye)return{...C};if(m?.includes(o))return{error:Yu};let f=p?.find(R=>R.drawPosition===o);if(!f)return{error:Rs};let{filled:g,containsBye:I,assignedParticipantId:h}=Rk(f);if(I)return{...C};if(g&&!I)return _({result:{error:Wa},stack:u});let S=yt({tournamentRecord:r,drawDefinition:n,event:c}).appliedPolicies??{},T=se({inContext:!0,drawDefinition:n,matchUpsMap:i}).matchUps??[],y={isCollectionMatchUp:!1},{matchUps:P}=Ut({provisionalPositioning:t,drawDefinition:n,matchUpFilters:y,matchUpsMap:i,structure:a});if(p?.forEach(R=>{R.drawPosition===o&&(R.bye=!0)}),a.structureType===Ge)return Ck({tournamentRecord:r,drawDefinition:n,drawPosition:o,matchUps:P}),bo({tournamentId:r?.tournamentId,drawDefinition:n,structure:a,event:c}),nv({assignedParticipantId:h,isPositionAction:e,appliedPolicies:S,drawDefinition:n,drawPosition:o,structureId:s,stack:u});let{roundProfile:U,roundMatchUps:E}=Ke({matchUps:P}),N=(U&&Object.keys(U).map(R=>parseInt(R)).reverse())?.find(R=>U?.[R].drawPositions?.includes(o)),D=N?E?.[N].find(({drawPositions:R})=>R?.includes(o)):void 0;D&&ov({tournamentRecord:r,drawDefinition:n,matchUp:D,event:c});let M=D?.drawPositions?.find(R=>R!==o);if(D&&M){let R=hS({sourceDrawPositions:D.drawPositions,matchUpId:D.matchUpId,inContextDrawMatchUps:T,drawPositionToAdvance:M,tournamentRecord:r,drawDefinition:n,matchUpsMap:i});if(R.error)return R}return bo({tournamentId:r?.tournamentId,drawDefinition:n,structure:a,event:c}),nv({assignedParticipantId:h,isPositionAction:e,appliedPolicies:S,drawDefinition:n,drawPosition:o,structureId:s,stack:u})}function nv({assignedParticipantId:t,isPositionAction:e,appliedPolicies:r,drawDefinition:n,drawPosition:o,structureId:i,stack:s}){return e&&cu({appliedPolicies:r,drawDefinition:n,positionAction:{removedParticipantId:t,drawPosition:o,structureId:i,name:s}}),_({result:{...C},stack:s})}function Rk(t){let e=t.bye,r=t.qualifier,n=t.participantId;return{containsBye:e,containsQualifier:r,assignedParticipantId:n,filled:e||r||n}}function ov({tournamentRecord:t,drawDefinition:e,eventId:r,matchUp:n,event:o}){Object.assign(n,{matchUpStatus:Nt,score:void 0,winningSide:void 0}),gt({tournamentId:t?.tournamentId,eventId:r??o?.eventId,context:"setMatchUpStatusBye",drawDefinition:e,matchUp:n})}function Ck({tournamentRecord:t,drawDefinition:e,drawPosition:r,matchUps:n,event:o}){n.forEach(i=>{i.drawPositions?.includes(r)&&ov({eventId:o?.eventId,tournamentRecord:t,drawDefinition:e,matchUp:i})})}function hS({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,matchUpsMap:i,matchUpId:s,event:a}){Rn({method:"advanceDrawPosition",color:"cyan",drawPositionToAdvance:t});let u=i.drawMatchUps.find(P=>P.matchUpId===s),m=e.find(P=>P.matchUpId===s)?.structureId,{structure:d}=at({drawDefinition:o,structureId:m}),{positionAssignments:l}=bt({structure:d}),f=l?.filter(P=>P.bye).map(P=>P.drawPosition),g=u?.drawPositions?.find(P=>P!==t),I=g&&f?.includes(g),{targetLinks:{loserTargetLink:h},targetMatchUps:{loserMatchUp:S,winnerMatchUp:T,loserTargetDrawPosition:y}}=ur({inContextDrawMatchUps:e,drawDefinition:o,matchUpId:s});if(T&&T.structureId===d?.structureId&&bk({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,winnerMatchUp:T,matchUpsMap:i,event:a}),S&&I&&S.structureId!==d?.structureId){let{roundNumber:P}=S;if(P===1){let U=Hr({structureId:h.target.structureId,drawPosition:y,tournamentRecord:n,drawDefinition:o,event:a});if(U.error)return U}else iv({loserTargetDrawPosition:y,tournamentRecord:n,loserTargetLink:h,drawDefinition:o,loserMatchUp:S,matchUpsMap:i,event:a})}return{...C}}function bk({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:r,tournamentRecord:n,drawDefinition:o,winnerMatchUp:i,matchUpsMap:s,event:a}){let c="advanceWinner",u=s.drawMatchUps.find(L=>L.matchUpId===i.matchUpId),m=e.find(L=>L.matchUpId===i.matchUpId)?.structureId,{structure:d}=at({drawDefinition:o,structureId:m}),{positionAssignments:l}=bt({structure:d}),g=l?.find(({drawPosition:L})=>L===t)?.bye,I=u.drawPositions?.filter(Boolean),h=l?.filter(L=>I?.includes(L.drawPosition)),S=l?.find(({drawPosition:L})=>L===t),T=r?.find(L=>L!==t),P=(T&&h?.find(({drawPosition:L})=>L===T))?.bye,U=g&&P;if(U&&console.log({isByeAdvancedBye:U}),I?.length>1&&g&&!P)return _({result:{error:Wa},stack:c});let E=I?.find(L=>L!==t),A=U,N=[...(u.drawPositions||[]).filter(Boolean),void 0,void 0].slice(0,2),D=N.map(L=>!L&&!A||L===t?(A=!0,t):L).sort(me);if(!A)return console.log("@@@@@@@",{advancingAssignmentIsBye:S,drawPositionToAdvance:t,existingAssignments:h}),_({result:{error:Wa},stack:c});let M=l?.find(({drawPosition:L})=>L===E)?.bye,R=l?.find(({drawPosition:L})=>L===t)?.bye;Object.assign(u,{matchUpStatus:R||M?Nt:Qt,score:void 0,winningSide:void 0,drawPositions:D});let v=u.drawPositions.find(L=>!N.includes(L));Rn({method:c,color:"brightyellow",changedDrawPosition:v,pairedDrawPositionIsBye:M,drawPositionIsBye:R}),gt({tournamentId:n?.tournamentId,matchUp:u,eventId:a?.eventId,context:c,drawDefinition:o});let{targetLinks:{loserTargetLink:O},targetMatchUps:{loserMatchUp:x,loserTargetDrawPosition:F}}=ur({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:o});if(M||R){let L=M?t:E;if(L)hS({drawPositionToAdvance:L,matchUpId:i.matchUpId,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:o,matchUpsMap:s});else if(R&&O&&x)if(x.feedRound)iv({loserTargetDrawPosition:F,tournamentRecord:n,loserTargetLink:O,drawDefinition:o,loserMatchUp:x,matchUpsMap:s});else{let V=1-i.roundPosition%2,k=x.drawPositions[V],W=Hr({structureId:O.target.structureId,drawPosition:k,tournamentRecord:n,drawDefinition:o,event:a});if(W.error)return W}}}function iv({loserTargetDrawPosition:t,tournamentRecord:e,loserTargetLink:r,drawDefinition:n,loserMatchUp:o,matchUpsMap:i,event:s}){let{roundNumber:a}=o;Rn({method:"assignFedDrawPositionBye",color:"cyan",loserTargetDrawPosition:t});let p=(i?.mappedMatchUps||{})[o.structureId].matchUps,{initialRoundNumber:m}=fs({drawPosition:t,matchUps:p});if(m===a){let d=Hr({structureId:r.target.structureId,drawPosition:t,tournamentRecord:e,drawDefinition:n,event:s});if(d.error)return d}}function SS({positionAssignments:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:n,structure:o,event:i}){let{matchUps:s}=Ut({drawDefinition:r,matchUpsMap:n,structure:o,event:i});s.forEach(a=>{let u=t.filter(({drawPosition:p})=>a.drawPositions?.includes(p)).filter(p=>p.bye).length;a.winningSide||(Object.assign(a,{matchUpStatus:u?Nt:Qt}),gt({tournamentId:e?.tournamentId,context:"modifyRoundRobinMatchUpsStatus",eventId:i?.eventId,drawDefinition:r,matchUp:a}))})}function lc(t){let{inContextDrawMatchUps:e,participantId:r,drawPosition:n}=t,{tournamentRecord:o,drawDefinition:i,structureId:s,matchUpsMap:a,event:c}=t,{structure:u}=at({drawDefinition:i,structureId:s}),m=(Se({drawDefinition:i,structure:u}).positionAssignments||[]).find(g=>r&&g.participantId===r||n&&g.drawPosition===n);if(m&&r&&!n&&(n=m?.drawPosition),!n)return{error:Cs};r||(r=m?.participantId);let{activeDrawPositions:d}=Pa({drawDefinition:i,structureId:s});return d.includes(n)?{error:Yu}:(e||({matchUps:e}=se({inContext:!0,drawDefinition:i,matchUpsMap:a})),XU({inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,structureId:s,drawPosition:n,matchUpsMap:a,event:c}).drawPositionCleared?(bo({tournamentId:o?.tournamentId,drawDefinition:i,structure:u,event:c}),{...C,participantId:r}):{error:vA})}function XU({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,matchUpsMap:o,structureId:i,event:s}){let{structure:a}=at({drawDefinition:r,structureId:i});if(!a)return{error:kt};let c=Se({drawDefinition:r,structure:a}).positionAssignments||[],u=c.some(T=>{if(T.drawPosition===n)return delete T.participantId,delete T.qualifier,delete T.bye,!0});if(a.structureType===Ge)return SS({positionAssignments:c,tournamentRecord:e,drawDefinition:r,matchUpsMap:o,structure:a}),{drawPositionCleared:u,...C};let p={isCollectionMatchUp:!1},{matchUps:m}=Ut({drawDefinition:r,matchUpFilters:p,matchUpsMap:o,structure:a,event:s}),{roundProfile:d,roundMatchUps:l}=Ke({matchUps:m}),g=(d&&Object.keys(d))?.map(T=>pt(T)),I=n,S=g?.map(T=>{let P=d?.[T]?.pairedDrawPositions?.find(v=>v.includes(I)),U=P?.find(v=>v!==I),E=c.find(v=>v.drawPosition===U),A=d?.[T+1],N=E?.bye,D=A?.pairedDrawPositions?.find(v=>v.includes(U)),M=N&&D&&A&&A.drawPositions?.includes(U),b=P&&{pairedDrawPositionByeAdvancedPair:!M&&D,pairedDrawPosition:U,targetDrawPosition:I,relevantPair:P,roundNumber:T};return M&&(I=U),b}).filter(T=>T?.targetDrawPosition)?.reduce((T,y)=>{let{roundNumber:P,relevantPair:U,targetDrawPosition:E,pairedDrawPosition:A,pairedDrawPositionByeAdvancedPair:N}=y,D={roundNumber:P,targetDrawPosition:E,relevantPair:U},M=N&&{roundNumber:P+1,targetDrawPosition:A,relevantPair:N,subsequentRoundRemoval:!0},R=[D,M].filter(Boolean);return T.concat(...R)},[]);return S?.forEach(({roundNumber:T,targetDrawPosition:y,relevantPair:P})=>{let U=l?.[T].find(E=>Fe(E.drawPositions?.filter(Boolean),P.filter(Boolean)));U&&(vk({inContextDrawMatchUps:t,targetDrawPosition:y,tournamentRecord:e,drawDefinition:r,structureId:i,roundNumber:T,matchUpsMap:o}),sv({inContextDrawMatchUps:t,positionAssignments:c,tournamentRecord:e,drawDefinition:r,targetMatchUp:U,drawPosition:n,matchUpsMap:o,structure:a,event:s}))}),{tasks:S,drawPositionCleared:u,positionAssignments:c}}function vk({inContextDrawMatchUps:t,targetDrawPosition:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,roundNumber:i,structureId:s}){let{structure:a}=at({drawDefinition:n,structureId:s});if(!a)return{error:kt};if(a.structureType===Ge)return;o=o||Ne({drawDefinition:n});let u=(o?.mappedMatchUps||{})[s].matchUps,{initialRoundNumber:p}=fs({drawPosition:e,matchUps:u}),m=u?.filter(l=>l.roundNumber>=i&&l.roundNumber!==p&&l.drawPositions?.includes(e)),d=bt({drawDefinition:n,structureId:s}).positionAssignments??[];return m?.forEach(l=>sv({drawPosition:e,targetMatchUp:l,inContextDrawMatchUps:t,positionAssignments:d,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,structure:a})),{...C}}function sv({inContextDrawMatchUps:t,positionAssignments:e,tournamentRecord:r,drawDefinition:n,targetMatchUp:o,drawPosition:i,matchUpsMap:s,structure:a,event:c}){let u="removeDrawPosition",p=o.drawPositions?.slice(),m=o.matchUpStatus,d=o.winningSide;s=s??Ne({drawDefinition:n});let f=s.mappedMatchUps[a.structureId].matchUps,{initialRoundNumber:g}=fs({drawPosition:i,matchUps:f});if(o.roundNumber&&g&&o.roundNumber>g){let D=(o.drawPositions??[]).map(M=>M===i?void 0:M);o.drawPositions=D}if(o.matchUpType===jt){let R=(t?.find(b=>b.matchUpId===o.matchUpId)?.sides??[]).reduce((b,v,O)=>v.drawPosition===i?O:b,void 0);R!==void 0&&o.sides?.[R]?.lineUp&&(delete o.sides?.[R].lineUp,gt({tournamentId:r?.tournamentId,context:`${u}-TEAM`,eventId:c?.eventId,matchUp:o,drawDefinition:n}))}let I=ur({matchUpId:o.matchUpId,inContextDrawMatchUps:t,drawDefinition:n}),{targetLinks:{winnerTargetLink:h},targetMatchUps:{loserMatchUp:S,winnerMatchUp:T,loserMatchUpDrawPositionIndex:y}}=I,U=e.filter(({drawPosition:D})=>o.drawPositions?.includes(D)).filter(D=>D.bye).length,E=U&&Nt||o.matchUpStatus&&[Mt,Ct].includes(o.matchUpStatus)&&o.matcHUpStatus||Qt;o.matchUpStatus=E,o.matchUpStatus&&[Ct,Mt].includes(o.matchUpStatus)&&(o.winningSide=void 0);let A=p?.find(D=>!o.drawPositions?.includes(D));if(p?.includes(i)&&m===o.matchUpStatus&&d===o.winningSide||(A&&Rn({method:u,color:"brightyellow",removedDrawPosition:A}),gt({tournamentId:r?.tournamentId,context:`${u}-${i}`,eventId:c?.eventId,matchUp:o,drawDefinition:n})),S&&S.structureId!==I.matchUp.structureId&&!U){let{drawPositions:D,roundNumber:M}=S;if(M===1){let R=D[y];XU({structureId:S.structureId,drawPosition:R,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,matchUpsMap:s})}else{let R=Math.min(...D.filter(Boolean)),b=Ok({loserMatchUpDrawPosition:R,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,loserMatchUp:S,matchUpsMap:s,event:c});if(b.error)return _({result:b,stack:u});let O=(s?.mappedMatchUps||{})[S.structureId].matchUps,{initialRoundNumber:x}=fs({drawPosition:R,matchUps:O});x===1&&(Rn({method:u,color:"brightyellow",loserMatchUpDrawPosition:R}),XU({structureId:S.structureId,drawPosition:R,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:n,matchUpsMap:s}))}}return T&&T.structureId!==I.matchUp.structureId&&(h.target.feedProfile,dn),{...C}}function Ok({loserMatchUpDrawPosition:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,loserMatchUp:o,matchUpsMap:i,event:s}){let{structure:a}=at({structureId:o.structureId,drawDefinition:n}),{positionAssignments:c}=bt({structure:a});if(c?.find(p=>p.drawPosition===t)?.bye){let p=lc({drawPosition:t,structureId:o.structureId,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,matchUpsMap:i,event:s});if(p.error)return p}return{...C}}function Ri({drawDefinition:t,stages:e}){if(!t)return{error:Z};let r=(t?.structures??[]).filter(o=>!e?.length||o.stage&&e.includes(o.stage)),n=ut(r.map(o=>{let{positionAssignments:i}=bt({structure:o});return i?i.map(St):[]}).flat().filter(Boolean));return{...C,assignedParticipantIds:n}}function Kn(t){let e=(t?.entries??[]).filter(Boolean).reduce((n,o)=>{let{entryStage:i,entryStatus:s}=o,a=`_${i||nt}${s||""}`;return n[a]||(n[a]=[]),n[a].push(o),n},{}),r=n=>isNaN(n)?1/0:n;return Object.keys(e).map(n=>e[n].sort((o,i)=>r(o.entryPosition)-r(i.entryPosition)).map((o,i)=>{let s=i+1;return{...o,entryPosition:s}})).flat()}function Ys(t){return[Ei,Gr].includes(t)}function dd({autoEntryPositions:t=!0,ignoreAssignment:e,tournamentRecord:r,drawDefinition:n,participantIds:o,entryStatus:i,entryStage:s,extension:a,eventSync:c,drawId:u,stage:p,event:m}){if(!o||!Array.isArray(o))return{error:mn,method:"modifyEntriesStatus",participantIds:o};if(!n&&!m)return{error:vt};if(i&&!VU.includes(i))return{error:zl};if(s&&!$c.includes(s))return{error:Oi};let d="modifyEntriesStatus",l=[];if(!i&&!a)return _({result:{error:st},info:"Missing entryStatus",stack:d});if(a&&!wn({extension:a,requiredAttributes:["name"]}))return _({result:{error:G},info:"Invalid extension",context:{extension:a},stack:d});let f=[];m?.drawDefinitions?.forEach(D=>{let M=Ri({stages:p&&[p],drawDefinition:D}).assignedParticipantIds??[];f.push(...M)});let g=r?.participants??[];if(!o.every(D=>{let M=Go({tournamentParticipants:g,participantId:D})?.participantType;return!(M&&[ft,yr].includes(M)&&Ys(i))&&!(i&&m?.eventType&&M===Tt&&[qr,Cr].includes(m.eventType)&&[nn,...Xf].includes(i))}))return{error:zl};let h=m&&Ht({event:m}).flightProfile,S=h?.flights?.find(D=>D.drawId===u),T=D=>{let M=(D||[]).filter(v=>!p||!v.entryStage||p===v.entryStage).filter(({participantId:v})=>o.includes(v)),R=v=>i&&f.includes(v.participantId)&&!(Xf.includes(v.entryStatus)&&Xf.includes(i));return M.every(v=>R(v)&&!e?!1:(i&&(v.entryStatus=i,delete v.entryPosition),s&&(v.entryStage=s,delete v.entryPosition),a&&(a.value?At({element:v,extension:a}):gr({element:v,name:a.name})),!0))?{...C}:{error:vs}},y=({flight:D,drawDefinition:M})=>{m&&(m.entries=Kn({entries:m.entries??[]})),D&&(D.drawEntries=Kn({entries:D.drawEntries})),M&&(M.entries=Kn({entries:M.entries}))},P=D=>{let{flight:M,drawDefinition:R}=D,b="updateDrawEntries";if(M){let v=T(M.drawEntries);if(v.error)return _({result:v,stack:b})}if(R){let v=T(R.entries);if(v.error)return _({result:v,stack:b});l.includes(R.drawId)||l.push(R.drawId)}return{...C}},U=m?.entries?.find(({entryPosition:D})=>D)??(S?.drawEntries?.find(({entryPosition:D})=>D)||n?.entries?.find(({entryPosition:D})=>D));if(t&&!U&&y({flight:S,drawDefinition:n}),S||n){let D=P({flight:S,drawDefinition:n});if(D.error)return _({result:D,stack:d})}let E=m?.drawDefinitions?.map(({drawId:D})=>D)??[],A=h?.flights?.filter(D=>!E.includes(D.drawId))||[];for(let D of A){let M=D&&P({flight:D});if(M?.error)return _({result:M,stack:d})}let N=h?.flights?.length===1&&(m?.drawDefinitions?.length??0)<=h?.flights?.length;if(!S&&!n&&i&&GU.includes(i))return{error:lE};if(!S&&!n||i===io||c&&N){let D=T(m?.entries);if(D?.error)return _({result:D,stack:d});let M;if(i===io&&(h?.flights?.every(R=>{let b=T(R.drawEntries);return b.error?(M=b.error,!1):(R.drawEntries=R.drawEntries.filter(({participantId:v})=>!o.includes(v)),!0)}),m?.drawDefinitions?.every(R=>{let b=T(R.entries);return b.error?(M=b.error,!1):(R.entries=R.entries?.filter(({participantId:v})=>!o.includes(v)),!0)})),M)return _({result:{error:M},stack:d})}t&&y({flight:S,drawDefinition:n});for(let D of m?.drawDefinitions??[])l.length&&!l.includes(D.drawId)||Ot({tournamentId:r.tournamentId,eventId:m?.eventId,drawDefinition:D});return{...C}}function yo({requireTimeStamp:t,scaleAttributes:e,participant:r}){if(!r)return{error:wi};if(!ht(e))return{error:G};if(r.timeItems||(r.timeItems=[]),Array.isArray(r.timeItems)){let{accessor:n,scaleType:o,eventType:i,scaleName:s}=e,a=[Ii,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!==Ii)return{error:Ka};let g=(n&&ls({element:u.itemValue,accessor:n}))?.value||u.itemValue,I={eventType:d,scaleDate:u.itemDate,scaleValue:g,scaleName:l,scaleType:m};return{...C,scaleItem:I}}}return{...C,scaleItem:void 0}}function av({publishedSeeding:t,usePublishState:e,withSeeding:r,participant:n,event:o}){let i={},s=m=>[Ii,ho,o.eventType,m].join("."),a=Object.assign({},...(n.timeItems||[]).filter(({itemType:m})=>m.split(".")[1]===ho).map(({itemType:m,itemValue:d})=>({[m]:d}))),c=(t?.stageSeedingScaleNames&&Object.values(t?.stageSeedingScaleNames)||Array.isArray(t?.seedingScaleNames)&&t.seedingScaleNames||[]).map(s),u=Yt(Object.keys(a),c);if(!!(!e||!Object.keys(a).length&&!t?.drawIds?.length||u.length)&&u.length){if(t?.stageSeedingScaleNames){let m=Object.keys(t.stageSeedingScaleNames).map(l=>{let f=s(t.stageSeedingScaleNames[l]),g=a[f];return[l,g]}).filter(l=>l[1]).map(l=>({[l[0]]:{seedValue:l[1]}})),d=Object.assign({},...m);i.seedAssignments=d}else if(u){let m=u.map(d=>a[d]);i.seedValue=m.pop()}}else if(!e&&typeof r=="object"){let m=Object.keys(r).map(l=>{let f=s(r[l]),g=a[f];return[l,g]}).filter(l=>l[1]).map(l=>({[l[0]]:{seedValue:l[1]}})),d=Object.assign({},...m);i.seedAssignments=d}else{let{categoryName:m,ageCategoryCode:d}=o.category||{},l=[d,o.eventId,m].filter(Boolean),f;for(let g of l){let I={eventType:o.eventType,scaleType:ho,scaleName:g},h=yo({scaleAttributes:I,participant:n});if(h.scaleItem){f=h.scaleItem;break}}if(f&&(!e||t?.published&&!t?.published?.drawIds?.length)){let I=f.scaleValue;i.seedValue=I}}return i}function cv({convertExtensions:t,seedAssignments:e,participant:r,withSeeding:n,seedValue:o,eventId:i,ranking:s,entry:a}){let{entryStatus:c,entryStage:u,entryPosition:p,extensions:m}=a,d=m?.length&&t?Object.assign({},...Sf(m??[])):{},l=Object.assign(d,{entryPosition:p,entryStatus:c,entryStage:u,ranking:s,eventId:i});r.events[i]=ot(l,!1,!1,!0),n&&(e&&(r.events[i].seedAssignments=e),o&&(r.events[i].seedValue=o))}function TS(t){let{participantMap:e,participantId:r,matchUpStatus:n,roundPosition:o,structureId:i,matchUpType:s,roundNumber:a,matchUpId:c,potential:u,schedule:p,drawId:m,score:d}=t;if(!p||!Object.keys(p).length)return;n===Nt||e[r].scheduleItems.push({...p,scheduledDate:Et(p?.scheduledDate),scheduledTime:Kt(p?.scheduledTime),checkScoreHasValue:Ie({score:d}),matchUpStatus:n,roundPosition:o,structureId:i,matchUpType:s,roundNumber:a,matchUpId:c,potential:u,drawId:m})}function Su(t){let e=rt(t,[{[ie]:!0}]);if(e.error)return e;let{tournamentRecord:r,status:n=Nr}=t,o=`${_o}.${xo}`;return J(Jm({tournamentRecord:r,itemType:o})?.timeItem?.itemValue?.[n],!1,!0)}function uv(t){let{tournamentId:e}=t??{};return!!e}function Xr({event:t,status:e=Nr}){let r=`${_o}.${xo}`;return du({itemType:r,event:t})?.timeItem?.itemValue?.[e]}function ld({drawDetails:t,drawId:e}){return t?.[e]?.publishingDetail?.published}function gs(t){let{tournamentRecord:e,drawDefinition:r,eventIds:n,eventId:o,drawIds:i,drawId:s,event:a}=t??{};if(e&&!uv(e))return{error:G};if(o&&!a)return{error:jr};if(Array.isArray(n)&&n?.length){let m={};for(let d of n){if(!Vt(d))return{error:G};let l=ze({tournamentRecord:e,eventId:d})?.event;if(!l)return{error:jr};let f=JU({event:l});m[d]=f}return{...C,publishState:m}}if(a){let m=JU({event:a}),d={};if(s)return r?{publishState:{status:{published:!!m.status.publishedDrawIds?.includes(s),drawDetail:m.status.drawDetails?.[s]},...C}}:{error:Mr};if(Array.isArray(i)&&i?.length){let l=a.drawDefinitions?.map(su)??[];for(let f of i){if(!Vt(f))return{error:G};if(!l.includes(f))return{error:Mr};d[f]={status:{published:!!m.status.publishedDrawIds.includes(f),drawDetail:m.status.drawDetails?.[f]}}}}else d=m;return{...C,publishState:d}}let c=[],u=!1,p={};for(let m of e?.events??[]){let d=JU({event:m});p[m.eventId]=d,d.status.published&&(c.push(m.eventId),u=!0);for(let{drawId:l}of m.drawDefinitions??[]){let f=d.status?.publishedDrawIds?.includes(l);f&&(p[l]={status:{published:f}})}}if(e){let m=Su({tournamentRecord:e});p.tournament=m??{},(m?.orderOfPlay?.published||m?.participants?.published)&&(u=!0),p.tournament.status={published:u,publishedEventIds:c}}return{...C,publishState:p}}function JU({event:t}){let e=Xr({event:t});if(!e)return{status:{published:!1}};let r={published:void 0,seedingScaleNames:[],drawIds:[]};e.seeding&&Object.assign(r,e.seeding);let n=e.drawDetails??{};for(let a of t.drawDefinitions?.map(su)||[])n[a]||(n[a]={publishingDetail:{published:!1}});let o=n&&Object.keys(n).length&&Object.keys(n).filter(a=>ld({drawDetails:n,drawId:a})),i=o?.length?o:e.drawIds??[];if(i?.length&&!o?.length)for(let a of i)n[a]={publishingDetail:{published:!0}};let s=i?.length>0;return{status:{publishedDrawIds:i,publishedSeeding:r,drawDetails:n,published:s}}}function Tu(t,e){return(t||"").localeCompare(e||"")}function pv({finishingPositionRange:t={},participantMap:e,finishingRound:r,participantWon:n,matchUpStatus:o,participantId:i,stageSequence:s,roundNumber:a,structureId:c,matchUpId:u,drawId:p,stage:m}){let d=e[i],l=S=>Math.abs(S[0]-S[1]);d.structureParticipation[c]||(d.structureParticipation[c]={rankingStage:m,walkoverWinCount:0,defaultWinCount:0,stageSequence:s,winCount:0,structureId:c,drawId:p});let f=d.structureParticipation[c],{winner:g,loser:I}=t,h=n?g:I;n&&(f.winCount+=1,o===Ct&&(f.walkoverWinCount+=1),o===Mt&&(f.defaultWinCount+=1)),h&&(!f.finishingPositionRange||l(h)<l(f.finishingPositionRange))&&(f.finishingPositionRange=h),r&&((!f.finishingRound||r<f.finishingRound)&&(f.finishingMatchUpId=u,f.finishingRound=r,f.roundNumber=a),r===1&&(f.participantWon=n))}function ZU(t){let{withScheduleItems:e,scheduleAnalysis:r,withTeamMatchUps:n,participantMap:o,withOpponents:i,withMatchUps:s,withEvents:a,withDraws:c,finishingPositionRange:u,finishingRound:p,matchUpStatus:m,stageSequence:d,roundNumber:l,structureId:f,score:g,stage:I,withRankingProfile:h,tieWinningSide:S,roundPosition:T,matchUpTieId:y,matchUpSides:P,collectionId:U,matchUpType:E,winningSide:A,matchUpId:N,schedule:D,eventId:M,drawId:R,sides:b}=t,v=i&&b?.length===2&&Object.assign({},...b.map(({sideNumber:O},x)=>{let F=b[1-x].participantId;return O&&{[O]:F}}).filter(Boolean));for(let O of b){let{participantId:x,sideNumber:F,bye:L}=O;if(L)continue;let w=A===F,V=H=>{let K=o[H]?.participant,q=K?.participantType,B=[{participantId:H,participantType:q}];if(q!==yr)for(let $ of K?.individualParticipantIds||[]){let z=o[$]?.participant;B.push({participantType:z?.participantType,participantId:$})}return B},k=(H,K)=>{if(s){if(o[H].matchUps[N]={participantWon:w,matchUpType:E,structureId:f,sideNumber:F,matchUpId:N,eventId:M,drawId:R,stage:I},i){let q=V(K);o[H].matchUps[N].opponentParticipantInfo=q}U&&(o[H].matchUps[N].collectionId=U)}i&&K&&(o[H].opponents[K]={participantId:K,matchUpId:N,eventId:M,drawId:R}),h&&pv({finishingPositionRange:u,participantMap:o,participantWon:w,finishingRound:p,matchUpStatus:m,participantId:H,stageSequence:d,roundNumber:l,structureId:f,matchUpId:N,drawId:R,stage:I}),(r||e)&&TS({participantMap:o,participantId:H,matchUpStatus:m,roundPosition:T,matchUpType:E,roundNumber:l,structureId:f,matchUpId:N,schedule:D,drawId:R,score:g})},W=({participant:H,partnerParticipantId:K})=>{let q=(B,$)=>{B&&(B.partnerParticipantIds||(B.partnerParticipantIds=[]),B.partnerParticipantIds.includes($)||B.partnerParticipantIds.push($))};c&&q(H?.draws?.[R],K),a&&q(H?.events?.[M],K),s&&q(H?.matchUps?.[N],K)};if(x&&o[x]){let H=v?.[F];k(x,H);let K=o[x]?.participant.participantType===ft,q=o[x]?.participant.individualParticipantIds||[];if(y){if(n){let B=$=>o[$].matchUps[y]={participantWon:S===F,matchUpId:y,matchUpType:jt,sideNumber:F};B(x),q.forEach(B)}if(c&&!o[x].draws[R]){let B=P.find(j=>j.sideNumber===F)?.participant?.participantId,$=o[B]?.draws?.[R]?.entryStatus,z=j=>o[j].draws[R]={entryStatus:$,eventId:M,drawId:R};z(x),q.forEach(z)}}if(K&&(q.forEach(B=>o[B]&&k(B,H)),q.forEach((B,$)=>{let z=q[1-$],j=o[B];j&&W({participant:j,partnerParticipantId:z})}),a&&P)){let B=P.find($=>$.sideNumber===F)?.participant?.participantId;if(B){let $=o[B]?.events[M];$?(o[x].events[M]={...$},q.forEach(z=>o[z].events[M]={...$})):console.log("Missing teamEntry",{eventId:M,teamParticipantId:B})}}if(A){let B=$=>{w?(o[$].counters[E].wins+=1,o[$].counters.wins+=1,m===Ct&&(o[$].counters[E].walkoverWins+=1,o[$].counters.walkoverWins+=1),m===Mt&&(o[$].counters[E].defaultWins+=1,o[$].counters.defaultWins+=1)):(o[$].counters[E].losses+=1,o[$].counters.losses+=1,m===Ct&&(o[$].counters[E].walkovers+=1,o[$].counters.walkovers+=1),m===Mt&&(o[$].counters[E].defaults+=1,o[$].counters.defaults+=1))};B(x),q.forEach(B)}}}}function mv(t){let{participantFilters:e,convertExtensions:r,policyDefinitions:n,tournamentRecord:o,usePublishState:i,participantMap:s,contextProfile:a,withPotentialMatchUps:c,withRankingProfile:u,withScheduleItems:p,scheduleAnalysis:m,withTeamMatchUps:d,withStatistics:l,withOpponents:f,withMatchUps:g,withSeeding:I,withEvents:h,withDraws:S}=t,T=e?.participantIds,y=b=>{let v=[b];return s[b]?.participant.individualParticipantIds?.forEach(O=>v.push(O)),v.some(O=>!T?.length||T.includes(O))?v:[]},P={withMatchUps:g||u,withEvents:h||u,withDraws:S||u,withPotentialMatchUps:c,withRankingProfile:u,withScheduleItems:p,scheduleAnalysis:m,withTeamMatchUps:d,withStatistics:l,participantMap:s,withOpponents:f,withSeeding:I},U=[],E={},A=[],N={},D={},M={},R=({eventType:b,scaleNames:v,participantId:O})=>s[O]?.participant?.rankings?.[b]?.find(x=>v.includes(x.scaleName))?.scaleValue;for(let b of o?.events||[]){if(e?.eventIds&&!e.eventIds.includes(b.eventId))continue;let{drawDefinitions:v=[],extensions:O=[],eventType:x,eventName:F,category:L,entries:w,eventId:V,gender:k}=b,{flightProfile:W}=Ht({event:b}),H=W?.flights??[],K=gs({event:b}).publishState;K&&(N[V]=K);let q=K?.status?.publishedSeeding;if(h||I||u){let $=r?Object.assign({},...Sf(O??[])):{};D[V]={...$,eventName:F,eventType:x,category:L,eventId:V,gender:k};let z=[L?.categoryName,L?.ageCategoryCode].filter(Boolean);for(let j of w){let{participantId:tt}=j;if(!tt||!s[tt])continue;let Q=R({eventType:x,scaleNames:z,participantId:tt}),X,lt;if(I){let Ft=s[tt].participant;({seedAssignments:X,seedValue:lt}=av({publishedSeeding:q,usePublishState:i,withSeeding:I,participant:Ft,event:b}))}let it=Ft=>{if(s[Ft]?.events?.[V])return;let Ue=s[Ft];cv({convertExtensions:r,seedAssignments:X,participant:Ue,withSeeding:I,seedValue:lt,eventId:V,ranking:Q,entry:j})};it(tt),(s[tt].participant.individualParticipantIds||[]).forEach(it)}}let B=N?.[V]?.publishedSeeding;if(S||u||I){let $=j=>j?Object.assign({},...j.map(({participantId:tt,seedValue:Q,seedNumber:X})=>({[tt]:{seedValue:Q,seedNumber:X}}))):void 0,z=ut([...v.map(su),...H.map(su)]);for(let j of z){let tt=v.find(zt=>zt.drawId===j),Q=[L?.categoryName,L?.ageCategoryCode].filter(Boolean),{structures:X=[],drawOrder:lt,drawName:it,drawType:Rt}=tt??{},Ft=H?.find(zt=>zt.drawId===j),Ue=tt?.entries||Ft?.drawEntries,fe=Ft?.flightNumber,Me=(tt?.structures||[]).sort((zt,pe)=>Si(zt,pe)).map(({structureId:zt,structures:pe})=>[zt,...(pe||[]).map(({structureId:Pe})=>Pe)]).flat(1/0),vr,Zr,lr,Xe,ee=0,Pt=X.filter(({stage:zt,stageSequence:pe})=>zt===nt&&pe===1||zt===ct).flatMap(zt=>{let{positionAssignments:pe}=bt({structure:zt}),{seedAssignments:Pe,stageSequence:Or,stage:Je}=zt;return Je===nt?(ee=pe?.length??0,lr=pe,Xe=Pe):Or===1&&(vr=pe,Zr=Pe),pe}).map(({participantId:zt})=>zt).filter(Boolean),ae=$(Xe),re=$(Zr),pr=tt?Ue.filter(({participantId:zt})=>Pt.includes(zt)):Ue,Jt=!i||B?.published&&(B?.drawIds?.length===0||B?.drawIds?.includes(j));for(let zt of pr){if(!s[zt.participantId])continue;let{entryStatus:pe,entryStage:Pe,entryPosition:Or,participantId:Je}=zt,De=R({participantId:Je,scaleNames:Q,eventType:x}),Ee=ge=>{if(!s[ge]||s[ge].draws?.[j])return;let _r=I&&Jt,fr=_r?{}:void 0,uo=_r?ae?.[Je]?.seedValue||ae?.[Je]?.seedNumber:void 0,be=uo?ae?.[Je]:void 0,Ar=_r?re?.[Je]?.seedValue||re?.[Je]?.seedNumber:void 0,Zi=Ar?re?.[Je]:void 0;fr&&uo&&(fr[nt]=be),fr&&Ar&&(fr[ct]=Zi);let Tn=uo||Ar;Tn&&(s[ge].participant.seedings[x]||(s[ge].participant.seedings[x]=[]),be&&s[ge].participant.seedings[x].push({...be,scaleName:j}),Zi&&s[ge].participant.seedings[x].push({...Zi,scaleName:j}),fr&&(s[ge].events[V].seedAssignments||(s[ge].events[V].seedAssignments={}),Object.keys(fr).forEach(ts=>s[ge].events[V].seedAssignments[ts]=fr[ts]))),(S||u)&&(s[ge].draws[j]=ot({seedAssignments:fr,entryPosition:Or,entryStatus:pe,entryStage:Pe,seedValue:Tn,eventId:V,ranking:De,drawId:j},!1,!1,!0))};[Gr,Ei].includes(pe)||(Ee(Je),(s[Je].participant.individualParticipantIds||[])?.forEach(Ee))}let Wt=(tt?.structures??[]).reduce((zt,pe)=>(zt.includes(pe.stage)||zt.push(pe.stage),zt),[]),mr=(tt?.links??[]).length;M[j]={qualifyingPositionAssignments:vr,qualifyingSeedAssignments:Zr,mainPositionAssignments:lr,qualifyingSeedingMap:re,mainSeedAssignments:Xe,orderedStructureIds:Me,mainSeedingMap:ae,flightNumber:fe,linksCount:mr,drawOrder:lt,drawName:it,drawType:Rt,drawSize:ee,drawId:j,stages:Wt}}}if(u||m||d||l||f||g||S){let $=!!m||c,z=$n({afterRecoveryTimes:!!m,policyDefinitions:n,tournamentRecord:o,inContext:!0,contextProfile:a,participantMap:s,nextMatchUps:$,event:b})?.matchUps??[];for(let j of z){let{finishingPositionRange:tt,potentialParticipants:Q,tieMatchUps:X=[],sides:lt=[],winningSide:it,matchUpType:Rt,matchUpId:Ft,eventId:Ue,drawId:fe,collectionId:Me,stageSequence:vr,finishingRound:Zr,matchUpStatus:lr,roundPosition:Xe,roundNumber:ee,structureId:Pt,schedule:ae,score:re,stage:pr}=j;E[Ft]=j;let Jt={finishingPositionRange:tt,finishingRound:Zr,stageSequence:vr,roundPosition:Xe,collectionId:Me,roundNumber:ee,structureId:Pt,schedule:ae,eventId:Ue,drawId:fe,score:re,stage:pr};ZU({...Jt,...P,matchUpStatus:lr,winningSide:it,matchUpType:Rt,matchUpId:Ft,sides:lt});for(let Wt of X){let{winningSide:mr,sides:zt=[],matchUpId:pe,matchUpStatus:Pe,matchUpType:Or}=Wt;ZU({...Jt,...P,winningSide:mr,tieWinningSide:it,matchUpTieId:Ft,matchUpId:pe,sides:zt,matchUpSides:lt,matchUpStatus:Pe,matchUpType:Or})}Array.isArray(Q)&&($||m||p)&&Q.flat().map(St).filter(Boolean)?.forEach(mr=>{y(mr)?.forEach(pe=>{s[pe]&&(s[pe].potentialMatchUps[Ft]=ot({tournamentId:o?.tournamentId,matchUpId:Ft,eventId:Ue,drawId:fe}))}),(m||p)&&TS({potential:!0,participantMap:s,participantId:mr,matchUpStatus:lr,roundPosition:Xe,structureId:Pt,matchUpType:Rt,roundNumber:ee,matchUpId:Ft,schedule:ae,drawId:fe,score:re})})}A.push(...z)}}if(l||u||m){let b=Object.values(s);for(let v of b){let{wins:O,losses:x,[xt]:{wins:F,losses:L},[_t]:{wins:w,losses:V}}=v.counters,k=(W,H,K)=>{let q=H+K,B=H,$=q&&B/q;v.statistics[W]={denominator:q,numerator:B,statValue:$,statCode:W}};if(l&&(k(td,O,x),k(`${td}.${xt}`,F,L),k(`${td}.${_t}`,w,V)),u){let W=(H=[])=>Math.abs(H[0]-H[1]);for(let H of Object.keys(v.draws)){let{orderedStructureIds:K=[],flightNumber:q}=M[H]||{};if(v.structureParticipation&&K.length){let B,$=0,z=K.map(j=>{let tt=v.structureParticipation[j];if(!tt)return;B||(B=tt?.finishingPositionRange),W(B)>W(tt?.finishingPositionRange)&&(B=tt?.finishingPositionRange);let Q=tt.stage!==ct;return Q&&($+=1),ot({...tt,participationOrder:Q?$:void 0,flightNumber:q})}).filter(Boolean);v.draws[H]&&(v.draws[H].finishingPositionRange=B,v.draws[H].structureParticipation=z)}}}if(m){let W=ht(m)?m.scheduledMinutesDifference:0,H=v.scheduleItems||[],K=v.potentialMatchUps||{},q=H.reduce(($,z)=>{let{scheduledDate:j,scheduledTime:tt}=z;return $[j]||($[j]=[]),tt&&$[j].push(z),$},{});Object.values(q).forEach($=>$.sort(XI));for(let $ of H){let{typeChangeTimeAfterRecovery:z,timeAfterRecovery:j,scheduledDate:tt,scheduledTime:Q}=$,X=q[tt],lt=qt(Q);for(let it of X){if(it.matchUpId===$.matchUpId||[Ct,Mt].includes(it.matchUpStatus)&&!it.checkScoreHasValue)continue;let Ue=$.matchUpType!==it.matchUpType&&z||j,fe=$.drawId===it.drawId,Me=K[$.matchUpId]&&K[it.matchUpId],vr=qt(it.scheduledTime),Zr=Math.abs(vr-lt),lr=vr>=lt;if((W&&!isNaN(W)?Zr<=W:lr&&qt(it.scheduledTime)<qt(Ue))&&!(Me&&fe)&&lr){let ee=[$.matchUpId,it.matchUpId].sort(Tu).join("|");v.scheduleConflicts[ee]={priorScheduledMatchUpId:$.matchUpId,matchUpIdWithConflict:it.matchUpId}}}}let B=v.participant.participantId;Object.keys(v.scheduleConflicts).length&&U.push(B),s[B].scheduleConflicts=v.scheduleConflicts}}}return{participantIdsWithConflicts:U,eventsPublishStatuses:N,derivedEventInfo:D,derivedDrawInfo:M,mappedMatchUps:E,participantMap:s,matchUps:A}}function yu({participantFilters:t={},tournamentRecord:e,participants:r=[]}){if(!Object.keys(t).length)return r;let{accessorValues:n,drawEntryStatuses:o,positionedParticipants:i,eventEntryStatuses:s,participantRoles:a,participantRoleResponsibilities:c,participantTypes:u,participantIds:p,signInStatus:m,enableOrFiltering:d,eventIds:l,genders:f}=t,g=qs(l)&&e?.events?.filter(y=>l?.includes(y.eventId))||e?.events||[],I=o&&_k({drawEntryStatuses:o,tournamentEvents:g}),h=s&&xk({eventEntryStatuses:s,tournamentEvents:g}),S=i!==void 0&&[!0,!1].includes(i)&&g.reduce((y,P)=>y.concat(...(P.drawDefinitions||[]).map(U=>Bh({drawDefinition:U}).allPositionedParticipantIds).filter(Boolean)),[]),T=y=>n?.reduce((P,U)=>{let{accessor:E,value:A}=U,{values:N}=ls({element:y,accessor:E});return P&&N?.includes(A)},!0);if(r=r?.filter(y=>{let P=rn({element:y,itemType:sc})?.timeItem?.itemValue,{participantRoleResponsibilities:U,participantType:E,participantRole:A,participantId:N,person:D}=y,M=Array.isArray(f)&&f?.length&&D?.sex&&f.includes(D.sex);return d?f&&M||i&&S.includes(N)||i===!1&&!S.includes(N)||I?.includes(N)||h?.includes(N)||p?.includes(N)||m&&P===m||u&&E&&qs(u)&&u.includes(E)||a&&A&&qs(a)&&a.includes(A)||c&&qs(U)&&qs(c)&&c.find(R=>U?.includes(R))||n?.length&&qs(n)&&T(y):(!f||M)&&(i===void 0||i&&S.includes(N)||i===!1&&!S.includes(N))&&(!I||I.includes(N))&&(!h||h.includes(N))&&(!p||p.includes(N))&&(!m||P===m)&&(!u||E&&qs(u)&&u.includes(E))&&(!a||A&&qs(a)&&a.includes(A))&&(!c||qs(U)&&qs(c)&&c.find(R=>U?.includes(R)))&&(!n?.length||qs(n)&&T(y))}),g.length&&l){let y=g.filter(P=>l.includes(P.eventId)).map(P=>{let U=(P.entries||[]).map(A=>A.participantId);if(ue(jn)(P.eventType))return U;let E=(e?.participants??[]).filter(A=>U.includes(A.participantId)).map(A=>A.individualParticipantIds).flat(1);return U.concat(...E)}).flat(1);r=r?.filter(P=>y.includes(P.participantId))}return r}function qs(t){return t&&Array.isArray(t)&&t.length}function _k({drawEntryStatuses:t,tournamentEvents:e}){let r=({entryStatus:n})=>Array.isArray(t)?t.includes(n):!0;return ut(e.reduce((n,o)=>{let{flightProfile:i}=Ht({event:o}),s=i?.flights?.map(({drawEntries:c})=>Array.isArray(c)?c.filter(r).map(St):[]).flat()||[],a=o.drawDefinitions?.map(({entries:c})=>c?c.filter(r).map(St):[])||[];return n.concat(...s,...a)},[]))}function xk({eventEntryStatuses:t,tournamentEvents:e}){return ut(e.reduce((r,n)=>{let o=(n.entries||[]).filter(({entryStatus:i})=>Array.isArray(t)?t.includes(i):!0).map(St);return r.concat(...o)},[]))}function Gt(t){let{withIndividualParticipants:e,participantFilters:r={},withPotentialMatchUps:n,withRankingProfile:o,convertExtensions:i,policyDefinitions:s,withScheduleItems:a,tournamentRecord:c,scheduleAnalysis:u,withSignInStatus:p,withTeamMatchUps:m,withScaleValues:d,usePublishState:l,contextProfile:f,withStatistics:g,withOpponents:I,withMatchUps:h,internalUse:S,withSeeding:T,withEvents:y,withDraws:P,withISO2:U,withIOC:E}=t;if(!c)return{error:Y};(h||o)&&sn({tournamentRecord:c});let A=Xh({convertExtensions:i,tournamentRecord:c,withSignInStatus:p,withScaleValues:d,internalUse:S,withISO2:U,withIOC:E}),{participantMap:N}=A,D=mv({withMatchUps:h??o,withEvents:y??o,withDraws:P??o,withPotentialMatchUps:n,participantFilters:r,withRankingProfile:o,convertExtensions:i,withScheduleItems:a,policyDefinitions:s,tournamentRecord:c,scheduleAnalysis:u,withTeamMatchUps:m,usePublishState:l,withStatistics:g,participantMap:N,withOpponents:I,contextProfile:f,withSeeding:T}),{participantIdsWithConflicts:M,eventsPublishStatuses:R,derivedEventInfo:b,derivedDrawInfo:v,mappedMatchUps:O}=D,x=D.matchUps;N=D.participantMap;let F=u??n,L=({potentialMatchUps:q,scheduleConflicts:B,scheduleItems:$,participant:z,statistics:j,opponents:tt,matchUps:Q,events:X,draws:lt})=>{let it=Object.values(lt),Rt=Object.values(tt);return I&&it?.forEach(Ft=>{Ft.opponents=Rt.filter(Ue=>Ue.drawId===Ft.drawId)}),ot({...z,scheduleConflicts:u?Object.values(B):void 0,draws:P||o?it:void 0,events:y||o?Object.values(X):void 0,matchUps:h||o?Object.values(Q):void 0,opponents:I?Rt:void 0,potentialMatchUps:F?Object.values(q):void 0,statistics:g?Object.values(j):void 0,scheduleItems:a?$:void 0},!1,!1,!0)},w=new Map;for(let q of Object.keys(N))w.set(q,L(N[q]));let V=[...w.values()],W=s?.[Vs]?.participant,H=yu({participants:V,participantFilters:r,tournamentRecord:c});if(e){let q=ht(e)?e:void 0;for(let B of H)for(let $ of B.individualParticipantIds??[]){let z=N[B.participantId].participant;z?.individualParticipants||(z.individualParticipants=[]),B.individualParticipants||(B.individualParticipants=[]);let j=w.get($),tt=q?Vi({template:q,source:j}):j;z?.individualParticipants&&z.individualParticipants.push(tt),B.individualParticipants.push(tt)}}let K=W?H.map(q=>Vi({source:q,template:W})):H;return{participantMap:t.returnParticipantMap!==!1?N:void 0,mappedMatchUps:t.returnMatchUps!==!1?O:void 0,matchUps:t.returnMatchUps!==!1?x:void 0,missingParticipantIds:A.missingParticipantIds,participantIdsWithConflicts:M,eventsPublishStatuses:R,derivedEventInfo:b,derivedDrawInfo:v,participants:K,...C}}function fc({participantId:t,drawDefinition:e,entryStatus:r,entryStage:n}){if(!e)return{error:Z};let o=e.entries?.find(i=>i.participantId===t&&(!r||r===i.entryStatus)&&(!n||n===i.entryStage));return t&&o}function Is(t){let{provisionalPositioning:e,drawDefinition:r,stageSequence:n,structureId:o,stage:i}=t;if(!r)return{error:Z};let{entryProfile:s}=lu({drawDefinition:r}),a=i&&n&&s?.[i]?.stageSequence?.[n]?.qualifiersCount||i&&s?.[i]?.qualifiersCount||0,c={};if(!o)return{qualifiersCount:a,roundQualifiersCounts:c};let{structure:u}=at({drawDefinition:r,structureId:o}),p=r.links?.filter(l=>l?.target?.structureId===u?.structureId),m=0;if(p?.length)for(let l of p){let f=at({structureId:l.source.structureId,drawDefinition:r})?.structure;if(f?.stage===ct){let g=l.source.roundNumber,I=l.target.roundNumber,h=0;if(f.structureType===Ge){let S=f.structures?.length??0,T=l.source.finishingPositions?.length??0;h=S*T}else h=Ut({matchUpFilters:{roundNumbers:[g]},structure:f,afterRecoveryTimes:!1,provisionalPositioning:e,inContext:!1}).matchUps?.length||0;c[I]||(c[I]=0),c[I]+=h,m+=h}}let d=Object.keys(c);if(d.length<=1){let l=d[0]||1;c[l]=Math.max(c[l]||0,a)}return m=Math.max(m,a),{qualifiersCount:m,roundQualifiersCounts:c}}function Mp({stage:t,drawDefinition:e}){let{entryProfile:r}=lu({drawDefinition:e});return r?.[t]?.drawSize||0}function dv(t){let{provisionalPositioning:e,drawDefinition:r,stageSequence:n,stage:o}=t,i=Mp({stage:o,drawDefinition:r}),{qualifiersCount:s}=Is({provisionalPositioning:e,drawDefinition:r,stageSequence:n,stage:o});return i&&i-s}function tP({stage:t,drawDefinition:e}){return!!(t===$e||Jf({stage:t,drawDefinition:e})&&Mp({stage:t,drawDefinition:e}))}function eP({entryStatus:t=kr,drawDefinition:e,stageSequence:r,stage:n}){if(t===nn)return Pb({stage:n,drawDefinition:e})?{positionsAvailable:1/0,...C}:{error:dE};let o=dv({drawDefinition:e,stageSequence:r,stage:n}),i=Db({drawDefinition:e,stage:n}),s=Zh({entryStatus:fu,drawDefinition:e,stage:n}),a=Zh({entryStatus:kr,drawDefinition:e,stage:n}),c=s+a,u=c>=o,p=o-c;return n!==$e&&u?{error:BI}:t===fu?s<i?{...C}:{error:BI}:{positionsAvailable:p,...C}}function fd(t){let e=rt(t,[{[Ve]:!0,[Nh]:!0}]);if(e.error)return e;let{suppressDuplicateEntries:r=!0,entryStatus:n=kr,entryStageSequence:o,entryStage:i=nt,ignoreStageSpace:s,drawDefinition:a,entryPosition:c,participant:u,roundTarget:p,extensions:m,extension:d,drawType:l,event:f}=t,g="addDrawEntry";if(l!==$r&&!tP({stage:i,drawDefinition:a}))return _({result:{error:Oi},stack:g});let I=eP({stageSequence:o,stage:i,drawDefinition:a,entryStatus:n});if(!s&&!I.success&&(!l||l!==$r))return{error:I.error};if(d&&!wn({extension:d}))return _({result:{error:G},info:"Invalid extension",context:{extension:d},stack:g});let h=t.participantId||u?.participantId;if(!h)return _({result:{error:oe},stack:g});let S=n===cs&&fc({participantId:h,drawDefinition:a,entryStatus:n}),T=i===$e&&fc({participantId:h,drawDefinition:a,entryStage:i}),y=fc({participantId:h,drawDefinition:a}),P=n!==cs&&i!==$e&&y;if(P)return r?(mt({payload:{drawId:a.drawId,eventId:f?.eventId,error:Tm,participantId:h},topic:Wh}),{...C}):_({result:{error:Tm},context:{participantId:h},stack:g});if(S||T)return _({context:{invalidEntry:P,invalidLuckyLoser:S,invalidVoluntaryConsolation:T},result:{error:zu},stack:g});let U=ot({entryStageSequence:o,participantId:h,entryPosition:c,entryStatus:n,entryStage:i,extensions:m});return d&&At({element:U,extension:d}),p&&At({extension:{name:"roundEntry",value:p},element:U}),a.entries||(a.entries=[]),a.entries.push(U),Ot({drawDefinition:a}),{...C}}function lv(t){let e="addDrawEntries",{suppressDuplicateEntries:r=!0,entryStatus:n=kr,autoEntryPositions:o=!0,ignoreStageSpace:i,participantIds:s,drawDefinition:a,stageSequence:c,stage:u=nt,roundTarget:p,extension:m,event:d}=t;if(!u)return{error:YA};if(!a)return{error:Z};if(!Array.isArray(s))return{error:wr};if(!tP({stage:u,drawDefinition:a}))return{error:Oi};if(m&&!wn({extension:m}))return _({result:{error:G},info:"Invalid extension",context:{extension:m},stack:e});let l=eP({drawDefinition:a,stageSequence:c,entryStatus:n,stage:u});if(!i&&!l.success)return{error:l.error};let f=l.positionsAvailable??0;if(!i&&u!==$e&&f<s.length)return{error:Kl};let g=[],I=a.drawId,h=d?.eventId,S=s.reduce((T,y)=>{let P=n===cs&&fc({participantId:y,drawDefinition:a,entryStatus:n}),U=u===$e&&fc({entryStage:u,drawDefinition:a,participantId:y}),E=fc({participantId:y,drawDefinition:a});return n!==cs&&u!==$e&&E&&(g.push(y),r&&mt({payload:{error:Tm,participantId:y,eventId:h,drawId:I},topic:Wh})),P||U?T.concat(y):T},[]);return g.length&&!r?_({context:{eventId:h,drawId:I,duplicateEntries:g},result:{error:Tm},stack:e}):(s.filter(T=>T&&!S.includes(T)).forEach(T=>{let y={entryStageSequence:c,entryStage:u,participantId:T,entryStatus:n};m&&At({element:y,extension:m}),p&&At({extension:{name:Mn,value:p},element:y}),a.entries||(a.entries=[]),a.entries.push(y)}),o&&(a.entries=Kn({entries:a.entries})),Ot({drawDefinition:a}),S?.length||g?.length?{info:"some participantIds could not be added",participantIdsNotAdded:S,duplicateEntries:g,...C}:{...C})}function sg({suppressDuplicateEntries:t=!0,autoEntryPositions:e=!0,entryStageSequence:r,ignoreStageSpace:n,participantIds:o,drawDefinition:i,entryStatus:s,roundTarget:a,entryStage:c,extension:u,drawId:p,event:m}){if(!o?.length)return{error:Uo};if(!m)return{error:jr};if(!p)return{error:an};let d=(m.entries||[]).map(St);if(o.filter(I=>!d.includes(I)).length)return{error:WA};if(i){let I=lv({stageSequence:r,suppressDuplicateEntries:t,autoEntryPositions:e,stage:c,ignoreStageSpace:n,participantIds:o,drawDefinition:i,entryStatus:s,roundTarget:a,extension:u});if(I.error)return I}let{flightProfile:f}=Ht({event:m}),g=f?.flights.find(I=>I.drawId===p);return g?.drawEntries&&(o.forEach(I=>{let h=s===cs&&rP({participantId:I,entryStatus:s,flight:g}),S=c===$e&&rP({participantId:I,entryStage:c,flight:g});!(s!==cs&&c!==$e&&rP({flight:g,participantId:I}))&&!h&&!S&&g.drawEntries.push({participantId:I,entryStatus:s,entryStage:c})}),e&&(g.drawEntries=Kn({entries:g.drawEntries}))),{...C}}function rP({participantId:t,entryStatus:e,entryStage:r,flight:n}){let o=n.drawEntries?.find(i=>i.participantId===t&&(!e||e===i.entryStatus)&&(!r||r===i.entryStage));return t&&o}function gc({autoEntryPositions:t=!0,participantIds:e=[],entryStatuses:r,stage:n,event:o}){let i="removeEventEntries";if(!o?.eventId)return{error:vt};if(!Array.isArray(e)||e.some(m=>!Vt(m)))return _({result:{error:mn},stack:i});let s=(o.drawDefinitions??[]).flatMap(m=>Ri({drawDefinition:m}).assignedParticipantIds??[]),a=(r?.length&&o.entries?.filter(m=>m.entryStatus&&r.includes(m.entryStatus))||[]).map(St).filter(m=>!s.includes(m)),c=(n&&o.entries?.filter(m=>m.entryStage&&m.entryStage===n)||[]).map(St).filter(m=>!s.includes(m));if(e.length?e=e.filter(m=>(!r?.length||a.includes(m))&&(!n||c.includes(m))):a.length&&c.length?e=Yt(a,c):a.length?e=a:c.length&&(e=c),e?.length&&s.some(m=>e.includes(m)))return _({result:{error:vs},stack:i});if(!e?.length)return{...C,participantIdsRemoved:[]};let u=[];o.entries=(o.entries??[]).filter(m=>{let d=!e.includes(m?.participantId);return d||u.push(m.participantId),d}),t&&(o.entries=Kn({entries:o.entries}));let{flightProfile:p}=Ht({event:o});return p?.flights?.forEach(m=>{m.drawEntries=(m.drawEntries||[]).filter(d=>!e.includes(d.participantId))}),o.drawDefinitions?.forEach(m=>{m.entries=(m.entries??[]).filter(d=>!e.includes(d.participantId))}),{...C,participantIdsRemoved:u}}var nP={[er]:{policyName:"matchUpActionsDefault",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[],disabledActions:[]}],participants:{enforceCategory:!0,enforceGender:!0},processCodes:{substitution:["RANKING.IGNORE","RATING.IGNORE"]},substituteAfterCompleted:!1,substituteWithoutScore:!1}},hs=nP;function Fn(t){let{suppressDuplicateEntries:e=!0,entryStatus:r=kr,autoEntryPositions:n=!0,enforceGender:o=!0,entryStageSequence:i,policyDefinitions:s,entryStage:a=nt,tournamentRecord:c,ignoreStageSpace:u,drawDefinition:p,roundTarget:m,extensions:d,extension:l,drawId:f,event:g}=t,I="addEventEntries";if(!Array.isArray(t.participantIds))return _({result:{error:wr},stack:I});let h=ut(t.participantIds??[]);if(!g)return{error:vt};if(!h?.length)return _({result:{error:Uo},stack:I});if(!g?.eventId)return{error:jr};let S=yt({tournamentRecord:c,event:g}).appliedPolicies??{},T=s?.[er]??S?.[er]??hs[er],y=(o??T?.participants?.enforceGender)!==!1,P=[],U=[];if(d&&(!Array.isArray(d)||!d.every(x=>wn({extension:x})))||l&&!wn({extension:l}))return _({context:ot({extension:l,extensions:d}),result:{error:G},info:"Invalid extension(s)",stack:I});let E=!!c,A=[],N,D=c?.participants?.filter(x=>{if(!h.includes(x.participantId))return!1;let F=ue(xt)(g.eventType)&&x.participantType===Tt&&!Ys(r),L=g.eventType===_t&&x.participantType===ft;return F&&(!g.gender||!y||[Tr,Pn].includes(g.gender)||g.gender===x.person?.sex)||L&&!Ys(r)||g.eventType===_t&&x.participantType===Tt&&Ys(r)?!0:F&&g.gender&&y&&![Tr,Pn].includes(g.gender)&&g.gender!==x.person?.sex?(A.push({participantId:x.participantId,sex:x.person?.sex}),!1):g.eventType===Lt&&(x.participantType===Lt||Ys(r)&&x.participantType===Tt)}).map(x=>x.participantId)??[],M=h.filter(x=>!E||D.includes(x));g.entries||(g.entries=[]);let R=g.entries.map(x=>x.participantId||x.participant?.participantId);if(M.forEach(x=>{if(!R.includes(x)){let F=ot({participantId:x,entryStatus:r,entryStage:a,extensions:d});l&&At({element:F,extension:l}),m&&At({extension:{name:Mn,value:m},element:F}),i&&(F.entryStageSequence=i),P.push(F.participantId),g.entries?.push(F)}}),f&&!Ys(a)){let x=sg({participantIds:M,suppressDuplicateEntries:e,autoEntryPositions:n,entryStageSequence:i,ignoreStageSpace:u,drawDefinition:p,entryStatus:r,roundTarget:m,entryStage:a,extension:l,drawId:f,event:g});x.error&&(N=x.error)}if(g.eventType&&[ko,Cr].includes(g.eventType)){let x=(g.entries||[]).map(k=>k.participantId),F=(g.entries||[]).filter(k=>Ys(k.entryStatus)).map(k=>k.participantId),w=(c?.participants??[]).filter(k=>x.includes(k.participantId)&&k.participantType&&[ft,Lt].includes(k.participantType)).map(k=>k.individualParticipantIds).flat(1/0),V=F.filter(k=>w.includes(k));V.length&&(U.push(...V),gc({participantIds:V,autoEntryPositions:!1,event:g}))}if(M.length!==h.length)return _({context:{mismatchedGender:A,gender:g.gender},result:{error:wr},stack:I});n&&(g.entries=Kn({entries:g.entries||[]}));let v=P.length,O=U.length;return _({result:{...C,addedEntriesCount:v,removedEntriesCount:O},stack:I,info:N})}var oP="ADMINISTRATION",wk="CAPTAIN",Lk="COACH",xe="COMPETITOR",iP="MEDIA",sP="MEDICAL",ag="OFFICIAL",aP="OTHER",cP="SECURITY",gd={ADMINISTRATION:oP,CAPTAIN:wk,COACH:Lk,COMPETITOR:xe,MEDIA:iP,MEDICAL:sP,OFFICIAL:ag,OTHER:aP,SECURITY:cP};function cg({addIndividualParticipantsToEvents:t,individualParticipantIds:e,groupingParticipantId:r,tournamentRecord:n,suppressErrors:o}){let i="removeIndividualParticipantIds";if(!n)return _({result:{error:Y},stack:i});if(!r||!e)return _({result:{error:st},stack:i});let a=(n.participants??[]).find(m=>m.participantId===r);if(!a)return _({result:{error:te},stack:i});if(![Lt,zr].includes(a.participantType))return _({result:{participantType:a.participantType,error:An},stack:i});let c=fv({individualParticipantIds:e,groupingParticipant:a,tournamentRecord:n,suppressErrors:o}),{removed:u,error:p}=c;if(p)return _({result:c,stack:i});if(t)for(let m of n.events??[]){let d=(m.entries??[]).map(({participantId:l})=>l).filter(Boolean);if(d.includes(r)){let l=u?.filter(f=>!d.includes(f));Fn({participantIds:l,entryStatus:Gr,tournamentRecord:n,event:m})}}return u&&mt({topic:nr,payload:{tournamentId:n.tournamentId,participants:[a]}}),{...C,...c}}function fv({individualParticipantIds:t=[],groupingParticipant:e,tournamentRecord:r,suppressErrors:n,mappedMatchUps:o,participants:i}){let s=[];if(!e)return{removed:s};let a=[],c=[];i||({participants:i,mappedMatchUps:o}=Gt({withMatchUps:!0,tournamentRecord:r,withEvents:!0}));let p=i?.find(({participantId:l})=>l===e.participantId)?.events?.map(({eventId:l})=>l),m=(e.individualParticipantIds??[]).filter(l=>{let f=t?.includes(l),g=f&&i?.find(h=>h.participantId===l)?.matchUps.filter(({eventId:h})=>p.includes(h)).map(({matchUpId:h})=>o?.[h]).filter(({winningSide:h,score:S})=>h||Ie({score:S})),I=f&&!g?.length;if(f&&!I&&c.push(l),I){s.push(l);for(let h of r.events??[])for(let S of h.drawDefinitions??[]){let{extension:T}=dt({element:S,name:Ro}),y=T?.value[e.participantId];T&&y&&(T.value[e.participantId]=y.filter(U=>U.participantId!==l),At({element:S,extension:T}),Ta({drawDefinition:S}));let P=or({drawDefinition:S,inContext:!1}).matchUps??[];for(let U of P){let E=U.sides??[];for(let A of E){let N=A.lineUp??[];N.find(M=>M.participantId===l)&&(A.lineUp=N.filter(M=>M.participantId!==l),gt({tournamentId:r?.tournamentId,drawDefinition:S,matchUp:U}))}}}}else a.push(l);return!I});e.individualParticipantIds=m;let d={groupingParticipantId:e.participantId,cannotRemove:c,notRemoved:a,removed:s};return c.length&&!n&&{...d,cannotRemove:c,error:Ku}||d}function Rp({participantRole:t=xe,individualParticipantIds:e=[],groupingTypes:r=[yr,zr],tournamentRecord:n}){if(!n)return{error:Y};let o=n.participants??[],{participants:i,mappedMatchUps:s}=Gt({withMatchUps:!0,tournamentRecord:n,withEvents:!0}),a=0;return o.filter(c=>(c.participantRole===t||!c.participantRole)&&c.participantType&&r.includes(c.participantType)).forEach(c=>{let{removed:u}=fv({groupingParticipant:c,individualParticipantIds:e,tournamentRecord:n,mappedMatchUps:s,participants:i});u&&a++}),a?C:{error:cE}}function $i(t){let e=rt(t,[{[ie]:!0},{participantIds:!0,[He]:Be,[fn]:Uo}]);if(e.error)return e;let{addIndividualParticipantsToEvents:r,tournamentRecord:n,participantIds:o}=t,i=n.participants?.length||0;if(!i)return{...C};let s=(n.events||[])?.filter(({eventType:f})=>f===_e).map(f=>f?.drawDefinitions?.map(({drawId:g})=>g)).flat(1/0),a=Gt({participantFilters:{participantIds:o},tournamentRecord:n,withDraws:!0}).participants??[],c=f=>{let I=(Te({matchUpFilters:{drawIds:f,matchUpTypes:[_t]},tournamentRecord:n}).matchUps??[]).flatMap(({sides:h})=>h?.map(({participantId:S})=>S||[])).filter(Boolean);return Yt(I,o)},u=s?.length?c(s):[],p=a.filter(f=>f.draws?.filter(g=>(!s?.length||!s?.includes(g.drawId))&&g.positionAssignments).length);if(u?.length||p.length)return{error:vs};let m={},d={};for(let f of n.events||[]){let g=gc({participantIds:o,event:f});if(g.error)return g;m[f.eventId]=g.participantIdsRemoved}n.participants=(n.participants??[]).filter(f=>{let g=o.includes(f.participantId)||f.participantType===ft&&f.individualParticipantIds?.some(I=>o.includes(I));if(!g&&f.participantType===_e&&f.individualParticipantIds?.some(I=>o.includes(I))&&(f.individualParticipantIds=f.individualParticipantIds.filter(I=>!o.includes(I))),g&&r&&f.participantType&&[ft,Lt].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(Rp({individualParticipantIds:o,tournamentRecord:n}),r)for(let f of n.events||[]){let I=m[f.eventId].map(h=>d[h]||[]).flat();Fn({participantIds:I,entryStatus:Gr,tournamentRecord:n,event:f})}return l&&mt({payload:{participantIds:o,tournamentId:n.tournamentId},topic:wf}),l?{...C,participantsRemovedCount:l}:{error:Ku}}function yS({selected:t=!0,drawDefinition:e,entryStatuses:r,drawId:n,event:o,stage:i}){let s=o.entries??[];if(n){let{flightProfile:c}=Ht({event:o}),u=c?.flights?.find(p=>p.drawId===n);u?s=u.drawEntries:e.entries&&(s=e?.entries)}let a=s.filter(c=>(!r?.length||!c.entryStatus||r.includes(c.entryStatus))&&(!i||!c.entryStage||c.entryStage===i)&&(!t||c.entryStatus&&Qr.includes(c.entryStatus)));return{entries:s,stageEntries:a}}function uP({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,stage:i,event:s}){let a="destroyGroupEntry";if(!e)return{error:Y};if(!n)return _({result:{error:oe},stack:a});if(!s)return{error:vt};if(!s.eventType||![ko,Cr].includes(s.eventType))return _({result:{error:Bn},stack:a});let c=e.participants??[],u=c.find(S=>S.participantId===n);if(!u)return _({result:{error:te},stack:a});if(!u.participantType||![ft,yr].includes(u.participantType)||u.participantType===yr&&s.eventType!==Cr||u.participantType===ft&&s.eventType!==ko)return{error:An};let m=(s.entries??[]).find(S=>S.participantId===n);if(!m)return{error:VI};let{stageEntries:d}=yS({selected:!1,drawDefinition:r,drawId:o,event:s,stage:i}),l=d.map(St),f=c.filter(({participantId:S})=>l.includes(S)).map(({individualParticipantIds:S})=>S).flat().filter(Boolean),g=u.individualParticipantIds?.filter(S=>mo(S,f).length===1),I=gc({participantIds:[n],event:s});if(I.error||g?.length&&(I=Fn({participantIds:g,entryStatus:Gr,entryStage:m.entryStage,tournamentRecord:e,drawDefinition:r,drawId:o,event:s}),I.error))return I;let h;return t&&$i({participantIds:[n],tournamentRecord:e}).success&&(h=!0),{...C,participantRemoved:h}}function ug({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,event:i}){return uP({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:r,participantId:n,drawId:o,event:i})}function pP(t){if(!t.tournamentRecord)return{error:Y};let{participantIds:e,...r}=t,n=0,o=[];for(let i of e){let s=uP({participantId:i,...r});s.success&&(n+=1),s.error&&o.push(s.error)}return n?{destroyedCount:n,...C}:{error:o}}function Au(t){let{tournamentRecord:e,replaceWithBye:r,drawDefinition:n,destroyPair:o,entryStatus:i,matchUpsMap:s,drawId:a}=t,c="removeDrawPositionAssignment",u=lc(t);if(u.error)return _({result:u,stack:c});let{participantId:p}=u,{drawPosition:m,event:d,structureId:l}=t,f=yt({tournamentRecord:e,drawDefinition:n,event:d}).appliedPolicies??{};if([nn,io].includes(i)&&p){let{tournamentRecord:h}=t,{participant:S}=To({tournamentRecord:h,participantId:p}),{participantType:T,individualParticipantIds:y}=S??{};if(o&&T===ft){let P=ug({tournamentRecord:h,drawDefinition:n,participantId:p,event:d});if(P.error)return _({result:P,stack:c});y&&dd({participantIds:y,tournamentRecord:h,drawDefinition:n,entryStatus:i,drawId:a,event:d})}else dd({participantIds:[p],tournamentRecord:h,drawDefinition:n,entryStatus:i,drawId:a,event:d})}if(r){let h=Hr({tournamentRecord:e,drawDefinition:n,drawPosition:m,structureId:l,matchUpsMap:s,event:d});if(h.error)return _({result:h,stack:c})}let{structure:g}=at({drawDefinition:n,structureId:l});return Qm({structure:g,drawPositions:[m]}),cu({appliedPolicies:f,drawDefinition:n,positionAction:{name:"removeDrawPositionAssignment",replaceWithBye:r,drawPosition:m,entryStatus:i,structureId:l}}),u}function mP(t){return Object.assign(t,{entryStatus:io}),Au(t)}function AS(t){return Vt(t)?t.split(" ").map(e=>e.split("").map((r,n)=>n?r.toLowerCase():r.toUpperCase()).join("")).join(" "):t}function Qe(t){return Vt(t)?AS(t.replace(/_/g," ")):""}var Ss=({finishingPosition:t=Gi,qualifyingRoundNumber:e,structureAbbreviation:r,seedAssignments:n=[],stageSequence:o=1,structureOrder:i,seedingProfile:s,matchUpFormat:a,structureType:c,structureName:u,matchUpType:p,matchUps:m=[],structureId:d,roundOffset:l,roundLimit:f,stageOrder:g,structures:I,stage:h})=>{let S={structureId:d??Dt(),structureAbbreviation:r,finishingPosition:t,seedAssignments:n,matchUpFormat:a,stageSequence:o,structureName:u};i&&(S.structureOrder=i),c&&(S.structureType=c),s&&(typeof s=="string"?S.seedingProfile=s:typeof s=="object"&&typeof s.positioning=="string"&&(S.seedingProfile=s.positioning)),p&&(S.matchUpType=p),l&&(S.roundOffset=l),g&&(S.stageOrder=g),f&&(S.roundLimit=f),h&&(S.stage=h),e&&(S.qualifyingRoundNumber=e);let T=m.flatMap(({drawPositions:y})=>y).filter(Boolean);return I?S.structures=I:(S.matchUps=m,S.positionAssignments=ut(T).sort((y,P)=>y-P).map(y=>({drawPosition:y}))),S},hn=Ss;function pg({structureName:t=Qe($e),structureAbbreviation:e,drawDefinition:r,matchUpType:n,structureId:o}){if(!r)return{error:Z};let i=hn({stage:$e,structureAbbreviation:e,structureName:t,matchUps:[],structureId:o,matchUpType:n});return r.structures||(r.structures=[]),r.structures.push(i),Ot({drawDefinition:r,structureIds:[i.structureId]}),{...C}}function mg({drawPositions:t}){if(!t?.length)return{error:ja};let e=o=>t.filter(i=>i!==o).map(i=>[o,i]),r=[].concat(...(t??[]).map(e)),n=ut(r.map(dg)).map(o=>o.split("|").map(i=>+i));return{groupMatchUps:r,uniqueMatchUpGroupings:n}}function dg(t=[]){return!Array.isArray(t)||!t.length?"":[...t].sort(me).join("|")}function dP({groupSize:t,drawPositionOffset:e}){if(!t)return[];let r=m=>[...Array(m)].map((d,l)=>l),n=r(2*Math.round(t/2)+1).slice(1),o=r(n.length-1).map(()=>[]),i=n.slice(0,n.length/2),s=n.slice(n.length/2);n.slice(1).forEach((m,d)=>{i.forEach((I,h)=>{o[d].push([i[h],s[h]])});let l=i.shift(),f=i.pop(),g=s.shift();i=[l,g,...i].filter(Boolean),s=[...s,f].filter(Boolean)});let a=i.shift(),c=i.pop(),u=s.shift();i=[a,u,...i].filter(Boolean),s=[...s,c].filter(Boolean);let p=m=>m[0].reduce((d,l)=>d+l);return[...o].reverse().sort((m,d)=>p(m)-p(d)).map(m=>m.filter(d=>d.every(l=>l<=t)).map(d=>{let l=d.map(f=>f+e);return dg(l)}))}function Fk({rounds:t,hash:e}){return t?.length?t?.reduce((r,n,o)=>n.includes(e)?o+1:r,void 0):{error:st}}var gv={getRoundRobinGroupMatchUps:mg,determineRoundNumber:Fk,drawPositionsHash:dg,groupRounds:dP};function Na(t){let{groupNameBase:e="Group",playoffAttributes:r,stageSequence:n=1,structureOptions:o,appliedPolicies:i,seedingProfile:s,stage:a=nt,matchUpType:c,roundTarget:u,structureId:p,groupNames:m,drawSize:d,idPrefix:l,isMock:f,uuids:g}=t,I=t.structureName??r?.["0"]?.name??Qe(nt),{groupCount:h,groupSize:S}=kk({structureOptions:o,appliedPolicies:i,drawSize:d}),T=li,y,P=et(1,h+1).map(E=>{let A=Gk({groupSize:S,structureOrder:E,matchUpType:c,drawSize:d,idPrefix:l,isMock:f});y=Array.isArray(A)?Math.max(...A.map(({roundNumber:D})=>D??0)):0;let N=m?.[E-1]??`${e} ${E}`;return Ss({structureId:g?.pop(),structureType:ap,finishingPosition:T,structureOrder:E,structureName:N,matchUps:A})}),U=Ss({structureId:p??g?.pop(),structureType:Ge,finishingPosition:T,seedingProfile:s,structureName:I,stageSequence:n,structures:P,stage:a});return u&&At({extension:{name:Mn,value:u},element:U}),{structures:[U],maxRoundNumber:y,groupCount:h,links:[],groupSize:S,...C}}function kk({appliedPolicies:t,structureOptions:e,drawSize:r}){let n=e?.groupSize,o=e?.groupSizeLimit||8,{validGroupSizes:i}=Cp({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 Cp(t){let{groupSizeLimit:e=10,drawSize:r=0}=t??{},n=et(3,e+1).filter(o=>{let i=Math.ceil(r/o),s=i*o-r,a=Math.ceil(r/i),c=Math.ceil(s/i);return(!s||s<o)&&a===o&&a>=3&&c<2});return{...C,validGroupSizes:n}}function Gk({structureOrder:t,matchUpType:e,groupSize:r,drawSize:n,idPrefix:o,isMock:i,uuids:s}){let a=(t-1)*r,c=et(1+a,r+1+a),u=mg({drawPositions:c}).uniqueMatchUpGroupings??[],p=dP({groupSize:r,drawPositionOffset:a});return u.map(l).sort((f,g)=>(f.roundNumber??1/0)-(g.roundNumber??1/0));function d(f){return p.reduce((g,I,h)=>I.includes(f)?h+1:g,void 0)}function l(f){let g=dg(f),I=d(g),h=[1,n],S=Vk({structureOrder:t,drawPositions:f,roundNumber:I,idPrefix:o,uuids:s}),T={matchUpStatus:I?Qt:Nt,matchUpType:e,finishingPositionRange:{winner:h,loser:h},drawPositions:f,roundNumber:I,matchUpId:S};return i&&(T.isMock=!0),T}}function Vk({structureOrder:t,drawPositions:e,roundNumber:r,idPrefix:n,uuids:o}){return n?`${n}-${t}-${r}-DP-${e.join("-")}`:o?.pop()||Dt()}function lg(t){let{roundRobinGroupsCount:e,participantsCount:r,cluster:n}=t;if(!It(r))return{seedBlocks:void 0,..._({result:{error:G},context:{participantsCount:r},stack:"getSeedBlocks"})};let o=es(r);if(e){let l=Math.min(e,o),f=[],g=1;for(et(0,l).forEach(()=>{f.push([g]),g++});g<o;){let I=et(g,g+l);g+=l,f.push(I)}return{...C,seedBlocks:f}}let i=et(1,o+1),s=[],a=o/2;for(;a>1;){let l=ye(i,a),f=l.length;l.forEach((g,I)=>{let h,S=I<f/2,T=I%2===0,y=g[0],P=g[g.length-1];n&&f>4?f===8?h=S?P:y:h=T?y:P:h=S?y:P,Fe(g,s)||s.push(h)}),a=a/2}let c=i.filter(l=>!s.includes(l));for(;c.length;)c.length%2===0?s.push(c.pop()):s.push(c.shift());let u=et(0,20).map(l=>Math.pow(2,l));u.unshift(1);let p=u.indexOf(o),m=0,d=[];return et(0,p).forEach(l=>{d.push(s.slice(m,m+u[l])),m+=u[l]}),{...C,seedBlocks:d}}function fg({roundRobinGroupsCount:t,drawSize:e}){let r="getSeedGroups";if(!It(e))return{seedGroups:void 0,..._({result:{error:G},context:{drawSize:e},stack:r})};if(t){if(!It(t))return{seedGroups:void 0,..._({context:{roundRobinGroupsCount:t},result:{error:G},stack:r})};let n=1,o=Math.floor(e/t);return{seedGroups:et(0,o).map(()=>{let s=et(n,n+t);return n+=t,s})}}else{let{seedBlocks:n}=lg({participantsCount:e,roundRobinGroupsCount:t}),o=0;return{seedGroups:(n||[]).map(s=>(s||[]).map(()=>(o+=1,o)))}}}function ES({roundRobinGroupsCount:t,participantsCount:e}){if(t){let{validGroupSizes:o}=Cp({drawSize:e});if(!o?.map(a=>Math.ceil(e/a))?.includes(t))return _({context:{roundRobinGroupsCount:t},result:{error:G}})}let{seedGroups:r}=fg({drawSize:e,roundRobinGroupsCount:t}),n=r?.map(o=>Math.min(...o))||[];return{...C,seedingThresholds:n}}function Ic(t){if(!t)return 1/0;if(It(t))return pt(t);let e=t.split("-")[0];return It(e)?pt(e):1/0}function Bk({size:t}){let e=[t],r=t;for(;r/2===Math.floor(r/2);)r=r/2,e.push(r);return e.includes(1)||e.push(1),e.sort(me),e.reverse(),e}function Iv({blockPattern:t,index:e}){let r=0;for(let n of t){if(r===e)return n;let o=0;for(;o<n.length;){if(r===e)return n;r+=1,o++}}}function hv({positioning:t,size:e}){let r=Bk({size:e}),n=[],o=[],i=d=>d[0],s=d=>d[d.length-1],a=(d,l)=>(t&&[Kc,mi].includes(t)&&l%2?s(d):i(d))||i(d),c=(d,l)=>{if(d.every(f=>!o.includes(f))){let f=a(d,l);return o.push(f),f}},u=d=>{let l=d.filter(f=>!o.includes(f));if(l.length)return o.push(...l),l},p=(d,l)=>{let f=a(d,l);if(!o.includes(f))return o.push(f),f},m=et(1,e+1);for(let d of r)if(d===1){let l=ye(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=ye(m,d).map(p).filter(Boolean);f.length&&n.push(f)}return{divisions:r,divisionGroupings:n}}function Ts({provisionalPositioning:t,returnAllProxies:e,appliedPolicies:r,seedingProfile:n,drawDefinition:o,allPositions:i,structure:s}){let a=[];if(!s)return{error:pi};let{matchUps:c,roundMatchUps:u}=Ut({matchUpFilters:{roundNumbers:[1]},provisionalPositioning:t,structure:s}),{seedAssignments:p}=on({provisionalPositioning:t,returnAllProxies:e,drawDefinition:o,structure:s}),{positionAssignments:m}=Se({structure:s}),d=m?.length,l=p?.length??0,f=[],I=Object.keys(u).map(L=>parseInt(L)).sort((L,w)=>L-w).map(L=>{let w=u[L].map(k=>k.drawPositions).flat(1/0).filter(Boolean),V=w.filter(k=>!f.includes(k));return f=f.concat(...w),V}).filter(L=>L.length).reverse(),h=I.pop()??[],S=h&&Math.min(...h)-1||0;n=n??r?.seeding?.seedingProfile;let T=h?.length||0,y=I.filter(L=>L.filter(w=>w<=l).length),{stage:P,structureType:U,roundLimit:E}=s,A=U===Ge,N=!A&&I?.length,D=!A&&P===ct&&E,M=y.flat(1/0),R=N?M?.length:0,b=i?d:l,v=id({drawDefinition:o,structure:s,matchUps:c}),O=v?0:!N&&b||b&&M.length<b&&b-M.length||0;if(D){let L=s?.matchUps?s.matchUps.filter(({roundNumber:V})=>V===s.roundLimit).length:0,w=h.length/L;if(!N){let V=vp(n),k=ye(h,w),W=1,H=et(0,k[0].length).map(()=>{let K=et(W,W+k.length);return W+=k.length,K});({validSeedBlocks:a}=Sv({drawPositionBlocks:k,nonRandom:n?.nonRandom,positioning:V,seedGroups:H}))}}else A?{validSeedBlocks:a}=Hk({nonRandom:n?.nonRandom,seedingProfile:n,structure:s}):N?a=y.map(L=>({seedNumbers:L,drawPositions:L})):v&&ye(h,2).map((w,V)=>({drawPositions:[w[0]],seedNumbers:[V+1]})).forEach(w=>a.push(w));if(!A&&!v&&!D){let{blocks:L}=Wk({drawPositionOffset:S,seedNumberOffset:R,seedCountGoal:O,seedingProfile:n,baseDrawSize:T});L.forEach(w=>a.push(w))}let F=a.flatMap(L=>L.drawPositions).reduce((L,w)=>h?.includes(w)&&L,!0);return!v&&!N&&!A&&!F?{error:GA,validSeedBlocks:[],isContainer:A,isFeedIn:N}:{isLuckyStructure:v,validSeedBlocks:a,isContainer:A,isFeedIn:N}}function Hk({seedingProfile:t,structure:e,nonRandom:r}){let n=e.structures||[],o=n.length,i=bt({structure:e})?.positionAssignments,s=vp(t),a=i?.length??0,{seedGroups:c}=fg({roundRobinGroupsCount:o,drawSize:a}),u=n.map(p=>bt({structure:p}).positionAssignments?.map(m=>m.drawPosition));return Sv({drawPositionBlocks:u,positioning:s,seedGroups:c,nonRandom:r})}function Sv({drawPositionBlocks:t,positioning:e,seedGroups:r,nonRandom:n}){let o=[],{divisionGroupings:i}=hv({size:r.length,positioning:e}),s=[];return r.forEach((a,c)=>{let u=Iv({blockPattern:i,index:c});a.forEach((p,m)=>{let d=c%2?t.length-m-1:m,f=t[d].slice().filter((I,h)=>u.includes(h+1)&&I);e!==mi?f=n?f:Ir(f):c%2&&f.reverse();let g=f.find(I=>!s.includes(I));g&&(s.push(g),o.push({drawPositions:[g],seedNumbers:[p]}))})}),{validSeedBlocks:o}}function Wk(t){let{drawPositionOffset:e=0,roundRobinGroupsCount:r,seedNumberOffset:n=0,seedingProfile:o,seedCountGoal:i,baseDrawSize:s}=t,a=1,c=[],{seedBlocks:u}=lg({cluster:vp(o)===Kc,participantsCount:s,roundRobinGroupsCount:r});a=0;for(let m of u){if(a+1>i)break;let d=m.map(f=>f+e),l=p(a+1,m.length).map(f=>+f+n);a+=m.length,c.push({drawPositions:d,seedNumbers:l})}return{blocks:c};function p(m,d){return Array.from(new Array(d),(l,f)=>f+m)}}function bp({appliedPolicies:t,drawDefinition:e,seedBlockInfo:r,drawPosition:n,structureId:o,seedNumber:i}){let{structure:s}=at({drawDefinition:e,structureId:o});t||(t=yt({drawDefinition:e}).appliedPolicies);let a=r?.validSeedBlocks;return!a&&s&&(a=Ts({appliedPolicies:t,drawDefinition:e,structure:s})?.validSeedBlocks),t?.seeding?.validSeedPositions?.ignore?!0:t?.seeding?.validSeedPositions?.strict?(a.find(m=>m.seedNumbers.includes(i))?.drawPositions||[]).includes(n):[].concat(...a.map(u=>u.drawPositions)).includes(n)}function US(t){let{provisionalPositioning:e,drawDefinition:r,seedingProfile:n,seedBlockInfo:o,structureId:i,randomize:s}=t,{structure:a}=at({drawDefinition:r,structureId:i}),{seedAssignments:c}=on({returnAllProxies:t.returnAllProxies,provisionalPositioning:e,drawDefinition:r,structure:a}),{positionAssignments:u}=Se({structure:a}),m=u?.filter(w=>w.participantId??w.bye??w.qualifier)?.map(w=>w.drawPosition).filter(Boolean),{appliedPolicies:d}=yt({drawDefinition:r}),g=(o?.validSeedBlocks||a&&Ts({returnAllProxies:t.returnAllProxies,provisionalPositioning:e,appliedPolicies:d,drawDefinition:r,seedingProfile:n,structure:a})?.validSeedBlocks||[]).filter(w=>w.drawPositions.filter(k=>!m?.includes(k)).length)[0],I=c?.map(w=>w.participantId).filter(Boolean),h=u?.map(w=>w.participantId).filter(Boolean),S=I?.filter(w=>h?.includes(w)),T=I?.filter(w=>!h?.includes(w)),y=c?.filter(w=>T?.includes(w.participantId)),P=c?.filter(w=>!w.participantId),E=(y?.length&&y.length>0?y.length:P?.length??0)&&g?.drawPositions.filter(w=>!m?.includes(w))||[],A=s?Ir(E):E,N=[],D=A.map(()=>{let V=L(y,N)?.participantId;return V&&N.push(V),V}).filter(Boolean),M=c?.filter(w=>S?.includes(w.participantId)).map(w=>w.seedNumber),b=(g?.seedNumbers||[]).filter(w=>!M?.includes(w)),v=c?.filter(w=>b.includes(w.seedNumber)).map(w=>w.participantId),O=d?.seeding?.duplicateSeedNumbers;return{nextSeedBlock:g,unplacedSeedParticipantIds:(O!==void 0?O:!0)?D:v,unplacedSeedNumbers:b,unfilledPositions:A,unplacedSeedAssignments:y};function L(w,V){let k=w.filter(q=>!V.includes(q.participantId)),W=Math.min(...k.map(q=>Ic(q.seedValue))),H=k.filter(q=>Ic(q.seedValue)===W);return Ir(H).pop()}}function vp(t){if(typeof t=="string")return t;if(typeof t=="object")return t.positioning}function $s({provisionalPositioning:t,tournamentRecord:e,drawDefinition:r,seedingProfile:n,participantId:o,seedBlockInfo:i,structureId:s,seedNumber:a,seedValue:c,eventId:u,event:p}){let m="assignSeed",{structure:d}=at({drawDefinition:r,structureId:s}),{positionAssignments:l}=Se({structure:d}),f=on({provisionalPositioning:t,drawDefinition:r,structure:d}).seedAssignments,g=f.map(U=>U.seedNumber),I=fc({drawDefinition:r,participantId:o});if(o&&!I)return _({result:{error:mn},context:{participantId:o},stack:m});let h=p?Ht({event:p}).flightProfile?.flights?.length:0,S=h&&h>1,y=l?.find(U=>U.participantId===o)?.drawPosition;if(y&&!bp({drawPosition:y,drawDefinition:r,seedBlockInfo:i,structureId:s,seedNumber:a}))return _({result:{error:Ll},context:{assignedDrawPosition:y},info:"invalid seed position",stack:m});g.includes(a)||f.push({seedNumber:a,seedValue:c});let P;return f.forEach(U=>{U.participantId===o&&U.seedNumber!==a&&(U.participantId=void 0),U.seedNumber===a&&(U.participantId=o,!n?.groupSeedingThreshold&&!S&&(U.seedValue=c??a),P=!0)}),P?(qh({tournamentId:e?.tournamentId,drawDefinition:r,structure:d,eventId:u}),{...C}):_({result:{error:kA},stack:m})}function Id({inContextTargetMatchUp:t,drawPositionSideIndex:e,teamParticipantId:r,tournamentRecord:n,drawDefinition:o,matchUp:i,event:s}){let a=t?.sides?.[e]?.sideNumber,c=a&&i.sides?.find(d=>d.sideNumber===a),{extension:u}=dt({element:o,name:Ro}),p=u?.value||{},m=J(p[r],!1,!0);if(c)i?.sides?.forEach(d=>{d.sideNumber===a&&(d.lineUp=m)});else{i.sides=[1,2].map(l=>({...i.sides?.find(g=>g.sideNumber===l)??{},sideNumber:l}));let d=i.sides.find(l=>l.sideNumber===a);d&&(d.lineUp=m)}gt({tournamentId:n?.tournamentId,context:"updateSidLineUp",eventId:s?.eventId,drawDefinition:o,matchUp:i})}function PS(t){let{sourceMatchUp:e}=t,{targetMatchUp:r,structure:n,matchUpsMap:o,drawPosition:i}=t,s=r.roundNumber>1&&r.roundNumber-1,a=oi({structureId:n.structureId,matchUpsMap:o});!e&&i&&(e=a.find(({drawPositions:f,roundNumber:g})=>g===s&&f?.includes(i)));let c=e?.roundPosition,u=c%2?1:-1,p=c+u,m=s&&a.find(({roundNumber:f,roundPosition:g})=>f===s&&g===p),d=m?.matchUpStatus,l=[he,Ce].includes(d);return{pairedPreviousMatchUp:m,pairedPreviousMatchUpIsDoubleExit:l}}function Tv({drawPosition:t,drawPositions:e}){let r=!1,n=!!e?.includes(t);return{updatedDrawPositions:n?e||[]:[...e,void 0,void 0].slice(0,2).map(s=>!s&&!n?(n=!0,r=!0,t):s).sort(me).filter(Boolean),positionAdded:r,positionAssigned:n}}function DS({structureId:t,matchUpsMap:e,matchUp:r}){let n=r?.roundPosition,o=n%2?1:-1,i=n+o;return{pairedPreviousMatchUp:oi({matchUpsMap:e,structureId:t}).find(({roundNumber:c,roundPosition:u})=>c===r?.roundNumber&&u===i)}}function NS({inContextDrawMatchUps:t,sourceMatchUpStatus:e,sourceMatchUpId:r,matchUpsMap:n,matchUp:o}){let i=t.find(a=>a.matchUpId===r),{pairedPreviousMatchUp:s}=DS({structureId:i?.structureId,matchUp:i,matchUpsMap:n});if(i&&s){let a=s?.matchUpId,c=t.find(p=>p.matchUpId===a),u=i?.structureId===c?.structureId?i?.roundPosition<c?.roundPosition&&1||2:i.structureId===c?.structureId&&2||1;o.matchUpStatusCodes=(o.matchUpStatusCodes??[]).map(p=>{let m=Vt(p)||!isNaN(p)?{code:p}:p;return m.sideNumber===u?{...m,previousMatchUpStatus:e}:m})}}function hd({inContextDrawMatchUps:t,drawPosition:e,matchUpId:r}){let n=t.filter(({winnerMatchUpId:s,loserMatchUpId:a})=>a===r||s===r).sort((s,a)=>s.roundPosition-a.roundPosition);return t.find(s=>s.matchUpId===r).feedRound?1:n.reduce((s,a,c)=>a.drawPositions?.includes(e)?c+1:s,void 0)}function hc({inContextDrawMatchUps:t,sourceMatchUpStatus:e,tournamentRecord:r,sourceMatchUpId:n,drawDefinition:o,matchUpStatus:i,drawPosition:s,matchUpsMap:a,matchUpId:c,event:u}){let p="assignMatchUpDrawPosition";a||(a=Ne({drawDefinition:o})),t||(t=se({inContext:!0,drawDefinition:o,matchUpsMap:a}).matchUps??[]);let m=t.find(b=>b.matchUpId===c),d=m?.structureId,l=o?.structures?.find(b=>b.structureId===d);if(!l)return{error:kt};let f=a?.drawMatchUps?.find(b=>b.matchUpId===c),g=f?.drawPositions??[],{positionAdded:I,positionAssigned:h,updatedDrawPositions:S}=Tv({drawPositions:g,drawPosition:s}),{positionAssignments:T}=bt({drawDefinition:o,structure:l}),P=T?.filter(b=>S.includes(b.drawPosition))?.find(({bye:b})=>b),U=f?.matchUpStatus&&[Ct,Mt].includes(f.matchUpStatus)&&S.filter(Boolean).length<2;if(i=P&&Nt||i||U&&f.matchUpStatus||f?.matchUpStatus&&[he,Ce].includes(f.matchUpStatus)&&f.matchUpStatus||Qt,f&&I){t=se({inContext:!0,drawDefinition:o,matchUpsMap:a}).matchUps??[];let b=U&&hd({inContextDrawMatchUps:t,drawPosition:s,matchUpId:c})||void 0;f?.matchUpStatusCodes&&NS({inContextDrawMatchUps:t,sourceMatchUpStatus:e,sourceMatchUpId:n,matchUpsMap:a,matchUp:f}),Object.assign(f,{drawPositions:S,winningSide:b,matchUpStatus:i}),gt({tournamentId:r?.tournamentId,eventId:m?.eventId,context:p,drawDefinition:o,matchUp:f})}let E=ur({inContextDrawMatchUps:t,inContextMatchUp:m,drawDefinition:o,matchUpId:c}),{targetMatchUps:{winnerMatchUp:A,loserMatchUp:N,loserTargetDrawPosition:D},targetLinks:{loserTargetLink:M}}=E,R=oi({structureId:l.structureId,matchUpsMap:a});if(h&&P){if(A)if([Nt,he,Ce].includes(i)){let b=hc({matchUpId:A.matchUpId,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:o,drawPosition:s,matchUpsMap:a});if(b.error)return b}else{let{structureId:b}=A;b!==l.structureId&&console.log("winnerMatchUp in different structure... participant is in different targetDrawPosition")}}else if(A&&m&&!m.feedRound){let{pairedPreviousMatchUpIsDoubleExit:b}=PS({targetMatchUp:f,drawPosition:s,matchUpsMap:a,structure:l});if(b){let v=hc({matchUpId:A.matchUpId,inContextDrawMatchUps:t,tournamentRecord:r,drawDefinition:o,drawPosition:s,matchUpsMap:a});if(v.error)return v}}if(f?.matchUpType===jt){let b=t?.find(({matchUpId:F})=>F===f.matchUpId),O=(b?.sides??[]).reduce((F,L,w)=>L.drawPosition===s?w:F,void 0),x=T?.find(F=>F.drawPosition===s)?.participantId;x&&O!==void 0&&Id({inContextTargetMatchUp:b,drawPositionSideIndex:O,teamParticipantId:x,tournamentRecord:r,drawDefinition:o,matchUp:f})}if(M?.linkCondition===On&&S.filter(Boolean).length===2&&!P&&R.filter(({drawPositions:O,roundNumber:x})=>x===1&&Fe(O,S)).every(({matchUpStatus:O})=>[le,rr].includes(O))&&N){let{structureId:O}=N,x=Hr({drawPosition:D,tournamentRecord:r,drawDefinition:o,structureId:O,matchUpsMap:a,event:u});if(x.error)return x}return h?{...C}:_({result:{error:Wa},context:{drawPosition:s},stack:p})}function MS({inContextDrawMatchUps:t,drawDefinition:e,assignments:r,matchUpsMap:n,structure:o}){let s=as({drawDefinition:e})?.containedStructures?.[o.structureId]?.map(({structureId:m})=>m)||[];s.push(o?.structureId);let a=r?.map(({drawPosition:m})=>m)||[],c=t?.filter(m=>s.includes(m.structureId)&&Yt(m.drawPositions??[],a).length)??[],u=c.map(({matchUpId:m})=>m),p=n?.drawMatchUps?.filter(m=>u.includes(m.matchUpId))??[];return{drawPositions:a,matchUps:p,targetMatchUps:c}}function Sd({lineUp:t}){if(!Array.isArray(t))return;let e={};return ut(t.flatMap(({collectionAssignments:n})=>n?.map(({collectionId:o,collectionPosition:i})=>[o,i].join("|"))).filter(Boolean)).forEach(n=>{let[o,i]=n.split("|"),s=parseInt(i),{assignedParticipantIds:a}=Np({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 ii(t){return`${t} must be an array`}function Td({lineUp:t,tieFormat:e}){let r=[];if(!Array.isArray(t))return r.push(ii("lineUp")),{valid:!1,errors:r,error:G};let n=t.every(s=>{if(typeof s!="object")return r.push("lineUp entries must be objects"),!1;let{participantId:a,collectionAssignments:c}=s;return a?typeof a!="string"?(r.push("participantIds must be strings"),!1):Array.isArray(c)?c.every(u=>{if(typeof u!="object")return r.push("collectionAssignments must be objects"),!1;let{collectionPosition:p}=u;return typeof p!="number"?(r.push("collectionPosition must be a number"),!1):!0}):(r.push(ii("collectionAssignments")),!1):(r.push("Missing participantId"),!1)}),o=ut(t.map(St)).length===t.length;return o||r.push("Duplicated participantId(s)"),{valid:n&&o,errors:r,error:r.length?G:void 0}}function Ki({drawDefinition:t,participantId:e,tieFormat:r,lineUp:n}){if(typeof t!="object")return{error:Z};if(typeof e!="string")return{error:oe};let o=Td({lineUp:n,tieFormat:r});if(!o.valid)return o;let{extension:i}=dt({element:t,name:Ro}),s=i?.value||{};return s[e]=Sd({lineUp:n}),At({element:t,extension:{name:Ro,value:s}}),Ta({drawDefinition:t}),{...C}}function gg({inContextDrawMatchUps:t,inheritance:e=!0,tournamentRecord:r,drawDefinition:n,matchUpsMap:o,assignments:i,structure:s,event:a}){if(!n)return{error:Z};let{drawPositions:c,matchUps:u,targetMatchUps:p}=MS({inContextDrawMatchUps:t,matchUpsMap:o,assignments:i,structure:s});for(let m of p)m.matchUpType===xr&&(m.sides??[]).forEach((d,l)=>{if(d?.drawPosition&&c?.includes(d.drawPosition)){let f=u.find(({matchUpId:g})=>g===m.matchUpId);if(f?.sides?.[l]){if(delete f.sides[l].lineUp,e===!1){let g=m.tieFormat,I=d.participantId;g&&I&&Ki({drawDefinition:n,participantId:I,lineUp:[],tieFormat:g})}gt({tournamentId:r?.tournamentId,context:"resetLineUps",eventId:a?.eventId,drawDefinition:n,matchUp:f})}}});return{...C}}function kn({provisionalPositioning:t,inContextDrawMatchUps:e,isQualifierPosition:r,sourceMatchUpStatus:n,tournamentRecord:o,drawDefinition:i,seedingProfile:s,participantId:a,seedBlockInfo:c,drawPosition:u,matchUpsMap:p,structureId:m,event:d}){let l="assignDrawPosition";if(!a&&!r)return _({result:{error:oe},stack:l});p=p??Ne({drawDefinition:i}),e||({matchUps:e}=se({inContext:!0,drawDefinition:i,matchUpsMap:p}));let f=at({drawDefinition:i,structureId:m});if(f.error)return _({result:f,stack:l});let{structure:g}=f;if(!g)return{error:kt};if(cr({structure:g}))return _({result:{error:dr},stack:l});let{seedAssignments:I}=on({provisionalPositioning:t,drawDefinition:i,structure:g}),S=I?.find(v=>v.participantId===a)?.seedNumber,{appliedPolicies:T}=yt({tournamentRecord:o,drawDefinition:i,structure:g,event:d});if(S&&!bp({seedNumber:S,appliedPolicies:T,drawDefinition:i,seedBlockInfo:c,drawPosition:u,structureId:m}))return _({result:{error:Ll},context:{drawPosition:u},stack:l});let P=Se({structure:g}).positionAssignments||[],U=P?.find(v=>v.drawPosition===u);if(!U)return _({result:{error:Rs},context:{drawPosition:u},stack:l});if(P?.map(St).includes(a))return _({result:{error:vs},context:{drawPosition:u},stack:l});let{containsParticipant:A,containsBye:N}=b(U);if(N){let v=lc({inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,drawPosition:u,structureId:m,matchUpsMap:p,event:d});if(v.error)return _({result:v,stack:l})}if(A&&U.participantId!==a){let{activeDrawPositions:v}=Pa({drawDefinition:i,structureId:m});if(v.includes(u))return _({result:{error:Yu},stack:l});gg({assignments:[U],inContextDrawMatchUps:e,tournamentRecord:o,drawDefinition:i,matchUpsMap:p,structure:g})}if(U.participantId=a,r&&(U.qualifier=!0),g.stage===nt&&(!g.stageSequence||g.stageSequence>1)||g.stage&&[qe,de].includes(g.stage)){let v=g.stage===ct?ct:nt,F=(i.structures?.find(L=>L?.stage===v&&L?.stageSequence===1)?.seedAssignments??[]).find(L=>L.participantId===a);if(F?.participantId){let{participantId:L,seedNumber:w,seedValue:V}=F;$s({eventId:d?.eventId,provisionalPositioning:t,tournamentRecord:o,drawDefinition:i,seedingProfile:s,participantId:L,seedNumber:w,seedValue:V,structureId:m,event:d})}}if(g.structureType!==Ge)jk({provisionalPositioning:t,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:o,drawDefinition:i,drawPosition:u,matchUpsMap:p,structure:g,event:d});else{SS({positionAssignments:P,tournamentRecord:o,drawDefinition:i,matchUpsMap:p,structure:g});let{drawPositions:v,matchUps:O,targetMatchUps:x}=MS({assignments:[U],inContextDrawMatchUps:e,drawDefinition:i,matchUpsMap:p,structure:g});if(v&&O?.length===1&&O[0].matchUpType===jt){let L=(x?.[0].sides??[]).reduce((w,V,k)=>v?.includes(V.drawPosition)?k:w,void 0);Id({inContextTargetMatchUp:x[0],teamParticipantId:a,matchUp:O[0],drawPositionSideIndex:L,tournamentRecord:o,drawDefinition:i})}}let M=i.entries?.find(v=>v.participantId===a),R=d?.entries?.find(v=>v.participantId===a);return!M&&R&&fd({entryStatus:R.entryStatus,entryStage:g.stage,ignoreStageSpace:!0,drawDefinition:i,participantId:a,event:d}),bo({tournamentId:o?.tournamentId,drawDefinition:i,structure:g,event:d}),{positionAssignments:P,...C};function b(v){let O=v.bye,x=v.qualifier,F=v.participantId;return{containsBye:O,containsQualifier:x,containsParticipant:F,filled:O||x||F}}}function jk({provisionalPositioning:t,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:n,drawDefinition:o,drawPosition:i,matchUpsMap:s,structure:a,event:c}){let u={isCollectionMatchUp:!1},{matchUps:p}=Ut({provisionalPositioning:t,matchUpFilters:u,drawDefinition:o,matchUpsMap:s,structure:a,event:c}),{roundMatchUps:m}=Ke({matchUps:p}),{initialRoundNumber:d}=fs({drawPosition:i,matchUps:p}),l=d&&m?.[d].find(f=>f.drawPositions?.includes(i));if(l){let f=hc({matchUpId:l.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:n,drawDefinition:o,drawPosition:i,matchUpsMap:s});if(f.error)return _({stack:"assignDrawPositionToMatchUps",context:{drawPosition:i},result:f})}return{...C}}function yd(t){let{participantIdAttributeName:e="participantId",isQualifierPosition:r,positionActionName:n,tournamentRecord:o,drawDefinition:i,participantId:s,drawPosition:a,structureId:c,event:u}=t,p="positionParticipantAction";if(!i)return{error:Z};let m=yt({tournamentRecord:o,drawDefinition:i,event:u}).appliedPolicies??{},{inContextDrawMatchUps:d,matchUpsMap:l}=t;l||(l=Ne({drawDefinition:i}),Object.assign(t,{matchUpsMap:l})),d||({matchUps:d}=se({inContext:!0,drawDefinition:i,matchUpsMap:l}),Object.assign(t,{inContextDrawMatchUps:d}));let{positionAssignments:f}=bt({drawDefinition:i,structureId:c}),g=f?.find(y=>y.drawPosition===a);if(g?.participantId){let y=g.participantId,P=kn({inContextDrawMatchUps:d,tournamentRecord:o,drawDefinition:i,participantId:s,drawPosition:a,structureId:c,matchUpsMap:l,event:u});return P.success?T({appliedPolicies:m,removedParticipantId:y}):_({result:P,stack:p})}let I=lc({inContextDrawMatchUps:d,tournamentRecord:o,drawDefinition:i,drawPosition:a,structureId:c,matchUpsMap:l,event:u});if(I.error)return _({result:I,stack:p});let h=I.participantId,S=kn({inContextDrawMatchUps:d,isQualifierPosition:r,tournamentRecord:o,drawDefinition:i,participantId:s,drawPosition:a,structureId:c,matchUpsMap:l,event:u});if(!S.success)return _({result:S,stack:p});return T({appliedPolicies:m,removedParticipantId:h});function T({appliedPolicies:y,removedParticipantId:P}){let{structure:U}=at({drawDefinition:i,structureId:c});Qm({drawPositions:[a],structure:U});let E={[e]:s,name:n,drawPosition:a,structureId:c};return cu({appliedPolicies:y,drawDefinition:i,positionAction:E}),_({context:{removedParticipantId:P},result:{...C},stack:p})}}function yv({luckyLoserParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o}){return yd({positionActionName:"luckyLoserDrawPositionAssignment",participantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o})}function lP(t){return yv(t)}function RS({params:t,modMap:e,structure:r}){let{tournamentRecord:n,drawDefinition:o,event:i}=t;for(let s of r.matchUps)e[s.matchUpId]&&(s.roundNumber=e[s.matchUpId],gt({tournamentId:n?.tournamentId,eventId:i?.eventId,drawDefinition:o,matchUp:s}))}function CS(t,e){let r=[{drawDefinition:!0,structureId:!0}];Array.isArray(e)&&r.push(...e);let n=rt(t,r);if(n.error)return n;let o=at(t);if(o.error)return o;let i=o.structure;if(!cr({structure:i}))return _({result:{error:Qo,message:"structure must be adHoc"}});let{roundMatchUps:a=[],roundNumbers:c}=Ke({matchUps:i?.matchUps});return c?.length?{valid:!0,structure:i,roundMatchUps:a,roundNumbers:c}:{error:Xn}}function fP(t){let e=CS(t,[{targetRoundNumber:!0,roundNumber:!0,[He]:cb}]);if(e.error)return e;let{structure:r,roundMatchUps:n,roundNumbers:o}=e,{targetRoundNumber:i,roundNumber:s}=t;if(!o?.includes(s)||!o?.includes(i))return _({result:{error:G},info:"roundNumbers must be valid rounds"});let a=i>s,c=a?et(s+1,i+1):et(i,s),u={};return c.forEach(p=>(n?.[p]??[]).forEach(({matchUpId:m})=>{u[m]=p-(a?1:-1)})),n?.[s]?.forEach(({matchUpId:p})=>u[p]=i),RS({params:t,modMap:u,structure:r}),{...C}}function gP({structurePositionAssignments:t,provisionalPositioning:e,tournamentRecord:r,drawDefinition:n,event:o}){if(!n)return{error:Z};if(!Array.isArray(t))return{error:G};let i="setPositionAssignments";for(let a of t){let{structureId:c,positionAssignments:u}=a;if(!u)continue;let p=at({drawDefinition:n,structureId:c});if(p.error)return p;let m=p.structure;if(!m)return{error:kt};let d=bt({structure:m}).positionAssignments?.map(({drawPosition:I})=>I),l=u?.map(({drawPosition:I})=>I);if(Yt(d,l).length!==d?.length)return _({result:{error:G},info:"drawPositions do not match",stack:i});let f=Ne({drawDefinition:n}),{matchUps:g}=se({inContext:!0,drawDefinition:n,matchUpsMap:f});for(let I of u||[]){let{drawPosition:h,participantId:S,bye:T,qualifier:y}=I;if(T){let P=Hr({tournamentRecord:r,drawDefinition:n,drawPosition:h,matchUpsMap:f,structureId:c,structure:m,event:o});if(P?.error)return P}else if(y)u.forEach(P=>{P.drawPosition===h&&(P.qualifier=!0,delete P.participantId,delete P.bye)});else if(S){let P=kn({provisionalPositioning:e,inContextDrawMatchUps:g,tournamentRecord:r,drawDefinition:n,participantId:S,drawPosition:h,matchUpsMap:f,structureId:c,event:o});if(P?.error)return P}}bo({tournamentId:r?.tournamentId,drawDefinition:n,structure:m,event:o})}let s=t.map(({structureId:a})=>a);return Ot({tournamentId:r?.tournamentId,eventId:o?.eventId,drawDefinition:n,structureIds:s}),{...C}}function IP(t){let e=CS(t,[{roundNumbers:!0,[He]:Be,[tr]:s=>s.length===2&&s.every(Zt)}]);if(e.error)return e;let{structure:r,roundMatchUps:n,roundNumbers:o}=e;if(!t.roundNumbers.every(s=>o?.includes(s)))return _({result:{error:G,message:"roundNumbers must be valid rounds"}});let i={};return t.roundNumbers.forEach((s,a)=>(n?.[s]??[]).forEach(({matchUpId:c})=>{i[c]=t.roundNumbers[1-a]})),RS({params:t,modMap:i,structure:r}),{...C}}function Av({qualifyingParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o}){return yd({positionActionName:"qualifierDrawPositionAssignment",participantId:t,isQualifierPosition:!0,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o})}function hP(t){return Av(t)}function SP({alternateParticipantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o,event:i}){return yd({positionActionName:"alternateDrawPositionAssignment",participantIdAttributeName:"alternateParticipantid",participantId:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,structureId:o,event:i})}function TP({validation:t=!0,tournamentRecord:e,drawDefinition:r,participantId:n,structureId:o,seedValue:i,event:s}){if(!r)return{error:Z};if(!o)return{error:Er};let a=(e?.participants??[]).find(l=>l.participantId===n);if(e&&!a)return{error:mn};let{structure:c}=at({drawDefinition:r,structureId:o});if(!c)return{error:kt};if(!(!t||Zt(i)||i===void 0||i===""||typeof i=="string"&&i.split("-").every(l=>Zt(l)&&pt(l)>0)))return{error:G};let{seedAssignments:p}=on({drawDefinition:r,structure:c}),m=p?.map(l=>l.seedNumber),d=p?.find(l=>l.participantId===n);if(d){let l=typeof i=="string"?i.includes("-")&&i.split("-").map(f=>parseInt(f)).join("-")||parseInt(i)>0&&parseInt(i)||"":i&&i>0&&i||"";d.seedValue=l}else{let f={seedNumber:Math.max(0,...m||[])+1,participantId:n};i&&(f.seedValue=i),c.seedAssignments||(c.seedAssignments=[]),c.seedAssignments.push(f)}return qh({tournamentId:e?.tournamentId,eventId:s?.eventId,drawDefinition:r,structure:c}),{...C}}function bS({drawDefinition:t,structureId:e}){if(!t)return{error:Z};let{structure:r}=at({drawDefinition:t,structureId:e}),n=(t?.links||[]).filter(i=>i.source?.structureId===e).map(i=>i.target?.structureId);return{playoffStructures:(t?.structures||[]).filter(i=>n.includes(i.structureId)),structure:r}}function Ig({withStageGrouping:t,stageSequences:e,stageSequence:r,roundTarget:n,stages:o,event:i,stage:s}){if(!i)return{error:vt};let a={},c=[];for(let u of i.drawDefinitions||[]){let{structures:p,stageStructures:m}=gn({withStageGrouping:t,stageSequences:e,drawDefinition:u,stageSequence:r,roundTarget:n,stages:o,stage:s});if(c.push(...p),m)for(let d of Object.keys(m))a[d]||(a[d]=[]),a[d].push(...m[d])}return{structures:c,stageStructures:a}}function vS({withStageGrouping:t,tournamentRecord:e,stageSequences:r,stageSequence:n,roundTarget:o,stages:i,stage:s}){if(!e)return{error:Y};let a={},c=[];for(let u of e.events||[]){let{structures:p,stageStructures:m}=Ig({withStageGrouping:t,stageSequences:r,stageSequence:n,roundTarget:o,stages:i,event:u,stage:s});if(p&&c.push(...p),m)for(let d of Object.keys(m))a[d]||(a[d]=[]),a[d].push(...m[d])}return{structures:c,stageStructures:a}}function si(t){if(!t?.drawDefinition)return!1;let e=hu(t),r=e?.includesTeamMatchUps,{completedMatchUps:n,pendingMatchUps:o,upcomingMatchUps:i}=e||{};return r&&(n=n?.filter(({matchUpType:a})=>a===jt),o=o?.filter(({matchUpType:a})=>a===jt),i=i?.filter(({matchUpType:a})=>a===jt)),!!(n?.length&&!o?.length&&!i?.length)}function OS(t){let{drawDefinition:e,structureId:r}=t;if(!e)return{error:Z};let{playoffStructures:n}=bS({drawDefinition:e,structureId:r});if(!n?.length)return!1;let o=e?.entries?.filter(c=>c?.entryStatus&&Qr.includes(c.entryStatus))?.length??0,i=0;return(n||[]).reduce((c,u)=>!!((bt({structure:u}).positionAssignments??[])?.filter(d=>(d.participantId&&i++,d?.bye??d?.participantId)).length&&c),!!n.length)||i===o}function _S({significantCharacters:t,accessors:e=[],value:r}){let n=[],o=e[0];if(r?.[o]){let s=e.slice(1);if(Array.isArray(r[o]))r[o].forEach(c=>{let u=_S({accessors:s,significantCharacters:t,value:c});n.push(...u)});else if(r=r[o],s.length){let a=_S({accessors:s,significantCharacters:t,value:r});n.push(...a)}else i({value:r})}function i({value:s}){if(s&&["string","number"].includes(typeof s)){let a=t?s.slice(0,t):s;n.push(a)}}return n}function Ev({targetParticipantIds:t,policyAttributes:e,idCollections:r,participants:n}){if(!Array.isArray(e))return{error:LI};if(!Array.isArray(n))return{error:$a};let o={};return t.forEach(i=>{let s=n.find(c=>c.participantId===i),{values:a}=yP({policyAttributes:e,idCollections:r,participants:n,participant:s});a&&a.forEach(c=>{o[c]||(o[c]=[]),o[c].includes(i)||o[c].push(i)})}),o}function yP({policyAttributes:t,idCollections:e,participants:r,participant:n}){if(!Array.isArray(t))return{error:LI};if(!n)return{error:wi};let o=[];return t.forEach(s=>{let{directive:a,groupings:c,key:u,significantCharacters:p}=s||{};if(u){let m=u.split(".");o.push(..._S({significantCharacters:p,value:n,accessors:m}))}else if(a){let m=s?.includeIds,d=(e?.[a]||[]).filter(l=>!m||m.includes(l));d?.length&&r?.length&&d.forEach(l=>{let f=r.find(g=>g.participantId===l);if(f?.individualParticipantIds?.includes(n.participantId)){let g=f?.participantId;o.push(g)}})}else c&&Object.keys(c).forEach(m=>{c[m].includes(n.participantId)&&o.push(m)})}),{values:ut(o)}}function AP({candidatePositionAssignments:t,participantsWithGroupings:e,policyAttributes:r,idCollections:n}){let o=Object.assign({},...e.map(i=>({[i.participantId]:i})));return t.map(i=>{let s=o[i.participantId],{values:a}=yP({participants:e,policyAttributes:r,idCollections:n,participant:s});return{...i,values:a}})}function Pv({participantIdGroups:t,positionAssignments:e,groupsToAvoid:r}){return Object.assign({},...e.filter(n=>n?.participantId).map(n=>{let{drawPosition:o,participantId:i}=n,s=t?t[i]||[]:[],a=!!r.some(c=>s.includes(c));return{[o]:{participantGroups:s,includesGroupsToAvoid:a}}}))}function Dv(t){let{unfilledPositions:e,chunkedDrawPositions:r}=t,n=Pv(t);return r.map(s=>{let a=e.filter(m=>s.includes(m)),c=i(a),p=a.filter(m=>!c.includes(m)).filter(m=>{let d=Uv(m);return!n[d]?.includesGroupsToAvoid});return{unassigned:a,unpaired:c,pairedNoConflict:p}});function i(s){return s.filter(c=>!a(c));function a(c){let u=Uv(c);return!s.includes(u)}}}function Nv(t){let{unfilledPositions:e,chunkedDrawPositions:r}=t,n=Pv(t);return r.map(o=>{let i=e.filter(u=>o.includes(u)),s=i.length===o.length?i:[],a=o.filter(u=>n[u]?.includesGroupsToAvoid).length;return{unassigned:i,unpaired:s,pairedNoConflict:a?[]:i,conflictsCount:a}})}function Uv(t){return Number(t%2?t+1:t-1)}function Mv({allGroups:t,participantId:e}){return Object.keys(t).filter(r=>t[r].includes(e))}function Rv({selectedParticipantGroups:t,participantIdGroups:e,positionAssignments:r,drawPositionChunks:n,unfilledPositions:o,isRoundRobin:i}){let s=n.map(a=>i?Nv({groupsToAvoid:t,chunkedDrawPositions:a,participantIdGroups:e,positionAssignments:r,unfilledPositions:o}):Dv({groupsToAvoid:t,chunkedDrawPositions:a,participantIdGroups:e,positionAssignments:r,unfilledPositions:o}));if(i){let a=s.map(p=>p.map(m=>m.unassigned).filter(m=>m?.length)).filter(p=>p?.length).sort((p,m)=>(m.length||0)-(p.length||0)),c=s.map(p=>p.map(m=>m.unpaired).filter(m=>m?.length)).filter(p=>p?.length),u=s.map(p=>p.map(m=>m.pairedNoConflict).filter(m=>m?.length)).filter(p=>p?.length).sort((p,m)=>(m.length||0)-(p.length||0));return{unassigned:a,unpaired:c,pairedNoConflict:u}}else{let a=s.map(p=>p.map(m=>m.unassigned).filter(m=>m?.length)).filter(p=>p?.length),c=s.map(p=>p.map(m=>m.unpaired).filter(m=>m?.length)).filter(p=>p?.length),u=s.map(p=>p.map(m=>m.pairedNoConflict).filter(m=>m?.length)).filter(p=>p?.length);return{unassigned:a,unpaired:c,pairedNoConflict:u}}}function xS({positionAssignments:t,participantIds:e}){let r=t.map(n=>n.participantId);return e.filter(n=>!r.includes(n))}function Cv({useSpecifiedGroupKey:t=!1,targetParticipantIds:e,largestFirst:r=!0,allGroups:n,groupKey:o}){let i=Object.assign({},...Object.keys(n).map(p=>[p,n[p].filter(m=>e.includes(m))]).filter(p=>p[1].length).map(([p,m])=>({[p]:m}))),s=Object.keys(i).reduce((p,m)=>i[m].length>p?i[m].length:p,0),a=Object.keys(i).filter(p=>i[p].length===s),c=r?yn(a):yn(Object.keys(i));return o=t&&i[o]?.length?o:c,{participantId:o&&i[o]?yn(i[o]):yn(e),groupKey:o}}function bv({drawPositionGroups:t,positionAssignments:e}){let r=Object.assign({},...e.map(n=>({[n.drawPosition]:n})));return t.map(n=>n.filter(Boolean).map(o=>r[o]).filter(Boolean).filter(o=>!o.participantId&&!o.bye).map(o=>o.drawPosition)).flat().filter(Boolean)}function vv({candidatePositionAssignments:t,unseededParticipantIds:e,participantIdGroups:r,drawPositionChunks:n,drawPositionGroups:o,pairedPriority:i,allGroups:s,groupKey:a}){let u=o.reduce((N,D)=>D.length>N?D.length:N,0)<=2,p=xS({positionAssignments:t,participantIds:e}),m=bv({positionAssignments:t,drawPositionGroups:o}),{participantId:d,groupKey:l}=Cv({targetParticipantIds:p,useSpecifiedGroupKey:u,allGroups:s,groupKey:a}),f=Mv({participantId:d,allGroups:s}),g=Rv({positionAssignments:t,isRoundRobin:u,selectedParticipantGroups:f,participantIdGroups:r,drawPositionChunks:n,unfilledPositions:m}),{unassigned:I,unpaired:h,pairedNoConflict:S}=g,T=S?.length&&S[0],y=h?.length&&h[0],P=i&&T?T:y,U=i?y:T,E=P?.length&&P||U?.length&&U,A;if(E?.length){let N=tn(E);A=tn(N)}else{let N=tn(I[0]);A=tn(N)}return{newGroupKey:l,selectedParticipantId:d,targetDrawPosition:A}}function Ad({isRoundRobin:t,groupedParticipants:e}){let r=[];return t?e.forEach(n=>{let o=n.map(a=>a.drawPosition),i=mg({drawPositions:o}).uniqueMatchUpGroupings??[],s=Object.assign({},...n.map(a=>({[a.drawPosition]:a})));i.forEach(a=>{Fe(s[a[0]].values||[],s[a[1]].values||[])&&(r.push(a),n.conflict=!0)})}):e.forEach(n=>{Fe(n[0]?.values||[],n[1]?.values||[])&&(r.push(n),n.conflict=!0)}),r}function Ov({positionedParticipants:t,potentialDrawPositions:e,drawPositionGroups:r,avoidanceConflicts:n,isRoundRobin:o}){return n.map(i=>{let s=i.map(c=>c.drawPosition);return i.filter(c=>e.includes(c.drawPosition)).map(c=>{let p=e.filter(m=>!s?.includes(m)).filter(m=>{let d=r.find(T=>T.includes(m)).find(T=>T!==m),l=t.find(T=>T.drawPosition===d),g=Ad({isRoundRobin:o,groupedParticipants:[[c,l]]}),h=[t.find(T=>T.drawPosition===m),l],S=Ad({isRoundRobin:o,groupedParticipants:[h]});return!g.length&&!S.length});if(p.length)return{drawPosition:c.drawPosition,possibleDrawPositions:p}}).filter(Boolean)}).flat(1)}function EP(t){let{initialPositionAssignments:e,participantsWithGroupings:r,opponentsToPlaceCount:n,unseededByePositions:o,drawPositionGroups:i,policyAttributes:s,idCollections:a,allGroups:c}=t,u=[],p,m=Math.min(...(i||[]).map(T=>T?.length).filter(Boolean)),d=m>2,l=J(e,!1,!0).filter(T=>!T.qualifier),f=e.filter(T=>!T.participantId&&(!T.bye||o?.includes(T.drawPosition))).map(T=>T.drawPosition);et(0,n).forEach(()=>{let{newGroupKey:T,selectedParticipantId:y,targetDrawPosition:P}=vv({...t,candidatePositionAssignments:l,allGroups:c,groupKey:p});p=T,l.forEach(U=>{U.drawPosition===P&&(U.participantId=y)})});let g=AP({candidatePositionAssignments:l,participantsWithGroupings:r,policyAttributes:s,idCollections:a}),I=ye(g,m),h=Ad({groupedParticipants:I,isRoundRobin:d}),S=0;for(;S<20&&h.length;){let T=Ov({positionedParticipants:g,potentialDrawPositions:f,avoidanceConflicts:h,drawPositionGroups:i,isRoundRobin:d});if(T.length){let y=Yk({candidatePositionAssignments:l,swapOptions:T});y.error&&console.log({result:y}),g=AP({candidatePositionAssignments:l,participantsWithGroupings:r,policyAttributes:s,idCollections:a}),I=ye(g,m),h=Ad({groupedParticipants:I,isRoundRobin:d}),S++}else S=20}return l.forEach(T=>{if(T.bye&&T.participantId){let y=_I;u.push(y)}if(T.qualifier&&T.participantId){let y=_I;u.push(y)}}),{positionAssignments:l,conflicts:h.length,groupedParticipants:I,errors:u}}function Yk({candidatePositionAssignments:t,swapOptions:e}){let r=tn(e);if(!r)return{error:{message:"No swap options"}};let n=r.drawPosition,o=tn(r.possibleDrawPositions),i=t.find(u=>u.drawPosition===n),s=t.find(u=>u.drawPosition===o)??{},a={participantId:s?.participantId,qualifier:s?.qualifier,bye:s?.bye},c={participantId:i.participantId,qualifier:i.qualifier,bye:i.bye};return Object.assign(i,a),Object.assign(s,c),{...C}}function _v({provisionalPositioning:t,unseededParticipantIds:e,inContextDrawMatchUps:r,unseededByePositions:n,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,participants:a,matchUpsMap:c,structureId:u,avoidance:p,drawSize:m,event:d}){if(!p)return{error:QA};let{candidatesCount:l=1,policyAttributes:f,targetDivisions:g}=p,{roundsToSeparate:I}=p,h="randomUnseededSeparation",{structure:S}=at({drawDefinition:i,structureId:u}),{matchUps:T}=Ut({provisionalPositioning:t,matchUpsMap:c,structure:S,event:d});if(g&&vn(g)&&!I){let k=aC(g)||0,W=T.reduce((H,K)=>K.roundNumber>H?K.roundNumber:H,0);I=W<k?1:W-k+1}let{positionAssignments:y}=Se({structure:S}),P=Xm({participantsProfile:{convertExtensions:!0},deepCopy:!1,participants:a}).participantsWithGroupings,U=y?.filter(k=>!k.participantId),E=y?.map(k=>k.drawPosition),A=S?.structureType===Ge,N=A?{structure:S,matchUps:T,allDrawPositions:E,roundsToSeparate:I}:{matchUps:T,allDrawPositions:E,roundsToSeparate:I},{drawPositionGroups:D,drawPositionChunks:M}=A?qk(N):$k(N),R={groupParticipants:a.filter(k=>k.participantType===zr).map(k=>k.participantId),teamParticipants:a.filter(k=>k.participantType===Lt).map(k=>k.participantId),pairParticipants:a.filter(k=>k.participantType===ft).map(k=>k.participantId)},b=Ev({targetParticipantIds:e,policyAttributes:f,idCollections:R,participants:a});if(b.error)return _({result:b,stack:h});let v=Object.assign({},...e.map(k=>{let W=Object.keys(b).filter(H=>(b[H]??[]).includes(k));return{[k]:W}})),O=xS({participantIds:e,positionAssignments:y});if(O.length>(U?.length||0))return{error:Ql};let x,F=O.length,L=et(0,l).map(()=>EP({initialPositionAssignments:y,participantsWithGroupings:P,unseededParticipantIds:e,opponentsToPlaceCount:F,pairedPriority:!1,unseededByePositions:n,participantIdGroups:v,drawPositionChunks:M,drawPositionGroups:D,policyAttributes:f,idCollections:R,allGroups:b,drawSize:m}));if(x=L.reduce((k,W)=>!k||(W.conflicts||0)<(k.conflicts||0)?W:k,void 0),!x||x.conflicts){let k=et(0,l).map(()=>EP({initialPositionAssignments:y,participantsWithGroupings:P,unseededParticipantIds:e,opponentsToPlaceCount:F,pairedPriority:!0,unseededByePositions:n,participantIdGroups:v,drawPositionChunks:M,drawPositionGroups:D,policyAttributes:f,idCollections:R,allGroups:b,drawSize:m}));x=L.concat(...k).filter(H=>!H.errors?.length).reduce((H,K)=>!H||(K.conflicts||0)<(H.conflicts||0)?K:H,void 0)}if(!x)return{error:Qu};let w=(bt({structure:S})?.positionAssignments??[]).filter(k=>k.participantId).map(k=>k.participantId),V=x.positionAssignments.filter(k=>!w.includes(k.participantId));for(let k of V)if(k.bye){let W=Hr({tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,event:d,...k});if(W.error)return _({result:W,stack:h})}else if(k.participantId){let W=kn({automaticPlacement:!0,inContextDrawMatchUps:r,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,event:d,...k});if(W.error)return _({result:W,stack:h,context:{assignment:k}})}return{...C}}function qk(t){let{structure:{structures:e}}=t,r=e.map(n=>n.positionAssignments.map(o=>o.drawPosition));return{drawPositionGroups:r,drawPositionChunks:[r]}}function $k({allDrawPositions:t,roundsToSeparate:e,matchUps:r}){let n=r.filter(d=>d.roundNumber===1).map(d=>d.drawPositions),o=n.flat().sort(me),i=Math.max(...o),s=t.filter(d=>d>i),a=o.length,u=et(a===2?1:2,a).filter(d=>d===Sm(d)),m=u.slice(0,e||u.length).reverse().map(d=>ye(o,d));return s.length&&console.log({fedDrawPositions:s}),{drawPositionGroups:n,drawPositionChunks:m}}function xv({provisionalPositioning:t,inContextDrawMatchUps:e,unseededByePositions:r,multipleStructures:n,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,participants:a,matchUpsMap:c,structureId:u,structure:p,drawSize:m,event:d}){let l="positionUnseededParticipants";p||({structure:p}=at({drawDefinition:i,structureId:u})),u||({structureId:u}=p);let{positionAssignments:f}=Se({structure:p}),{seedAssignments:g}=on({provisionalPositioning:t,drawDefinition:i,structure:p}),I=g?.map(M=>M.participantId).filter(Boolean),{stage:h,stageSequence:S}=p,T=h===ct?dt({element:p,name:Mn})?.extension?.value:void 0,P=Ui({provisionalPositioning:t,drawDefinition:i,stageSequence:S,entryStatuses:ri,structureId:u,roundTarget:T,stage:h}),E=P.filter(M=>!I?.includes(M.participantId)).map(M=>M.participantId),A=f?.filter(M=>!M.participantId&&!M.bye&&!M.qualifier).map(M=>M.drawPosition);if(!n&&E.length>(A?.length||0))return _({result:{error:Ql},context:{unseededParticipantsCount:E.length,unfilledDrawPositionsCount:A?.length},stack:l});let{appliedPolicies:N}=yt({tournamentRecord:o,drawDefinition:i,event:d}),D=N?.[ru];if(p.stage===de){let M=P.reduce((R,b)=>(R[b.groupingValue]||(R[b.groupingValue]=[]),R[b.groupingValue].push(b.participantId),R),{});Object.keys(M).length&&(D||(D={policyName:"Playoff Avoidance"}),D.policyAttributes||(D.policyAttributes=[]),D.policyAttributes.push({groupings:M}))}return D&&a?_v({provisionalPositioning:t,unseededParticipantIds:E,inContextDrawMatchUps:e,unseededByePositions:r,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,participants:a,matchUpsMap:c,structureId:u,avoidance:D,drawSize:m,entries:P}):Kk({provisionalPositioning:t,unseededParticipantIds:E,inContextDrawMatchUps:e,unfilledDrawPositions:A,multipleStructures:n,tournamentRecord:o,drawDefinition:i,seedBlockInfo:s,structureId:u,matchUpsMap:c,drawSize:m,event:d})}function Kk({provisionalPositioning:t,unseededParticipantIds:e,inContextDrawMatchUps:r,unfilledDrawPositions:n,multipleStructures:o,tournamentRecord:i,drawDefinition:s,seedBlockInfo:a,matchUpsMap:c,structureId:u,drawSize:p,event:m}){let d=p>2?Ir(n):n.reverse();for(let l of e){let f=d.pop();if(!o||f){let g=kn({provisionalPositioning:t,inContextDrawMatchUps:r,tournamentRecord:i,drawDefinition:s,seedBlockInfo:a,participantId:l,drawPosition:f,matchUpsMap:c,structureId:u,event:m});if(g?.error&&console.log("!!!!!",{result:g}),g?.error)return _({result:g,stack:"randomUnseededDistribution"})}}return{...C}}function wv(t){let e=t.structure??at(t).structure,r="positionQualifiers",n=[];if(e.stage===qe)return _({result:{error:Oi},stack:r});let{unplacedRoundQualifierCounts:o,positionAssignments:i,roundDrawPositions:s}=zk(t);for(let a of Object.keys(o)){let c=i?.filter(u=>s[a].includes(u.drawPosition)&&!u.participantId&&!u.qualifier&&!u.bye).map(u=>u.drawPosition);if(o[a]>(c||0))return _({result:{error:fE},context:{unfilledDrawPositions:c},stack:r});et(0,o[a]).forEach(()=>{let u=tn(c);n.push(u),i?.forEach(p=>{p.drawPosition===u&&(p.qualifier=!0,delete p.participantId,delete p.bye)})})}return{...C,qualifierDrawPositions:n}}function zk({drawDefinition:t,structure:e,structureId:r}){e||({structure:e}=at({drawDefinition:t,structureId:r})),r||({structureId:r}=e);let{positionAssignments:n}=Se({structure:e}),{stage:o,stageSequence:i}=e,{qualifiersCount:s,roundQualifiersCounts:a}=Is({drawDefinition:t,stageSequence:i,structureId:r,stage:o}),u=(a?Object.keys(a):[]).map(h=>pt(h)),{matchUps:p}=Ut({structure:e}),{roundProfile:m}=Ke({matchUps:p}),d=Object.assign({},...u.filter(h=>m?.[h]).map(h=>({[h]:m?.[h]?.drawPositions?.filter(Boolean)??[]}))),l=n?.filter(h=>h.qualifier).map(h=>h.drawPosition),f=s-(l?.length??0),g=l?.length;return{unplacedRoundQualifierCounts:Object.assign({},...u.map(h=>{let S=n?.filter(T=>T.qualifier&&d[h]?.drawPositions?.includes(T.drawPosition)).map(T=>T.drawPosition);return{[h]:(a?.[h]??0)-(S?.length??0)}})),unplacedQualifiersCount:f,placedQualifiersCount:g,roundQualifiersCounts:a,positionAssignments:n,roundDrawPositions:d,qualifiersCount:s}}function UP({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:r,appliedPolicies:n,validSeedBlocks:o,drawDefinition:i,seedingProfile:s,seedBlockInfo:a,participants:c,groupsCount:u,structureId:p,matchUpsMap:m,structure:d,event:l}){let f=[],g=[],I=0;if(d||({structure:d}=at({drawDefinition:i,structureId:p})),p||(p=d?.structureId),n||(n=yt({drawDefinition:i}).appliedPolicies),!o){let h=d&&Ts({provisionalPositioning:t,appliedPolicies:n,drawDefinition:i,seedingProfile:s,structure:d});h?.error&&g.push(h.error),o=h?.validSeedBlocks}return u=u??o?.length??0,et(0,u).forEach(()=>{if(I<(u||0)){let h=Qk({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:i,seedingProfile:s,seedBlockInfo:a,participants:c,structureId:p,matchUpsMap:m,event:l});h?.success&&(I++,f.push(...h.seedPositions??[])),h.error&&g.push({seedPositionError:h.error})}}),g.length?{error:g}:{...C,seedPositions:f}}function Qk({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,seedingProfile:o,seedBlockInfo:i,participants:s,structureId:a,matchUpsMap:c,event:u}){let{unplacedSeedParticipantIds:p,unfilledPositions:m}=US({provisionalPositioning:t,randomize:!0,drawDefinition:n,seedingProfile:o,seedBlockInfo:i,structureId:a,event:u}),{appliedPolicies:d}=yt({drawDefinition:n}),{avoidance:l}=d??{};l&&s&&p?.length>2;let f=[];for(let g of p){let I=m.pop();if(!I)return{error:Cs};f.push(I);let h=kn({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,seedingProfile:o,participantId:g,seedBlockInfo:i,drawPosition:I,matchUpsMap:c,structureId:a,event:u});if(!h.success)return h}return{...C,seedPositions:f}}function Lv({provisionalPositioning:t,drawDefinition:e,structure:r}){let{positionAssignments:n}=Se({structure:r}),{seedAssignments:o}=on({provisionalPositioning:t,drawDefinition:e,structure:r}),i=Object.assign({},...(o||[]).filter(s=>s.participantId).map(s=>({[s.participantId]:s})));return n?.map(s=>i[s.participantId]?{...s,seedNumber:i[s.participantId].seedNumber,seedValue:i[s.participantId].seedValue}:"").filter(Boolean)}function Fv({orderedSortedFirstRoundSeededDrawPositions:t,validSeedBlocks:e,byesToPlace:r}){let n=[];e.forEach(i=>{if(r-n.length>i.drawPositions.length)n.push(...i.drawPositions);else{let a=PP(ye(i.drawPositions,2)),c,u=t[n.length];for(;c=hg(a,u);)n.push(c),u=t[n.length]}});let o=n.map(i=>Array.isArray(i)?Ir(i):i).flat(1/0);return UI(r)&&e.map(s=>s.seedNumbers[0]).includes(r)?t:o}function hg(t,e){if(Array.isArray(t)&&t.length!==2)return t.pop();if(!Array.isArray(t[0]))return t.includes(e)?t.indexOf(e)?t.pop():t.shift():Math.round(Math.random())?t.pop():t.shift();let r=t[0].flat(1/0).length,n=t[1].flat(1/0).length;if(r===n){let o=t[0].flat(1/0).includes(e)?t[0]:t[1];return hg(e?o:t[Math.round(Math.random())],e)}return r<n?hg(t[1],e):hg(t[0],e)}function PP(t){let e=Math.floor(t.length/2);return t.length>2?[PP(t.slice(0,e)),PP(t.slice(e))]:t}function Gv({provisionalPositioning:t,relevantMatchUps:e,appliedPolicies:r,drawDefinition:n,seedingProfile:o,seedBlockInfo:i,byesToPlace:s,structure:a}){i||(i=Ts({provisionalPositioning:t,appliedPolicies:r,drawDefinition:n,seedingProfile:o,structure:a}));let{isFeedIn:c,isLuckyStructure:u,isContainer:p}=i,{validSeedBlocks:m}=i;r?.seeding?.containerByesIgnoreSeeding&&(m=[]);let d=Lv({provisionalPositioning:t,drawDefinition:n,structure:a})??[],l=ut([].concat(...e.map(P=>P.drawPositions))),f=d.filter(P=>l.includes(P.drawPosition)),g=(P,U)=>Ic(P.seedValue)-Ic(U.seedValue),h=m.reduce((P,U)=>{let E=f.filter(A=>U.drawPositions?.includes(A.drawPosition)).sort(g);return P.concat(...E)},[]).map(P=>P.drawPosition),S=Fv({orderedSortedFirstRoundSeededDrawPositions:h,validSeedBlocks:m,byesToPlace:s}),T=kv({orderedSeedDrawPositions:h,relevantMatchUps:e}).slice(0,s),y=kv({orderedSeedDrawPositions:S,relevantMatchUps:e}).slice(0,s);return{strictSeedOrderByePositions:T,blockSeedOrderByePositions:y,isLuckyStructure:u,positionedSeeds:d,isContainer:p,isFeedIn:c}}function kv({orderedSeedDrawPositions:t,relevantMatchUps:e}){let n=e.map(i=>i.drawPositions).map(i=>i?.sort((s,a)=>s-a)).filter(i=>i?.[0]+1===i?.[1]);return t.map(i=>n.find(s=>s?.includes(i))).filter(Boolean).map(i=>i?.reduce((s,a)=>t.includes(a)?s:a,void 0)).filter(Boolean)}function Vv({provisionalPositioning:t,seedOrderByePositions:e,isLuckyStructure:r,appliedPolicies:n,drawDefinition:o,seedLimit:i,structure:s,isFeedIn:a}){let c=n?.seeding?.seedingProfile,u=s.stage===ct,{positionAssignments:p}=Se({structure:s}),m=p?.filter(O=>O.participantId).map(O=>O.drawPosition),d={isCollectionMatchUp:!1},{matchUps:l,roundMatchUps:f}=Ut({provisionalPositioning:t,matchUpFilters:d,structure:s}),g=f?.[1]||[],I=s.structureType===Ge?l:g,h=ut([].concat(...I.map(O=>O.drawPositions))),S=Math.min(...h)-1,T=m?.filter(O=>h.includes(O)),y=O=>{let x=Math.ceil(O.length/2),F=[O.slice(0,x),O.slice(x)],L=F.map(B=>[].concat(...B.flat(1/0)).length),w=Math.min(...L.flat(1/0)),V=Math.max(...L.flat(1/0)),k=L.indexOf(V),W=w!==V,H=Ir(F),[K,q]=!w||W?[F[k],F[1-k]]:[H[0],H[1]];return{greaterHalf:K,lesserHalf:q}},P=O=>{let{greaterHalf:x,lesserHalf:F}=y(O),{greaterHalf:L,lesserHalf:w}=y(x),k=Ir(L.flat(1/0)).pop(),W=L.flat().filter(K=>K!==k);return{newlyFilteredChunks:[...F,...w,W],drawPosition:k}},U=O=>!e.includes(O),E=O=>!T?.includes(O),A=O=>{let F=ye(O.sort(me),Math.ceil(O.length/4)).map(V=>V.filter(E)),L=[].concat(...F.flat(1/0)).length,w=[];for(let V=0;V<L;V++){let{newlyFilteredChunks:k,drawPosition:W}=P(F);w.push(W),F=k}return w},{validSeedBlocks:N}=Ts({provisionalPositioning:t,allPositions:!0,appliedPolicies:n,drawDefinition:o,structure:s}),D=N?.map(O=>O.drawPositions?.map(x=>x+S)),M;if(a){let O=h.length,{seedBlocks:x}=lg({cluster:vp(c)===Kc,participantsCount:O});M=x.map(L=>L.map(w=>w+S)).map(A).filter(L=>L.length)}else u?M=D?.map(O=>O.filter(E)):M=D?.map(A).filter(O=>O.length);let R=I.map(O=>O.drawPositions).map(O=>O?.sort((x,F)=>x-F)).filter(O=>O?.[0]+1===O?.[1]),b=O=>R.reduce((x,F)=>F.includes(O)?F.reduce((L,w)=>w!==O?w:L,void 0):x,void 0),v=M.map(O=>O.map(b)).flat(1/0).filter(E).filter(U).filter(Boolean);if(u&&!s.structures){let O=i%4,x=v.slice(0,O),F=f[s.roundLimit]?.length,L=ye(v.slice(O),F).map(Ir).flat();v=x.concat(L)}return{unseededByePositions:v}}function Bv({provisionalPositioning:t,drawDefinition:e,matchUpsMap:r,structure:n,event:o}){let i={isCollectionMatchUp:!1},{matchUps:s,roundMatchUps:a}=Ut({afterRecoveryTimes:!1,provisionalPositioning:t,drawDefinition:e,matchUpFilters:i,matchUpsMap:r,structure:n,event:o}),c=a?.[1]||[],u=n?.structureType===Ge,p=u?s:c,m=u?n?.structures?.length||0:s.length,{structureId:d,stage:l,stageSequence:f}=n,g=Ui({entryStatuses:Qr,provisionalPositioning:t,drawDefinition:e,stageSequence:f,structureId:d,stage:l}),{qualifiersCount:I}=Is({provisionalPositioning:t,drawDefinition:e,stageSequence:f,structureId:d,stage:l}),h=g.length+I,{positionAssignments:S,unassignedPositions:T}=Se({structure:n}),y=T?.map(D=>D.drawPosition),P=S?.filter(D=>D.bye).length,U=S?.filter(D=>D.bye).map(D=>D.drawPosition),E=p.map(D=>D.drawPositions).filter(D=>D?.reduce((M,R)=>!U?.includes(R)&&M,!0)).flat(1/0).filter(D=>y?.includes(D)),A=S?.length,N=A?A-h:0;return N>m&&n.stageSequence===1&&n.stage!==qe&&(N=m),{placedByes:P,byesCount:N,relevantMatchUps:p,placedByePositions:U,roundMatchUps:a,positionsToAvoidDoubleBye:E}}function DP({provisionalPositioning:t,tournamentRecord:e,appliedPolicies:r,drawDefinition:n,seedBlockInfo:o,seedingProfile:i,matchUpsMap:s,structureId:a,structure:c,seedLimit:u,seedsOnly:p,event:m}){c||({structure:c}=at({drawDefinition:n,structureId:a})),a||(a=c?.structureId);let d=!(c?.structures??c?.stage===ct),{byesCount:l,placedByes:f,relevantMatchUps:g}=Bv({provisionalPositioning:t,drawDefinition:n,matchUpsMap:s,structure:c,event:m}),I=l-(f||0);if(I<=0)return{...C};let{strictSeedOrderByePositions:h,blockSeedOrderByePositions:S,isLuckyStructure:T,isFeedIn:y}=Gv({provisionalPositioning:t,relevantMatchUps:g,appliedPolicies:r,drawDefinition:n,seedingProfile:i,seedBlockInfo:o,byesToPlace:I,structure:c}),P=c?.structureType&&[Ge,ap].includes(c.structureType)&&r?.seeding?.containerByesIgnoreSeeding,U=d&&S?.length?S:h,{unseededByePositions:E}=Vv({provisionalPositioning:t,seedOrderByePositions:U,isLuckyStructure:T,appliedPolicies:r,drawDefinition:n,seedLimit:u,structure:c,isFeedIn:y}),A=R=>R%2,N=(R,b)=>(R||[]).every(v=>A(v)?b!==v+1:b!==v-1),D=[].concat(...U);if(!p)for(;E.length;){let R=E.find(b=>N(D,b));R?(D.push(R),E=E.filter(b=>b!==R)):(D.push(...E),E=[])}P&&(D=Ir(D),Ur({ignoreSeededByes:P})&&console.log({byePositions:D}));let M=D.slice(0,I);for(let R of M){let b=Hr({provisionalPositioning:t,tournamentRecord:e,drawDefinition:n,drawPosition:R,matchUpsMap:s,structureId:a,structure:c,event:m});if(b?.error)return b}return{...C,unseededByePositions:E,byeDrawPositions:M}}function Sc(t){let{drawDefinition:e}=t,{applyPositioning:r=!0,provisionalPositioning:n,multipleStructures:o,placeByes:i=!0,tournamentRecord:s,placementGroup:a,seedingProfile:c,structureId:u,seedLimit:p,seedsOnly:m,drawType:d,drawSize:l,event:f}=t,g=[];r||(LE(),e=J(e,!1,!0));let I=x=>(r||sf(),_({result:x,stack:"automatedPositioning"})),h=x=>(r||sf(),x),S=at({drawDefinition:e,structureId:u});if(S.error)return I(S);let T=S.structure;if(!T)return{error:kt};let y=t.appliedPolicies||yt({drawDefinition:e,structure:T,event:f})?.appliedPolicies,{qualifiersCount:P}=Is({stageSequence:T.stageSequence,provisionalPositioning:n,stage:T.stage,drawDefinition:e,structureId:u}),U=ri;if(!Ui({stageSequence:T.stageSequence,provisionalPositioning:n,stage:T.stage,placementGroup:a,drawDefinition:e,entryStatuses:U,structureId:u})?.length&&!P)return h({...C});let A=t.matchUpsMap??Ne({drawDefinition:e}),N=t.inContextDrawMatchUps??se({inContext:!0,drawDefinition:e,matchUpsMap:A})?.matchUps,D=[],M=Ts({provisionalPositioning:n,appliedPolicies:y,drawDefinition:e,seedingProfile:c,structure:T});if(M.error)return M;let{validSeedBlocks:R}=M;g.push({validSeedBlocks:R});let b=t.participants||(s?Gt({withIndividualParticipants:!0,convertExtensions:!0,tournamentRecord:s})?.participants:[]);if(vp(T.seedingProfile||c)===mi){let x=i?DP({provisionalPositioning:n,tournamentRecord:s,appliedPolicies:y,drawDefinition:e,seedBlockInfo:M,matchUpsMap:A,structure:T,seedLimit:p,seedsOnly:m,event:f}):void 0;if(x?.error)return I(x);D=x.unseededByePositions,g.push({action:"positionByes",unseededByePositions:D});let F=T.seedingProfile?{positioning:T.seedingProfile}:c;if(x=UP({seedingProfile:F,provisionalPositioning:n,inContextDrawMatchUps:N,tournamentRecord:s,appliedPolicies:y,validSeedBlocks:R,drawDefinition:e,seedBlockInfo:M,participants:b,matchUpsMap:A,structure:T,event:f}),x.error)return I(x);g.push({seedPositions:x.seedPositions,action:"positionSeedBlocks"})}else{if(d!==ki){let F=T.seedingProfile?{positioning:T.seedingProfile}:c,L=UP({seedingProfile:F,provisionalPositioning:n,inContextDrawMatchUps:N,tournamentRecord:s,appliedPolicies:y,validSeedBlocks:R,drawDefinition:e,seedBlockInfo:M,participants:b,matchUpsMap:A,structure:T,event:f});if(L.error)return I(L);g.push({action:"positionSeedBlocks",seedPositions:L.seedPositions})}let x=i?DP({provisionalPositioning:n,tournamentRecord:s,appliedPolicies:y,drawDefinition:e,seedBlockInfo:M,matchUpsMap:A,structure:T,seedLimit:p,seedsOnly:m,event:f}):void 0;if(x?.error)return I(x);D=x?.unseededByePositions,g.push({action:"positionByes",byeDrawPositions:x?.byeDrawPositions,unseededByePositions:D})}let v={};if(!m){let x=wv({inContextDrawMatchUps:N,tournamentRecord:s,appliedPolicies:y,validSeedBlocks:R,drawDefinition:e,seedBlockInfo:M,participants:b,matchUpsMap:A,structure:T});if(x.error||(x.conflicts&&(v.qualifierConflicts=x.conflicts),g.push({action:"positionQualifiers",qualifierDrawPositions:x.qualifierDrawPositions}),x=xv({provisionalPositioning:n,inContextDrawMatchUps:N,unseededByePositions:D,multipleStructures:o,tournamentRecord:s,drawDefinition:e,seedBlockInfo:M,participants:b,matchUpsMap:A,structureId:u,structure:T,drawSize:l,event:f}),x.error))return I(x);x.conflicts&&(v.unseededConflicts=x.conflicts),g.push({action:"positionUnseededParticipants"})}let{positionAssignments:O}=bt({drawDefinition:e,structure:T});return Ot({drawDefinition:e,structureIds:[u]}),r||sf(),{positionAssignments:O,conflicts:v,...C,positioningReport:g}}function Ks(t){let{applyPositioning:e=!0,provisionalPositioning:r,tournamentRecord:n,drawDefinition:o,seedingProfile:i,structureId:s,placeByes:a,seedsOnly:c}=t;if(!o)return{error:Mr};if(!si({drawDefinition:o,structureId:s})&&!r)return{error:wl};let p=bS({drawDefinition:o,structureId:s}).playoffStructures?.sort((l,f)=>Of(l)-Of(f)),m=[],d=[];if(p)for(let l of p){let{structureId:f}=l,g=Sc({structureId:f,provisionalPositioning:r,applyPositioning:e,tournamentRecord:n,drawDefinition:o,seedingProfile:i,placeByes:a,seedsOnly:c});if(g.error)return g;g.positionAssignments&&m.push({positionAssignments:g.positionAssignments,structureId:f}),g.positioningReport&&d.push(g.positioningReport)}return{...C,structurePositionAssignments:m,positioningReports:d}}function NP({drawDefinition:t,orderMap:e}){return t?((typeof e!="object"||!Object.values(e).every(r=>It(r)))&&_({result:{error:G},context:{orderMap:e}}),t.structures||(t.structures=[]),t.structures.forEach(r=>{let n=e[r.structureId];n&&(r.structureOrder=n)}),t.structures.sort((r,n)=>Ba(r.structureOrder)-Ba(n.structureOrder)),{...C}):{error:Z}}function Eu({drawDefinition:t}){let e=t.structures??[],r=t.links??[],n=new Map,o=I=>{let h=n.get(I)||n.set(I,{drawSources:[],drawTargets:[],progeny:[],sources:[],targets:[]})&&n.get(I);if(h&&!h?.stage){let S=e.find(T=>T.structureId===I);h.stage=S?.stage}return h},i={},s={},a=r.map(I=>{let h=I.source.structureId,S=I.target.structureId,T=o(h),y=o(S);return[di,En,cp,mi].includes(I.target.feedProfile)?(T?.targets.push(S),y?.sources.push(h)):I.target.feedProfile===dn&&(y?.drawSources.push(h),T?.drawTargets.push(S)),s[S]=s[S]||I.target.feedProfile===dn,i[S]=ut([...i[S]||[],h]).filter(Boolean),[I.source.structureId,I.target.structureId]});for(let I of n.keys()){let h=n.get(I);if(h){let S=h.targets??[];for(;S.length;){let T=S.pop(),y=T&&n[T];y?.targets?.length?S.push(...y.targets):y&&(h.rootStage=y.stage)}if(h.rootStage||(h.rootStage=h.stage),!h.targets?.length){let T=h.sources??[];for(;T.length;){let y=T.pop(),P=y&&n[y];if(P?.sources?.length){for(let U of P.sources)h.progeny?.includes(U)||h.progeny?.push(U);T.push(...P.sources)}}}}}let c=0;for(let I of n.keys()){let h=n.get(I);if(h&&h.rootStage===ct){let S=[h.drawTargets?.[0]],T=0;for(;S.length;){T+=1;let y=S.pop(),P=y?n.get(y):void 0;P?.drawTargets?.length&&S.push(P.drawTargets[0])}h.distanceFromMain=T,T>c&&(c=T)}}let u=a.length;et(0,Math.ceil(u/2)).forEach(()=>{a=et(0,u).map(I=>{let h=a[I],S=a.reduce((T,y)=>Fe(h,y)?T.concat(...y):T,[])||[];return ut(h.concat(...S))})});let p=a[0],m=(I,h)=>Yt(I,h).length===I.length,d=a.slice(1).reduce((I,h)=>I&&m(h,p),!0),l=[p].filter(Boolean),f=[p].filter(Boolean);e.forEach(I=>{let{structureId:h,stage:S}=I;l.find(y=>y.includes(h))||(l.push([h]),S!==$e&&f.push([h]))});let g=d&&f.length===1;return!r?.length&&e.length===1&&o(e[0].structureId),{structureProfiles:Object.fromEntries(n),allStructuresLinked:g,maxQualifyingDepth:c,sourceStructureIds:i,hasDrawFeedProfile:s,structureGroups:l}}function wS({drawDefinition:t}){let{maxQualifyingDepth:e,structureProfiles:r}=Eu({drawDefinition:t});for(let n of t.structures){let o=r[n.structureId];o.distanceFromMain&&(n.stageSequence=e+1-o.distanceFromMain)}return{...C}}function Sg(t){let e=rt(t,[{[ie]:!0,[Ve]:!0}]);if(e.error)return e;let{tournamentRecord:r,drawDefinition:n,structure:o,link:i}=t;return Xk({tournamentId:r.tournamentId,drawDefinition:n,structure:o,link:i})}function Xk(t){let e=rt(t,[{[Ve]:!0,[mp]:!0},{link:!0,[He]:Kr,[MA]:kl}]);if(e.error)return e;let{drawDefinition:r,tournamentId:n,structure:o,eventId:i,link:s}=t,a=s.target.structureId,c=at({drawDefinition:r,structureId:a});if(c.error)return _({stack:"attachQualifyingStructure",context:{targetStructureId:a},result:c});r.structures||(r.structures=[]),r.links||(r.links=[]),r.structures.push(o),r.links.push(s),wS({drawDefinition:r});let u=Ut({structure:o})?.matchUps||[];return Co({drawDefinition:r,tournamentId:n,matchUps:u,eventId:i}),Ot({drawDefinition:r,structureIds:[o.structureId]}),{...C}}function MP({drawDefinition:t,structureDetails:e}){if(!Array.isArray(e))return{error:G};if(!t)return{error:Z};let r=Object.assign({},...e.map(n=>{if(!ht(n))return;let{structureId:o,structureName:i}=n||{};if(!(!o||!i))return{[o]:i}}).filter(Boolean));if(!Object.values(r).length)return{error:st};for(let n of t.structures||[]){let o=r[n.structureId];if(o&&(n.structureName=o),n.structures)for(let i of n.structures){let s=r[i.structureId];s&&(i.structureName=s)}}return{...C}}function Tg({drawDefinition:t,timeItem:e}){if(!t)return{error:Mr};if(!e)return{error:Zl};let r=e&&Object.keys(e),n=["itemType","itemValue"];if(!(n.filter(s=>r.includes(s)).length===n.length))return{error:Jl};t.timeItems||(t.timeItems=[]);let i=new Date().toISOString();return Object.assign(e,{createdAt:i}),t.timeItems.push(e),Ta({drawDefinition:t}),{...C}}function RP(t){let{tournamentRecord:e,drawDefinition:r,structureId:n,event:o}=t,i=rt(t,[{drawDefinition:!0,structureId:!0}]);if(i.error)return i;let s=r.structures??[],a=s.find(h=>h.structureId===n);if(!a)return{error:kt};let c=s.find(({stage:h,stageSequence:S})=>h===nt&&S===1),u=n===c?.structureId,p=s.filter(({stage:h})=>h===ct).map(Br("structureId"));if(u&&!p.length)return{error:RA};let m=p.includes(n),d=Jk({isQualifyingStructure:m,structure:a,...t});if(d?.error)return d;let{structureIdsToRemove:l,relatedStructureIdsMap:f}=tG({qualifyingStructureIds:p,isQualifyingStructure:m,isMainStageSequence1:u,mainStageSequence1:c,drawDefinition:r,structureId:n}),{removedMatchUpIds:g,removedStructureIds:I}=eG({relatedStructureIdsMap:f,qualifyingStructureIds:p,isMainStageSequence1:u,mainStageSequence1:c,drawDefinition:r,structureIdsToRemove:l,structureId:n});if(Zk({removedMatchUpIds:g,drawDefinition:r}),u){let h=(c.matchUps??[])?.map(Br("matchUpId"));g.push(...h),c.positionAssignments=[],c.seedAssignments=[],c.matchUps=[],c.extensions&&(c.extensions=[])}return m&&wS({drawDefinition:r}),Yn({tournamentId:e?.tournamentId,matchUpIds:g,action:"removeStructure",eventId:o?.eventId,drawDefinition:r}),Ot({drawDefinition:r,eventId:o?.eventId}),{...C,removedMatchUpIds:g,removedStructureIds:I}}function Jk({isQualifyingStructure:t,tournamentRecord:e,drawDefinition:r,structureId:n,structure:o,event:i,force:s}){let a=[n];if(t){let p=d=>r.links?.find(l=>l.target.structureId===d),m=p(n)?.source.structureId;for(;m;)a.push(m),m=p(m)?.source.structureId}if(se({matchUpFilters:{structureIds:a},drawDefinition:r}).matchUps?.some(({score:p})=>Ie({score:p}))){let p=yt({tournamentRecord:e,drawDefinition:r,structure:o,event:i})?.appliedPolicies;if(!(s??p?.[en]?.allowDeletionWithScoresPresent?.structures))return{error:tp}}return{...C}}function Zk({removedMatchUpIds:t,drawDefinition:e}){let{matchUps:r}=se({drawDefinition:e});r?.forEach(n=>{n.winnerMatchUpId&&t.includes(n.winnerMatchUpId)&&delete n.winnerMatchUpId,n.loserMatchUpId&&t.includes(n.loserMatchUpId)&&delete n.loserMatchUpId})}function tG({qualifyingStructureIds:t,isQualifyingStructure:e,isMainStageSequence1:r,mainStageSequence1:n,drawDefinition:o,structureId:i}){let a=(o.structures??[]).map(Br("structureId")),c=d=>o.links?.map(l=>l.source.structureId===d&&l.target.structureId!==n?.structureId&&l.target.structureId).filter(Boolean)??[],u=d=>o.links?.map(l=>t.includes(l.source.structureId)&&l.target.structureId===d&&l.source.structureId).filter(Boolean)??[],p=new Map;return a.forEach(d=>p.set(d,e?u(d):c(d))),{structureIdsToRemove:r?p.get(i):[i],relatedStructureIdsMap:p}}function eG({relatedStructureIdsMap:t,qualifyingStructureIds:e,isMainStageSequence1:r,mainStageSequence1:n,drawDefinition:o,structureIdsToRemove:i,structureId:s}){let a=[],c=[];for(;i?.length;){let u=i.pop();c.push(...oG({idBeingRemoved:u,drawDefinition:o}));let p=nG({qualifyingStructureIds:e,isMainStageSequence1:r,idBeingRemoved:u,drawDefinition:o,structureId:s});a.push(...p.removedStructureIds);let m=rG({relatedStructureIdsMap:t,mainStageSequence1:n,idBeingRemoved:u,structureId:s});m?.length&&i.push(...m)}return{removedMatchUpIds:c,removedStructureIds:a}}function rG({idBeingRemoved:t,relatedStructureIdsMap:e,mainStageSequence1:r,structureId:n}){return t&&e.get(t)?.filter(o=>o!==r?.structureId||n===r.structureId)}function nG({qualifyingStructureIds:t,isMainStageSequence1:e,idBeingRemoved:r,drawDefinition:n,structureId:o}){let i=[];return n.links=n.links?.filter(s=>s.source.structureId!==r&&s.target.structureId!==r)??[],(!e||e&&t.length||r!==o)&&(n.structures=(n.structures??[]).filter(s=>(r&&r===s.structureId&&i.push(r),s.structureId!==r))),{removedStructureIds:i}}function oG({idBeingRemoved:t,drawDefinition:e}){let{structure:r}=at({structureId:t,drawDefinition:e}),n=Ut({structure:r}).matchUps;return $m(n)}function Op({stageSequence:t=1,drawDefinition:e,drawSize:r,stage:n}){if(!e)return{error:Z};if(!Jf({drawDefinition:e,stage:n}))return{error:Oi};let o=Nb({drawDefinition:e,stage:n}),{qualifiersCount:i}=Is({drawDefinition:e,stageSequence:t,stage:n}),s=o+i;if(r<s)return{error:OI};let{entryProfile:a}=qf({attributes:[{[n]:{drawSize:r}}],drawDefinition:e});return Ot({drawDefinition:e}),{...C,entryProfile:a}}function LS({qualifiersCount:t=0,drawDefinition:e,stage:r}){return e?Jf({drawDefinition:e,stage:r})?r!==nt?{error:OI,info:"qualifiersCount can only be set for main stage"}:(qf({attributes:[{[r]:{qualifiersCount:t}}],drawDefinition:e}),Ot({drawDefinition:e}),{...C}):{error:Oi}:{error:Z}}function Hv({drawDefinition:t,drawSize:e}){if(!t)return{error:Z};let r=Op({stage:$e,stageSequence:1,drawDefinition:t,drawSize:e});return r.error?r:(Ot({drawDefinition:t}),{...C})}function CP(t){return Hv(t)}var Wv="qualifierDrawPositionAssignment",jv="withdrawParticipantAtDrawPosition",Yv="alternateDrawPositionAssignment",qv="luckyLoserDrawPositionAssignment",bP="removeDrawPositionAssignment",FS="swapDrawPositionAssignments",$v="modifyPairAssignment",Kv="adHocPositionSwap",zv="modifyParticipantOtherName",vP="assignDrawPosition",Qv="removeSeededParticipant",Xv="assignDrawPositionBye",Jv="modifySeedAssignment",kS="addPenalty",yg="MODIFY_PAIR",_p="QUALIFIER",Ag="ALTERNATE",Eg="WITHDRAW",ys="ASSIGN",GS="REMOVE",Ug="LUCKY",xp="REMOVE_SEED",wp="SWAP",Uu="NICKNAME",zs="SEED_VALUE",Qs="PENALTY",Ed="BYE",Zv={MODIFY_PAIR_ASSIGNMENT:yg,QUALIFYING_PARTICIPANT:_p,ALTERNATE_PARTICIPANT:Ag,WITHDRAW_PARTICIPANT:Eg,ASSIGN_PARTICIPANT:ys,LUCKY_PARTICIPANT:Ug,REMOVE_ASSIGNMENT:GS,SWAP_PARTICIPANTS:wp,ADD_NICKNAME:Uu,REMOVE_SEED:xp,ADD_PENALTY:Qs,ASSIGN_BYE:Ed,SEED_VALUE:zs};function OP({tournamentRecord:t,drawDefinition:e,drawPositions:r,structureId:n,event:o}){if(!e)return{error:Z};if(!n)return{error:Er};if(r?.length!==2)return{error:G,drawPositions:r};let i=Ne({drawDefinition:e}),{matchUps:s}=se({inContext:!0,drawDefinition:e,matchUpsMap:i}),{structure:a}=at({drawDefinition:e,structureId:n});if(!a)return{error:kt};let c=yt({tournamentRecord:t,drawDefinition:e,event:o}).appliedPolicies??{},u;if(a.structureType===Ge?u=aG({inContextDrawMatchUps:s,tournamentRecord:t,drawDefinition:e,drawPositions:r,matchUpsMap:i,structure:a,event:o}):u=iG({inContextDrawMatchUps:s,tournamentRecord:t,drawDefinition:e,drawPositions:r,matchUpsMap:i,structure:a,event:o}),u.error)return u;if(Qm({structure:a,drawPositions:r}),cu({appliedPolicies:c,drawDefinition:e,positionAction:{name:FS,drawPositions:r,structureId:n}}),bo({tournamentId:t?.tournamentId,drawDefinition:e,structure:a,event:o}),o.eventType===Cr){let m=Ut({matchUpFilters:{matchUpTypes:[xr]},inContext:!0,structure:a}).matchUps.filter(l=>l.drawPositions?.some(f=>r.includes(f))),d=Ut({matchUpFilters:{matchUpTypes:[xr]},structure:a}).matchUps;m.forEach(l=>{(l.sides||[]).forEach(f=>{let g=f?.drawPosition;if(r.includes(g)){let I=f.participantId,h=d.find(({matchUpId:T})=>T===l.matchUpId),S=l?.sides?.reduce((T,y,P)=>y.drawPosition===g?P:T,void 0);Id({inContextTargetMatchUp:l,drawPositionSideIndex:S,teamParticipantId:I,tournamentRecord:t,drawDefinition:e,matchUp:h,event:o})}})})}return Ot({drawDefinition:e,structureIds:[n]}),{...C}}function iG({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPositions:n,matchUpsMap:o,structure:i,event:s}){let a=i?.positionAssignments.filter(p=>n?.includes(p.drawPosition));if(!a)return{error:G,structure:i,info:"Missing positionAssignments"};if(a.filter(({bye:p})=>p).length===2)return{...C};if(a.filter(({qualifier:p})=>p).length===2)return{...C};let c=a.some(({qualifier:p})=>p);return a.some(({bye:p})=>p)&&!c?tO({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s}):sG({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s})}function tO({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:n,matchUpsMap:o,structure:i,event:s}){let a=n.find(({bye:f})=>f),c=n.find(({participantId:f})=>f),u=a.drawPosition,{participantId:p,drawPosition:m}=c,{structureId:d}=i,l=Au({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o});return l.error||(l=Au({drawPosition:m,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o}),l.error)||(Hr({drawPosition:m,tournamentRecord:e,drawDefinition:r,structureId:d,matchUpsMap:o,event:s}),l=kn({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:d,participantId:p,matchUpsMap:o,event:s}),l.error)?l:{...C}}function sG({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:n,matchUpsMap:o,structure:i,event:s}){let a=Object.assign({},...n.map((c,u)=>{let{drawPosition:p}=c,m={...n[1-u],drawPosition:p};return{[p]:m}}));return i.positionAssignments=i.positionAssignments.map(c=>a[c.drawPosition]||c),gg({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:o,assignments:n,structure:i,event:s}),{...C}}function aG({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPositions:n,matchUpsMap:o,structure:i,event:s}){let a=i.structures?.reduce((p,m)=>{let d=m?.positionAssignments.filter(l=>n?.includes(l.drawPosition));return d&&p.push(...d),p},[]);if(a.filter(({bye:p})=>p).length===2)return{...C};if(a.filter(({qualifier:p})=>p).length===2)return{...C};gg({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,matchUpsMap:o,assignments:a,structure:i,event:s});let c=a.some(({qualifier:p})=>p);if(a.some(({bye:p})=>p)&&!c)tO({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,assignments:a,matchUpsMap:o,structure:i,event:s});else{let p=J(a,!1,!0);a.forEach((m,d)=>{let l=p[1-d].participantId;m.qualifier=p[1-d].qualifier,m.participantId=l})}return{...C}}function _P({tournamentRecord:t,drawDefinition:e,participantId:r,structureId:n}){let o="removeSeededParticipant";if(!t)return{error:Y};if(!e)return{error:Z};let i=(e.structures??[]).find(a=>a.structureId===n);return i?!i.stage||![nt,ct].includes(i.stage)||i.stage===nt&&i.stageSequence!==1?_({result:{error:Qo},stack:o}):i.seedAssignments?.find(a=>a.participantId===r)?{...C}:_({info:"participant not seeded",result:{error:ve},context:{participantId:r}}):_({result:{error:kt},stack:o})}function Ma({targetEntryRound:t=1,finishingPositions:e,sourceRoundNumber:r,sourceStructureId:n,targetStructureId:o,linkType:i=fo}){return!n||!o?{error:Er}:{link:ot({linkType:i,source:{roundNumber:r,structureId:n,finishingPositions:e},target:{feedProfile:dn,roundNumber:t,structureId:o}})}}function Ud({roundPosition:t,roundNumber:e,idPrefix:r,uuids:n}){return r?`${r}-${e}-${t}`:n?.pop()||Dt()}function Lp({includeMatchUpType:t,matchUpType:e,roundNumber:r,matchUps:n,idPrefix:o,isMock:i,uuids:s,nodes:a}){let c=0,u=[],p=1,m=r-1,d=a?.length;for(;c<(d||0);){let l=a?.[c],f=a?.[c+1];m&&(l.roundNumber=m),f&&m&&(f.roundNumber=m);let g=Ud({roundPosition:p,roundNumber:r,idPrefix:o,uuids:s}),I={roundPosition:p,children:[l,f],matchUpId:g};u.push(I);let h={drawPositions:I.children.map(S=>S?.drawPosition).filter(Boolean),matchUpStatus:Qt,matchUpId:I.matchUpId,roundPosition:p,roundNumber:r};t&&e&&(h.matchUpType=e),i&&(h.isMock=!0),n.push(h),p++,c+=2}return{roundNodes:u,matchUps:n}}function Cn({finishingPositionOffset:t,finishingPositionLimit:e,qualifyingRoundNumber:r,qualifyingPositions:n,matchUpType:o,roundLimit:i,idPrefix:s,drawSize:a,isMock:c,uuids:u}){if(isNaN(a)||a<2||n&&a<=n)return{matchUps:[],roundsCount:0};if(n&&(!vn(a)||a%n)){let I=n;for(;I<a;)I=2*I;a=I}let p=n&&!(a%2)&&(!isNaN(n)||r&&!isNaN(r))&&(a/n===Math.round(a/n)||r&&a/r===Math.round(a/r));if(!vn(a)&&!p)return{matchUps:[],roundsCount:0};let m=et(1,a+1).map(I=>({drawPosition:I})),d,l=[],f=1;for({roundNodes:d,matchUps:l}=Lp({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}=Lp({nodes:d,matchUpType:o,roundNumber:f,idPrefix:s,matchUps:l,isMock:c,uuids:u}),f++;let g=f-1;return l=Ea({finishingPositionOffset:t,finishingPositionLimit:e,roundsCount:g,roundLimit:i,matchUps:l}),i?l=l.filter(I=>i&&(I.roundNumber??0)<=i):i=f-1,{drawSize:a,matchUps:l,roundsCount:g,roundLimit:i}}function Pd(t){let e="generateQualifyingStructure";if(!t.drawDefinition)return _({result:{error:Z},stack:e});if(t.drawSize&&!It(t.drawSize)||t.participantsCount&&!It(t.participantsCount)||t.qualifyingPositions&&!It(t.qualifyingPositions))return _({result:{error:G},stack:e});let r=t.drawSize??hm(t.participantsCount),{qualifyingRoundNumber:n,qualifyingPositions:o,targetStructureId:i,structureOptions:s,appliedPolicies:a,drawDefinition:c,matchUpFormat:u,structureName:p,structureId:m,roundTarget:d,drawType:l,idPrefix:f,isMock:g,uuids:I}=t;if(!t.drawSize)return _({result:{error:Ya},context:{drawSize:r},stack:e});if(o&&o>=t.drawSize)return _({result:{error:G},context:{drawSize:r,qualifyingPositions:o},stack:e});let h,S,T,y,P=0,U,E=1,{structureProfiles:A}=Eu({drawDefinition:c}),N=A[i];if(!N)return _({result:{error:kt},context:{targetStructureId:i},stack:e});let D=c.matchUpType,M=d?`${d}-`:"",R=N.stage===ct,b=a?.[fa]?.namingConventions?.pre??bb[fa]?.namingConventions?.pre,v=R&&b?`${b}-`:"",O=p??(M?`${v}${Qe(ct)} ${M}`:`${v}${Qe(ct)}`);if(l===Nn){let{maxRoundNumber:L,structures:w,groupCount:V}=Na({structureName:p??O,structureId:m??I?.pop(),stage:ct,structureOptions:s,appliedPolicies:a,stageSequence:E,matchUpType:D,roundTarget:d,idPrefix:f,drawSize:r,isMock:g,uuids:I});P=V,h=L,T=w[0],U=[1]}else({drawSize:r,matchUps:y,roundLimit:h,roundsCount:S}=Cn({qualifyingRoundNumber:n,qualifyingPositions:o,matchUpType:D,idPrefix:f,drawSize:r,isMock:g,uuids:I})),h||(h=S),T=hn({structureName:p??O,structureId:m??I?.pop(),qualifyingRoundNumber:h,stage:ct,matchUpFormat:u,stageSequence:E,matchUpType:D,roundLimit:h,matchUps:y}),d&&At({extension:{name:Mn,value:d},element:T}),P=y?.filter(L=>L.roundNumber===h)?.length;let x=l===Nn?to:fo,F=T&&h&&Ma({sourceStructureId:T.structureId,sourceRoundNumber:h,targetStructureId:i,finishingPositions:U,linkType:x})?.link;return{qualifyingDrawPositionsCount:r,qualifiersCount:P,...C,structure:T,link:F}}function xP(t){if(!t.tournamentRecord)return{error:Y};let r=cG(t);return r.error,r}function cG(t){if(!t.drawDefinition)return{error:Z};if(!t.targetStructureId)return{error:Er};let e=Pd(t);if(e.error)return e;let{structure:r,link:n}=e;return!r||!n?{error:G}:Sg({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,structure:r,link:n})}function wP(t){let e=rt(t,[{[Ve]:!0,[Zc]:!0,[ln]:!0},{[rb]:!0,[tr]:m=>Number.isInteger(m)&&m>0},{[tr]:m=>Array.isArray(m)&&m.length===2&&m.every(Vt),[Fr]:wr,participantIds:!0}]);if(e.error)return e;let{drawDefinition:r,structureId:n,tournamentRecord:o,event:i}=t,{structure:s}=at({drawDefinition:r,structureId:n});if(!s)return{error:kt};if(!cr({structure:s}))return{error:Qo};let a=m=>m.sides?.map(d=>d.participantId).some(d=>t.participantIds.includes(d)),c=m=>m.roundNumber===t.roundNumber,u=m=>!Ie(m),p=(s?.matchUps??[]).filter(c).filter(u).filter(a);if(p.length!==2)return{error:wr};for(let m of p){let d=m?.sides?.find(l=>t.participantIds.includes(l?.participantId));if(d){let l=t.participantIds.find(f=>f!==d?.participantId);d.participantId=l,gt({tournamentId:o?.tournamentId,eventId:i?.eventId,drawDefinition:r,matchUp:m})}}return Ot({drawDefinition:r,structureIds:[n]}),{...C}}function eO({includeMatchUpType:t,drawPosition:e,roundNumber:r,matchUpType:n,idPrefix:o,matchUps:i,isMock:s,uuids:a,nodes:c,fed:u}){let p=c.length,m=e?e-p:void 0,d=et(0,p).map(g=>m?m+g:void 0),l=[];for(let g=0;g<p;g++){let I=d.shift(),h={drawPosition:I,fed:u+1,feed:!0},S=c[g];S.roundNumber=r-1;let T=Ud({roundPosition:S.roundPosition,roundNumber:r,idPrefix:o,uuids:a}),y={roundPosition:S.roundPosition,drawPositions:[I],matchUpStatus:Qt,roundNumber:r,matchUpId:T};t&&(y.matchUpType=n),s&&(y.isMock=!0),i.push(y);let P={children:[S,h]};l.push(P)}let f=e?e-p:void 0;return{roundNodes:l,matchUps:i,drawPosition:f}}function ai(t){let e=t.drawSize,{feedRoundsProfile:r,feedRounds:n=0,skipRounds:o=0,baseDrawSize:i}=t,{linkFedFinishingRoundNumbers:s,finishingPositionOffset:a,linkFedRoundNumbers:c,feedsFromFinal:u,isConsolation:p,matchUpType:m,idPrefix:d,isMock:l,uuids:f,fmlc:g}=t;i=i??F(e);let I=uG({drawSize:i}),h=I.length,S=0;if(r?.length)S=r.reduce((L,w)=>L+w,0);else if(e){let L=e-i;r=I.filter(w=>w<=L?(L-=w,!0):!1),S=r.reduce((w,V)=>w+V,0),n=r.length}else o>=h?n=0:u&&(n=h-u,o=0),r=I.filter((L,w)=>u&&!n||n&&w>=o+n||w<o?0:L),S=r.reduce((L,w)=>L+w,0),n=r.length;let T=[...I,...r].sort((L,w)=>w-L),y=T.length,U=[...(c??[]).map(L=>L-1),...(s??[]).map(L=>y-L)].map(L=>T[L]).reduce((L,w)=>L+w,0);S=S-U;let E=0,A=[],N,D=1,R=et(0,i).map((L,w)=>({drawPosition:w+1+S})),b=S+1;for(let L of I){if({roundNodes:N,matchUps:A}=Lp({matchUpType:m,roundNumber:D,idPrefix:d,matchUps:A,isMock:l,nodes:R,uuids:f}),D++,r.includes(L)){let w=Sr(r)[L],V=et(0,w),k=y+1-D,W=s?.includes(k)??c?.includes(D);V.forEach(()=>{({roundNodes:N,matchUps:A,drawPosition:b}=eO({drawPosition:!W&&b||void 0,nodes:N,matchUpType:m,roundNumber:D,idPrefix:d,matchUps:A,isMock:l,uuids:f,fed:E})),D++,E+=1})}R=N}y!==D-1&&console.log("ERROR");let v=i-S;A=Ea({finishingPositionOffset:p?v:a,positionsFed:S,roundsCount:y,matchUps:A,fmlc:g});let x=N?.length?N[0]:N;return x&&(x.roundNumber=D-1,x.matchUps=A),{draw:x,matchUps:A,roundsCount:y};function F(L){let w=Sm(L);return w>L?w/2:w}}function uG({drawSize:t}){let e=Math.ceil(Math.log(t)/Math.log(2));return et(0,e).reverse().map(n=>Math.pow(2,n))}function Tc(t){let{finishingPositionOffset:e=0,addNameBaseToAttributeName:r,playoffStructureNameBase:n,finishingPositionNaming:o,finishingPositionLimit:i,playoffAttributes:s,stageSequence:a=1,exitProfile:c="0",exitProfileLimit:u,roundOffsetLimit:p,roundOffset:m=0,drawDefinition:d,staggeredEntry:l,sequenceLimit:f,stage:g=nt,drawSize:I,idPrefix:h,isMock:S,uuids:T}=t;if(!(!s||!u||s?.[c])||I<2||f&&a>f)return{};let P=[],U=[],E=[],A=t.matchUpType??d?.matchUpType,N=e+1,D=e+I,M=`${N}-${D}`,R=s?.[c],b=n&&`${n} `||"",v=s?.[M]??o?.[M],O=t.structureName||v?.name||R?.name&&(r?`${b}${R?.name}`:R.name)||`${b}${M}`,x=v?.abbreviation??R?.abbreviation,F=t.structureId??R?.structureId??T?.pop(),L={idPrefix:h&&`${h}-${O}-RP`,finishingPositionOffset:e,matchUpType:A,drawSize:I,isMock:S,uuids:T},{matchUps:w}=l?ai(L):Cn(L),V=hn({structureAbbreviation:x,stageSequence:a,structureName:O,matchUpType:A,roundOffset:m,structureId:F,matchUps:w,stage:g});P.push(...w),U.push(V);let k=Math.ceil(Math.log(I)/Math.log(2)),W=p?Math.min(p-m,k):(!i||N<i)&&k||0;return I>2&&et(1,W+1).forEach(K=>H(K)),{structureId:V.structureId,matchUps:P,structureName:O,structures:U,links:E,...C};function H(K){let q=I/Math.pow(2,K);if(q<2)return;let B=I/Math.pow(2,K)+e;if(i&&B+1>i)return;let{structures:$,structureId:z,matchUps:j,links:tt}=Tc({finishingPositionOffset:B,exitProfile:`${c}-${K}`,roundOffset:m+K,stageSequence:a+1,drawSize:q,addNameBaseToAttributeName:r,playoffStructureNameBase:n,finishingPositionNaming:o,finishingPositionLimit:i,playoffAttributes:s,exitProfileLimit:u,roundOffsetLimit:p,drawDefinition:d,sequenceLimit:f,matchUpType:A,idPrefix:h,uuids:T,stage:g});if(V.structureId&&z){let Q={linkType:eo,source:{roundNumber:K,structureId:V.structureId},target:{roundNumber:1,feedProfile:En,structureId:z}};tt&&V&&tt.push(Q),tt?.length&&E.push(...tt)}return $?.length&&U.push(...$),j?.length&&P.push(...j),{structureId:z,childLinks:tt,structures:U}}}function Dd({drawDefinition:t,matchUpsMap:e,structureId:r}){let n=at({drawDefinition:t,structureId:r});if(n.error)return _({result:n});let{matchUps:o}=Ut({structure:n.structure,matchUpsMap:e});return{...Ke({matchUps:o}),matchUps:o,matchUpsMap:e}}function LP({finishingPositions:t,drawDefinition:e,structureId:r}){let{roundProfile:n}=Dd({drawDefinition:e,structureId:r});return(n&&Object.keys(n))?.reduce((i,s)=>(rO(n?.[s]).forEach(c=>{t.forEach(u=>{pG({position:u,rangeDefinition:c})&&(i[u]={roundNumber:s})})}),i),{})}function pG({position:t,rangeDefinition:e}){if(!Array.isArray(e)||e.reduce((i,s)=>i||isNaN(s),!1))return!1;let[r,n]=e;return et(r,(n||r)+1).includes(t)}function rO(t){return[ut(t?.finishingPositionRange?.loser||[]),ut(t?.finishingPositionRange?.winner||[])]}function nO(t){return rO(t).map(e=>et(e[0],e[1]&&e[1]+1||e[0]+1))}function yc({drawDefinition:t,structureIds:e,matchUpsMap:r}){if(e&&!Array.isArray(e))return{error:G,context:{structureIds:e}};if(!t)return{error:Z};e=e??(t.structures??[]).filter(a=>a.stage!==ct).map(({structureId:a})=>a);let n=e.map(a=>{let{roundProfile:c}=Dd({drawDefinition:t,matchUpsMap:r,structureId:a});return(c&&Object.values(c))?.map(nO).flat()}).flat(),o=n.filter(a=>a?.length===1).sort(me).flat();return{positionsNotPlayedOff:ut(n.flat()).filter(a=>!o.includes(a)),positionsPlayedOff:o}}function VS({excludeRoundNumbers:t=[],playoffPositions:e=[],drawDefinition:r,structureId:n}){if(!r)return{error:Z};if(!n)return{error:Er};if(!e)return{error:st,info:"missing playoffPositions"};let o=yc({drawDefinition:r});if(o.error)return o;let i=o.positionsPlayedOff,s=e.filter(S=>!i.includes(S)),a=LP({finishingPositions:s,drawDefinition:r,structureId:n}),u=Object.values(a).reduce((S,T)=>S.includes(T.roundNumber)?S:S.concat(T.roundNumber),[]).map(S=>pt(S)).filter(S=>!t.includes(S)),p=LP({finishingPositions:i,drawDefinition:r,structureId:n}),m=p?Object.values(p):[],d=p?m.reduce((S,T)=>S.includes(T.roundNumber)?S:S.concat(T.roundNumber),[]).map(S=>pt(S)):[],l=u.filter(S=>!d.includes(S)).sort(me),{roundProfile:f}=Dd({drawDefinition:r,structureId:n}),g=l.map(S=>{let T=f?.[S].finishingPositionRange.loser,[y,P]=T??[0,0];return et(y,(P||y)+1)}).flat().sort(me),{playoffRoundsRanges:I}=mG({playoffSourceRounds:l,roundProfile:f}),h=[...l,...d];return{playoffPositionsReturned:g,playedOffSourceRounds:d,playoffRoundsRanges:I,playoffSourceRounds:l,sourceRounds:h,roundProfile:f}}function mG({playoffSourceRounds:t,roundProfile:e}){return{playoffRoundsRanges:t.map(n=>{let o=e[n].finishingPositionRange.loser,[i,s]=o,a=et(i,(s||i)+1);return{finishingPositionRange:o.join("-"),finishingPositions:a,roundNumber:n}})}}function Pu({drawDefinition:t,structureId:e}){if(!t)return{error:Z};let{matchUps:r,matchUpsMap:n}=or({inContext:!0,drawDefinition:t}),{positionsNotPlayedOff:o,positionsPlayedOff:i}=yc({drawDefinition:t,matchUpsMap:n}),{structures:s}=gn({drawDefinition:t}),a=s.filter(u=>!e&&u.stage!==$e||u.structureId===e),c={};for(let u of a){let p=u?.structureId,m=dG({playoffPositions:o,drawDefinition:t,structure:u,matchUps:r}),{error:d,...l}=m;if(d)return m;c[p]={structureId:p,...l}}return e?{positionsPlayedOff:i,...c[e]}:{availablePlayoffProfiles:Object.values(c),availablePlayoffRounds:Object.values(c),positionsPlayedOff:i}}function dG({playoffPositions:t,drawDefinition:e,structure:r,matchUps:n}){let o=r?.structureId,{links:i}=Ws({drawDefinition:e,structureId:o});if(r.structureType===Ge||r.structures){let l=bt({structure:r})?.positionAssignments?.length,f=r.structures.length,g=(l??0)/f,I=i.source?.flatMap(({source:D})=>D?.finishingPositions||[])||[],h=et(1,g+1).filter(D=>!I.includes(D)),S=n.find(D=>D.containerStructureId===o&&D.finishingPositionRange)?.finishingPositionRange?.winner||[0,1],T=i?.source.map(({target:D})=>D.structureId),{positionsPlayedOff:y=[],positionsNotPlayedOff:P=[]}=yc({structureIds:T,drawDefinition:e}),U=[...y,...P],E=et(S[0],S[1]+1).filter(D=>!U.includes(D)),A=ye(E,E.length/h.length),N=h.map((D,M)=>{let R=A[M],b=[Math.min(...R||[]),Math.max(...R||[])].join("-");return{finishingPosition:D,finishingPositions:R,finishingPositionRange:b}});return{positionsNotPlayedOff:E,playoffFinishingPositionRanges:N,finishingPositionsAvailable:h,finishingPositionsPlayedOff:I,positionsPlayedOff:y,groupCount:f,groupSize:g}}let s=i?.source?.filter(l=>l.linkCondition!==On).map(l=>l.source?.roundNumber)||[],a=i?.source?.filter(l=>l.linkCondition===On).map(l=>l.source?.roundNumber)||[],c=VS({excludeRoundNumbers:s,playoffPositions:t,drawDefinition:e,structureId:o}),u=c?.playoffSourceRounds?[...c?.playoffSourceRounds||[]]:void 0,p=[...c?.playoffRoundsRanges||[]],{roundProfile:m,error:d}=c;for(let l of a){let f=i?.source.find(T=>T.source.roundNumber===l),g=f?.target.roundNumber,I=f?.target.structureId,h=n.filter(({roundNumber:T,structureId:y})=>y===I&&T===g),S=h.filter(({sides:T})=>T.find(y=>y.participantFed&&!y.participantId)).length;if(u&&S===h.length){u.push(l);let T=m?.[l]?.finishingPositionRange?.loser;if(T){let y=Math.min(...T),P=y+S,U=et(y,P),E={finishingPositionRange:[y,P-1].join("-"),finishingPositions:U,roundNumber:l};p.push(E)}}}return u&&u.sort(me),p.sort((l,f)=>l.roundNumber-f.roundNumber),{playoffRounds:u,playoffRoundsRanges:p,error:d}}function oO({playoffGroups:t,drawDefinition:e,structureId:r}){if(!e)return{error:Z};if(!Vt(r)||!Array.isArray(t))return{error:G};let n=t.map(({finishingPositions:a})=>a).flat();return{positionRangeMap:Pu({drawDefinition:e,structureId:r}).playoffFinishingPositionRanges?.filter(a=>n.includes(a.finishingPosition))?.reduce((a,c)=>(a[c.finishingPosition]=c,a),{})}}function BS(t){let{finishingPositionOffset:e=0,playoffAttributes:r,stageSequence:n=1,staggeredEntry:o,structureName:i,stage:s=nt,matchUpType:a,structureId:c,idPrefix:u,drawSize:p,isMock:m,uuids:d}=t,l={finishingPositionOffset:e,matchUpType:a,drawSize:p,idPrefix:u,isMock:m,uuids:d},{matchUps:f}=o?ai(l):Cn(l),g=hn({structureName:i||r?.["0"]?.name||Qe(nt),structureId:c||d?.pop(),stageSequence:n,matchUpType:a,matchUps:f,stage:s}),I=[g],h=[];if(p>2){let S=p/2,{matchUps:T}=Cn({finishingPositionOffset:e+S,idPrefix:u&&`${u}-c`,drawSize:S,matchUpType:a,isMock:m}),y=Qe(qe),P=r?.["0-1"]?.name??t.consolationStructureName??(i?`${i} ${y}`:y),U=hn({structureName:P,matchUps:T,structureId:d?.pop(),stage:qe,stageSequence:1,matchUpType:a});I.push(U);let E={linkType:eo,source:{roundNumber:1,structureId:g.structureId},target:{roundNumber:1,feedProfile:En,structureId:U.structureId}};h.push(E)}return{...C,structures:I,links:h}}function HS({consolationStructure:t,roundOffset:e=0,mainStructure:r,roundsCount:n,feedPolicy:o,fmlc:i}){let a=t.matchUps.reduce((p,m)=>(m.drawPositions||[]).filter(Boolean).length&&!p.includes(m.roundNumber)?p.concat(m.roundNumber):p,[]),c=o?.roundGroupedOrder||[],u=o?.roundFeedProfiles;return et(1+e,n+1+e).map(p=>{let m=u?.[p-1]?u[p-1]:p%2&&En||di,d=p-e<=2?p-e:(p-e-2)*2+2,l={linkType:eo,source:{roundNumber:p,structureId:r.structureId},target:{feedProfile:m,roundNumber:d,structureId:t.structureId}},f=c[p-1];return f&&(l.target.groupedOrder=f),Ur()&&(l.source.structureName=r.structureName,l.target.structureName=t.structureName),p===2&&i&&(l.linkCondition=On,l.target.feedProfile=En),a.includes(d)?l:void 0}).filter(Boolean)}function WS(t){let{playoffStructureNameBase:e,finishingPositionOffset:r,stageSequence:n=1,playoffAttributes:o,structureNameMap:i,staggeredEntry:s,stage:a=nt,matchUpType:c,structureId:u,drawSize:p,idPrefix:m,isMock:d,uuids:l}=t,f={finishingPositionOffset:r,matchUpType:c,drawSize:p,idPrefix:m,isMock:d,uuids:l},{matchUps:g,roundsCount:I}=s?ai(f):Cn(f),h=t.structureName??o?.["0"]?.name??Qe(nt),S=Ss({structureId:u||l?.pop(),structureName:h,stageSequence:n,matchUpType:c,matchUps:g,stage:a}),T=[S],y=[];if(p>2){let E=[0,2].slice(0,p/16).map((A,N)=>{let D=N+1,{consolationStructure:M}=lG({idPrefix:m&&`${m}-c${N}`,structureId:l?.pop(),playoffStructureNameBase:e,playoffAttributes:o,structureNameMap:i,stageSequence:D,roundOffset:A,matchUpType:c,drawSize:p,isMock:d,index:N,uuids:l});T.push(M);let R=HS({consolationStructure:M,roundsCount:2,mainStructure:S,roundOffset:A});return{consolationStructure:M,links:R}}).map(A=>A.links).flat();if(y.push(...E),p>=4&&p<=16||p>32){let{matchUps:A}=Cn({idPrefix:m&&`${m}-p3t4`,finishingPositionOffset:2,drawSize:2,matchUpType:c,isMock:d}),N=o?.["3-4"]?.name??Qe(de),D=i?.[N]||N,M=e?`${e} ${D}`:D,R=Ss({structureId:l?.pop(),matchUps:A,stageSequence:2,stage:de,structureName:M,matchUpType:c}),b={linkType:eo,source:{roundNumber:I-1,structureId:S.structureId},target:{structureId:R.structureId,feedProfile:En,roundNumber:1}};T.push(R),y.push(b)}}return{structures:T,links:y,...C}}function lG({playoffStructureNameBase:t,stageSequence:e=1,playoffAttributes:r,structureNameMap:n,roundOffset:o=0,matchUpType:i,structureId:s,idPrefix:a,drawSize:c,isMock:u,index:p,uuids:m}){let d=c/(2*Math.pow(2,o)),{matchUps:l,roundsCount:f}=ai({finishingPositionOffset:d,baseDrawSize:d,isConsolation:!0,feedRounds:1,matchUpType:i,idPrefix:a,isMock:u,uuids:m}),I=p===0&&r?.["0-1"]?.name||p===1&&r?.["0-3"]?.name||`${Qe(qe)} ${p+1}`,h=n?.[I]||I,S=t?`${t} ${h}`:h;return{consolationStructure:Ss({matchUps:l,stage:qe,structureName:S,stageSequence:e,matchUpType:i,structureId:s}),consolationRoundsCount:f}}function Ac(t){let{finishingPositionOffset:e,stageSequence:r=1,playoffAttributes:n,feedsFromFinal:o,staggeredEntry:i,structureName:s,stage:a=nt,structureId:c,matchUpType:u,skipRounds:p,feedRounds:m,idPrefix:d,drawSize:l,isMock:f,uuids:g,fmlc:I}=t,h=t.feedPolicy||t.policyDefinitions?.[rc]||t.appliedPolicies?.[rc],S={finishingPositionOffset:e,matchUpType:u,skipRounds:p,drawSize:l,idPrefix:d,isMock:f,uuids:g},{matchUps:T}=i?ai(S):Cn(S),y=hn({structureName:s||n?.["0"]?.name||Qe(nt),structureId:c||g?.pop(),stageSequence:r,matchUpType:u,matchUps:T,stage:a}),P=[y],U=[],E=l/2,{matchUps:A,roundsCount:N}=ai({finishingPositionOffset:E,idPrefix:d&&`${d}-c`,isConsolation:!0,feedsFromFinal:o,baseDrawSize:E,matchUpType:u,feedRounds:m,skipRounds:p,isMock:f,uuids:g,fmlc:I});if(l>2){let D=n?.["0-1"]?.name??Qe(qe),M=t.playoffStructureNameBase?`${t.playoffStructureNameBase} ${D}`:D,R=hn({matchUps:A,structureId:g?.pop(),stage:qe,stageSequence:1,structureName:M,matchUpType:u});P.push(R);let b=HS({consolationStructure:R,mainStructure:y,roundsCount:N,feedPolicy:h,fmlc:I});U.push(...b)}return{...C,structures:P,links:U}}function YS({requireSequential:t=!0,playoffMatchUpFormat:e,playoffAttributes:r,sourceStructureId:n,policyDefinitions:o,stageSequence:i,drawDefinition:s,playoffGroups:a,matchUpType:c,feedPolicy:u,groupCount:p,idPrefix:m,isMock:d,uuids:l}){u=u||o?.[rc];let f="processPlayoffGroups",g=0,I=[],h=[],S=[],{error:T,positionRangeMap:y}=oO({structureId:n,drawDefinition:s,playoffGroups:a});if(T)return _({result:{error:T},stack:f});if(!(!y||a?.every(U=>{let{finishingPositions:E=[]}=U;if(!E.length)return!1;let A=[...E].sort(me).map((N,D)=>(E[D+1]||N)-N).every(N=>N<2);return(!t||A)&&E.every(N=>y[N])})))return _({context:{validFinishingPositions:Object.values(y)},result:{error:G},stack:f});for(let U of a){let E=U.finishingPositions,A=y&&E.map(F=>y[F]?.finishingPositions).flat(),N=p*E.length,D=es(N),M=D===2&&go||U.drawType||go;A&&(g=Math.min(...A)-1);let R=A&&`${Math.min(...A)}-${Math.max(...A)}`,b=U.structureName||R&&U.playoffAttributes?.[R]?.name||U.playoffAttributes?.["0"]?.name,O={...{addNameBaseToAttributeName:U.addNameBaseToAttributeName,playoffStructureNameBase:U.playoffStructureNameBase,finishingPositionNaming:U.finishingPositionNaming,finishingPositionLimit:U.finishingPositionLimit,structureId:U.structureId??l?.pop(),playoffAttributes:U.playoffAttributes,structureNameMap:U.structureNameMap,sequenceLimit:U.sequenceLimit,structureName:b},idPrefix:m&&`${m}-po`,appliedPolicies:o,finishingPositionOffset:g,stage:de,stageSequence:i,matchUpType:c,drawSize:D,isMock:d,uuids:l},x=({playoffStructures:F,playoffLinks:L})=>{let[w]=F,V=jS({playoffStructureId:w.structureId,finishingPositions:E,sourceStructureId:n});S.push(V),S.push(...L),h.push(...F),I.push({structureId:w.structureId,finishingPositions:E}),g+=N};if(M===go){let{matchUps:F}=Cn({finishingPositionLimit:g+N,idPrefix:m&&`${m}-po`,finishingPositionOffset:g,matchUpType:c,drawSize:D,isMock:d,uuids:l}),L=hn({structureId:U.structureId??l?.pop(),matchUpFormat:e,stage:de,structureName:b,stageSequence:i,matchUps:F});h.push(L);let w=jS({playoffStructureId:L.structureId,finishingPositions:E,sourceStructureId:n});S.push(w),g+=N,I.push({structureId:L.structureId,finishingPositions:E})}else if([zc,Qc,de].includes(M)){let F={playoffAttributes:U.playoffAttributes??r,playoffStructureNameBase:U.playoffStructureNameBase,structureId:U.structureId??l?.pop(),structureName:U.structureName,idPrefix:m&&`${m}-po`,addNameBaseToAttributeName:!0,finishingPositionOffset:g,stage:de,roundOffset:0,stageSequence:i,drawSize:D,isMock:d,uuids:l};M===zc?Object.assign(F,{playoffAttributes:U?.playoffAttributes??r??yf,roundOffsetLimit:3}):M===Qc&&Object.assign(F,{playoffAttributes:U?.playoffAttributes??r??Af,roundOffsetLimit:2});let L=Tc(F);if(L.error)return L;if(L.links?.length&&S.push(...L.links),L.structures?.length&&h.push(...L.structures),h.sort(Si),L.structureId){let w=jS({playoffStructureId:L.structureId,finishingPositions:E,sourceStructureId:n});S.push(w),I.push({structureId:L.structureId,finishingPositions:E})}g+=N}else if([Jc,pp,xm,_m,Om,wm].includes(M)){let F=[l?.pop(),l?.pop()],L={playoffStructureNameBase:U.playoffStructureNameBase,structureId:U.structureId??l?.pop(),playoffAttributes:U.playoffAttributes,idPrefix:m&&`${m}-po`,finishingPositionOffset:g,uuids:F,stage:de,structureName:b,matchUpType:c,feedPolicy:u,drawSize:D,isMock:d},w={[Jc]:{fmlc:!0,feedRounds:1},[wm]:{feedRounds:1},[xm]:{feedsFromFinal:3},[_m]:{feedsFromFinal:2},[Om]:{feedsFromFinal:1}};Object.assign(L,w[M]||{});let{structures:V,links:k}=Ac(L),[W]=V,H=jS({playoffStructureId:W.structureId,finishingPositions:E,sourceStructureId:n});S.push(H),S.push(...k),h.push(...V),I.push({structureId:W.structureId,finishingPositions:E}),g+=N}else if([Nn].includes(M)){let{structures:F,links:L}=Na({...O,structureOptions:U.structureOptions||{groupSize:4}});x({playoffStructures:F,playoffLinks:L})}else if([up].includes(M)){let{structures:F,links:L}=BS(O);x({playoffStructures:F,playoffLinks:L})}else if([XC].includes(M)){let{structures:F,links:L}=WS(O);x({playoffStructures:F,playoffLinks:L})}else if([$r].includes(M)){let F=hn({structureId:U.structureId??l?.pop(),structureName:U.structureName,finishingPosition:td,stage:de,stageSequence:i,matchUps:[]});x({playoffStructures:[F],playoffLinks:[]})}}return{finishingPositionTargets:I,positionRangeMap:y,structures:h,links:S}}function jS({playoffStructureId:t,finishingPositions:e,sourceStructureId:r}){return{linkType:to,source:{structureId:r,finishingPositions:e},target:{structureId:t,feedProfile:dn,roundNumber:1}}}function Ra({matchUp:t,tieFormat:e,isMock:r,uuids:n}){let{collectionDefinitions:o}=e??{};return{tieMatchUps:(o??[]).map(s=>Du({matchUp:t,collectionDefinition:s,uuids:n,isMock:r})).filter(Boolean).flat()}}function Du({collectionPositionOffset:t=0,collectionDefinition:e,matchUpsLimit:r,matchUp:n,isMock:o,uuids:i}){let{matchUpCount:s,matchUpType:a,collectionId:c,processCodes:u}=e||{},p=r??s??0,m=d=>{if(!o&&!n?.isMock)return i?.pop()??Dt();let l=e?.collectionId;return i?.pop()??`${n?.matchUpId}-${l}-TMU-${d+1}`};return et(0,p).map(d=>{let l=t+d+1;return{sides:[{sideNumber:1},{sideNumber:2}],matchUpId:m(d),matchUpStatus:Qt,collectionPosition:l,collectionId:c,processCodes:u,matchUpType:a,isMock:o}})}function iO(t){let e="generateAndPopulateRRplayoffStructures";if(!t.playoffGroups)return _({result:{error:st},info:"playoffGroups required",stack:e});let{sourceStructureId:r,requireSequential:n,tournamentRecord:o,drawDefinition:i,playoffGroups:s,groupCount:a,groupSize:c,event:u}=t,p=YS({requireSequential:n,sourceStructureId:r,playoffGroups:s,groupCount:a,groupSize:c,...t});if(p.error)return _({result:p,stack:e});let{structures:m=[],links:d=[],finishingPositionTargets:l,positionRangeMap:f}=p,g=l?.map(({finishingPositions:A})=>A).flat().map(A=>f[A].finishingPositions).flat();i.structures.push(...m),i.links.push(...d);let{matchUps:I,matchUpsMap:h}=se({inContext:!0,drawDefinition:i}),S=m.map(({structureId:A})=>A),T=I?.filter(({structureId:A})=>S.includes(A)).map(Ae),y=h?.drawMatchUps?.filter(({matchUpId:A})=>T?.includes(A));if(y?.length){let A=We({drawDefinition:i,event:u})?.tieFormat;A&&y.forEach(N=>{let{tieMatchUps:D}=Ra({isMock:t.isMock,tieFormat:A,matchUp:N});Object.assign(N,{tieMatchUps:D,matchUpType:xr})})}let{positionAssignments:P}=bt({structureId:r,drawDefinition:i}),U={};P?.forEach(A=>{let M=dt({element:A,name:Jo})?.extension?.value?.groupOrder;M&&(U[M]||(U[M]=[]),U[M].push(A.participantId))});let E=Ks({provisionalPositioning:t.provisionalPositioning,structureId:r,applyPositioning:!0,event:t.event,tournamentRecord:o,drawDefinition:i});return E.error&&E.error?.code!==wl.code?_({result:E,stack:e}):{structures:m,links:d,positionsPlayedOff:g,drawDefinition:i,...C}}function Nu({value:t,sourceRange:e,targetRange:r}){let n=Math.min(...e),o=Math.max(...e),i=Math.min(...r),s=Math.max(...r);return(t-n)*(s-i)/(o-n)+i}var zn="ELO",FP="NTRP",fG="TRN",kP="UTR",Pg="WTN",sO={ELO:zn,NTRP:FP,TRN:fG,UTR:kP,WTN:Pg};var gG={[zn]:{defaultInitialization:1500,decimalsCount:0,range:[0,3e3],ascending:!0},[FP]:{accessors:["ntrpRating","dntrpRatingHundredths"],attributes:{ustaRatingType:""},accessor:"dntrpRatingHundredths",defaultInitialization:3,decimalsCount:1,ascending:!0,range:[1,7]},[kP]:{defaultInitialization:6,accessors:["utrRating"],accessor:"utrRating",decimalsCount:2,ascending:!0,range:[1,16]},[Pg]:{attributes:{confidence:{generator:!0,range:[60,100]}},accessors:["wtnRating","confidence"],defaultInitialization:23,accessor:"wtnRating",ascending:!1,decimalsCount:2,range:[40,1]}},we=gG;function aO({sourceRatingType:t,sourceRating:e}){let r=we[t].range,n=r[0]>r[1],o=we[zn].range;return Nu({value:n?r[0]-e:e,sourceRange:r,targetRange:o})}function cO({targetRatingType:t,sourceRating:e}){let r=we[t].decimalsCount||0,n=we[t].range,o=n[0]>n[1],i=Math.max(...n),s=we[zn].range,a=Nu({targetRange:n,sourceRange:s,value:e}),c=parseFloat(a.toFixed(r));return o?i-c:c}function GP(t){let e=rt(t,[{ratings:!0,[He]:Kr}]);if(e.error)return e;let r=t.matchUpType&&[xt,_t].includes(t.matchUpType)?t.matchUpType:xt,n=Object.keys(we),o=t.targetRatingType&&n.includes(t.targetRatingType)?t.targetRatingType:zn,i=t.ratings[r]?t.ratings[r].reduce((d,l)=>d.includes(l.scaleName)?d:d.concat(l.scaleName),[]):[];if(!i)return{error:ve};let s=t.ratings[r]?.find(d=>d.scaleName===o)??t.ratings[r][0];if(i[0]===o)return s;let a=s.scaleName,c=we[s.scaleName].accessor,u=c?s.scaleValue[c]:s.scaleValue,p=aO({sourceRatingType:a,sourceRating:u});return{convertedRating:cO({targetRatingType:o,sourceRating:p}),sourceRating:u}}function uO({participantResults:t,sides:e,score:r}){let n=e.find(({sideNumber:a})=>a===1),o=e.find(({sideNumber:a})=>a===2),i=n?.participant?.ratings,s=o?.participant?.ratings;if(i?.[xt]&&s?.[xt]){let a=zn,{convertedRating:c}=GP({ratings:i,targetRatingType:a}),{convertedRating:u}=GP({ratings:s,targetRatingType:a}),{side1pressure:p,side2pressure:m}=IG({side1ConvertedRating:c,side2ConvertedRating:u,score:r});p&&t[n?.participantId].pressureScores.push(p),m&&t[o?.participantId].pressureScores.push(m);let d=Math.max(...we[zn].range),l=_l((u-c)/d),f=_l((c-u)/d);t[n?.participantId].ratingVariation.push(l),t[o?.participantId].ratingVariation.push(f)}}function IG({side1ConvertedRating:t,side2ConvertedRating:e,score:r}){let n=t>e?t:e,o=t>e?e:t,i=Math.abs(t-e),s=we[zn].range,a=Math.max(...s),c=(a-n)*0,p=(n+c)/a*i,m=r?.sets?.reduce((T,y)=>T+(y?.side1Score??0),0),d=r?.sets?.reduce((T,y)=>T+(y.side2Score??0),0),l=t>e?2:1,f=(m||0)*(o+(l===1?p:0)),g=(d||0)*(o+(l===2?p:0)),I=f+g,h=I?_l(f/I):0,S=I?_l(g/I):0;return{side1pressure:h,side2pressure:S}}function Dg({winningSide:t,matchUpFormat:e=Dn,matchUpStatus:r,tallyPolicy:n,score:o}){let i=[0,0],s=o?.sets,a=typeof t=="number"&&t-1,c=Ye(e),u=VP(c?.bestOf??1);if(typeof a=="number"&&(r===Mt&&n?.setsCreditForDefaults||r===Ct&&n?.setsCreditForWalkovers))i[a]=u;else for(let p of s||[]){let{winningSide:m}=p;m&&(i[m-1]+=1)}return typeof a=="number"&&r===rr&&(+i[1-a]===u&&(i[1-a]-=1),n?.setsCreditForRetirements&&(i[a]=u)),i}function qS({matchUpFormat:t=Dn,winningSide:e,matchUpStatus:r,tallyPolicy:n,score:o}){let{sets:i}=o||{};if(!i)return[0,0];let s=typeof e=="number"&&e-1,a=Ye(t),c=a?.bestOf??1,u=VP(c),p=a?.setFormat?.tiebreakAt||0,m=[[],[]];if(typeof s=="number"&&(r===Mt&&n?.gamesCreditForDefaults||r===Ct&&n?.gamesCreditForWalkovers)){let d=a?.setFormat?.setTo||0,l=u*d;m[s].push(l)}else i.forEach((d,l)=>{let g=(d.setNumber||l+1)>u&&a?.finalSetFormat?"finalSetFormat":"setFormat",I=a?.[g]?.based,h=a?.[g].tiebreakSet,{side1Score:S,side2Score:T}=d;pO(I)&&(m[0].push(pt(S||0)),m[1].push(pt(T||0))),h&&d.winningSide&&n?.gamesCreditForTiebreakSets!==!1&&m[d.winningSide-1].push(1)});if(r===rr&&typeof s=="number"){let d=i.length>u&&a?.finalSetFormat?"finalSetFormat":"setFormat",l=a?.[d];if(pO(l.based)){let f=l?.setTo||0,g=S=>{if(!(!a||S===""))return+S===p-1||+S===p?pt(p||0)+1:+S<p?f:p},I=Dg({winningSide:e,score:{sets:i},matchUpStatus:r,matchUpFormat:t,tallyPolicy:n});if(m.map(S=>S[s]<=S[1-s]).reduce((S,T)=>S+(T?1:0),0)>I[1-s]){let S=m[s].length,T=g(m[1-s][S-1]);T&&(m[s][S-1]=T)}u>m[s].length&&n?.gamesCreditForRetirements&&m[s].push(f)}}return[m[0].reduce((d,l)=>d+l,0),m[1].reduce((d,l)=>d+l,0)]}function $S({matchUpFormat:t,score:e}){let r=t?Ye(t):void 0,n=r?.bestOf??1,o=VP(n),i=[0,0],s=[0,0];return e?.sets?.forEach((a,c)=>{let p=(a.setNumber||c+1)>o&&r?.finalSetFormat?"finalSetFormat":"setFormat",m=r?.[p]?.based;if(mO(m)){let{side1Score:d,side2Score:l}=a;d&&(s[0]+=pt(d||0)),l&&(s[1]+=pt(l||0))}else a.side1TiebreakScore&&(s[0]+=pt(a.side1TiebreakScore||0)),a.side2TiebreakScore&&(s[1]+=pt(a.side2TiebreakScore||0)),(a.side1TiebreakScore||a.side2TiebreakScore)&&a.winningSide&&(i[a.winningSide-1]+=1)}),{pointsTally:s,tiebreaksTally:i}}function VP(t){return t&&Math.ceil(t/2)||1}function mO(t){return t==="P"}function pO(t){return!mO(t)}function dO({participantResults:t,matchUpFormat:e,tallyPolicy:r,perPlayer:n,totalSets:o}){let i=e&&Ye(e)||{},s=i.bestOf,a=s&&Math.ceil(s/2)||1,c=i.setFormat?.setTo;Object.keys(t).forEach(u=>{let p=t[u].setsWon,m=t[u].setsLost,d=r?.groupTotalSetsPlayed?o:n*(a||0)||p+m,l=Math.round(p/d*1e3)/1e3;(l===1/0||isNaN(l))&&(l=d);let f=t[u].tieMatchUpsWon,g=t[u].tieMatchUpsLost,I=f+g,h=Math.round(f/I*1e3)/1e3;(h===1/0||isNaN(h))&&(h=f);let S=t[u].matchUpsWon,T=t[u].matchUpsLost,y=S+T,P=Math.round(S/y*1e3)/1e3;(P===1/0||isNaN(P))&&(P=S);let U=t[u].gamesWon||0,E=t[u].gamesLost||0,A=(n||0)*(a||0)*(c||0),N=Math.max(A,U+E),D=Math.round(U/N*1e3)/1e3;(D===1/0||isNaN(D))&&(D=0);let M=t[u].pointsWon+t[u].pointsLost,R=Math.round(t[u].pointsWon/M*1e3)/1e3;(R===1/0||isNaN(R))&&(R=0),t[u].setsWon=p,t[u].setsLost=m,t[u].setsPct=l,t[u].tieMatchUpsWon=f,t[u].tieMatchUpsPct=h,t[u].matchUpsPct=P,t[u].gamesWon=U,t[u].gamesLost=E,t[u].gamesPct=D,t[u].pointsPct=R,t[u].result=`${t[u].matchUpsWon}/${t[u].matchUpsLost}`})}function Mu({participantIds:t,pressureRating:e,matchUpFormat:r,tallyPolicy:n,perPlayer:o,matchUps:i}){let s={},a=n?.excludeMatchUpStatuses||[],c=i?.filter(m=>(m.tieMatchUps||!a.includes(m.matchUpStatus))&&(!t?.length||Yt(t,[Nd(m,0),Nd(m,1)]).length===2)),p=c?.flatMap(({score:m,tieMatchUps:d})=>d?d.filter(({matchUpStatus:l})=>!a.includes(l)).flatMap(({score:l})=>l?.sets?.length??0):m?.sets?.length??0)?.reduce((m,d)=>m+d,0);for(let m of c??[]){let{matchUpStatus:d,tieMatchUps:l,tieFormat:f,score:g,winningSide:I,sides:h}=m,S=f&&m._disableAutoCalc&&f.collectionDefinitions.every(({scoreValue:E})=>E),T=I&&hG(m),y=I&&SG(m);if(!T&&!y)if(d&&ce.includes(d)){let E=Nd(m,0),A=Nd(m,1);E&&(Ec(s,E),s[E].matchUpsCancelled+=1),A&&(Ec(s,A),s[A].matchUpsCancelled+=1)}else if(l?.length){o=0;for(let E of l){if(E.winningSide){let A=h?.find(({sideNumber:D})=>D===E.winningSide)?.participantId,N=h?.find(({sideNumber:D})=>D===E.winningSide)?.participantId;A&&N&&(Ec(s,A),Ec(s,N),s[A].tieMatchUpsWon+=1,s[N].tieMatchUpsLost+=1,ue(xt)(E.matchUpType)?(s[A].tieSinglesWon+=1,s[N].tieSinglesLost+=1):ue(_t)(E.matchUpType)&&(s[A].tieDoublesWon+=1,s[N].tieDoublesLost+=1))}lO({score:E.score,manualGamesOverride:S,participantResults:s,sides:h})}}else lO({manualGamesOverride:S,participantResults:s,score:g,sides:h});else if(Ec(s,T),Ec(s,y),l?.length){o=0;for(let E of l){let{matchUpType:A}=E,N=ue(_t)(A),D=ue(xt)(A);E.winningSide&&(E.winningSide===I?(T&&(s[T].tieMatchUpsWon+=1,D&&(s[T].tieSinglesWon+=1),N&&(s[T].tieDoublesWon+=1)),y&&(s[y].tieMatchUpsLost+=1,D&&(s[y].tieSinglesLost+=1),N&&(s[y].tieDoublesLost+=1))):E.winningSide!==I&&(y&&(s[y].tieMatchUpsWon+=1,D&&(s[y].tieSinglesWon+=1),N&&(s[y].tieDoublesWon+=1)),T&&(s[T].tieMatchUpsLost+=1,D&&(s[T].tieSinglesLost+=1),N&&(s[T].tieDoublesLost+=1)))),fO({matchUpFormat:E.matchUpFormat,matchUpStatus:E.matchUpStatus,matchUpType:E.matchUpType,score:E.score,sides:E.sides,winningParticipantId:T,losingParticipantId:y,manualGamesOverride:S,participantResults:s,isTieMatchUp:!0,pressureRating:e,tallyPolicy:n,winningSide:I})}gO({winningParticipantId:T,losingParticipantId:y,participantResults:s,matchUpStatus:d})}else fO({matchUpFormat:m.matchUpFormat??r,matchUpType:m.matchUpType,isTieMatchUp:void 0,winningParticipantId:T,manualGamesOverride:S,losingParticipantId:y,participantResults:s,pressureRating:e,matchUpStatus:d,tallyPolicy:n,winningSide:I,score:g,sides:h});let P=g?.sets?.reduce((E,A)=>E+(A?.side1Score??0),0),U=g?.sets?.reduce((E,A)=>E+(A.side2Score??0),0);if(S){let E=h?.find(({sideNumber:N})=>N===1)?.participantId,A=h?.find(({sideNumber:N})=>N===2)?.participantId;Ec(s,E),Ec(s,A),E&&(s[E].gamesWon+=P,s[E].gamesLost+=U),A&&(s[A].gamesWon+=U,s[A].gamesLost+=P)}}return dO({participantResults:s,matchUpFormat:r,tallyPolicy:n,perPlayer:o,totalSets:p}),{participantResults:s}}function hG(t){let e=t.winningSide-1;return Nd(t,e)}function SG(t){let e=1-(t.winningSide-1);return Nd(t,e)}function Nd(t,e){if(!t?.sides)return console.log("no sides:",{matchUp:t}),"foo";let r=t.sides[e];return r?r.participantId:(console.log("No Side",{matchUp:t,index:e}),"foo")}function Ec(t,e){e&&!t[e]&&(t[e]={allDefaults:0,defaults:0,defeats:[],gamesLost:0,gamesWon:0,matchUpsCancelled:0,matchUpsLost:0,matchUpsWon:0,pointsLost:0,pointsWon:0,pressureScores:[],ratingVariation:[],retirements:0,setsLost:0,setsWon:0,tieSinglesWon:0,tieSinglesLost:0,tieDoublesWon:0,tieDoublesLost:0,tieMatchUpsLost:0,tieMatchUpsWon:0,victories:[],walkovers:0})}function lO({manualGamesOverride:t,participantResults:e,score:r,sides:n}){let{sets:o}=r||{},i=[[],[]],s=[0,0];for(let c of o||[]){let{winningSide:u,side1Score:p,side2Score:m}=c;u&&(s[u-1]+=1),i[0].push(pt(p||0)),i[1].push(pt(m||0))}let a=[i[0].reduce((c,u)=>c+u,0),i[1].reduce((c,u)=>c+u,0)];n.forEach((c,u)=>{let{participantId:p}=c;p&&(Ec(e,p),e[p].setsWon+=s[u],e[p].setsLost+=s[1-u],t||(e[p].gamesWon+=a[u],e[p].gamesLost+=a[1-u]))})}function fO({winningParticipantId:t,manualGamesOverride:e,losingParticipantId:r,participantResults:n,pressureRating:o,matchUpFormat:i,matchUpStatus:s,isTieMatchUp:a,matchUpType:c,tallyPolicy:u,winningSide:p,score:m,sides:d}){let l=p&&p-1,f=1-l;o&&c===xt&&uO({participantResults:n,sides:d,score:m}),a||gO({winningParticipantId:t,losingParticipantId:r,participantResults:n,matchUpStatus:s});let g=Dg({matchUpStatus:s,matchUpFormat:i,tallyPolicy:u,winningSide:p,score:m}),I=qS({matchUpStatus:s,matchUpFormat:i,tallyPolicy:u,winningSide:p,score:m}),{pointsTally:h}=$S({score:m,matchUpFormat:i});t&&(n[t].setsWon+=g[l],n[t].setsLost+=g[f],e||(n[t].gamesWon+=I[l],n[t].gamesLost+=I[f]),n[t].pointsWon+=h[l],n[t].pointsLost+=h[f]),r&&(n[r].setsWon+=g[f],n[r].setsLost+=g[l],e||(n[r].gamesWon+=I[f],n[r].gamesLost+=I[l]),n[r].pointsWon+=h[f],n[r].pointsLost+=h[l])}function gO({winningParticipantId:t,losingParticipantId:e,participantResults:r,matchUpStatus:n}){e&&(n===Ct&&(r[e].walkovers+=1),n===Mt&&(r[e].defaults+=1),n===rr&&(r[e].retirements+=1),[Mt,rr,Ct].includes(n)&&(r[e].allDefaults+=1),r[e].matchUpsLost+=1),t&&(r[t].matchUpsWon+=1),e&&t&&(r[e].defeats.push(t),r[t].victories.push(e))}function IO({matchUps:t,order:e,report:r}){let n={};t.forEach(({sides:i})=>{i.forEach(s=>{s.participantId&&s.participant&&(n[s.participantId]=s.participant.participantName)})});let o=[];return Array.isArray(r)&&r.forEach((i,s)=>{if(i.excludedDirectives?.length){let a=i.excludedDirectives.map(({attribute:p})=>p).join(", "),c=`${a.length} directives were excluded due to participants limit}`;o.push(c);let u=`Excluded: ${a}`;o.push(u)}else{let a=(l,f)=>parseFloat(i.reversed?l:f)-parseFloat(i.reversed?f:l),c=i.groups?Object.values(i.groups).flat(1/0).length:i.participantIds?.length??0,u=l=>{l.groups&&Object.keys(l.groups).sort(a).forEach(f=>{let g=l.groups[f].map(h=>n[h]).join(", "),I=`${f} ${l.attribute}: ${g}`;o.push(I)})},p=i.reversed?" in reverse order":"",m=i.groups?"grouped":"separated",d=`Step ${s+1}: ${c} particiants were ${m}${p} by ${i.attribute}`;if(o.push(d),i.idsFilter){let l=`${i.attribute} was calculated considering ONLY TIED PARTICIPANTS`;o.push(l)}u(i)}o.push("----------------------")}),o.push("Final Order:"),e.forEach(i=>{let{participantId:s,resolved:a}=i,c=i.groupOrder||i.provisionalOrder;o.push(`${c}: ${n[s]} => resolved: ${!!a}`)}),o.join(`\r
|
|
4
4
|
`)}function BP({participantResults:t,participantIds:e,attribute:r}){return HP({participantResults:t,participantIds:e}).reduce((o,i)=>{let{participantId:s,results:a}=i,c=a?.[r];return!isNaN(c)&&s&&(o[c]?o[c].push(s):o[c]=[s]),o},{})}function HP(t){return(t.participantIds||Object.keys(t.participantResults)).reduce((r,n,o)=>(r.push({participantId:n,i:o,results:t.participantResults[n]}),r),[])}var TG=[{attribute:"matchUpsPct",idsFilter:!1},{attribute:"allDefaults",reversed:!0,idsFilter:!1},{attribute:"defaults",reversed:!0,idsFilter:!1},{attribute:"walkovers",reversed:!0,idsFilter:!1},{attribute:"retirements",reversed:!0,idsFilter:!1},{attribute:"setsPct",idsFilter:!1},{attribute:"gamesPct",idsFilter:!1},{attribute:"pointsPct",idsFilter:!1},{attribute:"matchUpsPct",idsFilter:!0},{attribute:"setsPct",idsFilter:!0},{attribute:"gamesPct",idsFilter:!0},{attribute:"pointsPct",idsFilter:!0}],WP={matchUpsPct:20,tieMatchUpsPct:16,pointsPct:4,gamesPct:8,setsPct:12};function jP(t){let{requireCompletion:e=!0,participantResults:r,subOrderMap:n,tallyPolicy:o}=t,i=[];if(e&&!yG(t))return{};let s=["tieMatchUpsWon","tieSinglesWon","tieDoublesWon","matchUpsWon","pointsWon","gamesWon","setsWon","gamesPct","setsPct","pointsPct","matchUpsPct"].includes(o?.groupOrderKey)?o.groupOrderKey:"matchUpsWon",a=BP({participantResults:r,attribute:s});i.push({attribute:s,groups:a});let p=Object.keys(a).map(S=>parseFloat(S)).sort((S,T)=>T-S).map(S=>a[S]).map(S=>{let T=hO({participantIds:S,...t});return i.push(...T.report??[]),T.order}).map((S,T)=>S.map(y=>y.resolved?y:{...y,subGroup:[T].concat(...y.subGroup??[])})).flat(),m,d=0,l=1,f;p.forEach((S,T)=>{T&&(S.resolved||f&&!S.resolved)&&(l+=1),f=S.resolved;let y=parseInt(S.subGroup?.join("")||0);S.resolved?(S.position=T+1,l=S.position):(m&&y>m&&(l+=d,d=0),S.position=l,d+=1),m=y});let g=p.map(({position:S})=>S),I=Sr(g);return p.forEach(S=>{let{participantId:T,position:y}=S||{},P=r[T];S.GEMscore=h(P);let U=I[y];S?.position!==void 0&&(U>1&&(S.ties=U,n&&(S.subOrder=n[T])),S.rankOrder=y,S.groupOrder=y+(S.subOrder||1)-1)}),{groupOrder:p,report:i.flat(1/0).filter(Boolean)};function h(S){return(Array.isArray(o?.GEMscore)?Object.keys(WP).filter(P=>o.GEMscore.includes(P)):Object.keys(WP)).map(P=>(S[P]||0)*Math.pow(10,WP[P].toFixed(3))).reduce((P,U)=>P+U,0)}}function yG({participantResults:t,participantsCount:e}){let n=HP({participantResults:t}).filter(o=>e-1===o.results.matchUpsWon+o.results.matchUpsLost+o.results.matchUpsCancelled);return e===n.length}function AG({disableHeadToHead:t,participantIds:e,matchUpFormat:r,tallyPolicy:n,attribute:o,idsFilter:i,matchUps:s,reversed:a}){let{participantResults:c}=Mu({participantIds:i&&e,matchUpFormat:r,tallyPolicy:n,matchUps:s}),u=BP({participantResults:c,participantIds:e,attribute:o}),p=[{attribute:o,reversed:a,groups:u,idsFilter:i}],m;return Object.keys(u).length>1&&e.length&&(m=Object.keys(u).map(f=>parseFloat(f)).sort((f,g)=>a?f-g:g-f).map(f=>u[f]).map(f=>{let g=hO({participantResults:c,disableHeadToHead:t,participantIds:f,matchUpFormat:r,tallyPolicy:n,matchUps:s});return p.push(...g.report??[]),g.order}).map((f,g)=>f.map(I=>I.resolved?I:{...I,subGroup:[g].concat(...I.subGroup??[])})).flat()),{order:m,report:p}}function hO({participantResults:t,disableHeadToHead:e,participantIds:r,matchUpFormat:n,tallyPolicy:o,matchUps:i}){let s=[],a=[],c;if(r?.length===1)return{order:[{resolved:!0,participantId:r[0]}]};if(r?.length===2&&(!o?.headToHead||!o.headToHead.disabled&&!e)){let m=EG({participantIds:r,participantResults:t});if(m){let d=m[0].participantId;return a.push({attribute:"head2Head",participantIds:r,headToHeadWinner:d}),{order:m,headToHeadWinner:d,report:a}}}let p=(o?.tallyDirectives||TG).filter(m=>{let d=!(Zt(m.maxParticipants)&&r?.length>m.maxParticipants);return d||s.push(m),d});return s.length&&a.push({excludedDirectives:s,participantIds:r}),p.every(({attribute:m,reversed:d,idsFilter:l,disableHeadToHead:f})=>(c=AG({disableHeadToHead:f,participantIds:r,matchUpFormat:n,tallyPolicy:o,attribute:m,idsFilter:l,matchUps:i,reversed:d}),a.push(c.report),!c.order)),c.order?{order:c.order,report:a}:{order:r?.map(m=>({participantId:m})),report:a}}function EG({participantIds:t,participantResults:e}){if(t){if(e[t[0]].victories.includes(t[1]))return t.map(r=>({resolved:!0,participantId:r}));if(e[t[1]].victories.includes(t[0]))return t.reverse().map(r=>({resolved:!0,participantId:r}))}}function Ca({policyDefinitions:t,generateReport:e,pressureRating:r,matchUpFormat:n,matchUps:o=[],subOrderMap:i,perPlayer:s}){if(!o?.length||!Vr(o))return{error:Xn};let a=ut(o.map(({structureId:y})=>y));if(a.length!==1)return _({result:{error:G,info:"Maximum one structureId"},stack:"tallyParticipantResults",context:{structureIds:a}});let c=o.filter(y=>y&&y.matchUpStatus!==Nt),u=c.length&&ut(c.map(({drawPositions:y})=>y).flat()).length,p=c.filter(y=>ds({matchUp:y})).length===c.length;p||(s=0);let m=o.every(({matchUpType:y,tieMatchUps:P})=>y===jt&&P?.every(U=>ds({matchUp:U}))),d=t?.[Mf],l=o.filter(y=>ds({matchUp:y})||y.matchUpType===jt),{participantResults:f}=Mu({matchUps:l,pressureRating:r,matchUpFormat:n,tallyPolicy:d,perPlayer:s}),g,I,{groupOrder:h,report:S}=jP({matchUps:l,participantResults:f,participantsCount:u,matchUpFormat:n,tallyPolicy:d,subOrderMap:i});if(r&&UG({participantResults:f}),p&&h)g=S,I=h,h.forEach(y=>{let{participantId:P,groupOrder:U,rankOrder:E,subOrder:A,ties:N,GEMscore:D}=y,M=f[P];Object.assign(M,{groupOrder:U,rankOrder:E,GEMscore:D,subOrder:A,ties:N})});else{let{groupOrder:y,report:P}=jP({requireCompletion:!1,participantResults:f,participantsCount:u,matchUpFormat:n,tallyPolicy:d,subOrderMap:i,matchUps:o});g=P,I=y,y&&y.forEach(U=>{let{participantId:E,groupOrder:A,GEMscore:N}=U,D=f[E];Object.assign(D,{provisionalOrder:A,GEMscore:N})})}let T={completedTieMatchUps:m,readableReport:"",participantResults:f,bracketComplete:p,order:[],report:g};if((p||m)&&(T.order=I),e||Ur({tally:!0})){let y=IO({matchUps:o,report:g,order:I});Ur({tally:!0})&&console.log(y),T.readableReport=y}return T}function UG({participantResults:t}){let e=o=>o.reduce((i,s)=>i+parseFloat(s),0),r=o=>parseFloat((e(o)/o.length).toFixed(2)),n=Object.keys(t).map(o=>{let i=t[o],{pressureScores:s}=i,a=s?.length?r(s):0;return{participantId:o,averagePressure:a}}).sort((o,i)=>(i.averagePressure||0)-(o.averagePressure||0)).map((o,i)=>({...o,order:i+1}));for(let o of n)t[o.participantId].pressureOrder=o.order}function KS({positionAssignments:t}){let e=(t||[]).filter(Br(ro)).map(i=>{let{extension:s}=dt({element:i,name:oc}),a=pt(s?.value),c=!isNaN(a)&&a;return c&&{participantId:i.participantId,subOrder:c}}).filter(Boolean),r=e.map(({subOrder:i})=>i),n=Sr(r);return{subOrderMap:Object.assign({},...e.filter(({subOrder:i})=>n[i]===1).map(({participantId:i,subOrder:s})=>({[i]:s})))}}function Md({positionAssignments:t,tournamentRecord:e,drawDefinition:r,matchUpFormat:n,matchUps:o,event:i}){if(!Vr(o))return{error:G};if(!t)return{error:G};let{policyDefinitions:s}=vo({policyTypes:[Mf],tournamentRecord:e,drawDefinition:r,event:i}),{subOrderMap:a}=KS({positionAssignments:t}),c=o.length?Ca({policyDefinitions:s,matchUpFormat:n,subOrderMap:a,matchUps:o}):void 0;if(c?.error)return c;let{participantResults:u={},bracketComplete:p,report:m}=c??{},d=Object.keys(u);return t.forEach(l=>{let{participantId:f}=l;if(d.includes(f)){let g={value:u[f],name:Jo};At({element:l,extension:g}),u[f].ties||gr({element:l,name:oc})}else gr({element:l,name:Jo}),gr({element:l,name:oc})}),Ot({drawDefinition:r}),{...C,participantResults:u,bracketComplete:p,report:m}}function zS({matchUps:t,matchUpId:e}){return{matchUp:(t||[]).find(n=>n.matchUpId===e)}}function Bt(t){let e=rt(t,[{[Ve]:!0,[ln]:!0}]);if(e.error)return e;let{tournamentParticipants:r,afterRecoveryTimes:n,contextProfile:o,drawDefinition:i,matchUpsMap:s,matchUpId:a,inContext:c,context:u,event:p}=t,{structures:m=[]}=gn({drawDefinition:i}),d=t.contextContent||o&&qn({contextProfile:o,drawDefinition:i});for(let l of m){let{matchUps:f}=Ut({tournamentParticipants:r,afterRecoveryTimes:n,contextContent:d,drawDefinition:i,contextProfile:o,matchUpsMap:s,inContext:c,structure:l,context:u,event:p}),{matchUp:g}=zS({matchUps:f,matchUpId:a});if(g)return{matchUp:g,structure:l}}return{error:Le}}function Fp(t){return!ht(t)||!t.notes?{error:st}:ht(t.element)?!Vt(t.notes)&&!t.notes?.testing?{error:G}:(Object.assign(t.element,{notes:t.notes}),{...C}):{error:G}}function Ng(t){return ht(t)?ht(t.element)?(t.element.notes&&delete t.element.notes,{...C}):{error:G}:{error:st}}var Ru={matchUpStatus:Qt,matchUpStatusCodes:[],score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0},matchUpFormat:void 0,winningSide:void 0};function Gn(t){let e="modifyMatchUpScore",r=t.matchUpFormat,n=t.matchUp,o,{matchUpStatusCodes:i,tournamentRecord:s,drawDefinition:a,matchUpStatus:c,removeScore:u,winningSide:p,matchUpId:m,event:d,notes:l,score:f}=t,I=t.appliedPolicies&&Object.keys(t.appliedPolicies).length?t.appliedPolicies:yt({policyTypes:[en],tournamentRecord:s,drawDefinition:a,structure:o,event:d})?.appliedPolicies,h=n.matchUpType===jt;if(h&&a){if(m&&n.matchUpId!==m){let A=Bt({drawDefinition:a,matchUpId:m,event:d});if(!A.matchUp)return{error:Le};({matchUp:n,structure:o}=A)}}else n.matchUpId!==m&&console.log("!!!!!");c&&[Ct,he].includes(c)||u?Object.assign(n,{...Ru}):f&&(n.score=f);let S=c&&n?.matchUpStatus===Mt&&c!==Mt;c&&(n.matchUpStatus=c),r&&(n.matchUpFormat=r),i&&(n.matchUpStatusCodes=i),p&&(n.winningSide=p),t.removeWinningSide&&(n.winningSide=void 0),!o&&a&&({structure:o}=Bt({drawDefinition:a,matchUpId:m,event:d})),c&&!n.winningSide&&Ie(n)&&!ce.includes(c)&&![ic,ss,pn].includes(c)&&(n.matchUpStatus=Ln);let T;if((S&&n?.processCodes?.length||c===Mt)&&(T=I?.[en]?.processCodes?.incompleteAssignmentsOnDefault),!n.collectionId){let A=o?.structureType===Ge,N=cr({structure:o});if(id({drawDefinition:a,structure:o})||N||A){let D=b=>{r=h?"SET1-S:T100":r??n.matchUpFormat??b?.matchUpFormat??a?.matchUpFormat??d?.matchUpFormat;let v=h?{matchUpTypes:[jt]}:void 0,{matchUps:O}=Ut({afterRecoveryTimes:!1,tournamentRecord:s,inContext:!0,matchUpFilters:v,drawDefinition:a,structure:b,event:d});return N&&(b.positionAssignments=ut(O.flatMap(x=>(x.sides??[]).map(F=>F.participantId)).filter(Boolean)).map(x=>({participantId:x}))),Md({positionAssignments:b.positionAssignments,tournamentRecord:s,drawDefinition:a,matchUpFormat:r,matchUps:O,event:d})},M=A&&o.structures.find(b=>b?.matchUps.find(v=>v.matchUpId===m)),R=D(M||o);if(R.error)return _({result:R,stack:e})}}if(l){let A=Fp({element:n,notes:l});if(A.error)return _({result:A,stack:e})}let y=s?.tournamentId,P=Lr().topics.includes(Sp),U=(P||T)&&Ne({drawDefinition:a}),E=U&&se({matchUpFilters:{matchUpIds:[m]},nextMatchUps:!0,tournamentRecord:s,inContext:!0,drawDefinition:a,matchUpsMap:U}).matchUps?.[0];if(P&&E&&Sb({tournamentId:y,inContextMatchUp:E}),Array.isArray(T)&&E&&!E.sides?.every(({participantId:A})=>A))if(c===Mt)n.processCodes=ut([...n.processCodes??[],...T]);else for(let A of T||[]){let N=A&&n?.processCodes?.lastIndexOf(A);n?.processCodes?.splice(N,1)}return gt({eventId:d?.eventId,context:e,drawDefinition:a,tournamentId:y,matchUp:n}),{...C}}function Rd(t){let{matchUpStatusCodes:e,matchUpStatus:r,structure:n,matchUp:o,dualMatchUp:i,inContextMatchUp:s,autoCalcDisabled:a}=t,c=Ua({matchUpStatus:r})||[oo,br].includes(r)&&i||a,u=o?.sides?.map(I=>I.participantId).filter(Boolean).length||s?.sides?.map(I=>I.participantId).filter(Boolean).length,p="attemptToModifyScore";if(!(cr({structure:n})&&u===1||r===Mt&&u||PG({structure:n,matchUp:o,inContextMatchUp:s})||t.appliedPolicies?.[en]?.requireParticipantsForScoring===!1))return _({result:{error:Vl},stack:p});let l=[Ct].includes(r),f=c?r:t.winningSide&&le||pn,g=Gn({...t,matchUpStatusCodes:c&&e||[],matchUpStatus:f,context:p,removeScore:l});return _({result:g,stack:p})}function PG({structure:t,matchUp:e,inContextMatchUp:r}){let{drawPositions:n}=e,{positionAssignments:o}=Se({structure:t}),i=o?.filter(a=>n?.includes(a.drawPosition)&&a.participantId),s=r?.sides?.every(a=>a.participantId);return i?.length===2||s}function QS({collectionGroups:t=[]}){let e=Object.assign({},...t.filter(n=>It(n?.groupValue)&&n?.groupNumber).map(n=>({[n.groupNumber]:{...n,allGroupMatchUpsCompleted:!0,matchUpsCount:0,sideWins:[0,0],values:[0,0]}}))),r=Object.keys(e).map(n=>pt(n));return{groupValueGroups:e,groupValueNumbers:r}}function SO({collectionDefinition:t,groupValueNumbers:e,groupValueGroups:r,sideTieValues:n,tieMatchUps:o}){let i=o.filter(S=>S.collectionId===t.collectionId),s=[0,0],a=[0,0],c=i.every(S=>ce.includes(S.matchUpStatus)),{collectionValueProfiles:u,collectionGroupNumber:p,collectionValue:m,matchUpValue:d,winCriteria:l,scoreValue:f,setValue:g}=t,I=p&&e.includes(p),h=[0,0];if(i.forEach(S=>{S.winningSide&&(h[S.winningSide-1]+=1)}),It(d)?i.forEach(S=>{S.winningSide&&(s[S.winningSide-1]+=d)}):It(g)?i.forEach(S=>{S.score?.sets?.forEach(T=>{T.winningSide&&(s[T.winningSide-1]+=g)})}):It(f)?i.forEach(S=>{S.score?.sets?.forEach(T=>{let{side1TiebreakScore:y=0,side2TiebreakScore:P=0,side1Score:U=0,side2Score:E=0}=T;(S.matchUpStatus===le||S.winningSide||T.winningSide)&&(U||E?(s[0]+=U,s[1]+=E):(y||P)&&T.winningSide&&(s[T.winningSide-1]+=1))})}):Array.isArray(u)&&i.forEach(S=>{if(S.winningSide){let T=S.collectionPosition,y=DG({collectionDefinition:t,collectionPosition:T});It(y)&&(s[S.winningSide-1]+=y)}}),It(m)){let S;if(l?.aggregateValue)c&&(It(d||g||f)&&s[0]!==s[1]?S=s[0]>s[1]?1:2:h[0]!==h[1]&&(S=h[0]>h[1]?1:2));else if(l?.valueGoal)S=s.reduce((T,y,P)=>y>=l.valueGoal?P+1:T,0);else{let T=Math.floor(t.matchUpCount/2)+1;S=h.reduce((y,P,U)=>P>=T?U+1:y,0)}S&&(I?r[p].values[S-1]+=m:a[S-1]+=m)}else I?(r[p].values[0]+=s[0]||0,r[p].values[1]+=s[1]||0):a=s;I?(r[p].sideWins[0]+=h[0]||0,r[p].sideWins[1]+=h[1]||0,r[p].allGroupMatchUpsCompleted=r[p].allGroupMatchUpsCompleted&&c,r[p].matchUpsCount+=i.length):a.forEach((S,T)=>n[T]+=S||0)}function DG({collectionDefinition:t,collectionPosition:e}){return(t.collectionValueProfiles||[])?.find(o=>o.collectionPosition===e)?.matchUpValue}function Uc(t){let{sideAdjustments:e=[0,0],separator:r="-",drawDefinition:n,matchUpsMap:o,structure:i,matchUp:s,event:a}=t;if(!Array.isArray(e)||e.length!==2||isNaN(e.reduce((y,P)=>y+P)))return{error:G};if(!s)return{error:hr};let c=We({matchUp:s,drawDefinition:n,structure:i,event:a})?.tieFormat||t?.tieFormat;if(!c)return{error:bs};let u=ar({tieFormat:c});if(u.error)return u;let p=c?.collectionDefinitions||[],m=s?.tieMatchUps??[],d=[0,0],{groupValueGroups:l,groupValueNumbers:f}=QS(c);for(let y of p)SO({collectionDefinition:y,groupValueNumbers:f,groupValueGroups:l,sideTieValues:d,tieMatchUps:m});for(let y of f){let P=l[y],{allGroupMatchUpsCompleted:U,matchUpCount:E,winCriteria:A,groupValue:N,sideWins:D,values:M}=P,R;if(A?.aggregateValue)U&&M[0]!==M[1]&&(R=M[0]>M[1]?1:2);else if(A?.valueGoal)R=M.reduce((b,v,O)=>v>=A.valueGoal?O+1:b,void 0);else{let b=Math.floor(E/2)+1;R=D.reduce((v,O,x)=>O>=b?x+1:v,void 0)}R&&(d[R-1]+=N||0)}let g=d.map((y,P)=>(y||0)+e[P]),I={side1Score:g[0],side2Score:g[1],winningSide:void 0},h=g.join(r),S=g.slice().reverse().join(r),T;if(c?.winCriteria){let{valueGoal:y,aggregateValue:P,tallyDirectives:U}=c.winCriteria;if(y?T=g.map((A,N)=>({sideNumber:N+1,points:A})).find(({points:A})=>A>=y)?.sideNumber:P&&m.every(A=>A.matchUpStatus&&ce.includes(A.matchUpStatus)||A.winningSide)&&g[0]!==g[1]&&(T=g[0]>g[1]?1:2),!T&&U){let E=s.matchUpId,A=s.hasContext?s:o?.drawMatchUps?.[E]||n&&Bt({inContext:!0,drawDefinition:n,matchUpId:E})?.matchUp;if(A){let{completedTieMatchUps:N,order:D}=Ca({matchUps:[A]});if(N&&D?.length){let M=D[0].participantId;T=A.sides.find(({participantId:R})=>R===M)?.sideNumber}}}}return T&&(I.winningSide=T),{scoreStringSide1:h,scoreStringSide2:S,winningSide:T,set:I}}function ba({inContextDualMatchUp:t,drawDefinition:e,tournamentId:r,dualMatchUp:n,eventId:o}){if(n){t||(t=Bt({matchUpId:n.matchUpId,inContext:!0,drawDefinition:e})?.matchUp);let{extension:i}=dt({element:e,name:Ro}),s=J(i?.value||{},!1,!0),a=({displaySideNumber:c,drawPosition:u,sideNumber:p})=>({drawPosition:u,sideNumber:p,displaySideNumber:c});n.sides=t?.sides?.map(c=>{let u=c.participantId,p=u&&s[u]||void 0,{lineUp:m,...d}=n.sides?.find(({sideNumber:f})=>f===c.sideNumber)??{},l=m?.length?m:p;return{...a(c),...d,lineUp:l}}),gt({context:"ensureSidLineUps",matchUp:n,drawDefinition:e,tournamentId:r,eventId:o})}}function ir(t){if(t)return J(t,!1,!0)}function Mg(t){let e=rt(t,[{[Re]:!0}]);return e.error?e:Object.keys(t.tournamentRecords).reduce((n,o)=>{n.tournamentIdMap[o]=[];let s=t.tournamentRecords[o].events??[],a=s.map(({eventId:u})=>u),c=s.map(u=>(u.drawDefinitions??[]).map(({drawId:p})=>p)).flat();return n.tournamentIdMap[o].push(...a,...c),n.eventIds.push(...a),n.drawIds.push(...c),n},{eventIds:[],drawIds:[],tournamentIdMap:{}})}function XS({tournamentRecords:t,eventId:e,drawId:r}){let{tournamentIdMap:n}=Mg({tournamentRecords:t});return(n?Object.keys(n):[]).find(i=>e&&n?.[i].includes(e)||r&&n?.[i].includes(r))}function co(t){let{exitWhenNoValues:e,drawDefinition:r,matchUpStatus:n,removeScore:o,matchUpsMap:i,matchUpId:s,event:a}=t,c=t.tournamentRecords||t.tournamentRecord&&{[t.tournamentRecord?.tournamentId]:t.tournamentRecord}||{},u=t.tournamentId||t.tournamentRecord?.tournamentId;c&&XS({tournamentRecords:c,...t});let p=u&&c[u];if(!p)return{error:Y};let m=Bt({drawDefinition:r,event:a,matchUpId:s});if(m.error)return m;if(!m.matchUp)return{error:Le};let{matchUp:d,structure:l}=m;if(!d.tieMatchUps)return{error:dr};ba({tournamentId:p?.tournamentId,eventId:a?.eventId,dualMatchUp:d,drawDefinition:r});let{extension:f}=dt({name:ga,element:d});if(f?.value)if(o)gr({element:d,name:ga});else return{...C,score:d.score};let g=We({drawDefinition:r,structure:l,matchUp:d,event:a})?.tieFormat;d.tieFormat=ir(g);let I=Uc({drawDefinition:r,matchUpsMap:i,structure:l,matchUp:d,event:a}),{winningSide:h,set:S,scoreStringSide1:T,scoreStringSide2:y}=I,P=S?.side1Score||S?.side2Score;if(e&&!d.score&&!P)return{...C};let U={scoreStringSide1:T,scoreStringSide2:y,sets:S?[S]:[]},E=h&&[1,2].includes(h),A=E&&le||ig({matchUpStatus:n??d.matchUpStatus,tieMatchUps:d.tieMatchUps,winningSide:d.winningSide,score:U})&&Ln||Qt,N=!!(d.winningSide&&!E),D=d.tieMatchUps.find(({score:R,winningSide:b,matchUpStatus:v})=>R?.sets?.length&&(R.sets[0].side1Score||R.sets[0].side2Score)||v&&ce.includes(v)||b),M;if(d.tieFormat&&!E&&!D){let R=We({drawDefinition:r,structure:l,event:a})?.tieFormat;R&&JSON.stringify(g)===JSON.stringify(R)&&(d.tieFormatId=void 0,d.tieFormat=void 0,M=!0)}return Gn({appliedPolicies:t.appliedPolicies,matchUpStatus:A,score:U,removeWinningSide:N,tournamentRecord:p,drawDefinition:r,removeScore:o,winningSide:h,matchUpId:s,matchUp:d,event:a}),{...C,score:U,removeWinningSide:N,tieFormatRemoved:M,winningSide:h}}function TO({winnerMatchUpDrawPositionIndex:t,inContextDrawMatchUps:e,projectedWinningSide:r,sourceMatchUpStatus:n,winningDrawPosition:o,tournamentRecord:i,winnerTargetLink:s,sourceMatchUpId:a,drawDefinition:c,winnerMatchUp:u,dualMatchUp:p,matchUpsMap:m,event:d}){let l="directWinner";if(s){let f=u.drawPositions||[],g=f[t],I=s.source.structureId,h=at({structureId:I,drawDefinition:c});if(h.error)return h;let{structure:S}=h,{positionAssignments:T}=Se({structureId:I,drawDefinition:c}),P=T?.find(R=>R.drawPosition===o)?.participantId,U=s.target.structureId,{positionAssignments:E}=Se({structureId:U,drawDefinition:c}),N=E?.find(R=>R.participantId===P)?.drawPosition,D=E?.filter(R=>{let b=f.includes(R.drawPosition),v=!R.participantId&&!R.bye&&!R.qualifier;return b&&v}).map(R=>R.drawPosition),M=D?.includes(g);if(P&&s.target.roundNumber===1&&M)kn({drawPosition:g,participantId:P,structureId:U,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,drawDefinition:c,matchUpsMap:m,event:d});else if(P&&D?.length){let R=D.pop();R&&kn({participantId:P,structureId:U,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,drawDefinition:c,drawPosition:R,matchUpsMap:m,event:d})}else if(N){let R=hc({drawPosition:N,matchUpId:u.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,sourceMatchUpId:a,drawDefinition:c,matchUpsMap:m});if(R.error)return _({result:R,stack:l})}else if(S?.stage!==ct){let R="winner target position unavaiallble";return console.log(R),{error:R}}if(S?.seedAssignments&&S.structureId!==U){let R=S.seedAssignments.find(({participantId:v})=>v===P),b=R?.participantId;R&&b&&$s({eventId:u?.eventId,structureId:U,...R,tournamentRecord:i,drawDefinition:c,participantId:b})}}else{let f=hc({matchUpId:u.matchUpId,drawPosition:o,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:i,sourceMatchUpId:a,drawDefinition:c,matchUpsMap:m});if(f.error)return f}if(p&&r){let f=p.sides?.find(g=>g.sideNumber===r);if(f?.lineUp){let g=p.roundPosition,I=u.roundPosition,h=g===I&&g!==1||Math.floor(g/2)===I?2:1,S=m?.drawMatchUps?.find(({matchUpId:P})=>P===u.matchUpId),T=[1,2].map(P=>({...S.sides?.find(E=>E.sideNumber===P)||{},sideNumber:P}));S.sides=T;let y=S.sides.find(P=>P.sideNumber===h);if(y){let P=f.lineUp?.filter(U=>U?.participantId);y.lineUp=Sd({lineUp:P}),gt({tournamentId:i?.tournamentId,eventId:u?.eventId,matchUp:S,context:l,drawDefinition:c})}}}return{...C}}function yO(t){let{loserMatchUpDrawPositionIndex:e,inContextDrawMatchUps:r,projectedWinningSide:n,sourceMatchUpStatus:o,loserDrawPosition:i,tournamentRecord:s,loserTargetLink:a,drawDefinition:c,loserMatchUp:u,dualMatchUp:p,matchUpsMap:m,event:d}=t,l="directLoser",f=a.linkCondition,g=u.drawPositions||[],I=f===On&&u.roundNumber===2&&Math.min(...g.filter(Boolean)),h=I||g[e],S=I||g[1-e],T=a.source.structureId,{structure:y}=at({structureId:T,drawDefinition:c}),{matchUps:P}=Ut({afterRecoveryTimes:!1,inContext:!0,drawDefinition:c,structure:y,event:d}),E=P.filter(H=>H.drawPositions?.includes(i)).filter(H=>{let K=H.sides.find(B=>B.drawPosition===i),q=H.matchUpStatus===Ct||H.matchUpStatus===Mt&&!Ie(H);return K?.sideNumber===H.winningSide&&!q}),A=f===On&&E.length===0,{positionAssignments:N}=Se({structureId:T,drawDefinition:c}),M=N?.find(H=>H.drawPosition===i)?.participantId,R=a.target.structureId,{positionAssignments:b}=Se({structureId:R,drawDefinition:c}),v=b?.filter(({drawPosition:H})=>g.includes(H));if(v?.some(H=>H.participantId===M))return{...C};let x=v?.filter(H=>{let K=g.includes(H.drawPosition),q=!H.participantId&&!H.bye&&!H.qualifier;return K&&q}).map(H=>H.drawPosition),F=x?.includes(h),L=a.target.roundNumber>1&&x?.length,w=a.target.roundNumber===1&&F;if(I){let H=V();if(H.error)return _({result:H,stack:l})}else if(w){let H=W();if(H.error)return _({result:H,stack:l})}else if(M&&L){x.sort(me);let H=x[0],K=kn({participantId:M,structureId:R,drawPosition:H,inContextDrawMatchUps:r,sourceMatchUpStatus:o,tournamentRecord:s,drawDefinition:c,matchUpsMap:m,event:d});if(K.error)return _({result:K,stack:l})}else return _({context:{loserDrawPosition:i,loserTargetLink:a,targetDrawPositionIsUnfilled:F},result:{error:F?Rs:TC},stack:l});if(y?.seedAssignments&&y.structureId!==R){let H=y.seedAssignments.find(({participantId:q})=>q===M),K=H?.participantId;H&&K&&$s({eventId:u?.eventId,structureId:R,...H,tournamentRecord:s,drawDefinition:c,participantId:K})}if(p&&n){let H=p.sides?.find(K=>K.sideNumber===3-n);if(H?.lineUp){let{roundNumber:K,eventId:q}=u,{roundPosition:B}=p,$=K===1?2-B%2:1,z=m?.drawMatchUps?.find(({matchUpId:Q})=>Q===u.matchUpId),j=[1,2].map(Q=>({...z.sides?.find(lt=>lt.sideNumber===Q)||{},sideNumber:Q}));z.sides=j;let tt=z.sides.find(Q=>Q.sideNumber===$);tt&&(tt.lineUp=Sd({lineUp:H.lineUp}),gt({tournamentId:s?.tournamentId,matchUp:z,context:l,drawDefinition:c,eventId:q}))}}return{...C};function V(){let H="loserLinkFedFMLC";return A?_({result:W(),stack:H}):_({result:k(),stack:H})}function k(){let H=Hr({drawPosition:S,structureId:R,tournamentRecord:s,drawDefinition:c,event:d});return _({result:H,stack:"assignLoserPositionBye"})}function W(){let H=M?kn({drawPosition:h,participantId:M,structureId:R,inContextDrawMatchUps:r,sourceMatchUpStatus:o,tournamentRecord:s,drawDefinition:c,matchUpsMap:m,event:d}):{error:oe};return _({result:H,stack:"assignLoserDrawPosition"})}}function JS(t){let e="directParticipants",r=Rd(t);if(r.error)return _({result:r,stack:e});let n=Ua({matchUpStatus:t.matchUpStatus}),{dualWinningSideChange:o,projectedWinningSide:i,inContextDrawMatchUps:s,tournamentRecord:a,drawDefinition:c,matchUpStatus:u,dualMatchUp:p,matchUpsMap:m,winningSide:d,targetData:l,matchUpId:f,structure:g,matchUp:I,event:h}=t,S=!!I.collectionId,T=cr({structure:g}),y=I.drawPositions,P;if(S){let{matchUpTieId:U,matchUpsMap:E}=t,A=co({appliedPolicies:t.appliedPolicies,matchUpId:U,tournamentRecord:a,drawDefinition:c,matchUpsMap:E,event:h});if(P=A&&{tieMatchUpResult:A},y=s.find(({matchUpId:D})=>D===U)?.drawPositions,!o)return _({result:{...C,...P},stack:e})}if(T)return _({result:{...C,...P},stack:e});if(y){let U=i?i-1:d-1,E=1-U,A=y[U],N=y[E],{targetLinks:{loserTargetLink:D,winnerTargetLink:M,byeTargetLink:R},targetMatchUps:{winnerMatchUpDrawPositionIndex:b,loserMatchUpDrawPositionIndex:v,winnerMatchUp:O,loserMatchUp:x,byeMatchUp:F}}=l;if(O){let L=TO({sourceMatchUpStatus:n&&u||le,winnerMatchUpDrawPositionIndex:b,sourceMatchUpId:f,inContextDrawMatchUps:s,projectedWinningSide:i,winningDrawPosition:A,tournamentRecord:a,winnerTargetLink:M,drawDefinition:c,winnerMatchUp:O,dualMatchUp:p,matchUpsMap:m,event:h});if(L.error)return _({result:L,stack:e})}if(x){let L=yO({sourceMatchUpStatus:n&&u||le,loserMatchUpDrawPositionIndex:v,sourceMatchUpId:f,inContextDrawMatchUps:s,projectedWinningSide:i,loserDrawPosition:N,tournamentRecord:a,loserTargetLink:D,drawDefinition:c,loserMatchUp:x,winningSide:d,matchUpsMap:m,dualMatchUp:p,event:h});if(L.error)return _({result:L,stack:e})}if(F){let L=F.drawPositions||[],w=Math.min(...L.filter(Boolean)),V=R.target.structureId,k=Hr({drawPosition:w,structureId:V,tournamentRecord:a,drawDefinition:c,event:h});if(k.error)return _({result:k,stack:e})}}else return _({result:{error:ja},stack:e});return _({result:{...C,...P},stack:e})}function Cd(t){let e="genPlayoffStructure";if(!t.drawDefinition)return _({result:{error:Z},stack:e});let r=Pu(t);if(r.error)return _({result:r,stack:e});let{structureId:n,addNameBaseToAttributeName:o,playoffStructureNameBase:i,finishingPositionNaming:s,finishingPositionLimit:a,playoffAttributes:c,playoffPositions:u,roundOffsetLimit:p,tournamentRecord:m,exitProfileLimit:d,roundProfiles:l,roundNumbers:f,idPrefix:g,isMock:I,event:h,uuids:S}=t,T=J(t.drawDefinition,!1,!0),{structure:y}=at({structureId:n,drawDefinition:T});if(!y)return _({result:{error:kt},stack:e});if(y.structureType===Ge||y.structures)return iO({sourceStructureId:y.structureId,...t,...r,drawDefinition:T});let{playoffRoundsRanges:P,playoffRounds:U}=r,{playoffPositionsReturned:E,error:A,playoffSourceRounds:N,playoffRoundsRanges:D}=VS(t);if(A)return _({result:{error:A},stack:e});let M=l?.length&&Object.assign({},...l),R=f||typeof l=="object"&&l.map(j=>Object.keys(j)).flat(),b=Array.isArray(R)&&R.map(j=>!isNaN(j)&&pt(j)).filter(Boolean);if(b){if(!Array.isArray(b))return _({result:{error:G},context:{validRoundNumbers:b},stack:e});b.forEach(j=>{if(!U?.includes(j))return _({result:{error:G},context:{roundNumber:j},stack:e})})}u&&u.forEach(j=>{if(!E?.includes(j))return _({result:{error:G},context:{playoffPosition:j},stack:e})});let v=b||N,O=b?P:D,x=[],F=[];for(let j of v??[]){let tt=O?.find(fe=>fe.roundNumber===j);if(!tt)return _({result:{error:G},context:{roundNumber:j},stack:e});let Q=tt.finishingPositions.length,X=Math.min(...tt.finishingPositions)-1,lt=2,it=j&&M?.[j]&<+M[j]-1,Rt=Tc({exitProfile:`0-${j}`,addNameBaseToAttributeName:o,playoffStructureNameBase:i,finishingPositionOffset:X,playoffAttributes:c,exitProfileLimit:d,stage:de,roundOffset:0,drawDefinition:T,sequenceLimit:it,stageSequence:lt,drawSize:Q,idPrefix:g,isMock:I,uuids:S,finishingPositionNaming:s,finishingPositionLimit:a,roundOffsetLimit:p});if(Rt.error)return _({result:Rt,stack:e});let{structures:Ft,links:Ue}=Rt;if(Ft?.length&&x.push(...Ft),Ue?.length&&F.push(...Ue),Rt.structureId&&j){let fe={linkType:eo,source:{structureId:n,roundNumber:j},target:{structureId:Rt.structureId,feedProfile:En,roundNumber:1}};F.push(fe)}}if(!x.length)return _({result:{error:G},info:"No structures generated",stack:e});T.structures.push(...x),T.links.push(...F);let{matchUps:L,matchUpsMap:w}=se({inContext:!0,drawDefinition:T}),V=x.map(({structureId:j})=>j),k=L?.filter(({structureId:j})=>V.includes(j)).map(Ae),W=w?.drawMatchUps?.filter(({matchUpId:j})=>k?.includes(j));if(W?.length){let j=We({drawDefinition:T,event:h})?.tieFormat;j&&W.forEach(tt=>{let{tieMatchUps:Q}=Ra({matchUp:tt,tieFormat:j,isMock:I});Object.assign(tt,{tieMatchUps:Q,matchUpType:jt})})}L?.filter(j=>ds({matchUp:j})&&j.structureId===n)?.forEach(j=>{let{matchUpId:tt,score:Q,winningSide:X}=j,lt=ur({inContextDrawMatchUps:L,drawDefinition:T,matchUpId:tt}),it=JS({inContextDrawMatchUps:L,tournamentRecord:m,drawDefinition:T,matchUpsMap:w,winningSide:X,targetData:lt,matchUpId:tt,structure:y,matchUp:j,score:Q,event:h});it.error&&console.log(it.error)}),L?.filter(j=>j.matchUpStatus===Nt&&j.structureId===n)?.forEach(j=>{let{matchUpId:tt}=j,Q=ur({inContextDrawMatchUps:L,drawDefinition:T,matchUpId:tt}),{targetLinks:{loserTargetLink:X},targetMatchUps:{loserMatchUpDrawPositionIndex:lt,loserMatchUp:it}}=Q;if(X&&it){let Rt=X.target.structureId,Ft=it.drawPositions[lt],Ue=Hr({drawPosition:Ft,structureId:Rt,tournamentRecord:m,drawDefinition:T,event:h});Ue.error&&console.log(Ue.error)}});let q=[],B=qi({inContextDrawMatchUps:L,drawDefinition:T,matchUpsMap:w}).goesToMap,{structure:$}=at({drawDefinition:t.drawDefinition,structureId:n}),{matchUps:z}=Ut({structure:$});return z.forEach(j=>{let tt=B?.loserMatchUpIds[j.matchUpId];if(tt&&j.loserMatchUpId!==tt){j.loserMatchUpId=tt;let X={tournamentId:m?.tournamentId,eventId:t.event?.eventId,context:e,matchUp:j};q.push(X)}let Q=B?.winnerMatchUpIds[j.matchUpId];if(Q&&j.winnerMatchUpId!==Q){j.winnerMatchUpId=Q;let X={tournamentId:m?.tournamentId,eventId:t.event?.eventId,context:e,matchUp:j};q.push(X)}}),{structures:x,matchUpModifications:q,links:F,drawDefinition:T,...C}}function ZS({element:t}){if(!t)return{error:G};if(!t.timeItems)return{};if(!Array.isArray(t.timeItems))return{error:G};let e=(r,n)=>(o,i)=>(i[r]&&(o[i[r]]=i[n]),o);return t.timeItems.reduce(e("itemType","itemValue"),{})}function Qn(t){let{duplicateValues:e=!0,creationTime:r=!0,removePriorValues:n,timeItem:o}=t;if(!o)return{error:Zl};let i=Kh(t);if(i.error)return i;if(!(ht(o)&&Vt(o.itemType)&&Object.keys(o).includes("itemValue")))return{error:Jl};if(!i.timeItems)i.timeItems=[];else if(NG({element:i,duplicateValues:e,timeItem:o}))return{...C};if(o.itemSubTypes&&!o.itemSubTypes.length&&delete o.itemSubTypes,r){let c=new Date().toISOString();Object.assign(o,{createdAt:c})}return n&&(i.timeItems=i.timeItems.filter(({itemType:c})=>o.itemType!==c)),n&&!o.itemValue||i.timeItems.push(o),{...C}}function NG({element:t,duplicateValues:e,timeItem:r}){let{itemType:n,itemSubTypes:o,itemValue:i}=r,s=n&&rn({itemSubTypes:o,itemType:n,element:t})?.timeItem;return s&&JSON.stringify(s?.itemValue)===JSON.stringify(i)&&!e}function Rg({creationTime:t=!0,removePriorValues:e,tournamentRecord:r,duplicateValues:n,participantId:o,timeItem:i}){if(!r)return{error:Y};if(!o)return{error:oe};let s=To({tournamentRecord:r,participantId:o});return s.error?s:Qn({element:s.participant,removePriorValues:e,duplicateValues:n,creationTime:t,timeItem:i})}function Pc(t){let{removePriorValues:e,tournamentRecord:r,duplicateValues:n,creationTime:o,timeItem:i}=t;if(!r)return{error:Y};let s=Qn({element:r,removePriorValues:e,duplicateValues:n,creationTime:o,timeItem:i});if(s.error)return s;let a=ZS({element:r});return mt({payload:{parentOrganisation:r.parentOrganisation,tournamentId:r.tournamentId,timeItemValues:a},topic:Bi}),s}function zi(t){let{removePriorValues:e,duplicateValues:r,creationTime:n,timeItem:o,event:i}=t;return i?Qn({removePriorValues:e,duplicateValues:r,element:i,creationTime:n,timeItem:o}):{error:jr}}function YP(t){return bg({...t,itemType:"attachConsolationStructures"})}function Cg(t){return bg({...t,itemType:"attachPlayoffStructures"})}function bg({itemType:t="attachStructures",matchUpModifications:e,tournamentRecord:r,drawDefinition:n,structures:o,links:i=[],event:s}){let a="attachStructures";if(!n)return{error:Z};if(!Array.isArray(o)||!Array.isArray(i))return _({result:{error:G},stack:a});let c=h=>[h.source.structureId,h.source.roundNumber||h.source.finishingPositions?.join("|"),h.target.roundNumber].join("|"),u=n.links?.map(c);if(i.some(h=>{let S=c(h);return u?.includes(S)}))return _({result:{error:of},info:"playoff structure exists",stack:a});i.length&&n.links?.push(...i);let m=o.map(({structureId:h})=>h),d=n.structures?.map(({structureId:h})=>h);n.structures=(n.structures??[]).map(h=>m.includes(h.structureId)?o.find(({structureId:S})=>S===h.structureId):h);let l=o?.filter(({structureId:h})=>!d?.includes(h));l.length&&n.structures.push(...l),qi({drawDefinition:n});let f=o.map(h=>Ut({structure:h})?.matchUps||[]).flat();Co({tournamentId:r?.tournamentId,eventId:s?.eventId,drawDefinition:n,matchUps:f});let g=o.map(({structureId:h})=>h);if(Ot({drawDefinition:n,structureIds:g}),e?.length){let h={};e.forEach(T=>{let y=T.matchUp?.matchUpId;y&&(h[y]=T)});let S=T=>{T.matchUps.forEach(y=>{if(h[y.matchUpId]){let{tieMatchUps:P,...U}=h[y.matchUpId].matchUp;if(Object.assign(y,U),P?.length){let E={};P.forEach(A=>h[A.matchUpId]=A),y.tieMatchUps.forEach(A=>Object.assign(A,E[A.matchUpId]))}h[y.matchUpId].matchUp=y,gt(h[y.matchUpId])}})};n.structures.forEach(T=>{if(d?.includes(T.structureId))if(T.structures)for(let y of T.structures)S(y);else S(T)})}let I=l.map(Br("structureId"));if(r){let S={itemValue:{structureIds:g,drawId:n.drawId},itemType:t};Qn({element:r,timeItem:S})}return{...C,addedStructureIds:I}}function kp(t){let{structures:e,links:r,matchUpModifications:n,error:o}=Cd(t);if(o)return{error:o};let i=t.drawDefinition;return Cg({tournamentId:t.tournamentRecord?.tournamentId,eventId:t.event?.eventId||t.eventId,matchUpModifications:n,drawDefinition:i,structures:e,links:r})}function Qi(t){let e=rt(t,[{_anyOf:{[Re]:!1,[ie]:!1,[Ve]:!1,[Do]:!1},[Ef]:!0}]);if(e.error)return e;let r=[],n=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(n){let o=AO(t,n);if(o.error)return o;r.push(...o?.applied??[]),t.drawDefinition&&Ot({drawDefinition:t.drawDefinition,tournamentId:t.tournamentId})}else if(t.tournamentRecords){let o=Object.keys(t.tournamentRecords);if(!o.length)return{error:Y};for(let i of o){let s=t.tournamentRecords[i],a=AO(t,s);if(a.error)return a;r.push(...a?.applied??[])}}else return{error:Y};return r.length?{...C,applied:r}:{error:FI}}function AO(t,e){let r=yt(t).appliedPolicies??{};e.extensions||(e.extensions=[]);let n=[],o=Object.keys(t.policyDefinitions);if(!o.length)return{error:$u};for(let i of o)if(!r[i]||t.allowReplacement){let s=t.policyDefinitions[i];if(!s)continue;if(!ht(s))return{error:G};let{policyName:a,...c}=s;if(!c||!Object.keys(c).length||a&&!Vt(a))return{error:G};r[i]=t.policyDefinitions[i],n.push(i)}return n?.length?{...At({element:e,extension:{name:nu,value:r}}),applied:n}:{applied:n,error:FI}}function vg({tournamentRecord:t,drawDefinition:e,flightProfile:r,drawName:n,drawId:o,event:i}){if(!n||typeof n!="string")return _({result:{error:G},context:{drawName:n}});r||(r=Ht({event:i}).flightProfile);let s=r?.flights?.find(a=>a.drawId===o);if(s){s.drawName=n;let a={name:un,value:{...r,flights:r.flights}};Mo({event:i,extension:a})}return e&&(e.drawName=n,Ot({tournamentId:t?.tournamentId,drawDefinition:e})),!s&&!e?{error:Z}:{...C,flight:s}}function qP({tournamentRecord:t,drawDefinition:e,drawUpdates:r,drawId:n,event:o}){if(!ht(r))return{error:G};let i=Ht({event:o}).flightProfile,s=r.drawName&&vg({drawName:r.drawName,tournamentRecord:t,drawDefinition:e,flightProfile:i,drawId:n,event:o});if(s?.error)return s?.error;let a=s?.flight||i?.flights?.find(c=>c.drawId===n);if(!a&&!e)return{error:Z};if(a){let c={name:un,value:{...i,flights:i.flights}};Mo({event:o,extension:c})}return e&&(r.policyDefinitions&&Qi({policyDefinitions:r.policyDefinitions,drawDefinition:e}),Ot({tournamentId:t?.tournamentId,drawDefinition:e})),{...C}}function $P({tournamentRecord:t,removeScheduling:e,drawDefinition:r}){if(!r)return{error:Z};let n=Ne({drawDefinition:r}),o=s=>n?.drawMatchUps?.find(a=>a.matchUpId===s);for(let s of r.structures||[]){let{positionAssignments:a,stage:c,stageSequence:u}=s;a&&(u!==1||![ct,nt].includes(c))&&(s.positionAssignments=a.map(d=>(delete d.participantId,d)),s.seedAssignments=[]);let{matchUps:p,isRoundRobin:m}=Ut({afterRecoveryTimes:!1,inContext:!0,matchUpsMap:n,structure:s});for(let d of p){let{matchUpId:l,roundNumber:f}=d,g=d.sides||[],I=o(l);if(I){if(delete I.extensions,delete I.notes,I.matchUpStatus!==Nt&&Object.assign(I,Ru),f&&f>1&&I.drawPositions?.length&&!m){let h=g?.map(({drawPosition:T,participantFed:y})=>!y&&T).filter(Boolean),S=I.drawPositions.map(T=>h.includes(T)?void 0:T);I.drawPositions=S}e?delete I.timeItems:I.timeItems?.length&&(I.timeItems=I.timeItems.filter(h=>h.itemType&&![so,Bo,Hi,eg,Wi,ji].includes(h.itemType))),gt({tournamentId:t?.tournamentId,context:"resetDrawDefiniton",drawDefinition:r,matchUp:I})}}}r.extensions=r.extensions.filter(s=>s.name!==nc);let i=(r.structures||[]).map(({structureId:s})=>s);return Ot({drawDefinition:r,structureIds:i}),{...C}}function Cu({tournamentRecord:t}){if(!t)return{error:Y};let e={positionsNoOutcomes:[],canBePruned:[],matchPlay:[],inactive:[],drawAnalysis:{}},r={};return(t.events?.map(o=>{let i=o.eventId;return r[i]=o,(o?.drawDefinitions||[]).map(s=>({drawDefinition:s,eventId:i}))}).flat().filter(Boolean)).forEach(({drawDefinition:o,eventId:i})=>{let s=0,a=0,c=0,{allStructuresLinked:u}=Eu({drawDefinition:o}),p=r[i],d=(o?.structures||[]).map(P=>{let{stage:U,stageSequence:E,structureId:A}=P,N=ks[U],{inContextStructureMatchUps:D}=Pa({drawDefinition:o,structure:P,event:p}),M=D?.filter(({winningSide:K})=>K),R=M.filter(Boolean).length||0;a+=R,c+=D.length-a;let b=Math.max(M.filter(({roundNumber:K})=>K===1).map(({roundPosition:K})=>K)),{positionAssignments:v}=bt({structure:P}),O=v?.filter(({participantId:K})=>K);s+=O?.length??0;let x=(v?.length??0)-(O?.length??0),{roundMatchUps:F,roundProfile:L,roundNumbers:w,maxMatchUpsCount:V}=Ke({matchUps:D}),k=L&&Object.keys(L).filter(K=>!L[K].inactiveRound).map(K=>parseInt(K)),W=L&&Object.keys(L).filter(K=>L[K].inactiveRound).map(K=>parseInt(K)),H=L&&Object.values(L).every(K=>K.inactiveRound);return{positionsAssignedCount:O?.length??0,maxWinningSideFirstRoundPosition:b,unassignedPositionsCount:x,inactiveStructure:H,maxMatchUpsCount:V,inactiveRounds:W,roundMatchUps:F,activeRounds:k,roundNumbers:w,roundProfile:L,structureId:A,stageSequence:E,orderNumber:N,stage:U}}),l=d.find(P=>P.orderNumber===2&&P.stageSequence===1),f=d.filter(({inactiveStructure:P})=>!P).length,{links:g}=Ws({structureId:l.structureId,drawDefinition:o}),I=pt(l.activeRounds[0])===1&&l.activeRounds.length===1&&f===1,h=d?.every(({inactiveStructure:P})=>P),S=!g.length&&l.activeRounds.length&&(l.roundProfile[1].inactiveCount||l.inactiveRounds.length),T=o.drawId;s&&!a&&e.positionsNoOutcomes.push(T),h&&e.inactive.push(T),I&&e.matchPlay.push(T),S&&e.canBePruned.push(T);let y={matchUpsWithWinningSideCount:a,matchUpsNoOutcomeCount:c,positionsAssignedCount:s,allStructuresLinked:u,structuresData:d,inactiveDraw:h,isMatchPlay:I,drawId:T};e.drawAnalysis[T]=y}),{...C,drawsAnalysis:e}}function KP({matchPlayDrawPositions:t=!0,tournamentRecord:e,drawDefinition:r,drawId:n}){if(!e)return{error:Y};if(!r)return{error:Z};let o=[],{drawsAnalysis:i}=Cu({tournamentRecord:e});if(i.canBePruned.includes(n)){let s=i.matchPlay.includes(n),a=i.drawAnalysis[n],{structures:[c]}=gn({stageSequence:1,drawDefinition:r,stage:nt}),u=a.structuresData.find(({structureId:l})=>c.structureId===l),p=(c.matchUps??[]).sort((l,f)=>l.roundPosition-f.roundPosition);o=p.filter(({roundNumber:l})=>!u.inactiveRounds.includes(l));let m=o.map(Ae),d=p.map(Ae).filter(l=>!m.includes(l));if(s){let l=o.filter(({roundNumber:T})=>!u.inactiveRounds.includes(T)).filter(({winningSide:T})=>T),f=l.map(Ae),g=m.filter(T=>!f.includes(T));d.push(...g);let h=l.flatMap(T=>T.drawPositions??[]).filter(Boolean).flat(),S=Object.assign({},...h.map((T,y)=>({[T]:y+1})));if(l.forEach(T=>{t?T.drawPositions=T.drawPositions.map(y=>S[y]):delete T.drawPositions}),t){let T=c?.positionAssignments?.filter(y=>h.includes(y.drawPosition)).map(y=>(y.drawPosition=S[y.drawPosition],y));c.positionAssignments=T}else c.positionAssignments=[];c.matchUps=l,o=l}Yn({tournamentId:e?.tournamentId,matchUpIds:d,drawDefinition:r}),Ot({drawDefinition:r})}return{...C,matchUps:o}}function zP({tournamentRecord:t,drawDefinition:e,participantId:r,drawPosition:n,structureId:o,qualifier:i,event:s,bye:a}){if(!e)return{error:Z};if(!n)return{error:Cs};if(!o)return{error:Er};if(a){let c=Hr({tournamentRecord:t,drawDefinition:e,drawPosition:n,structureId:o,event:s});if(c.error)return c}else{if(i)return{error:Zu};{let c=kn({tournamentRecord:t,drawDefinition:e,participantId:r,drawPosition:n,structureId:o,event:s});if(c.error)return c}}return{...C}}function tT(t){let e=t.matchUpIds??[],{drawDefinition:r}=t,n=t.structureId??r?.structures?.find(c=>c.matchUps?.some(({matchUpId:u})=>e.includes(u)))?.structureId??r?.structures?.[0]?.structureId;if(!n)return{error:kt};let o=r.structures?.find(c=>c.structureId===n);if(!o)return{error:kt};let i=o?.matchUps,s=i?.find(c=>!!c.roundPosition);if(o.structures||s||o.finishingPosition===Gi)return{error:Qo};let a=i.filter(({roundNumber:c})=>t.roundNumbers?.includes(c)).map(Ae);return e=e.filter(c=>!a.includes(c)),t.roundNumbers&&!e.length&&(e=a),{existingMatchUps:i,matchUpIds:e,structureId:n,structure:o}}function QP(t){let e=rt(t,[{[Ve]:!0},{[Gs]:{[ec]:!1,roundNumbers:!1},[Fr]:G,[He]:Be}]);if(e.error)return e;let{removeIncomplete:r=!1,removeUnAssigned:n=!0,removeCompleted:o=!1,tournamentRecord:i,drawDefinition:s,event:a}=t,c=tT(t);if(c.error)return c;let{structure:u,structureId:p,existingMatchUps:m,matchUpIds:d}=c,l=[],f=m?.filter(({matchUpId:h,score:S,winningSide:T})=>{if(T&&!o)return!1;if(T||Ie({score:S})){if(!T&&!r)return!1;l.push(h)}else if(!n)return!1;return d?.includes(h)})??[],g=f.map(Ae),I=f.map(({tieMatchUps:h})=>h?.map(Ae)).filter(Boolean).flat();if(g.length){u.matchUps=(u.matchUps??[]).filter(({matchUpId:T})=>!g.includes(T)),Yn({tournamentId:i?.tournamentId,matchUpIds:[...I,...g],action:"deleteAdHocMatchUps",eventId:a?.eventId,drawDefinition:s});let h=ut(u.matchUps.map(Br("roundNumber"))),S=fC(h);if(S.length){S.reverse();for(let T of S)u.matchUps.forEach(y=>{y.roundNumber&&y.roundNumber>T&&(y.roundNumber-=1,gt({tournamentId:i?.tournamentId,context:["adHoc round deletion"],eventId:a?.eventId,drawDefinition:s,matchUp:y}))})}if(l.length){u.positionAssignments=ut(u.matchUps.flatMap(N=>(N.sides??[]).map(D=>D.participantId)).filter(Boolean)).map(N=>({participantId:N}));let T=u?.matchUpFormat??s?.matchUpFormat??a?.matchUpFormat,P=c.existingMatchUps.some(N=>N.matchUpType===xr)?{matchUpTypes:[xr]}:void 0,{matchUps:U}=Ut({afterRecoveryTimes:!1,inContext:!0,matchUpFilters:P,structure:u,event:a});cr({structure:u})&&(u.positionAssignments=ut(U.flatMap(N=>(N.sides??[]).map(D=>D.participantId)).filter(Boolean)).map(N=>({participantId:N})));let A=Md({positionAssignments:u.positionAssignments,tournamentRecord:i,drawDefinition:s,matchUpFormat:T,matchUps:U,event:a});A.error&&console.log(A)}Ot({structureIds:[p],eventId:a?.eventId,drawDefinition:s})}return!g.length&&d.length?{error:tp}:{...C,deletedMatchUpsCount:[...g,...I].length}}function XP({removeCompletedMatchUps:t,tournamentRecord:e,drawDefinition:r,structureId:n,roundNumber:o,event:i}){if(!e)return{error:Y};if(!r)return{error:Z};if(!o)return _({result:{error:st},info:"roundNumber required"});let s=at({drawDefinition:r,structureId:n});if(s.error)return s;let a=s.structure;return a?.structures?{error:Qo}:cr({structure:a})?MG({tournamentId:e.tournamentId,removeCompletedMatchUps:t,eventId:i.eventId,drawDefinition:r,roundNumber:o,structure:a}):(console.log("not implemented"),{...C})}function MG({removeCompletedMatchUps:t,drawDefinition:e,tournamentId:r,roundNumber:n,structure:o,eventId:i}){let s=o?.matchUps??[],a=[],c=[],u=!1;if(s.reduce((m,d)=>{let l=d?.roundNumber;return l?m.includes(l)?m:m.concat(l):m},[]).sort(me).includes(n)){let m=s.filter(d=>{let l=d.roundNumber===n&&(!ce.includes(d.matchUpStatus)||t);return l&&(c.push(d.matchUpId),d.tieMatchUps&&a.push(...d.tieMatchUps.map(Ae))),!l});c.length&&(Yn({matchUpIds:[...a,...c],drawDefinition:e,tournamentId:r,eventId:i}),m.some(l=>l.roundNumber===n)||(m.forEach(l=>{l.roundNumber>n&&(l.roundNumber-=1,gt({drawDefinition:e,tournamentId:r,eventId:i,matchUp:l}))}),u=!0),o.matchUps=m)}return{deletedMatchUpsCount:c.length,roundRemoved:u,...C}}function bd(t){let{suppressNotifications:e,tournamentRecord:r,drawDefinition:n,matchUps:o,event:i}=t;if(typeof n!="object")return{error:Z};let s=t?.structureId;if(!s&&n.structures?.length===1&&(s=n.structures?.[0]?.structureId),typeof s!="string")return{error:Er};if(!Vr(o))return{error:G,info:ii("matchUps")};let a=n.structures?.find(l=>l.structureId===s);if(!a)return{error:kt};let u=(a?.matchUps).find(l=>!!l.roundPosition);if(a.structures||u||a.finishingPosition===Gi)return{error:Qo};let p=Te({tournamentRecord:r,inContext:!1})?.matchUps?.map(Ae)??[],m=o.map(Ae);if(Fe(p,m))return{error:OE,info:"One or more matchUpIds already present in tournamentRecord"};a.matchUps.push(...o);let d=o.map(({tieMatchUps:l})=>l).filter(Boolean).flat();return e||(Co({tournamentId:r?.tournamentId,matchUps:[...d,...o],eventId:i?.eventId,drawDefinition:n}),Ot({drawDefinition:n,structureIds:[s]})),{...C}}function JP({tournamentRecord:t,drawDefinition:e,drawPosition:r,structureId:n,subOrder:o,event:i}){if(!e)return{error:Z};if(!n)return{error:Er};if(!r)return{error:Cs};let{structure:s}=at({drawDefinition:e,structureId:n});if(!s)return{error:kt};let a=s;s.structures&&s.structureType===Ge&&(a=s.structures?.find(g=>g.positionAssignments?.find(I=>I.drawPosition===r)));let c=a?.positionAssignments,u=c?.find(g=>g.drawPosition===r);u&&At({element:u,extension:{name:oc,value:o}});let d=(i?.eventType===jt||e.matchUpType===jt||(i?.tieFormat??e?.tieFormat??s?.tieFormat))&&{matchUpTypes:[jt]},{matchUps:l}=Ut({structure:a,afterRecoveryTimes:!1,inContext:!0,matchUpFilters:d,event:i}),f=s?.matchUpFormat??e.matchUpFormat;return Md({positionAssignments:c,tournamentRecord:t,drawDefinition:e,matchUpFormat:f,matchUps:l,event:i}),Ot({drawDefinition:e,structureIds:[n]}),{...C}}var pD={};Xt(pD,{addGoesTo:()=>qi,allPlayoffPositionsFilled:()=>OS,checkValidEntries:()=>_d,findDrawDefinition:()=>oT,getAssignedParticipantIds:()=>Ri,getAvailableMatchUpsCount:()=>vd,getAvailablePlayoffProfiles:()=>Pu,getDrawDefinitionTimeItem:()=>zh,getDrawParticipantRepresentativeIds:()=>rT,getDrawStructures:()=>gn,getDrawTypeCoercion:()=>bu,getEligibleVoluntaryConsolationParticipants:()=>eT,getMatchUpsMap:()=>Ne,getParticipantIdFinishingPositions:()=>nT,getPositionAssignments:()=>Gp,getPositionsPlayedOff:()=>yc,getSeedingThresholds:()=>ES,getSeedsCount:()=>vu,getStructureSeedAssignments:()=>on,getTeamLineUp:()=>ms,getValidGroupSizes:()=>Cp,isAdHoc:()=>cr,isCompletedStructure:()=>si,isValidForQualifying:()=>hT,positionActions:()=>IT});function eT({excludedMatchUpStatuses:t=[],includeEventParticipants:e,includeQualifyingStage:r,finishingRoundLimit:n,policyDefinitions:o,roundNumberLimit:i,tournamentRecord:s,drawDefinition:a,matchUpsLimit:c,requirePlay:u,requireLoss:p,allEntries:m,winsLimit:d,event:l}){if(!a)return{error:Z};let f=[nt,de];r&&f.push(ct);let g=l?.eventType?{matchUpTypes:[l.eventType]}:void 0,I=a?.matchUpType?{matchUpTypes:[a.matchUpType]}:void 0,h=e&&l?$n({contextFilters:{stages:f},matchUpFilters:g,tournamentRecord:s,inContext:!0,event:l})?.matchUps??[]:or({contextFilters:{stages:f},matchUpFilters:I,tournamentRecord:s,inContext:!0,drawDefinition:a})?.matchUps??[],T=Ui({stage:$e,drawDefinition:a}).map(({participantId:w})=>w),y={},P={},U={},E={};o||(o=vo({policyTypes:[vh],tournamentRecord:s,drawDefinition:a,event:l}).policyDefinitions);let A=o?.[vh];t=t.length&&t||A?.excludedMatchUpStatuses||[],e=e??A?.includeEventParticipants,m=m??A?.allEntries,n=n??A?.finishingRoundLimit,i=i??A?.roundNumberLimit,c=c??A?.matchUpsLimit,u===void 0&&(u=A?.requirePlay!==void 0?A.requirePlay:!0),p===void 0&&(p=A?.requireLoss!==void 0?A.requireLoss:!0),d=d??A?.winsLimit;for(let w of h){if(u&&w.winningSide&&![1,2].includes(w.winningSide)&&w.matchUpStatus!==he||w.finishingRound&&n&&w.finishingRound>=n||w.finishingRound&&i&&w.finishingRound<=i)continue;let V=w.sides?.find(({sideNumber:W})=>w.winningSide&&W===3-w.winningSide),k=w.sides?.find(({sideNumber:W})=>w.winningSide&&W===w.winningSide);if(w.sides?.forEach(W=>{let H=W?.participant?.participantId;H&&(U[H]=W.participant,w.matchUpStatus===he&&!u&&(P[H]=W.participant,y[H]||(y[H]=0),(!w.matchUpStatus||!t.includes(w.matchUpStatus))&&(y[H]+=1)))}),V?.participant){let W=V.participant.participantId;P[W]=V.participant,y[W]||(y[W]=0),w.matchUpStatus&&!t.includes(w.matchUpStatus)&&(y[W]+=1)}if(k?.participant){let W=k.participant.participantId;E[W]||(E[W]=0),E[W]+=1,y[W]||(y[W]=0),w.matchUpStatus&&!t.includes(w.matchUpStatus)&&(y[W]+=1)}}let N=s?.participants&&!u&&!p&&m,D=N?((e&&l?l.entries:a.entries)??[]).filter(w=>![io,Gr].includes(w.entryStatus)).map(({participantId:w})=>w):[],M=Object.keys(P),R=N?(s?.participants??[]).filter(({participantId:w})=>D.includes(w)):p&&Object.values(P)||Object.values(U),b=w=>!p||M.includes(w),v=w=>!u||(y[w]||0)>=0,O=w=>!d||(E[w]||0)<=d,x=w=>!c||y[w]<=c,F=w=>!T.includes(w);return{eligibleParticipants:R.filter(w=>b(w.participantId)&&v(w.participantId)&&O(w.participantId)&&x(w.participantId)&&F(w.participantId)).map(w=>({...w,individualParticipants:w.individualParticipantIds?.map(V=>s?.participants?.find(k=>k.participantId===V))})),losingParticipantIds:M,...C}}function vd(t){let e=rt(t,[{drawDefinition:!0}]);if(e.error)return e;let{drawDefinition:r,roundNumber:n}=t,o=t.structureId??(r.structures?.length===1&&r.structures?.[0]?.structureId);if(typeof o!="string")return{error:Er};let i=r.structures?.find(g=>g.structureId===o);if(!i)return{error:kt};let s,c=(i.matchUps??[])?.reduce((g,I)=>(I.roundPosition&&(s=!0),(I?.roundNumber||0)>g?I.roundNumber:g),0);if(i.structures||s||i.finishingPosition===Gi)return{error:Qo};let u=r?.entries?.filter(g=>{let I=g.entryStatus;return Qr.includes(I)})??[],p=Math.floor(u?.length/2)||1,m=n??c??1,d=i.matchUps?.filter(g=>g.roundNumber===m)?.length??0,l=p-d,f=l>0?l:0;return{...C,availableMatchUpsCount:f,lastRoundNumber:c,roundMatchUpsCount:p}}function rT({drawDefinition:t}){let e=dt({name:"participantRepresentatives",element:t});return e.error?e:{representativeParticipantIds:e.extension?.value||[]}}function EO({tournamentParticipants:t,drawDefinition:e,event:r}){if(!e)return{error:Z};let n=se({tournamentParticipants:t,inContext:!0,drawDefinition:e,event:r}),o=J(n.matchUps,!1,!0),i=ut(o.reduce((a,c)=>a.concat(...c.sides.map(u=>u.participantId).filter(Boolean)),[])),s=Object.assign({},...i.map(a=>{let c=o.filter(u=>u.sides.map(m=>m.participantId).filter(Boolean).includes(a));return{[a]:c}}));return{participantIds:i,participantIdMatchUps:s}}function nT({byeAdvancements:t=!1,tournamentRecord:e,drawDefinition:r}){if(!r)return{error:Z};let{participantIds:n,participantIdMatchUps:o}=EO({tournamentParticipants:e?.participants,drawDefinition:r}),i=n?.map(s=>{let c=o[s].filter(d=>[le,Nt].includes(d.matchUpStatus)||d.winningSide),u=c.map(d=>{let l=d.sides.find(I=>I.bye),f=d.sides.find(I=>I.participantId===s).sideNumber;return(d.winningSide||t&&l&&f)===f?d.finishingPositionRange.winner:d.finishingPositionRange.loser}),p=d=>Math.abs(d[0]-d[1]),m=u.reduce((d,l)=>d&&p(d)<p(l)?d:l,void 0);return{[s]:{relevantMatchUps:c,finishingPositionRanges:u,finishingPositionRange:m}}})||[];return Object.assign({},...i)}function wo({tournamentRecords:t,tournamentRecord:e,tournamentId:r,drawId:n}){if(!e&&!t)return{error:Y};if(!n)return{error:an};if(!e&&t){if(typeof r!="string"&&(r=XS({tournamentRecords:t,drawId:n}),!r))return{error:ca};if(e=t[r],!e)return{error:Y}}let o=e&&ze({tournamentRecord:e,drawId:n});return o?.drawDefinition?{drawDefinition:o.drawDefinition,event:o.event,tournamentRecord:e,...C}:_({result:{error:Mr},stack:"findDrawDefinition"})}function oT(t){let{drawDefinition:e,error:r}=wo(t);return r?{error:r}:{drawDefinition:J(e)}}function Og({targetRoundNumber:t,finishingPosition:e,drawDefinition:r,structureId:n,linkType:o}){let{links:i}=Ws({drawDefinition:r,structureId:n})||{},a=(i?.target||[]).filter(({linkType:u})=>u===o).filter(({target:u})=>!t||t===u.roundNumber).map(u=>{let p=u.source.structureId,{structure:m}=at({structureId:p,drawDefinition:r});if(!(e&&m?.finishingPosition!==e))return u}).filter(Boolean);return{sourceStructureIds:a.map(({source:u})=>u.structureId),relevantLinks:a}}function UO({tournamentParticipants:t,returnParticipants:e,drawPosition:r,participant:n,drawId:o,event:i}){let s=i?.entries?.filter(({entryStatus:a})=>[Gr,Ei].includes(a)).map(({participantId:a})=>a)||[];if(s.length){let a=n.individualParticipantIds,c=e?t.filter(({participantId:m})=>s.includes(m)):void 0,u=e?t.filter(({participantId:m})=>a.includes(m)):void 0;return{validModifyAssignedPairAction:ot({payload:{participantId:n.participantId,replacementIndividualParticipantId:void 0,existingIndividualParticipantId:void 0,drawPosition:r,drawId:o},method:$v,availableIndividualParticipantIds:s,availableIndividualParticipants:c,existingIndividualParticipantIds:a,existingIndividualParticipants:u,type:yg},!1,!1,!0)}}return{}}function Ci(t){let{inContextDrawMatchUps:e,targetData:r,drawDefinition:n,relevantLink:o}=t;if(o?.linkCondition===On&&r?.matchUp?.matchUpStatus===Nt)return!1;let{targetMatchUps:{loserMatchUp:s,winnerMatchUp:a},targetLinks:c}=r,u=s&&ur({matchUpId:s.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),p=u?.targetMatchUps?.loserMatchUp,m=u?.targetMatchUps?.loserMatchUpDrawPositionIndex,d=p?.sides[m]?.participant,l=[Mt,Ct].includes(s?.matchUpStatus)&&!d,f=a?.drawPositions?.filter(Boolean).length||0;if(s?.winningSide&&!l||a?.winningSide&&f===2&&(!a.feedRound||![Ct,Mt].includes(a?.matchUpStatus)))return!0;let g=a&&ur({matchUpId:a.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),I=u&&Ci({relevantLink:c?.loserTargetLink,targetData:u,inContextDrawMatchUps:e,drawDefinition:n});return!!(g&&Ci({targetData:g,inContextDrawMatchUps:e,drawDefinition:n})||I)}var iT={[So]:{policyName:"positionActionsDefault",enabledStructures:[{stages:[ct,nt],stageSequences:[1],enabledActions:[],disabledActions:[]},{stages:[],stageSequences:[],enabledActions:[Uu,Qs,_p,zs],disabledActions:[]}],disbledStructures:[],otherFlightEntries:!1,activePositionOverrides:[]}};var _g="positionAction",sT="matchUpAction";function aT({actionType:t=_g,appliedPolicies:e,drawDefinition:r,structure:n}){let o=t===_g&&So||t===sT&&er,i=t===_g&&iT||t===sT&&nP,s=o&&(e?.[o]||i?.[o]),c=r.links?.filter(d=>d?.target?.structureId===n?.structureId)?.map(({target:d})=>d.feedProfile)??[],{enabledStructures:u,disabledStructures:p}=s||{},m=p?.find(d=>{let{stages:l,stageSequences:f,structureTypes:g,feedProfiles:I}=d;return(!I?.length||Array.isArray(I)&&I.some(h=>c.includes(h)))&&(!l?.length||Array.isArray(l)&&l?.includes(n?.stage))&&(!g?.length||Array.isArray(g)&&g?.includes(n?.structureType))&&(!f?.length||Array.isArray(f)&&f.includes(n?.stageSequence))});return{enabledStructures:u,actionsDisabled:m,actionsPolicy:s}}function tD({activePositionOverrides:t,activeDrawPositions:e,action:r}){return r&&t.includes(r)?!0:!e.length}function cT({enabledStructures:t,drawDefinition:e,structure:r}){if(t===!1)return{};if(!t?.length)return{policyActions:{enabledActions:[],disabledActions:[]}};let{stage:n,stageSequence:o,structureType:i}=r||{},a=e.links?.filter(u=>u?.target?.structureId===r?.structureId)?.map(({target:u})=>u.feedProfile)||[];return{policyActions:t.find(u=>{let{stages:p,stageSequences:m,structureTypes:d,feedProfiles:l}=u||{},f=!p?.length||Array.isArray(p)&&p.includes(n),g=!m?.length||Array.isArray(m)&&m.includes(o),I=!d?.length||Array.isArray(d)&&d.includes(i),h=!l?.length||Array.isArray(l)&&l.some(S=>a.includes(S));return g&&I&&h&&u&&f})}}function Vn({action:t,policyActions:e}){let r=!e?.enabledActions||e?.disabledActions?.length&&e.disabledActions.includes(t);return r?!1:(e?.enabledActions.length===0||e?.enabledActions.includes(t))&&!r}var eD="replaceTieMatchUpParticipantId",rD="assignTieMatchUpParticipantId",uT="removeTieMatchUpParticipantId",nD="assignMatchUpSideParticipant",PO="removeMatchUpSideParticipant",oD="substituteParticipant",pT="REMOVE_SUBSTITUTION",iD="REPLACE_PARTICIPANT",xg="REMOVE_PARTICIPANT",mT="setMatchUpStatus",dT="SUBSTITUTION",sD="SCHEDULE",RG="PENALTY",lT="REFEREE",aD="STATUS",fT="START",cD="SCORE",gT="END",DO={REPLACE_TEAM_POSITION_METHOD:eD,ASSIGN_TEAM_POSITION_METHOD:rD,REMOVE_TEAM_POSITION_METHOD:uT,REPLACE_PARTICIPANT:iD,SUBSTITUTION_METHOD:oD,REMOVE_SUBSTITUTION:pT,REMOVE_PARTICIPANT:xg,SCHEDULE_METHOD:mT,SUBSTITUTION:dT,SCHEDULE:sD,PENALTY:RG,REFEREE:lT,STATUS:aD,SCORE:cD,START:fT,END:gT};function NO({specifiedPolicyDefinitions:t,inContextDrawMatchUps:e,matchUpParticipantIds:r,matchUpActionsPolicy:n,inContextMatchUp:o,policyActions:i,enforceGender:s,participantId:a,sideNumber:c,matchUpId:u,matchUp:p,drawId:m,side:d}){let l=[],f=o.sides?.find(F=>F.participant),g=o.gender===Tr&&o.sideNumber&&o.sides?.filter(F=>F.particiapntId).length===1&&f?.participant?.person?.sex,I=o.matchUpType,S=(s??n?.participants?.enforceGender)!==!1?o.gender:void 0,y=o.sides?.flatMap(F=>F.participant?.individualParticipants||F.participant).filter(Boolean)?.map(St),P=o.sides?.filter(F=>!c||F.sideNumber===c).flatMap(F=>F.participant?.individualParticipants||F.participant).filter(Boolean),U=P?.map(St),A=e?.find(F=>F.matchUpId===o.matchUpTieId)?.sides?.map(F=>F?.participant?.individualParticipants?.filter(({participantId:L,person:w})=>!U?.includes(L)&&(!S||S===Pn||w.sex===S||S===Tr&&!g||g&&w.sex!==g))),N=c?A?.[c-1]:A?.map((F,L)=>({participants:F,sideNumber:L+1})),D=c?A?.[c-1]?.map(St):A?.map((F,L)=>({participants:F?.map(St),sideNumber:L+1})),M=c&&(ue(aa)(I)&&!U?.length||ue(vi)(I)&&(U?.length??0)<2)||!c&&(ue(aa)(I)&&(U?.length??0)<2||ue(vi)(I)&&(U?.length??0)<4),R=D?.filter(F=>!y?.includes(F)),b=N?.filter(({participantId:F})=>R.includes(F));if(M&&R?.length&&l.push({availableParticipantIds:R,method:rD,availableParticipants:b,type:ys,payload:{participantId:void 0,tieMatchUpId:u,sideNumber:c,drawId:m}}),U?.length&&(!Ie(p)||d?.substitutions?.length)&&l.push({method:uT,type:xg,existingParticipantIds:U,payload:{participantId:void 0,tieMatchUpId:u,drawId:m}}),b?.length&&(!c&&U?.length||c&&d?.participant)&&l.push({availableParticipantIds:R,method:eD,availableParticipants:b,type:iD,existingParticipantIds:U,payload:{existingParticipantId:void 0,participantId:void 0,tieMatchUpId:u,drawId:m}}),Vn({policyActions:i,action:pT})&&d?.substitutions?.length){let F=d.participant?.participantType===Tt&&[d.participantId]||d.participant?.participantType===ft&&d.participant.individualParticipantIds||[],L=d.substitutions.map(w=>w.participantId).filter(w=>F.includes(w));(!a||L.includes(a))&&l.push({method:uT,type:pT,substitutedParticipantIds:L,payload:{participantId:void 0,tieMatchUpId:u,drawId:m}})}let v=t?.[er],O=v?.substituteWithoutScore,x=v?.substituteAfterCompleted;if(Vn({policyActions:i,action:dT})&&r.length===2&&(!c&&U?.length||c&&d?.participant)&&(O||Ie(p))&&(x||p.matchUpStatus&&!ce.includes(p.matchUpStatus))&&P?.length&&N.length){let F=P.map(St);l.push({info:"list of team players available for substitution",method:oD,availableParticipantIds:D,existingParticipantIds:F,availableParticipants:N,existingParticipants:P,type:dT,payload:{substituteParticipantId:void 0,existingParticipantId:void 0,sideNumber:c,matchUpId:u,drawId:m}})}return l}function MO({tournamentParticipants:t=[],possiblyDisablingAction:e,activeDrawPositions:r,positionAssignments:n,returnParticipants:o,appliedPolicies:i,drawDefinition:s,drawPosition:a,validActions:c,structureId:u,structure:p,drawId:m,event:d}){if(r.includes(a))return{};let l=c.find(A=>A.type===ys)?.availableParticipantIds,f=i?.[So]?.otherFlightEntries,g=i?.[So]?.restrictQualifyingAlternates,I=(s.entries??[]).filter(({entryStage:A})=>!g||(p.stage===ct?A===ct:A!==ct)).sort((A,N)=>(A.entryPosition??1/0)-(N.entryPosition??1/0)).map(({participantId:A})=>A).filter(Boolean),{allPositionedParticipantIds:h}=Bh({drawDefinition:s}),S=n.map(A=>A.participantId).filter(Boolean),T=I.filter(A=>p.stage&&[ct,nt,de].includes(p.stage)?!h?.includes(A):!S.includes(A)),P=(d?.entries??[]).filter(A=>A.entryStatus===nn&&uD({restrictQualifyingAlternates:g,structure:p,entry:A})&&(p.stage&&[ct,nt,de].includes(p.stage)?!h?.includes(A.participantId):!S.includes(A.participantId))).sort((A,N)=>(A.entryPosition??1/0)-(N.entryPosition??1/0)).map(A=>A.participantId),U=ut(T.concat(P));if(f){let N=(d?Ht({event:d}).flightProfile:void 0)?.flights?.filter(D=>D.drawId!==m).map(D=>D.drawEntries.filter(M=>M.participantId&&![io,Gr,Ei].includes(M.entryStatus)&&!I.includes(M.participantId)).map(({participantId:M})=>M)).flat().filter(Boolean);N?.length&&U.push(...N)}l?.length&&(U=U.filter(A=>!l.includes(A)));let E=o?t?.filter(A=>U.includes(A.participantId)):void 0;return E?.forEach(A=>{let N=(s.entries??[]).find(D=>D.participantId===A.participantId);A.entryPosition=N?.entryPosition}),E?.sort((A,N)=>(A.entryPosition||1/0)-(N.entryPosition||1/0)),U.length?{validAlternatesAction:ot({payload:{drawId:m,structureId:u,drawPosition:a},willDisableLinks:e,method:Yv,availableAlternatesParticipantIds:U,type:Ag,availableAlternates:E})}:{}}function uD({restrictQualifyingAlternates:t,structure:e,entry:r}){let{stage:n}=e;if(!r.entryStage||r.entryStage===n||n===ct&&!t||r.entryStage===nt&&n===qe)return!0}function RO({eventEntries:t,structure:e}){let r=o=>o.entryStatus===nn&&uD({structure:e,entry:o}),n=(o,i)=>(o.entryPosition||1/0)-(i.entryPosition||1/0);return t.filter(r).sort(n).map(St)}function CO({restrictAdHocRoundParticipants:t,tournamentParticipants:e,matchUpParticipantIds:r,otherFlightEntries:n,drawDefinition:o,structureId:i,sideNumber:s,matchUpId:a,structure:c,matchUp:u,drawId:p,event:m}){let d=[],l=c?.matchUps??[],g=u.sides?.find(N=>N.sideNumber===s)?.participantId,I=l.filter(({roundNumber:N})=>N===u.roundNumber),h=o?.entries?.filter(({entryStatus:N})=>N&&ri.includes(N)).map(St)??[],S=I.map(N=>(N.sides??[]).flatMap(St)).flat().filter(Boolean),T=h.filter(N=>!r.includes(N)&&(!t||!S.includes(N))),y=e?.filter(N=>T?.includes(N.participantId)).map(N=>J(N,void 0,!0));y?.forEach(N=>{let D=(o.entries??[]).find(M=>M.participantId===N.participantId);N.entryPosition=D?.entryPosition}),T.length&&d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},method:nD,type:ys,availableParticipantIds:T,participantsAvailable:y});let P=m?.entries??[],U=RO({eventEntries:P,structure:c}),E=ut(h.concat(U));if(n){let D=(m?Ht({event:m}):void 0)?.flights?.filter(M=>M.drawId!==p).flatMap(M=>M.drawEntries.filter(R=>R.participantId&&![io,Gr,Ei].includes(R.entryStatus)).map(({participantId:R})=>R)).filter(Boolean);D?.length&&E.push(...D)}E=E.filter(N=>!r.includes(N)&&!T.includes(N)&&(!t||!S.includes(N)));let A=e?.filter(N=>E.includes(N.participantId)).map(N=>J(N,void 0,!0));if(A?.forEach(N=>{let D=(o.entries??[]).find(M=>M.participantId===N.participantId);N.entryPosition=D?.entryPosition}),A?.sort((N,D)=>(N.entryPosition||1/0)-(D.entryPosition||1/0)),E.length&&d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},availableParticipantIds:E,participantsAvailable:A,method:nD,type:nn}),!Ie(u)&&s&&g){d.push({payload:{drawId:p,matchUpId:a,structureId:i,sideNumber:s},method:PO,type:xg});let N=L=>L.sides.map(St),D=({matchUpId:L})=>L!==u.matchUpId,M=L=>!Ie(L),R=u.sides?.find(L=>L.sideNumber!==s)?.participantId,v=l.filter(({roundNumber:L})=>L!==u.roundNumber).filter(D).map(N),O=[R,...v.filter(L=>L.includes(g)).flat()].filter(Boolean),x=L=>!O.flat().includes(L),F=I.filter(M).filter(D).map(N).flat().filter(x);if(F.length){let L=e?.filter(w=>F.includes(w.participantId)).map(w=>J(w,void 0,!0));d.push({payload:{participantIds:[g],roundNumber:u.roundNumber,structureId:i,sideNumber:s,matchUpId:a,drawId:p},swappableParticipantIds:F,method:Kv,type:wp,swappableParticipants:L})}}return d}function Od(t){if(!t)return{error:G};let{drawDefinition:e,event:r}=t,{restrictAdHocRoundParticipants:n=!0,policyDefinitions:o,enforceGender:i,participantId:s,sideNumber:a,matchUpId:c}=t,u=t.tournamentRecord??(t.tournamentId&&Vt(t.tournamentId)&&t.tournamentRecords?.[t.tournamentId]);if(!u)return{error:Y};if(!c||!Vt(c))return{error:sr};if(a&&![1,2].includes(a))return _({result:{error:G},context:{sideNumber:a}});if(!e){let X=(Te({tournamentRecord:u}).matchUps??[]).find(it=>it.matchUpId===c);r=(u?.events??[]).find(it=>it.eventId===X?.eventId);let lt=(r?.drawDefinitions??[]).find(it=>it.drawId===X?.drawId);lt&&(e=lt)}if(!e)return{error:Z};let p=Gt({withIndividualParticipants:!0,tournamentRecord:u}).participants,{drawId:m}=e,{matchUp:d,structure:l}=Bt({drawDefinition:e,matchUpId:c,event:r});if(!d)return{error:Le};let f=yt({tournamentRecord:u,drawDefinition:e,structure:l,event:r}).appliedPolicies??{};Object.assign(f,o??{});let g=f?.[So]?.otherFlightEntries,I=f?.[er]??hs[er],{enabledStructures:h}=aT({actionType:sT,appliedPolicies:f,drawDefinition:e,structure:l}),{policyActions:S}=cT({enabledStructures:h,drawDefinition:e,structure:l}),T=t.matchUpsMap??Ne({drawDefinition:e}),y=t.inContextDrawMatchUps??se({tournamentParticipants:p,inContext:!0,drawDefinition:e,matchUpsMap:T,event:r}).matchUps,P=y?.find(Q=>Q.matchUpId===c),U=a&&P?.sides?.find(Q=>Q.sideNumber===a),E=P?.sides?.map(Q=>Q.participantId||Q.participant?.participantid).filter(Boolean)??[],{assignedPositions:A,allPositionsAssigned:N}=Se({structure:l}),{structureId:D}=l??{},M=[];if(!D)return{validActions:M};let R=cr({structure:l}),b=d.collectionId;if(R&&!b){let Q=CO({restrictAdHocRoundParticipants:n,tournamentParticipants:p,matchUpParticipantIds:E,otherFlightEntries:g,drawDefinition:e,structureId:D,sideNumber:a,matchUpId:c,structure:l,matchUp:d,drawId:m,event:r});M.push(...Q)}let v=si({drawDefinition:e,structure:l}),O=A?.filter(Q=>Q.participantId).map(Q=>Q.drawPosition),x=A?.filter(Q=>Q.bye).map(Q=>Q.drawPosition),F=d.matchUpStatus===Nt||!b&&d.drawPositions?.reduce((Q,X)=>x?.includes(X)||Q,!1);if(F)return{validActions:M,isByeMatchUp:F};Vn({policyActions:S,action:lT})&&M.push({type:lT,payload:{matchUpId:c}});let L=!Ua({matchUpStatus:d.matchUpStatus}),w=f?.scoring?.structures,V=l?.stage&&w?.stage&&w?.stage[l.stage],k=l?.stageSequence&&V?.stageSequence&&V.stageSequence[l.stageSequence],H=!(f?.scoring?.requireAllPositionsAssigned||V?.requireAllPositionsAssigned||k?.requireAllPositionsAssigned)||N,K=d.sides&&d.sides.filter(Q=>Q?.participantId).length===2,q=d.matchUpStatus&&[he,Ce].includes(d.matchUpStatus),B=ur({inContextDrawMatchUps:y,drawDefinition:e,matchUpId:c}),$=Ci({inContextDrawMatchUps:y,drawDefinition:e,targetData:B}),j=(P?.drawPositions?.length===2&&P.drawPositions.every(Q=>O?.includes(Q))&&P?.sides?.length===2&&P.sides.every(({participantId:Q})=>Q)||K)&&!(q&&$),tt={method:kS,type:Qs,payload:{drawId:m,matchUpId:c,penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0}};if(L&&M.push({payload:{drawId:m,matchUpId:c,schedule:{}},method:mT,type:sD}),Vn({policyActions:S,action:Qs})&&(U?.participant||!a&&E?.length)&&M.push(tt),L&&j&&M.push({type:aD}),H&&j){let{matchUpId:Q,matchUpFormat:X}=d,lt={drawId:m,matchUpId:Q,matchUpFormat:X,outcome:{scoreStringSide1:void 0,scoreStringSide2:void 0,sets:[]},winningSide:void 0};M.push({info:"set outcome and winningSide",method:mT,type:cD,payload:lt}),Vn({policyActions:S,action:fT})&&M.push({type:fT}),Vn({policyActions:S,action:gT})&&M.push({type:gT})}if(b&&P){let Q=NO({specifiedPolicyDefinitions:o,inContextDrawMatchUps:y,matchUpParticipantIds:E,matchUpActionsPolicy:I,inContextMatchUp:P,policyActions:S,enforceGender:i,participantId:s,sideNumber:a,matchUpId:c,matchUp:d,drawId:m,side:U});M.push(...Q)}return{structureIsComplete:v,validActions:M,isDoubleExit:q,...C}}function bO({tournamentParticipants:t=[],sourceStructuresComplete:e,possiblyDisablingAction:r,isWinRatioFedStructure:n,activeDrawPositions:o,positionAssignments:i,drawDefinition:s,drawPosition:a,structureId:c,structure:u,drawId:p,event:m}){if(o.includes(a)||n&&!e)return{};let{sourceStructureIds:d,targetStructureIds:l}=s.links?.reduce((h,S)=>{let T=S.source?.structureId,y=S.target?.structureId;return h.sourceStructureIds.includes(T)||h.sourceStructureIds.push(T),h.targetStructureIds.includes(y)||h.targetStructureIds.push(y),h},{sourceStructureIds:[],targetStructureIds:[]})||{},f=[],g=s.links?.filter(h=>h.target?.structureId===u.structureId)??[];for(let h of g){let S=h?.source?.structureId,{structure:T}=at({structureId:S,drawDefinition:s}),y=T?.finishingPosition===Gi&&(d?.length!==1||l?.length!==1),P={};if(y){let{matchUps:N}=Ut({drawDefinition:s,structure:u,event:m}),{initialRoundNumber:D}=fs({drawPosition:a,matchUps:N}),R=s.links?.find(b=>b.target?.structureId===u?.structureId&&b.target.roundNumber===D)?.source?.roundNumber;P.roundNumbers=[R]}let{completedMatchUps:U}=hu({structureId:S,inContext:!0,matchUpFilters:P,drawDefinition:s}),E=i.map(N=>N.participantId).filter(Boolean);U?.filter(({matchUpType:N,winningSide:D})=>D&&(m?.eventType!==_e||N===_e)).map(({winningSide:N,sides:D})=>N&&D?.[1-(N-1)]).map(St).filter(N=>N&&!E.includes(N))?.forEach(N=>{f.includes(N)||f.push(N)})}let I=t?.filter(h=>f?.includes(h.participantId));return I?.forEach(h=>{let S=(s.entries??[]).find(T=>T.participantId===h.participantId);h.entryPosition=S?.entryPosition}),f?.length?{validLuckyLosersAction:{type:Ug,method:qv,availableLuckyLosers:I,availableLuckyLoserParticipantIds:f,willDisableLinks:r,payload:{drawId:p,structureId:c,drawPosition:a}}}:{}}function vO({positionSourceStructureIds:t,unassignedParticipantIds:e,possiblyDisablingAction:r,provisionalPositioning:n,tournamentParticipants:o,isWinRatioFedStructure:i,positionAssignments:s,returnParticipants:a,appliedPolicies:c,drawDefinition:u,seedingProfile:p,isByePosition:m,drawPosition:d,structureId:l,event:f}){let{drawId:g}=u,I=[],h,S,T=[],y=c?.[xn]?.validSeedPositions?.ignore;if(y||({unplacedSeedParticipantIds:h,unplacedSeedAssignments:S,unfilledPositions:T}=US({provisionalPositioning:n,returnAllProxies:!0,randomize:!0,drawDefinition:u,seedingProfile:p,structureId:l,event:f})),T?.length||(T=s.filter(P=>!P.participantId&&!P.bye&&!P.qualifier).map(P=>P.drawPosition)),m||I.push({payload:{drawId:g,structureId:l,drawPosition:d,isPositionAction:!0},willDisableLinks:r,method:Xv,type:Ed}),i&&y){let P=s.map(D=>D.participantId).filter(Boolean),U={structureIds:t},{completedMatchUps:E}=js({inContext:!0,matchUpFilters:U,drawDefinition:u}),A=ut((E??[]).filter(({matchUpType:D})=>f?.eventType!==_e||D===_e)?.map(({sides:D})=>D?.map(St)).flat().filter(D=>D&&!P.includes(D))),N=a?o?.filter(D=>A?.includes(D.participantId)).map(D=>J(D,void 0,!0)):void 0;return N?.forEach(D=>{let M=(u.entries??[]).find(R=>R.participantId===D.participantId);D.entryPosition=M?.entryPosition}),N?.length&&I.push(ot({payload:{drawId:g,structureId:l,drawPosition:d},willDisableLinks:r,method:vP,type:ys,availableParticipantIds:A,participantsAvailable:N})),{validAssignmentActions:I}}if(T.includes(d)||m){let P;if(S?.length){let E=S.filter(A=>h?.includes(A.participantId));E.sort(CG),P=E.map(A=>A.participantId)}else P=e;let U=a?o?.filter(E=>P.includes(E.participantId)).map(E=>J(E,void 0,!0)):void 0;U?.length&&I.push(ot({payload:{drawId:g,structureId:l,drawPosition:d},willDisableLinks:r,method:vP,type:ys,availableParticipantIds:P,participantsAvailable:U}))}return{validAssignmentActions:I}}function CG(t,e){return t.bye||Ic(t.seedValue)<Ic(e.seedValue)||t.seedValue&&!e.seedValue?-1:(t.seedNumber||0)-(e.seedNumber||0)}function OO({drawPositionInitialRounds:t,tournamentParticipants:e,positionAssignments:r,returnParticipants:n,appliedPolicies:o,drawDefinition:i,drawPosition:s,structureId:a,drawId:c}){let u=[],p=[],m=[],d=[],l=r.map(P=>P.participantId).filter(Boolean),f=o?.[So],g=!f?.disableRoundRestrictions&&t[s],I=f?.requireCompletedStructures,{sourceStructureIds:h,relevantLinks:S}=Og({targetRoundNumber:g,linkType:fo,drawDefinition:i,structureId:a})||{};h?.length&&d.push(...h);let{sourceStructureIds:T,relevantLinks:y}=Og({targetRoundNumber:g,linkType:to,drawDefinition:i,structureId:a})||{};T?.length&&d.push(...T);for(let P of S){let U=i.structures?.find(A=>A.structureId===P.source.structureId);if(U?.stage!==ct)continue;let E=si({structureId:P.source.structureId,drawDefinition:i});if(!I||E){let A=U.qualifyingRoundNumber,{matchUps:N}=Ut({matchUpFilters:{roundNumbers:[A],hasWinningSide:!0},afterRecoveryTimes:!1,tournamentParticipants:e,inContext:!0,structure:U});for(let D of N){let M=D.sides.find(b=>b?.sideNumber===D.winningSide),R=D.matchUpStatus===Nt&&D.sides?.find(({participantId:b})=>b);if(M||R){let{participantId:b,participant:v}=M||R||{};b&&!l.includes(b)&&(v&&n&&u.push(v),p.push(b))}}}}for(let P of y){let U=i.structures?.find(A=>A.structureId===P.source.structureId);if(U?.stage!==ct)continue;let E=si({structureId:P.source.structureId,drawDefinition:i});if(!I||E){let{positionAssignments:A}=bt({structure:U}),N=A?.map(D=>{let M=D.participantId,R=dt({element:D,name:Jo}).extension?.value;return R?{participantId:M,groupOrder:R?.groupOrder}:{}}).filter(({groupOrder:D,participantId:M})=>D===1&&!l.includes(M)).map(({participantId:D})=>D)??[];if(N&&p.push(...N),n){let D=e.filter(({participantId:M})=>N.includes(M));u.push(...D)}}}return p.length&&m.push(ot({qualifyingParticipants:n?u:void 0,method:Wv,type:_p,qualifyingParticipantIds:p,payload:{qualifyingParticipantId:void 0,drawPosition:s,structureId:a,drawId:c}})),{validAssignmentActions:m,sourceStructureIds:d}}function _O({onlyAssignedPositions:t=!0,possiblyDisablingAction:e,tournamentParticipants:r,inactiveDrawPositions:n,activeDrawPositions:o,positionAssignments:i,returnParticipants:s,byeDrawPositions:a,drawDefinition:c,isByePosition:u,drawPosition:p,structureId:m,structure:d,drawId:l,event:f}){if(o.includes(p))return{};let g=D=>!t||D.participantId||D.qualifier||D.bye,I=n?.filter(D=>D!==p&&!(u&&a.includes(D))),h=i?.filter(D=>g(D)&&I?.includes(D.drawPosition))??[],S=h.map(({drawPosition:D})=>D),{matchUps:T}=Ut({afterRecoveryTimes:!1,inContext:!0,drawDefinition:c,structure:d,event:f}),y=T.filter(({drawPositions:D})=>Fe(D,S)),P=Object.assign({},...y.map(D=>D.sides?.filter(({sourceDrawPositionRange:M})=>M).map(({drawPosition:M,sourceDrawPositionRange:R})=>({[M]:R}))).flat()),U=h.map(D=>D.participantId).filter(Boolean),E=(r??[]).filter(D=>U.includes(D.participantId)),A=Object.assign({},...E.map(D=>({[D.participantId]:D}))),N=h.map(D=>{let M=A?.[D.participantId],R=P[D.drawPosition];return ot({...D,participant:s?J(M,!1,!0):void 0,sourceDrawPositionRange:R})});return N.length?{validSwapAction:{payload:{drawId:l,structureId:m,drawPositions:[p]},willDisableLinks:e,method:FS,type:wp,availableAssignments:N}}:{}}function IT(t){let e=rt(t,[{event:!0,drawDefinition:!0,structureId:!0}]);if(e.error)return e;let{policyDefinitions:r,returnParticipants:n=!0,provisionalPositioning:o,tournamentRecord:i,drawDefinition:s,drawPosition:a,event:c}=t,u=t.tournamentParticipants??(i&&Gt({withIndividualParticipants:!0,tournamentRecord:i}).participants)??[],p=at({structureId:t.structureId,drawDefinition:s});if(p.error)return p;let m=p.containingStructure||p.structure;if(!m)return{error:kt};let d=m.structureId;if(p=Pa({drawDefinition:s,structureId:d}),a===void 0&&!p.isAdHoc)return{error:Cs};if(p.isAdHoc)return Od(t);if(p.error)return p;let{drawPositionInitialRounds:l,inactiveDrawPositions:f,activeDrawPositions:g,byeDrawPositions:I}=p,h=yt({tournamentRecord:i,drawDefinition:s,structure:m,event:c}).appliedPolicies??{};Object.assign(h,r??{});let{actionsPolicy:S,enabledStructures:T,actionsDisabled:y}=aT({actionType:_g,appliedPolicies:h,drawDefinition:s,structure:m}),P=S?.activePositionOverrides||[],{sourceStructureIds:U}=Og({finishingPosition:li,targetRoundNumber:1,linkType:to,drawDefinition:s,structureId:d})||{},E;U?.length&&(E=U.every(j=>si({structureId:j,drawDefinition:s})));let A=U.length,N=U.length&&!E,{policyActions:D}=cT({enabledStructures:T,drawDefinition:s,structure:m}),M=![ct,nt].includes(m.stage)||m.stageSequence!==1,{drawId:R}=s,b=[],{assignedPositions:v,positionAssignments:O}=Se({structure:m}),x=v?.find(j=>j.drawPosition===a),F=!!x;if(!O?.map(j=>j.drawPosition)?.includes(a))return{error:Rs};let{stage:w,stageSequence:V}=m,k=[w];w===qe&&k.push(nt),w===nt&&k.push(qe);let W=Ui({entryStatuses:ri,provisionalPositioning:o,drawDefinition:s,stageSequence:V,structureId:d,stages:k}),H=Ri({drawDefinition:s,stages:k}).assignedParticipantIds??[],K=W.filter(j=>!H.includes(j.participantId)).map(j=>j.participantId),q=I.includes(a),B=g.includes(a);if(y)return{info:"Actions Disabled for structure",isActiveDrawPosition:B,isDrawPosition:!0,hasPositionAssigned:F,validActions:[],isByePosition:q};if(Vn({policyActions:D,action:ys})&&!B&&O&&!N&&(!x||q)){let{validAssignmentActions:j}=vO({positionSourceStructureIds:U,unassignedParticipantIds:K,possiblyDisablingAction:M,isWinRatioFedStructure:A,tournamentParticipants:u,positionAssignments:O,returnParticipants:n,appliedPolicies:h,drawDefinition:s,isByePosition:q,drawPosition:a,structureId:d,event:c});j?.forEach(tt=>b.push(tt))}if(Vn({policyActions:D,action:_p})&&!B){let{validAssignmentActions:j}=OO({drawPositionInitialRounds:l,tournamentParticipants:u,positionAssignments:O,returnParticipants:n,appliedPolicies:h,drawDefinition:s,drawPosition:a,structureId:d,drawId:R});j?.forEach(tt=>b.push(tt))}let{participantId:$}=x||{},z=$&&u.find(j=>j.participantId===$);if(x){Vn({policyActions:D,action:GS})&&!B&&(b.push({type:GS,method:bP,payload:{drawId:R,structureId:d,drawPosition:a},willDisableLinks:M}),q||b.push({type:Eg,method:jv,payload:{drawId:R,structureId:d,drawPosition:a},willDisableLinks:M}),Vn({policyActions:D,action:Ed})&&!q&&b.push({type:Ed,method:bP,payload:{drawId:R,structureId:d,drawPosition:a,replaceWithBye:!0},willDisableLinks:M}));let j=m.stage===ct||m.stage===nt&&m.stageSequence===1;if(!q&&tD({activePositionOverrides:P,activeDrawPositions:g,action:zs})&&Vn({policyActions:D,action:zs})&&bp({drawDefinition:s,structureId:d,drawPosition:a})&&j){let{seedAssignments:tt}=on({returnAllProxies:!0,drawDefinition:s,structure:m}),{seedNumber:Q,seedValue:X}=tt?.find(lt=>lt.participantId===$)??{};b.push({type:zs,method:Jv,participant:z,seedNumber:Q,payload:{drawId:R,structureId:d,participantId:$,seedValue:X}})}if(!q&&tD({activePositionOverrides:P,activeDrawPositions:g,action:xp})&&Vn({policyActions:D,action:xp})&&bp({drawDefinition:s,structureId:d,drawPosition:a})&&j){let{seedAssignments:tt}=on({returnAllProxies:!0,drawDefinition:s,structure:m}),{seedNumber:Q}=tt?.find(X=>X.participantId===$)??{};b.push({method:Qv,type:xp,participant:z,seedNumber:Q,payload:{participantId:$,structureId:d,drawId:R}})}if(!q&&$){if(Vn({policyActions:D,action:Qs})){let tt={type:Qs,method:kS,participant:z,payload:{penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0,drawId:R}};b.push(tt)}if(Vn({policyActions:D,action:Uu})){let tt={type:Uu,method:zv,participant:z,payload:{participantId:$,otherName:void 0}};b.push(tt)}}if(Vn({policyActions:D,action:wp})){let{validSwapAction:tt}=_O({possiblyDisablingAction:M,tournamentParticipants:u,inactiveDrawPositions:f,activeDrawPositions:g,positionAssignments:O,returnParticipants:n,byeDrawPositions:I,drawDefinition:s,isByePosition:q,drawPosition:a,structureId:d,structure:m,drawId:R});tt&&b.push(tt)}}if(Vn({policyActions:D,action:Ag})&&!N){let{validAlternatesAction:j}=MO({possiblyDisablingAction:M,tournamentParticipants:u,positionAssignments:O,activeDrawPositions:g,returnParticipants:n,appliedPolicies:h,drawDefinition:s,drawPosition:a,validActions:b,structureId:d,structure:m,drawId:R,event:c});j&&b.push(j)}if(Vn({policyActions:D,action:Ug})&&!N&&!B&&O){let{validLuckyLosersAction:j}=bO({sourceStructuresComplete:E,possiblyDisablingAction:M,isWinRatioFedStructure:A,tournamentParticipants:u,activeDrawPositions:g,positionAssignments:O,drawDefinition:s,drawPosition:a,structureId:d,structure:m,drawId:R});j&&b.push(j)}if(z?.participantType===ft&&Vn({policyActions:D,action:yg})){let{validModifyAssignedPairAction:j}=UO({tournamentParticipants:u,returnParticipants:n,drawPosition:a,participant:z,drawId:R,event:c});j&&b.push(j)}return{isActiveDrawPosition:B,isDrawPosition:!0,hasPositionAssigned:F,isByePosition:q,validActions:b,...C}}function bu({policyDefinitions:t,appliedPolicies:e,drawType:r}){let n=t?.[Vm]?.drawTypeCoercion,o=e?.[Vm]?.drawTypeCoercion;return(typeof n=="boolean"?n:void 0)??(r&&n?.[r])??(typeof o=="boolean"?o:void 0)??(r&&o?.[r])??!0}function Gp({tournamentRecord:t,drawDefinition:e,stage:r=nt,structureId:n,structure:o}){if(!t)return{error:Y};if(!o&&!e)return{error:Z};if(!o&&!n&&e?.structures?.filter(a=>a.stage===r).length===1&&(o=e.structures.find(a=>a.stage===r)),!o&&!n)return{error:Er};let{error:i,positionAssignments:s}=bt({drawDefinition:e,structureId:n,structure:o});return{positionAssignments:s??[],structureId:o?.structureId,error:i}}function hT({structureId:t,drawDefinition:e}){if(!e)return{error:Z};if(!Vt(t))return{error:G};let r=Ws({drawDefinition:e,structureId:t});if(r.error)return r;let n=r.links.target.flatMap(i=>i.target.feedProfile).filter(Boolean),o=!Yt([di,En,cp,mi],n).length;return{...C,valid:o}}function ST({participantsCount:t,participantCount:e}){if(t=t??e,!t)return{error:G};let r=es(t);return r?{drawSize:r}:_({result:{error:G},stack:"getEliminationDrawSize",context:{participantsCount:t}})}function vu(t){let{drawSizeProgression:e=!1,policyDefinitions:r,drawSize:n}=t||{},{requireParticipantCount:o=!0,tournamentRecord:i,drawDefinition:s,event:a}=t||{},c="getSeedsCount",u=t?.participantsCount??t?.participantCount;if(!r){let I=vo({tournamentRecord:i,drawDefinition:s,event:a});if(I.error)return _({result:I,stack:c});r=I.policyDefinitions}let p=It(u);if(u&&!p)return _({result:{error:G},context:{participantsCount:u},stack:c});if(o&&!p)return _({result:{error:uE},stack:c});if(isNaN(n))if(u)({drawSize:n}=ST({participantsCount:u}));else return _({result:{error:Ya},stack:c});let m=o&&u||n;if(m&&m>n)return{error:Kl};let d=r?.[xn];if(!d)return{error:XA};let l=d.seedsCountThresholds;return l?(d.drawSizeProgression!==void 0&&(e=d.drawSizeProgression),{seedsCount:l.filter(I=>e?I.drawSize<=n:n===I.drawSize).reduce((I,h)=>u&&u>=h.minimumParticipantCount?h.seedsCount:I,0)}):{error:wA}}function _d({consideredEntries:t,policyDefinitions:e,tournamentRecord:r,appliedPolicies:n,participantMap:o,enforceGender:i,participants:s,event:a}){if((!s||!o)&&r&&({participants:s,participantMap:o}=Gt({tournamentRecord:r})),!s)return{error:$a};if(!Array.isArray(s))return{error:G};if(!a)return{error:vt};let c=e?.[er]??n?.[er]??hs[er],u=(i??c?.participants?.enforceGender)!==!1,{eventType:p,gender:m}=a,d=p===ko,l=p===Cr&&Lt||d&&ft||Tt,f=Object.assign({},...(t??a.entries??[]).map(S=>({[S.participantId]:S.entryStatus}))),g=Object.keys(f),h=s.filter(S=>g.includes(S.participantId)).filter(S=>{let T=bG({participant:S,participantType:l,eventType:p,entryStatusMap:f}),y=vG({genderEnforced:u,participantMap:o,eventGender:m,participant:S,isDoubles:d,mismatch:T});return T||!y});if(h.length){let S=h.map(T=>T.participantId);return{error:jA,invalidParticipantIds:S}}return{...C,valid:!0}}function bG({participant:t,participantType:e,eventType:r,entryStatusMap:n}){let o=n[t.participantId],i=r&&[ko,Cr].includes(r)&&t.participantType===Tt&&(Ys(o)||o===io);return t.participantType!==e&&!i}function vG(t){let{participant:e,participantMap:r,eventGender:n,mismatch:o,isDoubles:i,genderEnforced:s}=t,a=!o&&i&&ut(e?.individualParticipantIds?.map(m=>r?.[m]?.participant?.person?.sex).filter(Boolean)??[])||[],c=!n||!a?.length||Pn===n||[$t,ne].includes(n)&&a[0]===n||Tr===n&&(a.length===1&&e.individualParticipantIds?.length===1||a.length===2),u=e?.person?.sex,p=!e?.person||!n||[Pn,Tr].includes(n)||[$t,ne].includes(n)&&u===n;return!s||c&&p}function TT({qualifyingProfiles:t,appliedPolicies:e,idPrefix:r,isMock:n,uuids:o}){let i="generateQualifyingSTructures",s=[],a=[],c=[],u=(g,I)=>g.stageSequence-I.stageSequence,p=(g,I)=>g.roundTarget-I.roundTarget,m=0,d=0,l,f=1;for(let g of t.sort(p)){let I=g.structureProfiles||[];f=g.roundTarget||f;let h=1,S=0,T,y,P;for(let U of(I||[]).sort(u)){let E=hm(U.drawSize||U.participantsCount),{qualifyingRoundNumber:A,structureOptions:N,matchUpFormat:D,structureName:M,structureId:R,drawType:b}=U,v=U.matchUpType,O=U.qualifyingPositions||OG({drawSize:E,qualifyingRoundNumber:A}),x,F,L;if(!It(E))return _({result:{error:Ya},stack:i});let w=t.length>1?`${f}-`:"",V=I.length>1||w?h:"",k=M||(w||V?`${Qe(ct)} ${w}${V}`:Qe(ct));if(b===Nn){let{structures:W,groupCount:H,maxRoundNumber:K}=Na({structureName:U.structureName||k,structureId:R||o?.pop(),stage:ct,structureOptions:N,appliedPolicies:e,stageSequence:h,matchUpType:v,roundTarget:f,drawSize:E,idPrefix:r,isMock:n,uuids:o});S=H,x=K,F=W[0],l=[1]}else({drawSize:E,matchUps:L,roundLimit:x}=Cn({qualifyingRoundNumber:A,qualifyingPositions:O,matchUpType:v,drawSize:E,idPrefix:r,isMock:n,uuids:o})),F=hn({structureName:U.structureName||k,structureId:R||o?.pop(),qualifyingRoundNumber:x,stage:ct,matchUpFormat:D,stageSequence:h,matchUpType:v,roundLimit:x,matchUps:L}),f&&At({extension:{name:Mn,value:f},element:F}),S=L?.filter(W=>W.roundNumber===x)?.length||0;if(h>1){let{link:W}=Ma({sourceStructureId:y,sourceRoundNumber:T,targetStructureId:F.structureId,finishingPositions:P===to?[1]:void 0,linkType:P});c.push(W),m+=(E||0)-S}else m+=E||0;P=b===Nn?to:fo,y=F.structureId,T=x,a.push(F),h+=1}d+=S,s.push({qualifiersCount:S,finalQualifyingRoundNumber:T,finalQualifyingStructureId:y,finishingPositions:l,roundTarget:f,linkType:P}),f+=1}return{qualifiersCount:d,qualifyingDrawPositionsCount:m,qualifyingDetails:s,structures:a,...C,links:c}}function OG({drawSize:t,qualifyingRoundNumber:e}){let r=t,n=0;for(;n<e;)r=Math.floor(r/2),n+=1;return r}function yT(t){let{drawTypeCoercion:e,enforceMinimumDrawSize:r}=t,n=pt(t.drawSize),o=e&&t.drawType!==$r&&(typeof e=="boolean"||e<=2)&&n===2&&go||t.drawType||go,i=dU.includes(o);if(n&&i){if(e&&(typeof e=="boolean"&&n<4||n<=e))o=go;else if(n<4&&r)return{..._({context:{enforceMinimumDrawSize:r,drawSize:n,drawType:o},result:{error:qu},stack:"getCoercedDrawType"}),drawType:o}}return{drawType:o}}function xO(t){let{drawDefinition:e,structureOptions:r,requireSequential:n}=t,o={structureName:Qe(nt),...t,stage:nt},{structures:i,groupCount:s,groupSize:a}=Na(o);if(s<1)return{error:NE};let c=r?.playoffGroups||[{finishingPositions:[1],structureName:Qe(de)}],[u]=i,{structures:p,links:m}=YS({sourceStructureId:u.structureId,requireSequential:n,drawDefinition:e,playoffGroups:c,groupCount:s,groupSize:a,...t});return p&&i.push(...p),{...C,structures:i,links:m}}function wO({mainStructure:t,consolationStructure:e,deciderStructure:r}){let o=e.matchUps.reduce((p,m)=>(m.drawPositions||[]).filter(Boolean).length&&!p.includes(m.roundNumber)?p.concat(m.roundNumber):p,[]),i=t.matchUps.reduce((p,m)=>!p||m.roundNumber>p?m.roundNumber:p,void 0),s=e.matchUps.reduce((p,m)=>!p||m.roundNumber>p?m.roundNumber:p,void 0),a=o.map((p,m)=>{let l=o.indexOf(p)%2?En:di,f=1+m;return{linkType:eo,source:{roundNumber:f,structureId:t.structureId},target:{feedProfile:l,roundNumber:p,structureId:e.structureId}}}),c={linkType:fo,source:{roundNumber:s,structureId:e.structureId},target:{feedProfile:En,roundNumber:i,structureId:t.structureId}},u=[{linkType:fo,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:En,roundNumber:1,structureId:r.structureId}},{linkType:eo,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:En,roundNumber:1,structureId:r.structureId}}];return[...a,c,...u]}function LO({structureName:t,matchUpType:e,idPrefix:r,drawSize:n,isMock:o,uuids:i}){let s=[],{matchUps:a}=ai({linkFedFinishingRoundNumbers:[1],drawSize:n+1,matchUpType:e,idPrefix:r,isMock:o}),c=Ss({structureName:t||Qe(nt),structureId:i?.pop(),stageSequence:1,stage:nt,matchUpType:e,matchUps:a});s.push(c);let u=n/2,{matchUps:p}=ai({finishingPositionOffset:u,idPrefix:r&&`${r}-c`,drawSize:n-1,isConsolation:!0,matchUpType:e,isMock:o,uuids:i}),m=Ss({structureName:Qe(mU),matchUps:p,structureId:i?.pop(),stage:qe,stageSequence:2,matchUpType:e});s.push(m);let{matchUps:d}=Cn({idPrefix:r&&`${r}-p1t2`,drawSize:2,matchUpType:e,isMock:o}),l=Ss({structureName:Qe(pU),matchUps:d,structureId:i?.pop(),stageSequence:3,stage:de,matchUpType:e});s.push(l);let f=wO({mainStructure:c,consolationStructure:m,deciderStructure:l});return{structures:s,links:f,...C}}function FO(t){let{qualifyingRoundNumber:e,finishingPositionOffset:r,qualifyingPositions:n,matchUpType:o,idPrefix:i,drawSize:s,isMock:a,uuids:c}=t;if(!It(s)||s<2)return{matchUps:[],roundsCount:0};if(vn(s))return Cn(t);let u=_G(s),p=u.shift(),m=et(1,(p?.participantsCount||0)+1).map(I=>({drawPosition:I})),d=[],l=1;({matchUps:d}=Lp({roundNumber:l,matchUpType:o,idPrefix:i,matchUps:d,isMock:a,nodes:m,uuids:c})),l++;let f=t.roundLimit||e;for(let I of u){let h=I.participantsCount/2,S=et(1,h+1);n&&h===n&&(f=l-1);let T=S.map(y=>{let P=Ud({roundPosition:y,roundNumber:l,idPrefix:i,uuids:c});return{roundPosition:y,roundNumber:l,matchUpId:P}});d.push(...T),l++}let g=l-1;return d=Ea({finishingPositionOffset:r,lucky:!0,roundsCount:g,roundLimit:f,matchUps:d}),f&&(d=d.filter(I=>I.roundNumber<=f)),{matchUps:d,roundsCount:g,roundLimit:f}}function _G(t){let e=pt(t),r=e%2?e+1:e,n=!!(Math.ceil(r/2)%2),o=[{participantsCount:r,preFeedRound:n}];for(;r>2;){let i=Math.ceil(r/2),s=i===1,a=!!(!s&&i%2);r=!s&&a?i+1:i;let c=!!(r!==2&&Math.ceil(r/2)%2);o.push({participantsCount:r,preFeedRound:c,feedRound:a})}return o}function AT(t){let{playoffAttributes:e,stageSequence:r=1,stage:n=nt,matchUpType:o,drawSize:i,uuids:s}=t,a=()=>!t.isMock&&!t.idPrefix?void 0:`${t.drawDefinition.drawId}-s-0`,c=t.structureId||a()||s?.pop(),u=t.appliedPolicies??yt(t),p=t.policyDefinitions?.[rc]||u?.[rc];t.skipRounds=t.skipRounds||i<=4&&(p?.feedFromMainFinal?0:1)||0;let m=t.structureName??e?.["0"]?.name??Qe(nt),d=()=>{let{matchUps:f}=Cn(t);return{structures:[hn({stageSequence:r,structureName:m,matchUpType:o,structureId:c,matchUps:f,stage:n})],links:[],...C}};return{generators:{[$r]:()=>({structures:[hn({finishingPosition:li,stageSequence:r,structureName:m,matchUps:[],matchUpType:o,structureId:c,stage:n})],links:[],...C}),[ki]:()=>{let{matchUps:f}=FO(t);return{structures:[hn({stageSequence:r,structureName:m,matchUpType:o,structureId:c,matchUps:f,stage:n})],links:[],...C}},[go]:()=>d(),[Xc]:()=>LO(t),[zc]:()=>Tc({...t,roundOffsetLimit:3,playoffAttributes:e??yf}),[Qc]:()=>Tc({...t,roundOffsetLimit:2,playoffAttributes:e??Af}),[de]:()=>Tc(t),[da]:()=>{let{matchUps:f}=ai({drawSize:i,uuids:s,matchUpType:o});return{structures:[hn({stageSequence:r,structureName:m,matchUpType:o,structureId:c,stage:nt,matchUps:f})],links:[],...C}},[up]:()=>BS(t),[Jc]:()=>Ac({...t,feedRounds:1,fmlc:!0}),[uU]:()=>Ac({...t,feedRounds:1}),[yh]:()=>Ac({...t,feedsFromFinal:1}),[Ah]:()=>Ac({...t,feedsFromFinal:2}),[Eh]:()=>Ac({...t,feedsFromFinal:3}),[pp]:()=>Ac(t),[Tf]:()=>WS(t),[Nn]:()=>Na(t),[Io]:()=>xO(t)}}}function xd(t){let{enforceMinimumDrawSize:e=!0,overwriteExisting:r,appliedPolicies:n,staggeredEntry:o,drawDefinition:i,tieFormat:s,isMock:a,uuids:c}=t||{},u=pt(t.drawSize),p=t.drawTypeCoercion??bu({appliedPolicies:n,drawType:t.drawType}),m="generateDrawStructuresAndLinks",d=yT({drawType:t.drawType,enforceMinimumDrawSize:e,drawTypeCoercion:p,drawSize:u});if(d.error)return d;let l=d.drawType,f=[],g=[],I=t?.matchUpType??xt,h=i?.structures?.filter(({stage:W})=>W===ct);h&&f.push(...h);let S=h?.map(({structureId:W})=>W),T=i?.structures?.find(({stage:W,stageSequence:H})=>W===nt&&H===1),y=i?.links?.filter(W=>W.target.structureId===T?.structureId&&S?.includes(W.source.structureId)),P=(W,H)=>{if(W.linkType===to&&H?.structures){let K=W.source.finishingPositions||[];return H.structures.length*K.length}else if(W.linkType===fo&&H?.matchUps?.length){let K=W.source.roundNumber;return H.matchUps.filter(({roundNumber:B})=>B===K).length}},U=h?.map(W=>{let H=y?.find(z=>z.target.structureId===W.structureId),K=bt({structure:W})?.positionAssignments?.length??0;if(!H)return K;let q=H?.source.structureId,B=i.structures?.find(z=>z.structureId===q),$=P(H,B)||0;return K-$}).filter(Boolean).reduce((W,H)=>W+H,0),E=y?.map(W=>{let H=W.source.structureId,K=h?.find(q=>q.structureId===H);return P(W,K)}).filter(Boolean).reduce((W,H)=>W+H,0),A=!!(T&&!T?.matchUps?.length);if(h?.length&&!A)return{error:WI};let N=!h?.length&&t.qualifyingProfiles,D=N?.length&&TT({idPrefix:t.idPrefix,qualifyingProfiles:N,appliedPolicies:n,isMock:a,uuids:c});if(D?.error)return D;let{qualifyingDrawPositionsCount:M,qualifyingDetails:R,qualifiersCount:b}=D||{qualifyingDrawPositionsCount:U,qualifiersCount:E};M&&(D?.structures&&f.push(...D.structures),D?.links&&g.push(...D.links)),Object.assign(t,ot({drawSize:u,matchUpType:I,tieFormat:s}));let v=l!==$r&&(!u||u<2||!o&&![da,ki].includes(l)&&([Io,Nn].includes(l)&&u<3||![Nn,Io].includes(l)&&!vn(u)));if(v&&!M)return _({context:{drawSize:u,invalidDrawSize:v},result:{error:qu},stack:m});let{generators:O,error:x}=AT(t);if(x)return{error:x};let F=O[l];if(!F)return{error:Fl};let L=F?.();if(L.error)return L;let{structures:w,links:V}=L;if(w?.length){let W=w.find(({stage:H,stageSequence:K})=>H===nt&&K===1);if(T&&W){if(A){let H=W.structureId;if(W.structureId=T.structureId,V?.length)for(let K of V)K.source.structureId===H&&(K.source.structureId=T.structureId),K.target.structureId===H&&(K.target.structureId=T.structureId)}else if(!r)return{error:WI}}f.push(...w)}f.sort(Si),V?.length&&g.push(...V);let k=L.structures.find(({stage:W,stageSequence:H})=>W===nt&&H===1);for(let W of R||[]){let{finalQualifyingRoundNumber:H,finalQualifyingStructureId:K,roundTarget:q,finishingPositions:B,linkType:$}=W,z=k&&Ma({targetStructureId:k.structureId,sourceStructureId:K,sourceRoundNumber:H,finishingPositions:B,targetEntryRound:q,linkType:$})?.link;if(z?.error)return z;z&&g.push(z)}return y&&g.push(...y),{...C,qualifyingResult:{qualifyingDrawPositionsCount:M,qualifiersCount:b},structures:f,links:g}}function wd(t){let{modifyOriginal:e=!0,stageSequence:r=1,isMock:n}=t||{},o="generateDrawTypeAndModifyDrawDefinition";if(!t.drawDefinition)return _({result:{error:Z},stack:o});let i=e?t.drawDefinition:J(t.drawDefinition,!1,!0),{tieFormat:s,matchUpType:a}=t;if(s){let T=ar({tieFormat:s});if(T.error)return T}s=ir(s??We({drawDefinition:i})?.tieFormat),a=a??(i.matchUpType||xt),t.tieFormat=s,t.matchUpType=a;let c=Mp({drawDefinition:i,stage:nt});t.drawSize=t.drawSize??c,!c&&t.drawSize&&Op({drawSize:t.drawSize,drawDefinition:i,stageSequence:r,stage:nt});let u=Ne({drawDefinition:i}).drawMatchUps.map(Ae),p=xd(t);if(p.error)return _({result:p,stack:o});let{structures:m,links:d,qualifyingResult:l}=p;i.structures=m,i.links=d;let f=Math.max(t.qualifiersCount??0,l?.qualifiersCount||0);if(l?.qualifyingDrawPositionsCount&&!Mp({stage:ct,drawDefinition:i})){let y=Op({drawSize:l.qualifyingDrawPositionsCount,stage:ct,drawDefinition:i});if(y.error)return y}if(f){let T=LS({qualifiersCount:f,drawDefinition:i,stage:nt});if(T.error)return T}let g=t.drawSize??c;Object.assign(t,ot({drawSize:g,matchUpType:a,tieFormat:s}));let{matchUps:I,matchUpsMap:h}=se({drawDefinition:i});s&&I?.forEach(T=>{if(!u.includes(T.matchUpId)){let{tieMatchUps:y}=Ra({tieFormat:s,matchUp:T,isMock:n});Object.assign(T,{tieMatchUps:y,matchUpType:a})}});let{inContextDrawMatchUps:S}=qi({drawDefinition:i,matchUpsMap:h});return Ot({tournamentId:t.tournamentRecord?.tournamentId,drawDefinition:i}),{inContextDrawMatchUps:S,drawDefinition:i,matchUpsMap:h,...C,structures:m,matchUps:I,links:d}}function Dc(t){let{removePriorValues:e,tournamentRecord:r,participantId:n,scaleItem:o}=t,i,s;if(!kO({scaleItem:o}))return{error:Ka};if(n&&Array.isArray(r.participants)&&(s=r.participants.find(a=>a.participantId===n),s)){if(s.participantType===yr&&o?.eventType!==Cr)return{error:Ka};let a=GO({removePriorValues:e,participant:s,scaleItem:o});if(a.error)return a;i=!a.valueChanged;let{topics:c}=Lr();c.includes(nr)&&mt({topic:nr,payload:{tournamentId:r.tournamentId,participants:[s]}})}return i&&{...C,info:rf,existingValue:o?.scaleValue}||s&&{...C,newValue:o?.scaleValue}||{error:te}}function mD(t){let{scaleItemsWithParticipantIds:e=[],removePriorValues:r,tournamentRecord:n,auditData:o,context:i}=t;if(!n)return{error:Y};if(!n.participants)return{error:$a};let s=0,a={},c=[];for(let m of e){let d=m?.participantId;if(Array.isArray(m?.scaleItems))for(let l of m.scaleItems)if(kO({scaleItem:l}))Array.isArray(a[d])||(a[d]=[]),a[d].push(l);else return{error:Ka}}for(let m of n.participants){let{participantId:d}=m||{};if(Array.isArray(a[d]))for(let l of a[d]){if(m.participantType===yr&&l?.eventType!==Cr)return _({context:{participantId:d,scaleItem:l,participantType:m.participantType},info:"Invalid participantType for eventType",result:{error:Ka}});GO({participant:m,scaleItem:l,removePriorValues:r}),c.push(m),s++}}let u=s?void 0:_s,{topics:p}=Lr();if(p.includes(nr)&&s&&mt({topic:nr,payload:{tournamentId:n.tournamentId,participants:c}}),i){let{eventId:m,drawId:d,...l}=i,f=l.scaleAttributes?.scaleType&&[l.scaleAttributes.scaleType];if(Object.keys(l).length){let g={itemType:xf,itemValue:l};if(f&&(g.itemSubTypes=f),d||m){let{drawDefinition:I,event:h}=ze({tournamentRecord:n,eventId:m,drawId:d});d&&Tg({drawDefinition:I,timeItem:g}),m&&zi({event:h,timeItem:g})}else Pc({tournamentRecord:n,timeItem:g})}}return o&&p.includes(Ti)&&mt({topic:Ti,payload:o}),ot({...C,modificationsApplied:s,info:u})}function kO({scaleItem:t}){let e=t&&Object.keys(t),r=["scaleType","eventType","scaleName"];return!!(r.filter(o=>e?.includes(o)).length===r.length)}function GO({removePriorValues:t,participant:e,scaleItem:r}){if(!e)return{error:wi};let n=r&&Object.keys(r),o=["scaleType","eventType","scaleName"];if(!(o.filter(p=>n.includes(p)&&r[p]).length===o.length))return{error:Ka};let s=new Date().toISOString();e.timeItems||(e.timeItems=[]);let{scaleItem:a}=yo({scaleAttributes:r,participant:e}),c=p=>[void 0,null,""].includes(p),u=!(c(a?.scaleValue)&&c(r.scaleValue))&&JSON.stringify(a?.scaleValue)!==JSON.stringify(r.scaleValue);if(u){let{scaleType:p,eventType:m,scaleName:d}=r,l=[Ii,p,m,d].join("."),f=ot({itemValue:r.scaleValue,itemDate:r.scaleDate,createdAt:s,itemType:l});r.scaleId&&(f.itemSubTypes=[r.scaleId]),t&&(e.timeItems=e.timeItems.filter(g=>g.itemType!==l)),e.timeItems.push(f)}return{...C,valueChanged:u,newValue:r.scaleValue}}function wg(t){let{tournamentRecord:e,modifiedScaleValues:r,removePriorValues:n}=t,o=rt(t,[{[ie]:!0},{modifiedScaleValues:!0,[He]:Kr}]);if(o.error)return o;for(let i in r){let s=Dc({scaleItem:r[i],removePriorValues:n,tournamentRecord:e,participantId:i});if(s.error)return s}return{...C}}function Nc(t){let{tournamentRecord:e,scaleAttributes:r,participantId:n}=t,o=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!n)return{error:oe};let{participant:i,tournamentId:s}=To({tournamentRecords:o,tournamentRecord:e,participantId:n});return i?{...yo({participant:i,scaleAttributes:r}),tournamentId:s}:{error:te}}var xG=(t=0)=>250/Math.pow(t+5,.4),wG=()=>1;function LG(t=3,e=2){let r=t/e;return isNaN(r)?Ld.kDefault():r}var Ld={nSpread:400,diffThreshold:.125,kCalc:xG,kMultiplier:LG,kDefault:wG};function ET(t){let{winnerRating:e,loserRating:r}=t,{ratings:n=we,winnerCountables:o=1,loserCountables:i=0,ratingType:s=zn,maxCountables:a,countables:c}=t||{},u=n?.[s];if(!u)return{error:st};let p=u.range||t.ratingRange;e=e||u.defaultInitialization,r=r||u.defaultInitialization;let m=p[0]>p[1],d=u.decimalsCount||0,l=m?p.slice().reverse():p,f=(x,F)=>parseFloat(F)>=Math.min(...x)&&parseFloat(F)<=Math.max(...x);(!f(p,e)||!f(p,r))&&(f(p,e)||(e=u.defaultInitialization),f(p,r)||(r=u.defaultInitialization));let g=Nu({targetRange:we[zn].range,sourceRange:l,value:m?p[0]-e:e}),I=Nu({targetRange:we[zn].range,sourceRange:l,value:m?p[0]-r:r}),h=(x,F)=>1/(1+Math.pow(10,(F-x)/Ld.nSpread)),S=h(g,I),T=h(I,g),y=Ld.kCalc(o),P=Ld.kCalc(i),U=Ld.kMultiplier(a,c),E=g+U*y*(1-S),A=I+U*P*(0-T),N=Nu({sourceRange:we[zn].range,value:E,targetRange:l}),D=Nu({sourceRange:we[zn].range,value:A,targetRange:l}),M=m?p[0]-N:N,R=parseFloat(M.toFixed(d)),b=m?p[0]-D:D,v=parseFloat(b.toFixed(d)),O=Math.max(...p)?Math.abs(e-r)/Math.max(...p):0;return(N>D&&O>Ld.diffThreshold||R<0||v<0)&&(R=e,v=r),{newWinnerRating:R,newLoserRating:v}}var VO=t=>t?.reduce((e,r)=>(r.winningSide&&(e[r.winningSide-1]+=1),e),[0,0])||[0,0];function UT(t){let e=rt(t,[{[ie]:!0},{matchUpIds:!0,[He]:Be,[fn]:rs},{ratingType:!1,[tr]:S=>we[S]}]);if(e.error)return e;let{updateParticipantRatings:r,removePriorValues:n=!0,tournamentRecord:o,ratingType:i=zn,refreshDynamic:s,considerGames:a,drawDefinition:c,matchUpIds:u,asDynamic:p}=t,m=we[i],{accessor:d}=m,l={},f=(t.matchUps||s&&or({drawDefinition:c,tournamentRecord:o,inContext:!0,matchUpFilters:{matchUpStatuses:ce}}).matchUps||Te({matchUpFilters:{matchUpIds:u,matchUpStatuses:ce},tournamentRecord:o,inContext:!0}).matchUps)??[],g=`${i}.${Gm}`,I=p?g:i;f.sort(Mi);for(let S of f){let{endDate:T,matchUpFormat:y,score:P,sides:U,winningSide:E}=S,A=S.matchUpType,N={eventType:A,scaleName:i,scaleType:gi},D={scaleName:g,eventType:A,scaleType:gi},M=Object.assign({},...(U??[]).map(V=>{let{sideNumber:k,participant:W}=V;return k&&{[k]:[W?.participantId,...W?.individualParticipantIds??[]].filter(Boolean).flat()}})),R=Object.assign({},...Object.values(M).flat().map(V=>{let k=l[V],H=!s||k?Nc({scaleAttributes:D,tournamentRecord:o,participantId:V}).scaleItem:void 0,K=Nc({tournamentRecord:o,scaleAttributes:N,participantId:V}).scaleItem,q=d?{[d]:void 0}:void 0;return V&&{[V]:H??K??{scaleName:I,eventType:A,scaleDate:T,scaleType:gi,scaleValue:q}}})),b=y?Ye(y):{},v=b?.bestOf||1,O=b?.setsTo||1,x=a?v&O:v,F=P?.sets&&VO(P.sets)||E===1&&[1,0]||[0,1],L=E?M[E]:[],w=E?M[3-E]:[];for(let V of L){let k=R[V]?.scaleValue,W=typeof k=="object"?k[d]:k;for(let H of w){let K=R[H]?.scaleValue,q=typeof K=="object"?K[d]:K,B=E?F[E]:[0,0],$=E?F[3-E]:[0,0],{newWinnerRating:z,newLoserRating:j}=ET({winnerCountables:B,loserCountables:$,maxCountables:x,winnerRating:W,loserRating:q,ratingType:i}),tt=d?{...k,[d]:z}:z,Q=d?{...K,[d]:j}:j;R[V].scaleValue=tt,R[H].scaleValue=Q,R[V].scaleName=I,R[H].scaleName=I}}Object.assign(l,R),r&&wg({tournamentRecord:o,modifiedScaleValues:l,removePriorValues:n})}let h=f.map(({matchUpId:S})=>S);return{...C,modifiedScaleValues:l,outputScaleName:I,processedMatchUpIds:h}}function Ou(t){let{matchUpIds:e=[],drawDefinition:r,roundNumber:n,newRound:o,isMock:i,event:s}=t;if(typeof r!="object")return{error:Z};let{participantIdPairings:a,matchUpsCount:c}=t,u=vd(t);if(u.error)return _({result:u});let{lastRoundNumber:p,availableMatchUpsCount:m=0,roundMatchUpsCount:d=0}=u;if(!c)o?c=d:m>0&&(c=m);else if(c>d&&t.restrictMatchUpsCount!==!1)return _({result:{error:G,info:"matchUpsCount error",context:{roundMatchUpsCount:d}}});if(a&&!Array.isArray(a)||c&&!It(c)||e&&!Array.isArray(e)||!a&&!c)return{error:G,info:"matchUpsCount or pairings error"};if(c&&t.restrictMatchUpsCount!==!1&&c>32)return{error:G,info:"matchUpsCount must be less than 33"};if(n&&!t.ignoreLastRoundNumber&&n-1>(p||0))return{error:G,info:"roundNumber error"};let l=n??(o&&(p??0)+1||p||1);a=a??et(0,c).map(()=>({participantIds:[void 0,void 0]}));let f=I=>{if(!t.idPrefix)return;let h=r.drawId,S=t.idPrefix??"ah";return`${h}-${S}-${l}-${I}`},g=a?.map((I,h)=>{let S=I?.participantIds??[void 0,void 0];S.push(void 0,void 0);let y=S.slice(0,2).map((U,E)=>ot({sideNumber:E+1,participantId:U})),P=e[h]??f(h)??Dt();return{roundNumber:l,matchUpStatus:Qt,matchUpId:P,sides:y}});if(g?.length){let I=We({drawDefinition:r,event:s})?.tieFormat;I&&g.forEach(h=>{let{tieMatchUps:S}=Ra({tieFormat:I,matchUp:h,isMock:i});Object.assign(h,{tieMatchUps:S,matchUpType:jt})})}return{roundNumber:l,matchUpsCount:g?.length??0,matchUps:g,...C}}function HO({maxIterations:t=4e3,valueSortedPairings:e,pairingValues:r,valueObjects:n,deltaObjects:o}){let i=Object.assign({},...e.map(S=>({[S.pairing]:S.value}))),s=Object.keys(r),a=[],c=BO({actorsCount:s.length,valueSortedPairings:e,pairingValueMap:i,deltaObjects:o,valueObjects:n}),u=[dD(c)];a.push(c);let p=c.value,m=c,d=1,l=0,f=s.length,g;do f-=1,g=s.length*r[s[0]].length;while(g>t&&f>5);let I=[];s.forEach(S=>{r[S].slice(0,f).forEach(y=>{l+=1;let P=va(S,y.opponent);if(!I.includes(P)){let U=BO({stipulated:[[S,y.opponent]],actorsCount:s.length,valueSortedPairings:e,pairingValueMap:i,deltaObjects:o,valueObjects:n});if(!u.includes(dD(U))){u.push(dD(U)),a.push(U);let{maxDelta:E,value:A}=U;E<m.maxDelta&&(m=U),(A<p||A===p&&Math.round(Math.random()))&&(p=A),I.push(P),d+=1}}}),a=a.filter(y=>Math.abs(y.value-p)<5)}),a.sort((S,T)=>S.maxDiff-T.maxDiff);let h=tn(a);return{candidatesCount:d,deltaCandidate:m,maxIterations:t,iterations:l,candidate:h}}function dD(t){return t.participantIdPairings.map(({participantIds:e})=>e.sort().join("|")).sort().join("/")}function BO({valueSortedPairings:t,stipulated:e=[],pairingValueMap:r,deltaObjects:n,valueObjects:o,actorsCount:i}){let s=[].concat(...e),a=[],c=0;e.filter(Boolean).forEach(d=>{let[l,f]=d,g=va(l,f),I=r[g];a.push({participantIds:d,value:I}),c+=r[g]}),ye(t,i).map(d=>Ir(d).map(l=>({...l,value:l.value+Math.random()*Math.round(Math.random())}))).flat().forEach(d=>{let l=d.pairing.split("|");if(!l.reduce((g,I)=>s.includes(I)||g,!1)){s.push(...l);let g=d.value;c+=g,a.push({participantIds:l,value:g})}}),a.sort((d,l)=>d.value-l.value);let p=a.reduce((d,l)=>{let[f,g]=l.participantIds,I=va(f,g),h=n[I];return h>d?h:d},0),m=a.reduce((d,l)=>{let[f,g]=l.participantIds,I=va(f,g),h=o[I];return h>d?h:d},0);return{value:c,participantIdPairings:a,maxDelta:p,maxDiff:m}}function va(t,e){return[t,e].sort(Tu).join("|")}function lD({participantIds:t}){let e={},r=[];t.forEach(o=>{e[o]=t.filter(i=>i!==o),e[o].forEach(i=>{let s=va(i,o);r.includes(s)||r.push(s)})});let n=Object.assign({},...r.map(o=>({[o]:0})));return{uniquePairings:r,possiblePairings:e,deltaObjects:n}}function WO({matchUps:t}){let e=[];for(let r of t){let n=r.sides.map(St);if(n.length===2){let[o,i]=n,s=va(o,i);e.includes(s)||e.push(s)}}return{encounters:e}}function jO({possiblePairings:t,valueObjects:e}){let r={};for(let o of Object.keys(t)){let i=t[o].map(s=>n(o,s));r[o]=i.sort((s,a)=>s.value-a.value)}function n(o,i){let s=va(o,i);return{opponent:i,value:e[s]}}return{pairingValues:r}}var FG=0;function YO({tournamentParticipants:t,adHocRatings:e,eventType:r,scaleName:n,pairing:o}){let i=we[n]?.defaultInitialization??FG;return o.split("|").map(s=>{if(r===qr){let a=t?.find(c=>c.participantId===s)?.individualParticipantIds;return a?a?.map(c=>e[c]||i):i*2}else return e[s]||i})}function qO(t){let{tournamentParticipants:e,adHocRatings:r={},possiblePairings:n,uniquePairings:o,maxIterations:i,minimizeDelta:s,deltaObjects:a,valueObjects:c,eventType:u,scaleName:p,salted:m}=t;o.forEach(T=>{let y=YO({tournamentParticipants:e,adHocRatings:r,scaleName:p,eventType:u,pairing:T}),P=typeof m=="number"&&m||.5,U=m&&(Math.round(Math.random())?P:P*-1)||0,E=Math.abs(y[0]-y[1])+U,A=Math.abs(y[0]-y[1]);a[T]=A,c[T]||(c[T]=0),c[T]+=E?Math.pow(E,2):0});let d=o.map(T=>({pairing:T,value:c[T]})).sort((T,y)=>T.value-y.value),{pairingValues:l}=jO({possiblePairings:n,valueObjects:c}),{candidate:f,candidatesCount:g,deltaCandidate:I,iterations:h}=HO({valueSortedPairings:d,maxIterations:i,pairingValues:l,deltaObjects:a,valueObjects:c}),{participantIdPairings:S}=s?I:f;return{participantIdPairings:S,candidatesCount:g,deltaCandidate:I,iterations:h,candidate:f}}var kG=100,GG=100,VG=4e3;function Fd(t){let{encounterValue:e=kG,sameTeamValue:r=GG,maxIterations:n=VG,updateParticipantRatings:o,generateMatchUps:i=!0,ignoreLastRoundNumber:s,iterationMatchUps:a,tournamentRecord:c,dynamicRatings:u,refreshDynamic:p,participantIds:m,drawDefinition:d,roundNumber:l,structureId:f,matchUpIds:g,eventType:I,scaleName:h,idPrefix:S,isMock:T,salted:y,event:P}=t;if(!d)return{error:Z};if(!t.structure&&!f)return{error:kt};let U=t.structure||at({drawDefinition:d,structureId:f}).structure;if(!ht(U))return{error:pi};if(!m?.length)return{error:Uo};let E=[...a??[],...U?.matchUps??[]],{encounters:A}=WO({matchUps:E}),N=c?.participants??[],D={};if(u){let B=ut(U?.matchUps?U.matchUps.map(({roundNumber:z})=>z):[]),$=Math.max(...B,0);if($){let z=U?.matchUps?.filter(({roundNumber:tt})=>tt===$).map(({matchUpId:tt})=>tt),j=UT({ratingType:h??P?.category?.ratingType,updateParticipantRatings:o,tournamentRecord:c,asDynamic:!0,refreshDynamic:p,drawDefinition:d,matchUpIds:z});if(j.error)return j;j.modifiedScaleValues&&(D=j.modifiedScaleValues)}}let{valueObjects:M}=BG({tournamentParticipants:N,encounterValue:e,sameTeamValue:r,encounters:A}),{uniquePairings:R,possiblePairings:b,deltaObjects:v}=lD({participantIds:m}),O=Object.values(D).length?D:t.adHocRatings,x={tournamentParticipants:N,possiblePairings:b,participantIds:m,uniquePairings:R,drawDefinition:d,maxIterations:n,adHocRatings:O,deltaObjects:v,valueObjects:M,eventType:I,scaleName:h,structure:U,salted:y},{candidatesCount:F,participantIdPairings:L,deltaCandidate:w,iterations:V,candidate:k}=qO(x);if(!F)return{error:Qu};let W,H;if(i){let B=Ou({structureId:U?.structureId,ignoreLastRoundNumber:s,participantIdPairings:L,newRound:!0,drawDefinition:d,roundNumber:l,matchUpIds:g,idPrefix:S,isMock:T,event:P});if(B.error)return B;W=B.roundNumber,H=B.matchUps}let{maxDelta:K,maxDiff:q}=k;return{roundNumber:W,participantIdPairings:L,modifiedScaleValues:D,candidatesCount:F,deltaCandidate:w,...C,iterations:V,matchUps:H,maxDelta:K,maxDiff:q}}function BG({encounters:t,tournamentParticipants:e,encounterValue:r,sameTeamValue:n}){let o={};for(let s of t)o[s]||(o[s]=0),o[s]+=r;let i=e?.filter(({participantType:s})=>s===Lt);if(i)for(let s of i){let a=s.individualParticipantIds??[],{uniquePairings:c}=lD({participantIds:a});for(let u of c)o[u]||(o[u]=0),o[u]+=n}return{valueObjects:o}}function PT(t){let{drawType:e=go,attachConsolation:r=!0,applyPositioning:n=!0,tournamentRecord:o,staggeredEntry:i,automated:s,placeByes:a,isMock:c,event:u}=t,p=t?.drawDefinition;if(!p)return{error:Z};let m=$e,d=Ui({stageSequence:1,drawDefinition:p,stage:m}),l=[Nn,Xc,Io].includes(e)?d.length:es(d.length);if(!i&&e===da&&d.length<2||e===Nn&&d.length<3)return{error:qu};let{tieFormat:f,matchUpType:g}=t;if(f){let R=ar({tieFormat:f});if(R.error)return R}f=ir(f??We({drawDefinition:p})?.tieFormat),g=g??p.matchUpType??xt;let{structures:I}=gn({stageSequence:1,drawDefinition:p,stage:m});if(I.length>1)return{error:qA};if(I?.[0]?.matchUps?.length)return{error:of};let S=I?.[0]?.structureId;Object.assign(t,ot({structureName:t.structureName??Qe($e),structureId:S,matchUpType:g,tieFormat:f,drawSize:l,stage:m}));let T=AT(t);if(T.error)return T;let y=T.generators[e];if(!y)return{error:Fl};let P=y?.();if(P.error)return P;let{structures:U,links:E}=P,A=U.map(R=>Ut({structure:R}).matchUps).flat();f&&A.forEach(R=>{let{tieMatchUps:b}=Ra({matchUp:R,tieFormat:f,isMock:c});Object.assign(R,{tieMatchUps:b,matchUpType:g})}),(!n||!r)&&(p=J(p,!1,!0)),p.links||(p.links=[]),E.length&&p.links.push(...E);let N=U.map(({structureId:R})=>R);p.structures||(p.structures=[]);let D=p.structures.map(({structureId:R})=>R);p.structures=p.structures.map(R=>N.includes(R.structureId)?U.find(({structureId:b})=>b===R.structureId):R);let M=U.filter(({structureId:R})=>!D.includes(R));return M.length&&p.structures.push(...M),s&&Sc({seedingProfile:t.seedingProfile,applyPositioning:n,tournamentRecord:o,drawDefinition:p,structureId:S,placeByes:a,drawSize:l,event:u}),r&&Ot({drawDefinition:p}),{links:E,structures:U,...C}}var Hg={};Xt(Hg,{addGame:()=>yD,addPoint:()=>TD,addSet:()=>ED,addShot:()=>AD,analyzeScore:()=>Gg,analyzeSet:()=>wu,calculateHistoryScore:()=>ID,checkScoreHasValue:()=>Ie,checkSetIsComplete:()=>Hp,clearHistory:()=>SD,generate:()=>gD,generateScoreString:()=>jo,generateTieMatchUpScore:()=>Uc,getSetComplement:()=>Bg,getTiebreakComplement:()=>qp,helpers:()=>JD,isValidMatchUpFormat:()=>Pr,keyValueScore:()=>qD,mutate:()=>ND,parseMatchUpFormat:()=>Ye,parseScoreString:()=>jd,query:()=>ZD,redo:()=>UD,reverseScore:()=>fD,setServingSide:()=>hD,stringifyMatchUpFormat:()=>ip,tidyScore:()=>XD,umo:()=>DD,undo:()=>PD,validateScore:()=>Vg,validateTieFormat:()=>ar});var gD={};Xt(gD,{generateScoreString:()=>jo,generateTieMatchUpScore:()=>Uc,reverseScore:()=>fD});function jo(t){let{winnerFirst:e=!0,addOutcomeString:r,reversed:n=!1,matchUpStatus:o,matchUpFormat:i,autoComplete:s,winningSide:a,sets:c}=t;if(!c)return{error:st,info:"missing sets"};let u=i&&Ye(i),{bestOf:p,finalSetFormat:m,setFormat:d}=u??{},f=n||!(!e||!a||a===1),g=r?HG({matchUpStatus:o}):"",I=c?.sort(WG).map(h).filter(Boolean).join(" ")||"";if(!g)return I;if(a===2)return`${g} ${I}`;return`${I} ${g}`;function h(S){let y=p&&S.setNumber===p&&m?m:d,P=H=>Zt(H?.side1Score)||Zt(H?.side2Score),U=H=>Zt(H?.side1TiebreakScore)||Zt(H?.side2TiebreakScore),E=y?.tiebreakSet||!P(S)&&U(S),{side1Score:A,side2Score:N,side1TiebreakScore:D,side2TiebreakScore:M}=S,R=D||(Zt(D)||s?0:""),b=M||(Zt(M)||s?0:"");if(E)return`[${(f?[b,R]:[R,b]).join("-")}]`;let v=Math.min(R,b),O=v===R?1:2,x=v?`(${v})`:"",F=A||(Zt(A)||s?0:""),L=N||(Zt(N)||s?0:""),w=H=>O===H?x:"",V=`${F}${w(1)}`,k=`${L}${w(2)}`,W=f?`${[k,V].join("-")}`:`${[V,k].join("-")}`;return["-"," "].includes(W)&&(W=""),W}}function HG({matchUpStatus:t}){let e={[rr]:"RET",[Ct]:"WO",[Ce]:"DF/DF",[he]:"WO/WO",[ss]:"SUS",[br]:"ABN",[Mt]:"DEF",[au]:"DR"};return t&&e[t]||""}function WG(t,e){return t.setNumber-e.setNumber}function fD(t){if(!t?.score)return{error:st};let{sets:e}=t.score,r=e.map(i=>{let{side1TiebreakScore:s,side2TiebreakScore:a,winningSide:c,side1Score:u,side2Score:p,setNumber:m}=i;return ot({winningSide:c?3-c:void 0,side1TiebreakScore:a,side2TiebreakScore:s,side1Score:p,side2Score:u,setNumber:m})}),n=jo({sets:r}),o=jo({sets:r,reversed:!0});return{reversedScore:{sets:r,scoreStringSide1:n,scoreStringSide2:o},...C}}var ND={};Xt(ND,{addGame:()=>yD,addPoint:()=>TD,addSet:()=>ED,addShot:()=>AD,calculateHistoryScore:()=>ID,clearHistory:()=>SD,redo:()=>UD,setServingSide:()=>hD,umo:()=>DD,undo:()=>PD});function Yo({matchUp:t}){let{extension:e}=dt({name:Ym,element:t});if(!e)return{error:ve};let{history:r=[],undoHistory:n=[]}=e.value;return{history:r,undoHistory:n,...C}}function ID(t){if(!t)return{error:st};let{matchUp:e,updateScore:r}=t;if(!e)return{error:hr};let n=Yo({matchUp:e})?.history||[];if(!Array.isArray(n))return{error:G,info:"history is not an array"};let{matchUpFormat:o}=e;if(!o)return{error:Wl};if(!Pr({matchUpFormat:o}))return{error:Hl};let i=Ye(o),{bestOf:s,finalSetFormat:a,setFormat:c}=i,u=["0","15","30","40","A","G"],p={sets:[]},m=[],d,l=[0,0],f=1,g=0,I,h=0,S=D=>[1,2].includes(D),T=()=>(g+=1,{winningSide:void 0,side1Score:0,side2Score:0,setNumber:g,games:[]}),y=()=>({winningSide:void 0,points:[]}),P=()=>({winningSide:void 0,side1Score:"",side2Score:"",shots:[]}),U=P(),E=y(),A=T(),N=0;for(let D of n){N+=1,I=p.sets.length+1===s;let M=I&&a?a:c,{tiebreakAt:R,setTo:b,NoAD:v,tiebbreakFormat:O}=M,x=A.side1Score===R&&A.side1Score===A.side2Score,F=!!M.tiebreakSet,L=F?M.tiebreakSet:O,{tiebreakTo:w,NoAD:V}=L||{},k=()=>{d=void 0,l=[0,0],f=3-f,A.side1TiebreakScore=0,A.side2TiebreakScore=0,A.side1PointScore="",A.side2PointScore="",h=0},W=q=>{A.winningSide=q;let{s:B,...$}=A;p.sets.push($),U=P(),E=y(),A=T(),k()},H=q=>{E.winningSide=q;let{g:B,...$}=E;A.games.push($),U=P(),E=y(),k();let z=`side${q}Score`;A[z]+=1},K=q=>{U.winningSide=q;let{p:B,...$}=U;E.points.push($),U=P(),h=0;let z=()=>l.reduce((X,lt)=>X+lt)%4/4>.5?f:3-f,j=q-1;if(x||F){l[j]+=1,d=z(),A[`side${q}TiebreakScore`]=l[j],A[`side${3-q}TiebreakScore`]=l[1-j];let tt=V?1:2;if(l[j]>=w&&l[j]>=l[1-j]+tt)return H(q),{gameCompleted:!0}}else if(l[1-j]===4&&l[j]===3?l[1-j]-=1:l[j]+=1,A.side1PointScore=u[l[0]],A.side2PointScore=u[l[1]],l[j]===5||l[j]===4&&l[1-j]<3||v&&l[j]===4)return H(q),{gameCompleted:!0}};if(S(D.srv)&&(f=D.srv),["p","s","g","o"].includes(D.u)&&m.push(D.u),D.shotOutcome&&(U.shots.push(D),D.shotType==="SERVE"&&["OUT","NET"].includes(D.shotOutcome)&&(h+=1),h===2)){let B=3-f;K(B)}if(S(D.p)||It(D.pointNumber)){let q=D.winningSide||D.p;if(K(q)?.gameCompleted)continue}if(S(D.g)||It(D.gameNumber)){let q=D.winningSide||D.g;E.winningSide=q;let B=`side${q}Score`,$=`side${3-q}Score`;if(m.length&&(m.includes("p"),m=[]),H(q),A[B]===b&&A[B]-A[$]>=(v?1:2)&&(W(q),I))break}if(S(D.s)||It(D.setNumber)){let q=D.winningSide||D.s;if(W(q),m.length&&(m.includes("p"),m.includes("g"),m=[]),I)break}}return N!==n.length&&console.log({error:"Match completed with excess history"}),(A.side1Score||A.side2Score||A.games.length||A.side1TiebreakScore||A.side2TiebreakScore)&&p.sets.push(A),p.scoreStringSide1=jo({...p,matchUpFormat:o}),p.scoreStringSide2=jo({...p,matchUpFormat:o,reversed:!0}),f=d||f,r&&(e.score=p),{...C,servingSide:f,score:p}}function qo({undoHistory:t,history:e,matchUp:r}){return At({element:r,extension:{value:{history:e,undoHistory:t},name:Ym}})}function hD({matchUp:t,sideNumber:e}){if(![1,2].includes(e))return{error:jl};let{history:r=[]}=Yo({matchUp:t});return r.push({srv:e}),qo({matchUp:t,history:r})}function SD({matchUp:t}){return qo({matchUp:t})}function TD({matchUp:t,point:e}){if(!e||!t)return{error:st};if(typeof e!="object")return{error:G,context:{point:e}};let{history:r=[]}=Yo({matchUp:t});return r.push(e),qo({matchUp:t,history:r})}function yD({matchUp:t,game:e}){if(typeof e!="object")return{error:G,context:{game:e}};let{history:r=[]}=Yo({matchUp:t});return r.push(e),qo({matchUp:t,history:r})}function AD({matchUp:t,shot:e}){if(typeof e!="object")return{error:st};let{history:r=[]}=Yo({matchUp:t});return r.push(e),qo({matchUp:t,history:r})}function ED({matchUp:t,set:e}){if(typeof e!="object")return{error:st};let{history:r=[]}=Yo({matchUp:t});return r.push(e),qo({matchUp:t,history:r})}function UD({matchUp:t}){let{history:e=[],undoHistory:r=[]}=Yo({matchUp:t});return r.length&&e.push(r.pop()),qo({matchUp:t,history:e,undoHistory:r})}function PD({matchUp:t}){let{history:e=[],undoHistory:r=[]}=Yo({matchUp:t});return r.push(e.pop()),qo({matchUp:t,history:e,undoHistory:r})}var DD={};var JD={};Xt(JD,{keyValueScore:()=>qD,parseMatchUpFormat:()=>Ye,stringifyMatchUpFormat:()=>ip,tidyScore:()=>XD});var Js=" ",DT="DEF",$O="COMPLETED",MD="WO",jG="WO/WO",RD="ABN",CD="SUS",bD="RET",vD="INT",NT=[bD,DT,MD,jG,RD,CD,vD];var MT="DEFAULTED";var OD="WALKOVER";var RT="ABANDONED",CT="SUSPENDED",_D="RETIRED",bT="INTERRUPTED";var KO=[_D,MT,OD],YG="Enter Score",As="()",Es="[]",xD=["up","left","shift+tab"],wD=["enter","down","tab","right"],kd="backspace",LD="r",FD="s",kD="a",GD="d",VD="w",BD="i",Gd=[LD,GD,VD,kD,FD,BD],Vp="space",vT=["[","("],Vd=[...xD,...wD,Vp,"]"],zO="-",qG="/",Zs=zO,ci=zO,HD=[qG],QO=0,$G=["=","+","num_1","num_2","shift+=","shift+-"],Xs=["0","1","2","3","4","5","6","7","8","9"].concat(Gd),XO=Xs.map(t=>`shift+${t}`),WD=[Zs,kd].concat(Vd,HD),jD=[Xs,XO,WD].join(","),KG=[jD,xD,wD,$G].join(","),yRt=[].concat(...Xs,...Xs,...WD,...Xs,...Xs,...Xs,...Xs,...Xs,...Xs),JO={OUTCOMEKEYS:Gd,SIDE1KEYS:Xs,SIDE2KEYS:XO,MODIFIERS:WD,PROMPT:YG,MOVEUP:xD,MOVEDOWN:wD,HOTKEYS:KG};function Bp({scoreString:t,lowSide:e,outcome:r}){if({scoreString:t}=ZO({scoreString:t}),e===2){let o=(t&&t[t.length-1])!==Js?Js:"";return t+o+r}else return r+Js+t}function ZO({scoreString:t}){if(!t)return{scoreString:""};let e=!1;for(let r of NT){let n=t?.indexOf(r);n===0?t=t.slice(r.length+1).trim()+Js:n>0&&(t=t.slice(0,n)),n>=0&&(e=!0)}return t?.trim()||(t=""),{scoreString:t,removed:e}}function Lg({analysis:t,scoreString:e,sets:r,lowSide:n}){let o,i;if(!e)return{scoreString:e,sets:r};let{scoreString:s,removed:a}=ZO({scoreString:e});if(e=s,a)return{scoreString:e,sets:r,outcomeRemoved:!0};let c=r[r.length-1]||{},u=Object.values(c).filter(g=>g!==void 0).length;c.setNumber&&u===1&&(r=r.slice(0,r.length-1),c=r[r.length-1]||{});let{tiebreakSet:p}=t.setFormat,{tiebreakTo:m,NoAD:d}=p||{},{isTiebreakEntry:l}=_u({brackets:Es,scoreString:e}),f=zG(e);if(f>=0){o=e.slice(0,f);let{isTiebreakEntry:g}=_u({brackets:As,scoreString:o}),{lastOpenBracketIndex:I,isTiebreakEntry:h}=_u({brackets:Es,scoreString:o}),S=o&&o[o.length-1].trim(),T=o&&!isNaN(S),y=t.isIncompleteSetScore;if(l&&h){let U=o.slice(I+1).split(ci),E=U?.length>0&&U[0]!==void 0&&!isNaN(parseInt(U[0]))&&parseInt(U[0])||void 0,A=U?.length>1&&U[1]!==void 0&&parseInt(U[1])||void 0,N=[E,A];if(A){let D=n===1?1:0;N[D]=(N?.[1-D]||0)+(d?1:2),(N[D]||0)<m&&(N[D]=m),o=e.slice(0,I+1),o+=N.join(ci)}else E!==void 0?(o=e.slice(0,I+1),o+=E):(o=e.slice(0,I),y=!0);c.side1TiebreakScore=N[0]||0,c.side2TiebreakScore=N[1]||0}if(o.length||(o=void 0),y){let P=c.side1Score?.toString();if(P){let U=P?.slice(0,P.length-1);c.side1Score=!isNaN(U)&&parseInt(U)||void 0,c.side1Score===void 0&&(c.side2Score=void 0)}t.isTimedSet?(i=c.side1Score?r:r?.slice(0,r.length-1)||[],i[r.length-1]=c):i=r?.slice(0,r.length-1)||[]}else if(T){let P=c.side2Score?.toString(),U=c.side1Score?.toString();if(!t.isTiebreakEntry&&!t.isMatchTiebreak)if(c.side2Score){let E=P?.slice(0,P.length-1);c.side2Score=!isNaN(E)&&parseInt(E)||void 0}else{let E=U?.slice(0,U.length-1);c.side1Score=!isNaN(E)&&parseInt(E)||void 0}t.isTimedSet?c.side1Score?(i=r||[],i[r.length-1]=c):i=r?.slice(0,r.length-1)||[]:(i=r||[],i[r.length-1]=c),i[i.length-1]&&Object.assign(i[i.length-1],{winningSide:void 0})}else g?(i=r||[],Object.assign(i[i.length-1]||{},{winningSide:void 0,side1TiebreakScore:void 0,side2TiebreakScore:void 0})):(l&&!h?i=r?.slice(0,r.length-1)||[]:(i=r,i[r.length-1]=c),l||(i[i.length-1].side2Score=0,i[i.length-1].winningSide=void 0));return{scoreString:o,sets:i}}return{scoreString:e,sets:r}}function _u({brackets:t=As,scoreString:e}){if(!e)return{};let[r,n]=t.split(""),o=e.split(""),i=Math.max(...mo(r,o)),s=Math.max(...mo(n,o));return{isTiebreakEntry:i>s,lastOpenBracketIndex:i}}function t_({scoreString:t}){if(!t)return!1;let e=t&&t[t.length-1].trim(),r=t&&!isNaN(e),[n,o]=Es.split(""),i=t.split(""),s=Math.max(...mo(n,i)),a=Math.max(...mo(o,i)),c=Math.max(...mo(ci,i));return r&&s>a&&c>s}function zG(t){return t.split("").reduce((n,o,i)=>(o.match(/\d+/g)&&n.push(i),n),[]).pop()}function OT(t){let{lowValue:e=0,NoAD:r=!1,tiebreakTo:n}=t||{},o=r?1:2;return e+1>=n?e+o:parseInt(n)}function YD({matchUpFormat:t,matchUpStatus:e,winningSide:r,sets:n}){let o=Ye(t),{bestOf:i}=o,s=Math.ceil(i/2),c=n?.reduce((u,p)=>{let{winningSide:m}=p;return m&&u[m-1]++,u},[0,0])?.indexOf(s)+1||void 0;return KO.includes(e)&&r&&(c=r),{matchUpWinningSide:c}}function Hp({ignoreTiebreak:t=!1,matchUpScoringFormat:e,matchUpFormat:r,isTiebreakSet:n,isDecidingSet:o,isTimedSet:i,set:s}){if(!s)return{error:st,info:"missing set"};e=e||r&&Ye(r);let a=o&&e.finalSetFormat||e?.setFormat||{},{side1Score:c,side2Score:u}=s,{setTo:p,tiebreakAt:m}=a,d=c||u,l=Wp({set:s}),f=Math.abs(c-u),g=c>=p||u>=p,I=n||c>=p&&u>=p||m&&m<p&&(c===m||u===m),h=t||I&&(l===1&&s.side1TiebreakScore>s.side2TiebreakScore||l===2&&s.side2TiebreakScore>s.side1TiebreakScore),S=!I&&a.NoAD||I||n&&a.tiebreakFormat?.NoAD?1:2,T=f>=S;return!!((i&&d||g&&(T||I)||n)&&(!I||h))}function Wp({set:t}){if(t.side1Score||t.side2Score){if(t.side1Score>t.side2Score)return 1;if(t.side2Score>t.side1Score)return 2}else if(t.side1TiebreakScore||t.side2TiebreakScore){if(t.side1TiebreakScore>t.side2TiebreakScore)return 1;if(t.side2TiebreakScore>t.side1TiebreakScore)return 2}}function Bd({analysis:t,set:e}){let r=Wp({set:e}),{isDecidingSet:n,isTiebreakSet:o,matchUpScoringFormat:i}=t;return Hp({matchUpScoringFormat:i,isDecidingSet:n,isTiebreakSet:o,set:e})&&r}function e_({analysis:t,scoreString:e,sets:r,value:n}){let o;if(!r?.length)return{sets:[]};let i=r[r.length-1];n=pt(n);let{validSide2Score:s,requiresTiebreak:a}=QG({analysis:t,set:i,value:n});if(s){o=!0,e=(e||"")+n,i.side2Score=n;let c=Bd({analysis:t,set:r[r.length-1]});if(i.winningSide=c||void 0,a){let u=As.split("")[0];e+=u}else t.isDecidingSet||(e+=Js)}return{sets:r,scoreString:e,updated:o}}function QG({analysis:t,set:e={},value:r}){let n=t.isDecidingSet&&t.matchUpScoringFormat.finalSetFormat||t.matchUpScoringFormat.setFormat,{tiebreakAt:o,setTo:i,NoAD:s}=n,{side1Score:a}=e,c,u;return o&&o<i?a===o?c=r<=i:c=r<=o:a===i?s?c=r<i:c=r<=i+1:a===i-1?s?c=r<=i:c=r<=i+1:a===i+1?c=r===i||r===i-1:c=r<=i,c&&(o&&o<i?u=a===i&&r===o||a===o&&r===i:u=a>=i&&r>=i&&a!==r),{validSide2Score:c,requiresTiebreak:u}}function _T({lowSide:t,value:e,sets:r,scoreString:n,winningSide:o,matchUpStatus:i}){let s;return e===LD?n?(s=!0,n=Bp({scoreString:n,lowSide:t,outcome:bD}),o=t===2?1:2,i=_D):(s=!0,n=Bp({scoreString:n,lowSide:t,outcome:DT}),o=t===2?1:2,i=MT):e===GD?(s=!0,n=Bp({scoreString:n,lowSide:t,outcome:DT}),o=t===2?1:2,i=MT):e===VD?(s=!0,r=[],n=MD,o=t===2?1:2,i=OD):e===FD&&n?(s=!0,n=Bp({scoreString:n,lowSide:t,outcome:CD}),i=CT,o=void 0):e===kD?(s=!0,n=Bp({scoreString:n,lowSide:t,outcome:RD}),i=RT,o=void 0):e===BD&&n&&(s=!0,n=Bp({scoreString:n,lowSide:t,outcome:vD}),i=bT,o=void 0),{updated:s,sets:r,scoreString:n,matchUpStatus:i,winningSide:o}}function r_(t){let{sets:e,info:r,scoreString:n,winningSide:o,matchUpStatus:i}=t,{analysis:s,lowSide:a,value:c}=t,u,p;!e?.length&&c!==kd&&(e=[{setNumber:1}]);let m=e.length-1;if(Gd.includes(c)){let d=e[e.length-1]||{},{side1Score:l,side2Score:f}=d;l&&!f?r="missing side2Score":s.finalSetIsComplete||o?r="final set is already complete":s.isIncompleteSetScore?r="incomplete set scoreString":s.isIncompleteSetScore||({sets:e,scoreString:n,winningSide:o,matchUpStatus:i,updated:u}=_T({lowSide:a,value:c,sets:e,scoreString:n,matchUpStatus:i,winningSide:o}))}else if(c===kd){if({scoreString:n,sets:e,outcomeRemoved:p}=Lg({analysis:s,scoreString:n,sets:e}),n?.trim()===""&&(n=n.trim()),n||(e=[]),p){let d=e[e.length-1]||{},{side1Score:l,side2Score:f}=d;if(l&&f){let g=l>f&&1||f>l&&2||void 0;g&&(d.winningSide=g,e.push({setNumber:e.length+1}))}}i=void 0,o=void 0,u=!0}else if(s.hasOutcome)r="has outcome";else{if(o)return{sets:e,scoreString:n,winningSide:o,matchUpStatus:i,updated:!1,info:"matchUp is complete"};if(c===Vp){let d=e[e.length-1]||{},{side1Score:l,side2Score:f}=d,g=l>f&&1||f>l&&2||void 0;g&&!o&&!s.isIncompleteSetScore&&(e[e.length-1].winningSide=g,e.push({setNumber:e.length+1}),n+=" ",u=!0)}else if(c===Zs&&e[m].side1Score!==void 0&&e[m].side2Score===void 0&&n&&s.isNumericEnding)n+="-",e[m].side2Score=0,i=void 0,o=void 0,u=!0;else if(!isNaN(c)){let d;if(e[m].side2Score===void 0){let l=pt((e[m].side1Score||0).toString()+c).toString().slice(0,2);e[m].side1Score=pt(l),d=e[m].side1Score.toString(),u=!0}else{let l=pt((e[m].side2Score||0).toString()+c).toString().slice(0,2);e[m].side2Score=pt(l),d=[e[m].side1Score,e[m].side2Score].join("-"),u=!0}if(u){let l=(e.slice(0,m)||[]).filter(f=>f).map(f=>{let{side1Score:g,side2Score:I}=f;return[g,I].join("-")}).join(" ");l?n=l+" "+d:n=d}}}return{sets:e,scoreString:n,winningSide:o,matchUpStatus:i,info:r,updated:u}}function n_({analysis:t,auto:e,lowSide:r,scoreString:n="",sets:o,value:i}){let s,a,{tiebreakSet:{tiebreakTo:c,NoAD:u}}=t.setFormat,[p]=Es.split("");if(t.isMatchTiebreakEntry||(n+=p),o[t.setNumber-1]){let{lastOpenBracketIndex:d}=_u({brackets:Es,scoreString:n}),f=(n.slice((d??0)+1)+(e?"":i)).split(ci);if((f[r-1]?.length||0)>=2)a="tiebreak digit limit";else if(e){r===1&&(f[0]=(f[0]||"")+i),r===2&&(f[1]=(f[1]||"")+i);let I=[f[0]||0,f[1]||0].map(T=>pt(T)),h=r===1?1:0;I[h]=I[1-h]+(u?1:2),I[h]<c&&(I[h]=c);let S=o[o.length-1];S.side1TiebreakScore=I[0],S.side2TiebreakScore=I[1],n=n.slice(0,(d??0)+1),n+=I.join(ci),s=!0}else{let I=[f[0]||0,f[1]||0].map(S=>pt(S)),h=o[o.length-1];h.side1TiebreakScore=I[0],h.side2TiebreakScore=I[1],n+=i,s=!0}}else{let d=OT({lowValue:pt(i||0),tiebreakTo:c,NoAD:u}),l=[pt(i),d];r===2&&l.reverse();let f={side1TiebreakScore:l[0],side2TiebreakScore:l[1],setNumber:o?.length+1||1};o.push(f),n+=l.join(ci),s=!0}return{info:a,scoreString:n,sets:o,updated:s}}function o_({analysis:t,lowSide:e,scoreString:r,value:n}){let{setTo:o,tiebreakAt:i,NoAD:s}=t?.setFormat||{},a=n===parseInt(i||o);if(i&&i<o&&n>i)return{scoreString:r};if(s&&n===o||n>o)return{scoreString:r};let c=g(),u=[n,c];e===2&&u.reverse();let m=As.split("")[0],d=u.join(Zs)+(a?m:Js);r=(r||"")+d;let l={side1Score:u[0],side2Score:u[1]},f=Bd({analysis:t,set:l});return l.winningSide=f||void 0,{scoreString:r,set:l};function g(){return a?n+1:n+1===o?n+(s?1:2):o}}function i_({matchUpFormat:t,scoreString:e,winningSide:r,value:n,sets:o}){let s=(o?.filter(H=>H?.winningSide)?.length||0)+(r?0:1),a=Ye(t),c=s===a?.bestOf,u=c&&a?.finalSetFormat||a?.setFormat||{},p=u?.timed,m=c&&o[a?.bestOf-1],d=m?.winningSide,{isTiebreakEntry:l}=_u({brackets:As,scoreString:e}),{isTiebreakEntry:f}=_u({brackets:Es,scoreString:e}),g=l||f,I=!!u.tiebreakSet,h=e?.[e.length-1]?.trim(),S=e&&!isNaN(h),T=!g&&h===Zs,y=l&&vT.includes(h),P=f&&vT.includes(h),U=f&&h===ci,E=e?.split(""),[A]=Es.split(""),N=E&&Math.max(...mo(A,E)),D=E&&Math.max(...mo(ci,E)),M=E&&D>N,R=o[o.length-1]?.winningSide,b=o?.length&&!R,v=NT.find(H=>e?.indexOf(H)>=0),O=!isNaN(n),x=n===Vp,F=Vd.includes(n),L=e?.split("").find(H=>vT.includes(H)),w=F&&f&&!P&&(U||!t_({scoreString:e}));return{isTiebreakSetValue:I&&O,matchUpScoringFormat:a,setNumber:s,setFormat:u,matchTiebreakHasJoiner:M,isGameScoreEntry:b,isSpace:x,isCloser:F,isTiebreakCloser:F&&L&&g&&S,isDecidingSet:c,isTiebreakSet:I,isTimedSet:p,isNumericEnding:S,isNumericValue:O,hasOpener:L,hasOutcome:v,finalSet:m,finalSetIsComplete:d,lastSetIsComplete:R,isInvalidSetTiebreakValue:x&&g&&y,isInvalidMatchTiebreakValue:w,isTiebreakEntry:g,isSetTiebreakEntry:l,isMatchTiebreakEntry:f,isIncompleteSetScore:T,isIncompleteSetTiebreak:y,isIncompleteMatchTiebreak:P,isPartialMatchTiebreakValue:U}}function qD(t){let{lowSide:e=1,value:r}=t,{scoreString:n,sets:o,winningSide:i,matchUpStatus:s}=t,{matchUpFormat:a,shiftFirst:c,auto:u=!0}=t,p,m,d=c&&e===2||!c&&e===1;if(!jD.includes(r))return{updated:!1,info:"invalid key"};c&&(e=3-e);let{matchUpWinningSide:l}=YD({sets:o,winningSide:i,matchUpStatus:s,matchUpFormat:a});i=l;let f=i_({value:r,winningSide:i,scoreString:n,sets:o,matchUpFormat:a});if(HD.includes(r)&&(r=Zs),f.hasOpener&&f.isTiebreakEntry&&!f.isTiebreakSet&&d&&pt(r)===0&&(f.isTiebreakCloser=!0),Vd.includes(r)&&f.hasOpener&&(r=""),Vd.includes(r)&&(r=Vp),f.lastSetIsComplete){let g=n?.length&&n[n.length-1];n&&g!==" "&&(n+=" ")}if(f.isTimedSet)({info:m,sets:o,scoreString:n,updated:p,matchUpStatus:s,winningSide:i}=r_({analysis:f,lowSide:e,scoreString:n,sets:o,matchUpStatus:s,winningSide:i,value:r}));else if(Gd.includes(r))f.finalSetIsComplete||i?m="final set is already complete":!f.isTiebreakEntry&&!f.isIncompleteSetScore?{sets:o,scoreString:n,matchUpStatus:s,winningSide:i,updated:p}=_T({lowSide:e,sets:o,scoreString:n,matchUpStatus:s,winningSide:i,value:r}):f.isTiebreakEntry||f.isIncompleteSetScore?m="incomplete set scoreString or tiebreak entry":console.log("handle case",{value:r});else if(r===kd)p=!0,{scoreString:n,sets:o}=Lg({analysis:f,scoreString:n,sets:o,lowSide:e}),n||(o=[]),s=void 0,i=void 0;else if(f.hasOutcome)m="has outcome";else if(r===Zs&&!f.isMatchTiebreakEntry)(!f.isSetTiebreakEntry||f.isSetTiebreakEntry&&!f.isNumericEnding)&&(p=!0,{scoreString:n,sets:o}=Lg({analysis:f,scoreString:n,sets:o,lowSide:e}),s=void 0);else if(r===ci&&f.isMatchTiebreakEntry&&!f.isSetTiebreakEntry)f.matchTiebreakHasJoiner?m="existing joiner":f.isNumericEnding&&(p=!0,n+=ci);else if([Zs,ci].includes(r))m="invalid location for joiner";else{if(i)return{updated:!1,info:"matchUp is complete"};if(f.isIncompleteSetScore)f.isNumericValue&&({sets:o,scoreString:n,updated:p}=e_({analysis:f,scoreString:n,sets:o,value:r}));else if(f.isInvalidMatchTiebreakValue)m="invalid matchUp tiebreak character";else if(f.isInvalidSetTiebreakValue)m="invalid set tiebreak character";else if(f.isTiebreakCloser){let g=f.isSetTiebreakEntry?As:Es,I=g.split("").reverse()[0],h=g.split("")[0],S=o[o.length-1],{tiebreakFormat:T}=f.setFormat,{tiebreakTo:y,NoAD:P}=T||{},U=Wp({set:S});if(!f.isTiebreakSet){let A=parseInt(n.split(h).reverse()[0]),N=OT({lowValue:A,tiebreakTo:y,NoAD:P});U===1?(S.side1TiebreakScore=N,S.side2TiebreakScore=A):(S.side1TiebreakScore=A,S.side2TiebreakScore=N)}n=(n||"")+I,f.isDecidingSet||(n+=Js);let E=Bd({analysis:f,set:S});S.winningSide=E||void 0,p=!0}else if(f.isTiebreakSetValue)({info:m,scoreString:n,sets:o,updated:p}=n_({analysis:f,auto:u,lowSide:e,scoreString:n,sets:o,value:r}));else if(f.isSetTiebreakEntry){let[g]=As.split(""),I=Math.max(...mo(g,n.split(""))),h=n.slice(I+1),S=h&&pt(h)===QO,T=pt(h?h+r:r),{tiebreakFormat:y}=f.setFormat,{tiebreakTo:P,NoAD:U}=y||{};!S&&h.length<2?U&&T>P-1?m="invalid low value for NoAD tiebreak":(p=!0,n=(n||"")+r):m=S?"tiebreak begins with zero":"tiebreak digit limit"}else if(f.isCloser)m=`invalid key: ${r}`;else if(f.isGameScoreEntry)m="game scoreString entry";else if(f.lastSetIsComplete||!o.length){p=!0;let{scoreString:g,set:I}=o_({analysis:f,lowSide:e,scoreString:n,value:pt(r)});I&&(I.setNumber=o?.length+1||1),o=o?.concat(I).filter(Boolean)||[I],n=g||void 0}else console.log("error: unknown outcome")}if(p){o=o?.filter(Boolean);let{matchUpWinningSide:g}=YD({sets:o,winningSide:i,matchUpStatus:s,matchUpFormat:a});return i=g,g&&(!s||[Qt,pn].includes(s))?(s=$O,o=o.filter(I=>{let{side1Score:h,side2Score:S,side1TiebreakScore:T,side2TiebreakScore:y}=I;return h||S||T||y})):n&&!i&&![CT,RT,bT].includes(s)&&(s=void 0),{updated:p,scoreString:n,sets:o,winningSide:i,matchUpStatus:s,info:m}}return{updated:p,scoreString:n,sets:o,winningSide:i,matchUpStatus:s,info:m}}var Hd="\\d+-\\d+",jp="\\d+-\\d+\\(\\d+\\)",Fg="\\[\\d+-\\d+\\]",XG="\\d+-\\d+\\(\\d+-\\d+\\)",s_=new RegExp(`(${Hd}),`,"g"),a_=new RegExp(`(${jp}),`,"g"),JG=[Hd,jp,Fg,XG],ZG=["0","1","2","00","01","10","11","002","012","102","112","000","001","010","100","011","101","110","111","002","012","102","112","0002","0012","0102","1002","0112","1012","1102","1112","3","03","13","013","103"],tV=ZG.map(t=>{let r=t.split("").map(n=>JG[n]).join(" ");return new RegExp(`^${r}$`)});function $D(t){return!t||tV.some(e=>e.test(t))}function c_(t){let e="[];",r="()",n=e+r,o=[e[0],r[0]],i=Object.assign({},...n.split("").map(c=>({[c]:0}))),s="",a=t.split("").map(c=>{let u=n.includes(c)&&c,p=o.includes(u);if(p&&u)return i[u]+=1,s=u,c;if(!p&&u&&s&&u!==s){i[s]-=1;let m=e.includes(s)&&e||r.includes(s)&&r||"",d=m.split("").find(l=>l!==s);if(m.includes(u))i[s]||(s="");else return i[u]||(s=""),d}return c}).join("");return t!==a?a:t}function Wd(t){return/^\(\d+\)$/.test(t)||/^\(\d+$/.test(t)}function u_(t){return/^\(\d+-\d+\)$/.test(t)||/^\[\d+-\d+\]$/.test(t)}function Oa(t){let r=(n=>n?.split("-").join("").split("/").join(""))(t);if(/^\d+$/.test(r)&&r.length===2){let n=r.split("");return Math.abs(n.reduce((i,s)=>+i-+s))===1}return!1}function Yp(t,e){let r=[t.slice(e,e+2),e?t.slice(0,1):t.slice(2)].map(i=>parseInt(i.join("")));e&&r.reverse();let n=r;if(Math.abs(n.reduce((i,s)=>+i-+s))>=2)return n.join("-")}function KD(t){return t.length===2?t.split("").join("-"):([", ",",","/"," "].forEach(e=>t=t.split(e).join("-")),t=t.replace(/-{2,}/,"-"),t)}function p_(t){return t.startsWith("(")&&t.endsWith(")")}function m_({score:t,applied:e}){t=c_(t);let r=/\)(\d+)/g;if(r.test(t))for(let U of t.match(r)){let E=U.replace(")",") ");t=t.replace(U,E)}t=t.replace(/\)\//g,") / "),t=t.replace(/\/\)/g,")");let n=/\(([\d- ]+)\)/g,o=/\(([\d- ]+)\)/,i=t.match(n);for(let U of i||[]){let[E]=U.match(o).slice(1),A=E.replace(/ /g,"");t=t.replace(U,`(${A})`)}let s=/\(\(\d-\d\)\)/g;if(s.test(t)){let U=t.match(s);U.length&&U.forEach(E=>{let A=E.match(/\((\(\d-\d\))\)/).slice(1)[0];t=t.replace(E,A)})}if(s=/\(\((\d)\)\)/g,s.test(t)){let U=t.match(s);U.length&&U.forEach(E=>{let A=E.match(/\((\(\d\))\)/).slice(1)[0];t=t.replace(E,A)})}/(^|\s)6-,/.test(t)&&(t=t.replace(/(^|\s)6-,/g,"6-0,"));let a=new RegExp(/[-,]{2,}/g);t=t.replace(a,"-"),["- "," -"].forEach(U=>{let E=new RegExp(`(\\d+)${U}(\\d+)`,"g"),A=t.match(E);A&&A.forEach(N=>t=t.replace(N,N.split(U).join("-")))}),/^[(-/,]+$/.test(t)&&(t=""),/\)[-/,]+$/.test(t)&&(t=t.slice(0,t.length-1)),/\d \/\d/.test(t)&&(t=t.replace(/ \//g,"/")),t.includes(" /")&&(t=t.replace(/ \//g," "));let c=/\(\d+, \)/g;c.test(t)&&t.match(c).forEach(E=>{let[A]=E.match(/\((\d+), \)/).slice(1);A.length===2?t=t.replace(E,`(${A})`):A.length===1&&A==="6"&&(t=t.replace(E,"(6-0)"))});let u=/\((\d+)\/\)/g;u.test(t)&&t.match(u).forEach(E=>{let[A]=E.match(/\((\d+)\/\)/).slice(1);A.length===2?t=t.replace(E,`(${A})`):A.length===1&&A==="6"?t=t.replace(E,"(6-0)"):t=t.replace(E,`(${A})`)});let p=/\d\/\d\/,/g;p.test(t)&&t.match(p).forEach(E=>{let[A]=E.match(/(\d\/\d)\/,/).slice(1);t=t.replace(E,`${A},`),e.push("slashComma")});let m=/\(\/(\d+)\)/g;m.test(t)&&t.match(m).forEach(E=>{let[A]=E.match(/\(\/(\d+)\)/).slice(1);A.length===2?t=t.replace(E,`(${A})`):A.length===1&&parseInt(A)<6?t=t.replace(E,`(6-${A})`):t=t.replace(E,`(${A})`)});let d,l,f,g,I,h=()=>{I=Sr(t.split("")),l=I["("]===(I[")"]||0)+1,d=(I["("]||0)+1===I[")"],f=I["["]===I["]"]+1,g=l&&!f};h();let S=/(\d+-\d+\(\d+)0,/;if(S.test(t)){let[U]=t.match(S).slice(1);t=t.replace(S,U+")")}if(I["("]===I[")"]&&I["("]>1){let U=t.split(")(").join(") (").split(" ");U.every(p_)?t=U.map(E=>{let A=E.slice(1,E.length-1);return A.length>2?A:E}).join(" "):t=U.join(" ")}h();let T=/[A-Za-z]+/.test(t),y=/\d+/.test(t);if(!T&&!y)return{score:""};if(/^\[.+\]$/.test(t)&&"()/,- ".split("").some(U=>I[U])&&(t=t.slice(1,t.length-1)),/^\(.+\)$/.test(t)&&I["("]===1&&I[")"]===1&&"[]/,".split("").some(U=>I[U]>1)&&(t=t.slice(1,t.length-1)),t.startsWith("(")&&t.endsWith("))")&&(t=t.slice(1,t.length-1)),I["("]>(I[")"]||0)&&t[t.length-1]==="("&&(t=t.slice(0,t.length-1)+")",h()),I["("]===1&&!I[")"]&&t[0]==="("&&(t=t+")",h()),I["("]>(I[")"]||0)&&t.slice(0,2)==="(("&&(t=t.slice(1)),d){if(/^9\d/.test(t))t="("+t.slice(1);else if(t[0]!=="(")t="("+t;else{let U=[],E=0;for(let A of t.split("").reverse())A===")"&&(E?U.push("("):E+=1),A==="("&&(E-=1),U.push(A);U.reverse(),t=U.join("")}h()}if(I[")"]>(I["("]||0)&&t[0]===")"&&(t="("+t.slice(1),h()),g&&(t.endsWith(9)||/\d+0$/.test(t))&&(t=t.slice(0,t.length-1)+")",h()),g&&(!t.endsWith(")")||t.startsWith("(("))&&(t=t+")",h()),g){let U="",E=0;for(let A of t.split(""))A==="("&&(E?U+=")":E+=1),A===")"&&(E-=1),U+=A;t=U}h(),f&&!l&&(t=t+"]"),t.includes("([")&&t.includes("])")&&(t=t.split("([").join("[").split("])").join("]"),h()),/\(\d+0$/.test(t)&&(t=t.slice(0,t.length-1)+")"),h(),I[")"]===1&&!I["("]&&t.endsWith(")")&&(t=t.slice(0,t.length-1)),t.startsWith("(")&&t.endsWith(")")&&I["("]===1&&I[")"]===1&&(t=t.slice(1,t.length-1),h());let P=U=>{let E=U.indexOf("("),A=U.indexOf(")");return E>=0&&A>=0&&E<A};if(/^\([\d ]+.*[\d ]+\)$/.test(t)&&I["("]===I[")"]){let U=t.slice(1,t.length-1);P(U)&&(t=U,h())}return{score:t,applied:e}}function xu(t){if(!/^[\d-]+(\(\d\))*$/.test(t))return t;let e=mo("-",t.split(""));if(!e.length)return t;let r=t.split("-"),n=!(r.length%2),o=!!(e.length%2);return n&&o&&e.length>r.length/2&&e.filter((s,a)=>a%2).forEach(s=>{t=t.substring(0,s)+" "+t.substring(s+1)}),t}function d_({score:t,applied:e}){return t.includes("( ")&&(e.push("removeParenSpacingAfterOpen"),t=t.split("( ").map(r=>r.trim()).join("(")),t.includes(" )")&&(e.push("removeParenSpacingBeforeClose"),t=t.split(" )").map(r=>r.trim()).join(")")),[s_,a_].forEach(r=>{let n=t.match(r);n?.length&&(n.forEach(o=>{t=t.replace(o,o.slice(0,o.length-1)+" ")}),e.push("setsEndComma"))}),t=t.split(" ").filter(Boolean).map(xu).join(" "),{score:t,applied:e}}function l_({score:t}){if(typeof t!="string")return{score:t};let e=d=>d?.split("-").join("").split("/").join(""),r=d=>d.split("[").join("(").split("]").join(")");t=t.split(", ").join(" ");let n=t.split(" ");t=n.map(d=>{let l=/^-(\d+)$/;if(l.test(d)){let[f]=d.match(l).slice(1);if(f.length===2)return f.split("").join("-")}return d}).join(" "),n=t.split(" ");let o=n.filter(Wd),i=0,s="";for(let d of o){let l=mo(d,n).filter(h=>!i||h>i)[0],f=n.slice(i,l-1),g=n[l-1],I=e(g);if(/^\d+$/.test(I)&&I.length===2){let h=I.split(""),S=Math.abs(h.reduce((T,y)=>+T-+y));if(S===1){let T=[f.join(" "),[g,d].join("")].join(" ");s+=T,i=l+1}else if(S===0){let T=Math.max(...h);if([4,5,6,7,8,9].includes(T)){let y=[6,4].includes(T)?T+1:T-1,P=[T,y].sort().reverse().join("-"),U=[f.join(" "),[P,d].join("")].join(" ");s+=U,i=l+1}}}}if(o.length&&s.length){let d=n.slice(i).join(" ");return s=[s,d].join(" "),{score:s.trim()}}if(n.length===2&&["(","["].some(d=>n[1].includes(d))){let l=e(n[0]).split("");if(Math.abs(l.reduce((g,I)=>+g-+I,0))===1)return n[1]=r(n[1]),{score:n.join("")}}let a=n.map(d=>u_(d)&&"bracket"||Oa(d)&&"set");if(a.includes("set")&&a.includes("bracket")){let d,l="";return n.forEach((f,g)=>{a[g]==="bracket"&&d==="set"?(f=r(f),l+=f):l+=` ${f}`,d=a[g]}),{score:l.trim()}}n=t.split(" ");let c,u=n.map(d=>{let l=new RegExp(/^(\d+)-(\d+)$/);if(l.test(d)){let[f,g]=d.match(l).slice(1),I=Math.abs([f,g].reduce((S,T)=>+S-+T)),h=Math.max(f,g);if(I===1)return c="tiebreakSet",c;if(I>=2&&h>=7&&c==="tiebreakSet")return c="tiebreak",c}}),p=mo("tiebreak",u);if(p.length){let d="";n.forEach((l,f)=>{p.includes(f)?d+=`(${l}) `:p.includes(f+1)?d+=`${l}`:d+=`${l} `}),t=d.trim()}let m=/(\d+-\d+)\((\d+)-(\d+)\)$/;if(m.test(t)){let[d,l,f]=t.match(m).slice(1),I=Math.max(l,f)>=10;!Oa(d)&&I&&(t=t.replace(m,`${d} [${l}-${f}]`))}return u=[],t=t.split(" ").map(d=>{let l=/^\((.*)\)$/,f=l.test(d),g=new RegExp(Fg).test(d)&&"super"||new RegExp(jp).test(d)&&"tiebreak"||new RegExp(Hd).test(d)&&"standard"||"unknown";return u.push(g),g==="standard"&&f?d.match(l)[1]:d}).join(" "),{score:t}}function f_({score:t,applied:e}){for(let D of[".",","," ","/"]){let M=new RegExp(`^(\\d+)\\${D}(\\d+)$`);if(M.test(t)){let R=t.match(M).slice(1).map(v=>parseInt(v)),b=Math.abs(R[0]-R[1]);b<=10&&b>=2&&(t=t.split(D).join("-"),e.push("variedJoinerPattern"))}}t.includes(";")&&(t=t.split(";").join(" "),e.push("semicolon set separation"));let r=/(^|\s)(\d)\/(\d)(\d)\/(\d)(\(|$)/;if(r.test(t)){let[D,M,R,b,v,O]=t.match(r).slice(1);t=t.replace(r,`${D}${M}-${R} ${b}-${v}${O}`),e.push("smashSlashPattern")}/.*\s6[/-]+$/.test(t)&&(t+="0",e.push("incompleteFinalSetPattern"));let o=/\(6,\)/g;o.test(t)&&(t=t.replace(o,"(6, 0)"),e.push("missingZeroPattern1"));let i=/^\d{3,}\(/,s=/\(\d+\)\d+/;[i,s].forEach(()=>{t=t.split(" ").map(M=>(i.test(M)&&(M=M.replace("("," (")),s.test(M)&&(M=M.replace(")",") ")),M)).join(" "),e.push("spaceConsiderationPatterns")});let c=xu(t);c!==t&&(t=c,e.push("deDashMash"));let u=/^(\d)[-/,]+(\d{2})[-/,]+(\d)$/;if(u.test(t)){let[D,M,R]=t.match(u).slice(1),[b,v]=M.split("");t=`${D}-${b} ${v}-${R}`,e.push("smashSetPattern")}let p=/^(\d+)[ -](\d+)$/,m=/^([\d -]+)\/([\d -]+)$/;if(m.test(t)){let[D,M]=t.match(m).slice(1),R=D.trim(),b=M.trim();if(p.test(R)&&p.test(b)){let v=R.match(p).slice(1,3).join("-"),O=b.match(p).slice(1,3).join("-");t=`${v} ${O}`,e.push("slashSeparationPattern")}}let d=/^([\d -]+),([\d -]+)$/;if(d.test(t)){let[D,M]=t.match(d).slice(1),R=D.trim(),b=M.trim();if(p.test(R)&&p.test(b)){let v=R.match(p).slice(1,3).join("-"),O=b.match(p).slice(1,3).join("-");t=`${v} ${O}`,e.push("commaSeparationPattern")}}let l=/^\d \d,/;if(l.test(t)){let D=t.match(l)[0],M=D.slice(0,D.length-1).split(" ").join("-");t=t.replace(D,M),e.push("singleSetCommaSeparationPattern")}let f=0,g=/(\d+)-(\d{2})-(\d+)/;for(;g.test(t)&&f<3;){let[D,M,R]=t.match(g).slice(1),b=M.split(""),v=`${D}-${b[0]} ${b[1]}-${R}`;t=t.replace(g,v),e.push("noSetSeparationPattern"),f+=1}let I=/(^|\s)7-6\s(\d+)\s/g,h=t.match(I);if(h?.length){let D=/(^|\s)7-6\s(\d+)\s/;h.forEach(M=>{let R=M.match(D).slice(2)[0];t=t.replace(M,`7-6(${R}) `),e.push("floatingTiebreakPattern1")})}let S=t.match(/\d \d /);S?.forEach(D=>{let M=D.slice(0,D.length-1).split(" ").join("-");t=t.replace(D,M),e.push("spaceSeparatedSetPattern1")}),S=t.match(/ \d \d$/),S?.forEach(D=>{let M=" "+D.slice(1).split(" ").join("-");t=t.replace(D,M),e.push("spaceSeparatedSetPattern2")});let T=/^\d, *\d\/\d, *\d/;if(T.test(t)){let D=t.match(T)[0],M=D.split("/").map(R=>`(${R})`).join(" ")+" ";t=t.replace(D,M),e.push("slashCommaSetPattern")}let y=/\(6-\)/g;y.test(t)&&(t=t.replace(y,"(6-0)"),e.push("missingZeroPattern2"));let P=/(?<!-)(\d+)\/(\d+)(?!-)/g;if(P.test(t)){let D=t.match(P),M=/(?<!-)(\d+)\/(\d+)(?!-)/,R=t;D.forEach(b=>{let[v,O]=b.match(M).slice(1),x=`${v}-${O}`;R=R.replace(b,x)}),t=R,e.push("slashSetPattern")}let U=/(.*)\s(1\d)\s(\d+)$/;if(U.test(t)){let[D,M,R]=t.match(U).slice(1);D.replace(/\D/g,"").length>=4&&(t=D+` ${M}${R}`,e.push("spaceSeparatedSuperPattern"))}let E=/(^|\s)(\d+-\d+)\s(\d+)(\s|$)/g;for(let D of t.match(E)||[]){let[M,R,b,v]=D.match(/(^|\s)(\d+-\d+)\s(\d+)(\s|$)/).slice(1),[O,x]=R.split("-").map(L=>parseInt(L));Math.abs(O-x)===1&&(t=t.replace(D,`${M}${R}(${b})${v}`),e.push("spaceSeparatedSetPattern"))}let A=/\d-\d \(\d{1,2}\)(\s|$|,)/g;for(let D of t.match(A)||[]){let M=/(\d-\d) \((\d{1,2})\)(\s|$|,)/,[R,b,v]=D.match(M).slice(1),[O,x]=R.split("-").map(L=>parseInt(L));Math.abs(O-x)===1&&(t=t.replace(D,`${R}(${b})${v}`),e.push("floatingTiebreakPattern2"))}let N=/(^|\s)(\d \d)\(/g;for(let D of t.match(N)||[]){let M=/(^|\s)(\d \d)\(/,[R,b]=D.match(M).slice(1);t=t.replace(D,`${R}${b.split(" ").join("-")}(`),e.push("spacedTiebreakPattern")}return{score:t,applied:e}}function g_({score:t,matchUpStatus:e}){let r=t?.split(" ");t=r.map(a=>{if(a.endsWith("]")){let c=a.split("[");if(Oa(c[0]))return c[0]+`(${c[1].slice(0,c[1].length-1)})`}return a}).join(" ");let n=new RegExp(/(\([\d ]+\))/g);if(n.test(t))for(let a of t.match(n)){let u=a.replace(" ","-").match(/\((.*)\)/)?.[1];if(Zt(u)&&u?.[0]>2){if([2,4].includes(u.length))u=u.split("").join("-");else if(u.length===3){let p=u.indexOf("1");u=Yp(u.split(""),p)}}t=t.replace(a,`(${u})`)}r=t?.split(" ");let o=new RegExp(/^(\d[-/]+\d)\((\d+)[-/]+(\d+)\)$/),i=r.length-1;t=r.map((a,c)=>{let u=[void 0,"","COMPLETED"].includes(e)||c!==i;if(o.test(a)&&u){let[p,m,d]=Array.from(a.match(o)).slice(1),l=Math.min(m,d);return`${p}(${l})`}return a}).join(" "),r=t?.split(" "),o=new RegExp(/^(\d{2})\((\d+)\)$/),t=r.map(a=>{if(o.test(a)){let[c,u]=Array.from(a.match(o)).slice(1),p=c.split("");return`${p[0]}-${p[1]}(${u})`}return a}).join(" "),r=t?.split(" "),o=new RegExp(/^\((\d[-/]+\d)\)(\d+)$/),t=r.map(a=>{if(o.test(a)){let[c,u]=Array.from(a.match(o)).slice(1);return Oa(c)?`${c}(${u})`:c}return a}).join(" "),r=t?.split(" "),o=new RegExp(/^1-0\((\d+)\)$/),t=r.map(a=>{if(o.test(a)){let[c]=a.match(o).slice(1);return`[${c<9?10:parseInt(c)+2}-${c}]`}return a}).join(" ");let s=/\((\d)+0 /;if(s.test(t)){let a=t.match(s)[1];t=t.replace(s,`(${a}) `)}return{score:t}}function I_({score:t,attributes:e,identifier:r}){if(typeof t!="string")return{score:t,identifier:r};let n=new RegExp(/\([\d,/ ]+\)/g),o=t.match(n);for(let m of o||[]){let l=m.match(/^\((.*)\)$/)?.slice(1)?.[0],g=t.split(m)[0].split(")").reverse()[0].replace(/\D/g,"");if(l?.length===2&&g?.length>=2){let S=g.slice(g.length-2).split("").map(y=>parseInt(y));if(Math.abs(S[0]-S[1])===1)continue}let I=KD(l),h=xu(I);t=t.replace(m,`(${h})`).trim()}let i=new RegExp(/\[[\d,/ ]+\]/g);t.match(i)?.forEach(m=>{let d=KD(m.match(/^\[(.*)\]$/)[1]);t=t.replace(m,`(${d}) `).trim()});let a=[")","]"],c=[")(","), (",") (",")[",") [","](","] ("];if(t.startsWith("(")&&a.some(m=>t.endsWith(m))&&c.some(m=>t.includes(m))){let m="",d=t.split(/[)\]]/).filter(Boolean).map(h=>(h.startsWith(",")&&(h=h.slice(1)),h.trim())),l=d.every(h=>h.includes(",")||Wd(h)),f=d.every(h=>h.includes("/")||Wd(h)),g=d.every(h=>h.includes("-")||Wd(h)),I=l&&","||g&&"-"||f&&"/";if(I){let h;d.forEach(S=>{if(S.startsWith("("))if(h==="set"&&(m+=" "),S.includes(I))m+=S.slice(1).split(I).map(T=>T.trim()).join("-"),h="set";else{let T=S.slice(1);m+=`(${T}) `,h="tiebreak"}else if(S.startsWith("[")){let T=S.slice(1).split(I).map(P=>parseInt(P.trim())),y=Math.min(...T);h==="set"?m+=`(${y}) `:m+=`[${T.join("-")}] `,h="tiebreak"}}),t=m.trim()}}let u=Sr(t.split(""));u["("]===1&&u[")"]===1&&t.startsWith("(")&&t.endsWith(")")&&(t=t.slice(1,t.length-1),u["-"]===1&&Oa(t)&&Zt(e?.removed)&&(t=t+`(${e.removed})`,e.removed=void 0));let p=/\(\)/g;return p.test(t)&&(t=t.replace(p,"").trim()),{score:t}}function xT({score:t}){let e=t.split(""),r=[],n,o=()=>n=[void 0,void 0,void 0],i=()=>{let a=`${n[0]}-${n[1]}`;return n[2]&&(a+=` (${n[2]})`),o(),n.push(n),a};o();let s=()=>n[0]!==void 0&&n[1]!==void 0&&Math.abs(parseInt(n[0])-parseInt(n[1]));for(;e.length;){let a=e.shift(),c=Zt(a)&&parseInt(a),u=n[0]!==void 0&&n[1]!==void 0;if(Zt(c)){if(n[0]===void 0){n[0]=c;continue}if(n[1]===void 0&&(n[1]=c,s())){r.push(i()),n=[void 0,void 0];continue}if(u&&e.length===1&&Zt(e[0])){let p=e.pop();n[0]=n[0].toString()+n[1].toString(),n[1]=p,r.push(i()),n=[void 0,void 0]}u&&s()}}return{sets:r}}function kg(t){let e=t.indexOf("1"),r=t.split(""),n=r.every(o=>!isNaN(o));if(n&&t.length===3&&e===0){let o=Yp(r,e);if(o)return o}if(n&&t.length===7&&e>3){let o=r.slice(4),i=Yp(o,e-4);if(i)return`${r[0]}-${r[1]} ${r[2]}-${r[3]} ${i}`}}function zD(t){let{score:e}=t,{applied:r,matchUpStatus:n}=t,o=e?.toString().split(""),i=o?.every(a=>Zt(a)),s=a=>Math.abs(a[0]-a[1]);if(typeof e=="number"||i){e=e.toString().toLowerCase(),i&&(e=o.join(""));let a=i?o.map(u=>parseInt(u)):e.split("").map(u=>parseInt(u)),{sets:c}=xT({score:e});if(a.length,e.length===3&&s(a.slice(0,2))===1){let[u,p,m]=a;e=`${u}-${p}(${m})`,r.push("numericTiebreakPattern1")}else if(e.length===3&&a[0]===1){let[u,p,m]=a;e=`[${u}${p}-${m}]`,r.push("numericTiebreakPattern2")}else if(e.length===4&&s(a.slice(0,2))===1&&"987654".split("").includes(a[0].toString())){let[u,p,m,d]=a,l=Math.min(m,d);e=`${u}-${p}(${l})`,r.push("numericTiebreakPattern3")}else if(e.length===4&&a[0]===1&&a[2]===1){let[u,p,m,d]=a;e=`[${u}${p}-${m}${d}]`,r.push("bigSuper")}else if(e.length===4){let[u,p,m,d]=a;e=`${u}${p} ${m}${d}`,r.push("split4")}else if(e.length===5&&s(a.slice(0,2))===1){let[u,p,m,d,l]=a;e=`${u}-${p}(${m}) ${d}-${l}`,r.push("numericTiebreakPattern4")}else if(e.length===5&&s(a.slice(3))===1){let[u,p,m,d,l]=a;e=`${u}-${p} ${m}-${d}(${l})`,r.push("numericTiebreakPattern5")}else if(a.length===7)if(s(a.slice(0,2))>1&&s(a.slice(2,4))>1&&a[4]===1){let[u,p,m,d,l,f,g]=a;e=`${u}-${p} ${m}-${d} [${l}${f}-${g}]`,r.push("numericTiebreakPattern6")}else if(s(a.slice(0,2))===1&&s(a.slice(3,5))>1&&s(a.slice(5,7))>1){let[u,p,m,d,l,f,g]=a;e=`${u}-${p}(${m}) ${d}-${l} ${f}-${g}`,r.push("numericTiebreakPattern7")}else if(s(a.slice(0,2))>1&&s(a.slice(2,4))===1&&s(a.slice(5,7))>1){let[u,p,m,d,l,f,g]=a;e=`${u}-${p} ${m}-${d}(${l}) ${f}-${g}`,r.push("numericTiebreakPattern8")}else if(s(a.slice(0,2))>1&&s(a.slice(2,4))>1&&s(a.slice(4,6))===1){let[u,p,m,d,l,f,g]=a;e=`${u}-${p} ${m}-${d} ${l}-${f}(${g})`,r.push("numericTiebreakPattern9")}else e=e.slice(0,2)+" "+e.slice(2,4)+" "+e.slice(4),r.push("numericMatchTiebreakPattern");else if(e.length%2){let u=kg(e);u&&e!==u&&r.push("parsedSuperPattern"),e=u??e}else{let u=ye(e.split(""),2).map(h=>h.join("")),p=u.map(h=>{let[S,T]=h.split("").map(U=>parseInt(U)),y=Math.abs(S-T),P=S>T?1:2;return y>1&&P||P*-1}),m=p.reduce((h,S)=>h>0&&S>0,1),d=Sr(p),l=p.map(h=>Math.abs(h)),f=Sr(l),g=p[0]<0,I=!g&&p[1]<0;if(p[0]>0&&p[1]>0&&p[0]!==p[1])e=[u.slice(0,2).join(" "),u.slice(2).join("-")].join(" "),r.push("numeric3rdSetTiebreakPattern");else if(m)e=u.join(" "),r.push("chunkSplit");else if(a.length===6){if(d[1]===2||d[2]===2)if(!Object.values(f).includes(3))e=u.join(" "),r.push("chunkSplit");else{let[h,S,T,y,P,U]=a,E=p.reduce((A,N,D)=>N<0?D:A,void 0);if(E===0){let A=Math.min(T,y);e=`${h}-${S}(${A}) ${P}-${U}`,r.push("chunkSplitTiebreak1")}else if(E===1){let A=Math.min(P,U);e=`${h}-${S} ${T}-${y}(${A})`,r.push("chunkSplitTiebreak2")}else e=`${h}-${S} ${T}-${y}`,r.push("chunkSplitTrimExtraneous")}}else if(a.length===8){let[h,S,T,y,P,U,E,A]=a;g||I?a[5]===1&&(g?e=`${h}-${S}(${T}) ${y}-${P} [${U}${E}-${A}]`:e=`${h}-${S} ${T}-${y}(${P}) [${U}${E}-${A}]`):(p[0],p[1])}}}return{score:e,applied:r,matchUpStatus:n}}function wT(t){let e=[0,0],r=[],n=t.split(" "),o=/(\d+)-(\d+)/;n.forEach(c=>{if(o.test(c)){let u=c.match(o).slice(1).map(m=>parseInt(m)),p=u[0]>u[1]&&1||u[1]>u[0]&&2;p&&(e[p-1]+=1,r.push(p))}});let i=e[0]>e[1]&&1||e[1]>e[0]&&2,s=e[0]>0&&e[0]===e[1],a=e.reduce((c,u)=>c+u,0);return{setsWon:e,setsTied:s,setWinners:r,totalSets:a,winningSide:i}}function h_({score:t,matchUpStatus:e,attributes:r}){let n=[],o,i=t.split(" "),s=i.length;t=i.map((p,m)=>{if(new RegExp(jp).test(p)){let l=p.slice(3),f=p.slice(0,3),g=f.split("-");if(!Oa(f)&&!e){let I=Math.max(...g),h=f.indexOf(I),S=[I,I-1];return h&&S.reverse(),S.join("-")+l}}else if(p.length===2&&Zt(p))return p.split("").join("-");p=xu(p);let d=new RegExp(`^${Fg}$`).test(p)&&"super"||new RegExp(`^${jp}$`).test(p)&&"tiebreak"||new RegExp(`^${Hd}$`).test(p)&&"standard"||"unknown";if(n.push(d),s>1&&d==="standard"&&m<2){let[l,f]=p.split("-"),g=Math.abs(parseInt(l)-parseInt(f)),I=Math.max(l,f),h=Math.min(l,f),S=[parseInt(l),parseInt(f)].indexOf(h);if(I>9&&g>2){let T=I.toString().split(""),y=T.find(P=>parseInt(P)>h||m&&parseInt(P)<=o)??T[0];y&&(p=S?[y,h].join("-"):[h,y].join("-"))}I>(o||0)&&(o=I)}if(d==="standard"){let[l,f]=p.split("-");if(!Math.abs(parseInt(l)-parseInt(f))&&e!=="RETIRED")return""}return p}).filter(Boolean).join(" ");let{setsWon:a,setWinners:c,totalSets:u}=wT(t);if(u===1&&r?.removed==="6"&&(t+=" 6-0"),t.split(" ").length>2&&Math.max(...a)>=2&&c[0]===c[1]&&(t=t.split(" ").slice(0,2).join(" ")),Math.max(...a)>2){let p=[0,0];t=t.split(" ").map((m,d)=>(p[c[d]]+=1,Math.max(...p)>2?void 0:m)).filter(Boolean).join(" ")}return{score:t,profile:n}}function S_({score:t}){let{setsTied:e,winningSide:r}=wT(t),n=/\s\((\d+)\)$/;if(!r&&e&&n.test(t)){let a=t.match(n).slice(1)[0],c=a<=8?10:a+2;t=t.replace(n,` [${c}-${a}]`)}let o=t.split(" "),i=o[o.length-1];if(!i.includes("-")||i.indexOf("(")>0)return{score:t};let s=i.split("(").join("").split(")").join("").split("-");if(!s.every(a=>Zt(a)))return{score:t};if(s[0]==="76"){let a=s[1].length===2?Math.min(...s[1].split("").map(c=>parseInt(c))):s[1];t=[...o.slice(0,o.length-1),`7-6(${a})`].join(" ")}else{s=s.map(u=>parseInt(u));let a=Math.max(...s),c=Math.abs(s[0]-s[1]);if(a>=10){if(c>2&&s.every(u=>+u>=10)){let u=s.map(p=>p===a?p-10:10).sort();c=Math.abs(u[0]-u[1]),c>2&&(s=u)}t=[...o.slice(0,o.length-1),`[${s.join("-")}]`].join(" ")}else o.length===3&&a>=7&&c>2&&(t=[...o.slice(0,o.length-1),`[${s.join("-")}]`].join(" "))}return{score:t}}function eV({score:t}){return t=t?.toString().toLowerCase()||"",{score:t}}function rV({score:t,applied:e}){return typeof t!="string"?{score:t}:(t.toLowerCase().includes("o")&&(t=t.toLowerCase().split(" ").map(r=>r.split("o").join("0")).join(" "),e.push("replaceOh")),{score:t,applied:e})}function nV({score:t,applied:e}){return typeof t!="string"?{score:t}:(t=t.toLowerCase().split(" ").map(r=>{if(/^\d+$/.test(r)&&r.length>2){let n=r.indexOf("1");if(r.length%2){if(r.length===3&&n===0){let o=Yp(r.split(""),n);return e.push("getSuper"),o}}else{let{score:o,applied:i}=zD({score:r,applied:[]});o!==r&&(r=o,e.push(...i))}}return r}).join(" "),{score:t,applied:e})}function oV({score:t,applied:e}){return typeof t!="string"?{score:t}:[3,4].includes(t.length)&&kg(t)?{score:kg(t)}:(t=t.toLowerCase().split(" ").map(r=>{if(/^\d+$/.test(r)&&r.length===1){e.push("removeErroneous1");return}return r}).filter(Boolean).join(" "),{score:t,applied:e})}function iV({score:t,applied:e}){return["walkover","wo","w/o","w-o"].includes(t?.toString().toLowerCase())?(e.push("handleWalkover"),{matchUpStatus:"walkover",score:"",applied:e}):{score:t}}function sV({score:t,profile:e,applied:r}){t=t?.toString().toLowerCase();let n=/^(.*\d+.*)(ret|con)+[A-Za-z ]*$/;if(n.test(t)){let[a]=t.match(n).slice(1);return r.push("handleRetired"),{score:a.trim(),matchUpStatus:"retired",applied:r}}let o=e?.matchUpStatuses?.retired,s=["rtd",...Array.isArray(o)?o:[o].filter(Boolean)].find(a=>t?.endsWith(a));return s?(r.push("handleRetired"),{matchUpStatus:"retired",score:t?.replace(s,"").trim(),applied:r}):{score:t}}function aV({score:t,attributes:e}){(t.endsWith(" am")||t.endsWith(" pm"))&&(t=""),t=t.replace(/[A-Za-z]+/g,"").trim(),[".",","].some(o=>t.endsWith(o))&&(t=t.slice(0,t.length-1));let r="()/-".split("").some(o=>t.includes(o));/ \d$/.test(t)&&r&&(e={removed:t.slice(t.length-2).trim()},t=t.slice(0,t.length-2));let n=/(.*)[A-Za-z]+$/;return n.test(t)&&(t=t.match(n).slice(1)[0].trim()),{score:t,attributes:e}}function cV({score:t}){return new RegExp(/-\d+\/\d+-/).test(t)&&(t=t.split("/").join(" ")),{score:t}}function uV({score:t}){let e=new RegExp(/^\d+\/\d+/),r=t.split(" ");r.some(o=>e.test(o))&&(t=r.map(o=>e.test(o)?o.replace("/","-"):o).join(" "));let n=/^(\d+), *(\d+)$/;if(n.test(t)){let[o,i]=t.match(n).slice(1);t=[o,i].join("-")}return{score:t}}function pV({score:t}){let e=new RegExp(/\(\d+\/\d+\)/g),r=t.match(e);for(let n of r||[]){let o=n.replace("/","-");t=t.replace(n,o)}return{score:t}}function mV({score:t}){if(t.includes(",")){let e=t.split(",").map(o=>o.trim()),r=o=>/\d \d/.test(o);e.every(r)&&(t=e.map(o=>{let i=/\d+ \d+/g;for(let s of o.match(i)){let[a,c]=s.match(/(\d+) (\d+)/).slice(1);o=o.replace(s,`${a}-${c}`)}return o}).join(" "))}if(t.includes(" ")){let e=t.replace(/[ ,]/g,"");e.split("").every(n=>Zt(n))&&e.length===4&&(t=e)}return{score:t}}function dV({score:t}){let e=new RegExp(/^\[\d+\](.*)$/);e.test(t)&&(t=t.match(e).slice(1)[0].trim());let r=/\(,/g;return r.test(t)&&(t=t.replace(r,"(")),{score:t}}var T_={handleTiebreakSlashSeparation:pV,handleSetSlashSeparation:cV,punctuationAdjustments:m_,handleGameSeparation:uV,joinFloatingTiebreak:l_,handleBracketSpacing:d_,handleSpaceSeparator:mV,separateScoreBlocks:nV,matchKnownPatterns:f_,removeDanglingBits:aV,removeErroneous:oV,handleWalkover:iV,properTiebreak:g_,handleNumeric:zD,handleRetired:sV,containedSets:I_,sensibleSets:h_,stringScore:eV,superSquare:S_,setBuilder:xT,excisions:dV,replaceOh:rV};var QD={},lV=[],fV=["handleNumeric","handleWalkover","handleRetired","replaceOh","stringScore","punctuationAdjustments","excisions","handleSpaceSeparator","matchKnownPatterns","removeDanglingBits","handleBracketSpacing","matchKnownPatterns","containedSets","separateScoreBlocks","handleGameSeparation","removeErroneous","joinFloatingTiebreak","handleSetSlashSeparation","handleTiebreakSlashSeparation","properTiebreak","sensibleSets","superSquare"],gV=["handleNumeric","separateScoreBlocks","sensibleSets","superSquare"];function XD(t){if(!t.score)return{error:G};let{score:e,sheetName:r,identifier:n,fileName:o,stepLog:i,fullLog:s,profile:a}=t,c=[],u,p=[],m,d,l=e,f=I=>{I.forEach(h=>{d=T_[h]({profile:a,identifier:n,matchUpStatus:u,attributes:m,applied:p,score:l});let S=d.score!==l;S&&c.push({method:h,score:d.score}),i&&(s||S||d.matchUpStatus!==u)&&console.log(u?{score:d.score,matchUpStatus:u}:{score:d.score},h),d.matchUpStatus&&(u=d.matchUpStatus),d.attributes&&(m=d.attributes),d.applied&&(p=d.applied),l=d.score})};f(fV);let g=$D(l);return g||(l=e.toString().replace(/\D/g,""),m?.removed&&(m.removed=void 0),f(gV),g=$D(l),g||(lV.push({score:l,fileName:o,sheetName:r}),l="")),p.forEach(I=>{QD[I]||(QD[I]=0),QD[I]+=1}),{matchUpStatus:u?.toUpperCase(),modifications:c,attributes:m,isValid:g,score:l}}var ZD={};Xt(ZD,{analyzeScore:()=>Gg,analyzeSet:()=>wu,checkScoreHasValue:()=>Ie,checkSetIsComplete:()=>Hp,getSetComplement:()=>Bg,getTiebreakComplement:()=>qp,isValidMatchUpFormat:()=>Pr,parseScoreString:()=>jd,validateScore:()=>Vg,validateTieFormat:()=>ar});function Gg({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}){let i=o?.sets??[],a=(i?.filter(E=>E?.winningSide)||[]).reduce((E,A)=>{let{winningSide:N}=A;if(!N)return E;let D=N-1;return E[D]++,E},[0,0]),c=n?n-1:void 0,u=c!==void 0?1-c:void 0,p=c!==void 0&&a[c],m=u!==void 0&&a[u],d=e?Ye(e):void 0,l=Math.max(...a),f=Sr(a)[l],g=d?.setFormat?.timed||d?.finalSetFormat?.timed,I=d?.bestOf,h=I&&Math.ceil(I/2)||1,S=r??t,T=S&&[Mt,rr,Ct].includes(S),y=!d||!i.length||i.every((E,A)=>{let N=A+1,D=N===I,M=N===i.length,{side1Score:R,side2Score:b,side1TiebreakScore:v,side2TiebreakScore:O,winningSide:x}=E,F=Math.max(R??0,b??0),L=v??O,{finalSetFormat:w,setFormat:V}=d,k=D&&w||V;if(L){let{tiebreakTo:H,NoAD:K}=k?.tiebreakFormat||{},q=Math.max(v??0,O??0);if(K&&q>H||q<H&&x&&(M&&!T||!M))return!1}return k.setTo?!(!k.noTiebreak&&F>k.setTo+1):!0}),P=(!e||l===h)&&f===1&&a.indexOf(l)+1||void 0;return{valid:!!(y&&(n&&p>m&&n===P||n&&T||!n&&!P&&(![le,Mt,rr,Ct].includes(S)||g&&S===le)))}}function Vg({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}){if(typeof o!="object")return{error:G};let{sets:i,scoreStringSide1:s,scoreStringSide2:a}=o,c="scoreString must be a string!";if(s!==void 0&&typeof s!="string")return{error:G,info:c};if(a!==void 0&&typeof a!="string")return{error:G,info:c};if(i!==void 0&&!Array.isArray(i))return{error:G,info:ii("sets")};if(i?.length){let u=i.map(m=>m?.setNumber).filter(Boolean);if(u.length!==ut(u).length)return{error:G,info:"setNumbers not unique"};for(let m of i){let{side1Score:d,side2Score:l,side1TiebreakScore:f,side2TiebreakScore:g,side1PointScore:I,side2PointScore:h,winningSide:S,setNumber:T}=m;if(![[d,l],[f,g],[I,h]].filter(U=>U.some(E=>![void 0,null].includes(E))).every(U=>U.every(E=>It(E))))return{error:G,info:"non-numeric values"};if(![T,S].filter(U=>![void 0,null].includes(U)).every(U=>It(U)))return{error:G,info:"non-numeric values"};if(S&&![1,2].includes(S))return{error:G,info:"winningSide must be 1 or 2"}}let{valid:p}=Gg({existingMatchUpStatus:t,matchUpStatus:r,matchUpFormat:e,winningSide:n,score:o});if(!p)return{error:nE,info:"score is invalid for matchUpFormat or winningSide does not match calculated winningSide"}}return{valid:!0}}var Bg=t=>{let{isSide1:e,lowValue:r,setTo:n,tiebreakAt:o,NoAD:i}=t;if(r===void 0)return!1;let s=pt(r);s?.toString().length>2&&(s=parseInt(s.toString().slice(0,2))),o&&o<n&&s>o&&(s=o);let a;return i&&!o?(s>n&&(a=n),a=s<n?n:n-1):a=s+1<n&&n||o&&o<n&&s===o&&n||!o&&s+2||n+1,[e?s:a,e?a:s]},qp=t=>{let{isSide1:e,lowValue:r,tiebreakTo:n,tiebreakNoAd:o}=t;if(r===void 0)return!1;let i=typeof r=="string"?parseInt(r):r;i?.toString().length>2&&(i=parseInt(i.toString().slice(0,2))),o&&i>n-1&&(i=n-1);let s=IV({lowValue:i,NoAD:o,tiebreakTo:n});return[e?i:s,e?s:i]};function IV(t){let{lowValue:e,NoAD:r,tiebreakTo:n}=t,o=r?1:2;return e+1>=n?e+o:n}function jd({tiebreakTo:t=7,scoreString:e=""}){return e?.split(" ").filter(Boolean).map((n,o)=>r({set:n,setNumber:o+1}));function r({set:n,setNumber:o}){let i=/\(([^)]+)\)/,s=/\[([^)]+)\]/,a=i.exec(n),c=s.exec(n),u=n?.startsWith("[")&&c&&c[1].split("-").map(y=>parseInt(y)),p=a&&n.replace(a[0],"")||c&&n.replace(c[0],"")||n,m=!u&&p.split("-").map(y=>parseInt(y)),d=u?u[0]>u[1]&&1||u[0]<u[1]&&2||void 0:m[0]>m[1]&&1||m[0]<m[1]&&2||void 0,l=a?a[1]:void 0,g=(l&&qp({lowValue:l,isSide1:d===2,tiebreakTo:t}))??[],[I,h]=m||[],[S,T]=u||g||[];return{side1Score:I,side2Score:h,side1TiebreakScore:S,side2TiebreakScore:T,winningSide:d,setNumber:o}}}function y_({matchUpScoringFormat:t,isDecidingSet:e,isTiebreakSet:r,isTimedSet:n,setObject:o}){if(!o)return;let i=Wp({set:o});return Hp({matchUpScoringFormat:t,set:o,isDecidingSet:e,isTiebreakSet:r,isTimedSet:n})&&i||void 0}function wu(t){let{setObject:e,matchUpScoringFormat:r}=t;if(!e)return{error:Yl};let{setNumber:n}=e||{},{bestOf:o,exactly:i}=r||{},s=o||i,a=!!(n&&s&&n===s),c=a&&r?.finalSetFormat||r?.setFormat,u=!!c?.tiebreakSet,p=!!c?.timed,m=!u&&!p,d=!!(n&&s&&n<=s),l=[e?.side1Score,e?.side2Score],f=[e?.side1PointScore,e?.side2PointScore],g=[e?.side1TiebreakScore,e?.side2TiebreakScore],I=l.filter(L=>L!==void 0).length,h=f.filter(L=>L!==void 0).length,S=g.filter(L=>L!==void 0).length,T=l?.filter(L=>!isNaN(L)).length,y=g?.filter(L=>!isNaN(L)).length,{tiebreakAt:P}=c||{},U=P&&l.filter(L=>L>=P).length===2,E=U&&(l[0]>l[1]&&1||l[1]>l[0]&&2||void 0),A=!!(y&&!T),N=!!e?.winningSide,{error:D,result:M}=hV({sideTiebreakScores:g,sideGameScores:l,setFormat:c,setObject:e}),{error:R,result:b}=SV({sideTiebreakScores:g,setObject:e,setFormat:c}),v=m&&!A&&M||u&&A&&b||p,O=d&&!(u&&!A)&&!(m&&A)&&(!N||v),x=y_({isTimedSet:p,matchUpScoringFormat:r,isDecidingSet:a,isTiebreakSet:A,setObject:e}),F={expectTiebreakSet:u,expectTimedSet:p,hasTiebreakCondition:U,isCompletedSet:N,isDecidingSet:a,isTiebreakSet:A,isValidSet:O,isValidSetNumber:d,isValidSetOutcome:v,leadingSide:E,setFormat:c,sideGameScores:l,sideGameScoresCount:I,sidePointScores:f,sidePointScoresCount:h,sideTiebreakScores:g,sideTiebreakScoresCount:S,winningSide:x};return e?.winningSide!==void 0&&(A?(F.isValidTiebreakSetOutcome=b,b||(F.tiebreakSetError=R)):(F.isValidStandardSetOutcome=M,M||(F.standardSetError=D))),F}function hV({setObject:t,setFormat:e,sideGameScores:r,sideTiebreakScores:n}){if(!t)return{result:!1,error:Yl};let o=!!e?.tiebreakSet,i=!!e?.timed;if(!e||o||i)return{result:!1,error:G};if(!(r?.filter(M=>!isNaN(M)).length===2))return{result:!1,error:kI};let{setTo:a,tiebreakAt:c,tiebreakFormat:u,NoAD:p}=e||{};if(!!!(a&&r?.find(M=>M>=a)))return{result:!1,error:kI};let d=[1,2].includes(t?.winningSide);if(!t||!d)return{result:!1,error:Em};let l=t?.winningSide-1,f=1-l,g=r[l],I=r[f],h=g-I;if(!(g>I))return{result:!1,error:{message:"winningSide game scoreString is not high"}};let T=c&&u,y=n?.filter(M=>!isNaN(M)).length===2,P=n?.[l],U=n?.[f],E=c&&r.filter(M=>M>=c).length===2;if(T){let{NoAD:M,tiebreakTo:R}=u;if(E){if(h>1)return{result:!1,error:{message:"invalid winning game scoreString (5)"}};if(!y)return{result:!1,error:{message:"invalid tiebreak scores (1)"}};if(isNaN(R))return{result:!1,error:{message:"tiebreakTo error"}};if(!!!(R&&n?.find(V=>V>=R)))return{result:!1,error:{message:"invalid tiebreak scores (2)"}};let O=c<a?a:a+1;if(g>O)return{result:!1,error:{message:"invalid winning game scoreString (1)"}};if(!P||!U||P<U)return{result:!1,error:{message:"winningSide tiebreak value is not high"}};let x=M?1:2,F=P-U,L=U>=R-1;if(F&&L&&F<x)return{result:!1,error:{message:"invalid tiebreak scores (3)"}}}if(g>a&&!E)return{result:!1,error:{message:"invalid winning game scoreString (2)"}}}let A=p?1:2,N=I>=a-1;return h&&N&&!E&&h<A?{result:!1,error:{message:"invalid winning game scoreString (3)"}}:h>A&&g>a?{result:!1,error:{message:"invalid winning game scoreString (4)"}}:{result:!0}}function SV({setObject:t,setFormat:e,sideTiebreakScores:r}){if(!t)return{result:!1,error:Yl};let n=!!e?.tiebreakSet,o=!!e?.timed;if(!e||!n||o)return{result:!1,error:{message:"not tiebreak set"}};let i=[1,2].includes(t?.winningSide);if(!t||!i)return{result:!1,error:Em};let{tiebreakSet:s}=e||{},{NoAD:a,tiebreakTo:c}=s||{};if(!(r?.filter(T=>!isNaN(T)).length===2))return{result:!1,error:{message:"invalid tiebreak scores (1)"}};if(isNaN(c))return{result:!1,error:{message:"tiebreakTo error"}};if(!!!r?.find(T=>T>=c))return{result:!1,error:{message:"invalid tiebreak scores (2)"}};let m=t?.winningSide-1,d=1-m,l=r[m],f=r[d];if(!l||!f||l<f)return{result:!1,error:{message:"winningSide tiebreak value is not high"}};let g=a?1:2,I=l-f,h=f>=c-1;return I&&h&&I<g?{result:!1,error:{message:"invalid tiebreak scores (3)"}}:{result:!0}}function A_(t){let{existingDrawDefinition:e,hydrateCollections:r,enforceGender:n,tieFormatName:o,matchUpType:i,eventType:s,isMock:a,event:c}=t,{tieFormat:u,matchUpFormat:p}=t;if(i===_e&&s===_e){let m=e?.structures?.find(({stage:d})=>d===nt)?.tieFormat;u=u||m||o&&c?.tieFormat?.tieFormatName===o&&c.tieFormat||o&&Zn({namedFormat:o,hydrateCollections:r,isMock:a,event:c})||c?.tieFormat||Zn({event:c,isMock:a,hydrateCollections:r}),p=void 0}else p||(u=void 0,c?.matchUpFormat||(p=Dn));if(u){let m=ar({gender:c?.gender,enforceGender:n,tieFormat:u});if(m.error)return m}return{tieFormat:u,matchUpFormat:p}}function E_(t){let e=t.drawDefinition,{existingQualifyingPlaceholderStructureId:r,appliedPolicies:n,drawEntries:o,structureId:i,idPrefix:s,isMock:a,event:c}=t,u=t.qualifyingProfiles,p=u?.length?TT({uuids:t.uuids,qualifyingProfiles:u,appliedPolicies:n,idPrefix:s,isMock:a}):void 0;if(p?.error)return p;e.structures=e.structures?.filter(({structureId:T})=>T!==r),e.links=e.links?.filter(({source:T})=>T.structureId!==r);let{qualifiersCount:m,qualifyingDrawPositionsCount:d,qualifyingDetails:l}=p??{};d&&(p?.structures&&e.structures?.push(...p.structures),p?.links&&e.links?.push(...p.links));let f=e.structures?.find(({stage:T,stageSequence:y})=>T===nt&&y===1),{qualifiersCount:g}=Is({stageSequence:1,drawDefinition:e,structureId:i,stage:nt}),I=Math.max(m??0,g??0),h=LS({qualifiersCount:I,drawDefinition:e,stage:nt});if(h.error||(h=Op({drawSize:d,stage:ct,drawDefinition:e}),h.error))return h;TV({drawDefinition:e,drawEntries:o,event:c});let S=yV({mainStructure:f,qualifyingDetails:l,drawDefinition:e});return S.error?S:{drawDefinition:e,structureId:i}}function TV({drawDefinition:t,drawEntries:e,event:r}){for(let n of(e??[]).filter(({entryStage:o})=>o===ct)){let o={...n,entryStage:n.entryStage??nt,drawDefinition:t,event:r};fd(o)}}function yV({mainStructure:t,qualifyingDetails:e,drawDefinition:r}){for(let n of e||[]){let{finalQualifyingRoundNumber:o,finalQualifyingStructureId:i,roundTarget:s,finishingPositions:a,linkType:c}=n,u=t&&Ma({targetStructureId:t.structureId,sourceStructureId:i,sourceRoundNumber:o,finishingPositions:a,targetEntryRound:s,linkType:c})?.link;if(u?.error)return u;u&&(r.links||(r.links=[]),r.links.push(u))}return{error:void 0}}function LT(t){let{participantIds:e}=t,r=t.drawDefinition?.entries?.filter(n=>{let o=n.entryStatus;return!t.restrictEntryStatus||Qr.includes(o)}).map(St)??[];if(e){let n=e.filter(o=>!r?.includes(o));if(n?.length)return _({result:{error:mn},info:{invalidParticipantIds:n}})}else e=r;return t.roundsCount&&t.restrictRoundsCount!==!1&&t.roundsCount>e.length-1&&(!t.enableDoubleRobin||t.roundsCount>(e.length-1)*2)?{error:G,info:"Not enough participants for roundsCount"}:t.roundsCount&&t.restrictRoundsCount!==!1&&t.roundsCount>31?{error:G,info:"roundsCount must be less than 32"}:{participantIds:e}}function Yd(t){let e=[],{roundsCount:r=1,drawDefinition:n,matchUpsCount:o,structureId:i,idPrefix:s,isMock:a,event:c}=t,u,p=LT(t);if(p.error)return p;for(let m of et(1,r+1)){let d=Ou({restrictMatchUpsCount:t.restrictMatchUpsCount,ignoreLastRoundNumber:!!u,newRound:!u,drawDefinition:n,matchUpsCount:o,structureId:i,roundNumber:u,idPrefix:s,isMock:a,event:c});if(d.error)return _({result:d,info:{iteration:m}});d.matchUps?.length&&e.push(...d.matchUps),u=(d?.roundNumber??1)+1}return{matchUps:e}}function P_(t){let{tournamentRecord:e,participantIds:r,scaleName:n,eventType:o,adHocRatings:i={}}=t,s=t.scaleAccessor??we[n]?.accessor,a=e.participants??[];for(let c of r??[]){let u=a?.find(m=>m.participantId===c),p=U_({scaleName:`${n}.${Gm}`,participant:u,eventType:o});!p&&n&&(p=U_({scaleAccessor:s,participant:u,scaleName:n,eventType:o})),p&&!i[c]&&(i[c]=p)}return i}function U_({scaleType:t=gi,scaleAccessor:e,participant:r,scaleName:n,eventType:o}){let a=(r&&yo({scaleAttributes:{eventType:o??Fs,scaleType:t,scaleName:n},participant:r}))?.scaleItem?.scaleValue;return e&&ht(a)?a[e]:a}function qd(t){let e=EV(t);if(e?.error)return e;let r=LT(t);if(r.error)return r;let n=AV(t);if(n.error)return n;let o=P_(t),i=t.tournamentRecord?.isMock??t.isMock,s=t.eventType??t.event?.eventType,a=[],c=[],u;for(let p of et(1,(t.roundsCount??1)+1)){let m=Fd({...t,participantIds:r.participantIds,structure:n.structure,ignoreLastRoundNumber:!0,iterationMatchUps:a,adHocRatings:o,roundNumber:u,eventType:s,isMock:i});if(m.error)return m;let{matchUps:d,...l}=m;l.modifiedScaleValues&&(o=l.modifiedScaleValues),c.push({...l,iteration:p,matchUpsCount:d?.length}),u=(l?.roundNumber??1)+1,d?.length&&a.push(...d)}return{...C,matchUps:a,roundResults:c}}function AV(t){if(t.structureId)return t.structureId;let e=t.drawDefinition,r=e?.structures?.filter(i=>i.stageSequence===1)?.reduce((i,s)=>{let a=s.stage&&ks[s.stage];return cr({structure:s})&&a>(ks[i?.stage]||1)?s:i},void 0),n=e?.structures?.find(i=>i.structureId===r?.structureId);return n?cr({structure:n})?{structure:n}:{error:ua}:{error:kt}}function EV(t){return t.roundsCount&&typeof t.roundsCount!="number"?{error:G,info:"roundsCount must be a number"}:typeof t.drawDefinition!="object"||t.drawDefinition.drawType&&t.drawDefinition.drawType!==$r?{error:ua}:!Array.isArray(t.drawDefinition?.entries)&&t.participantIds&&!Array.isArray(t.participantIds)?{error:G,info:"Missing Entries"}:{error:void 0}}function D_(t){let{tournamentRecord:e,drawDefinition:r,structureId:n,idPrefix:o,isMock:i,event:s}=t,a=s?.entries?.filter(({entryStage:p,entryStatus:m})=>(!p||p===nt)&&m&&Qr.includes(m)),c=a?.map(St),u=a?Math.floor(a.length/2):0;if(t.automated)return UV({...t,participantIds:c});{let p=Yd({roundsCount:t.roundsCount,drawDefinition:r,matchUpsCount:u,idPrefix:o,isMock:i,event:s});if(p.error)return p;p.matchUps?.length&&bd({matchUps:p.matchUps,suppressNotifications:!0,tournamentRecord:e,drawDefinition:r,structureId:n,event:s})}return{...C}}function UV(t){let{restrictEntryStatus:e,generateMatchUps:r,structureId:n,matchUpIds:o,scaleName:i,scaleAccessor:s}=t.drawMatic??{},a=qd({...t,eventType:t.drawMatic?.eventType??t.matchUpType,generateMatchUps:r??!0,scaleAccessor:s??t.scaleAccessor,scaleName:i??t.scaleName,participantIds:t.participantIds,roundsCount:t.roundsCount,restrictEntryStatus:e,structureId:n,matchUpIds:o});return a.error?a:(a?.matchUps?.length&&bd({tournamentRecord:t.tournamentRecord,drawDefinition:t.drawDefinition,suppressNotifications:!0,matchUps:a.matchUps,event:t.event,structureId:n}),{...C})}function N_({requireParticipantCount:t=!0,enforcePolicyLimits:e=!0,drawSizeProgression:r,participantsCount:n,participantCount:o,appliedPolicies:i,drawDefinition:s,seedingProfile:a,structureId:c,seedsCount:u}){n=n??o;let p=at({drawDefinition:s,structureId:c});if(p.error)return p;let m=p.structure;if(!m)return{error:kt};let{positionAssignments:d}=Se({structure:m}),l=d?.length||0;if(u>l)return{error:xA};let f=m.structures?.length,g=It(a?.groupSeedingThreshold)&&a?.groupSeedingThreshold,I=fg({roundRobinGroupsCount:f,drawSize:l})?.seedGroups,{seedsCount:h}=vu({policyDefinitions:i,requireParticipantCount:t,drawSizeProgression:r,participantsCount:n,drawSize:l});return h&&i?.[xn]&&u>h&&e&&(u=h),m.seedLimit=u,m.seedAssignments=et(1,u+1).map(S=>{let T=I?.find(U=>U.includes(S)),y=T&&Math.min(...T),P=g&&S>=g?y:S;return{participantId:void 0,seedNumber:S,seedValue:P}}),Ot({drawDefinition:s,structureIds:[c]}),{...C,seedLimit:u}}function ta({sortDescending:t=!1,tournamentRecord:e,scaleAttributes:r,scaleSortMethod:n,stageSequence:o,entries:i,event:s,stage:a}){if(!e)return{error:Y};return i=i??s?.entries??[],{scaledEntries:i.filter(d=>(!a||!d.entryStage||d.entryStage===a)&&(!o||!d.entryStageSequence||d.entryStageSequence===o)&&Qr.includes(d.entryStatus)).map(d=>{let{participantId:l}=d,{scaleItem:f}=Nc({tournamentRecord:e,scaleAttributes:r,participantId:l});return{...d,...f}}).filter(d=>{let l=d.scaleValue;return!n&&(isNaN(l)||!parseFloat(l))?!1:l}).sort(n||p)};function p(d,l){return t?m(l)-m(d):m(d)-m(l)}function m(d){return parseFloat(d.scaleValue||(t?-1:1e5))}}function FT(t){let e="prepareStage",{drawDefinition:r}=t,{structures:n}=gn({stageSequence:t.stageSequence||1,roundTarget:t.roundTarget,stage:t.stage,drawDefinition:r}),o=t.preparedStructureIds||[],i=n?.find(({structureId:l})=>!o.includes(l));if(!i)return _({result:{error:kt},stack:e});let s=i?.structureId,{seedsCount:a,stageEntries:c,seedLimit:u}=vV({...t,structureId:s});(t.seededParticipants||t.event||t.seedingScaleName)&&NV({...t,seedsCount:a,structure:i,structureId:s});let p=t.automated!==!1&&t.drawType!==$r&&!(t.qualifyingOnly&&t.stage!==ct),m=(n?.length||0)>1,d=p?DV({...t,multipleStructures:m,seedLimit:u,structureId:s}):{};return d?.error?_({result:d,stack:e}):{...d,stageEntries:c,structureId:s,seedsCount:a}}function PV({entries:t,stage:e,stageSequence:r,roundTarget:n}){return t.filter(o=>{let i=dt({name:Mn,element:o})?.extension?.value;return(!o.entryStage||o.entryStage===e)&&(!r||!o.entryStageSequence||o.entryStageSequence===r)&&(!n||!i||i===n)&&ri.includes(o.entryStatus)})}function DV(t){let e=typeof t.automated=="object"&&t.automated.seedsOnly,r=Sc({...t,seedsOnly:e});if(r.error)return r;let n=r?.positionAssignments,o=r?.positioningReport;return{conflicts:r.conflicts,positionAssignments:n,positioningReport:o}}function NV(t){let{seededParticipants:e,seedingScaleName:r,entries:n,event:o}=t,i=n.map(St);e?MV({...t,enteredParticipantIds:i}):(o||r)&&RV({...t,enteredParticipantIds:i})}function MV(t){let{provisionalPositioning:e,enteredParticipantIds:r,seededParticipants:n,tournamentRecord:o,appliedPolicies:i,drawDefinition:s,seedingProfile:a,structureId:c,structure:u,event:p}=t,m=u?Ts({provisionalPositioning:e,appliedPolicies:i,drawDefinition:s,seedingProfile:a,structure:u}):void 0;n.filter(({participantId:d})=>r.includes(d)).filter(d=>!d.seedNumber||d.seedNumber<=n.length).sort((d,l)=>d.seedNumber<l.seedNumber?-1:d.seedNumber<l.seedNumber?1:0).forEach(d=>{let{participantId:l,seedNumber:f,seedValue:g}=d;$s({provisionalPositioning:e,tournamentRecord:o,drawDefinition:s,seedingProfile:a,participantId:l,seedBlockInfo:m,structureId:c,seedNumber:f,seedValue:g,event:p})})}function RV(t){let e=t.seedsCount,{provisionalPositioning:r,enteredParticipantIds:n,seedAssignmentProfile:o,assignSeedsCount:i,tournamentRecord:s,drawDefinition:a,seedByRanking:c,seedingProfile:u,structureId:p,event:m}=t,{categoryName:d,ageCategoryCode:l}=m?.category||{},f=m?.eventType,g=CV({...t,ageCategoryCode:l,categoryName:d,eventType:f})||c&&bV({...t,ageCategoryCode:l,categoryName:d,eventType:f}),I=g?.length??0;I<e&&(e=I),g?.filter(({participantId:h})=>n.includes(h)).slice(0,i||e).forEach((h,S)=>{let T=S+1,{participantId:y,scaleValue:P}=h,U=o?.[T]||P||T;$s({provisionalPositioning:r,tournamentRecord:s,drawDefinition:a,seedingProfile:u,participantId:y,structureId:p,seedNumber:T,seedValue:U,event:m})})}function CV(t){let{tournamentRecord:e,seedingScaleName:r,stageSequence:n,entries:o,stage:i,event:s}=t,{categoryName:a,ageCategoryCode:c}=s?.category||{},u=s?.eventType,p={scaleName:r||a||c||s.eventId,scaleType:ho,eventType:u};return ta({scaleAttributes:p,tournamentRecord:e,stageSequence:n,entries:o,stage:i}).scaledEntries}function bV(t){let{tournamentRecord:e,stageSequence:r,event:n,entries:o,stage:i}=t,{categoryName:s,ageCategoryCode:a}=n?.category||{},c=n?.eventType;return ta({scaleAttributes:{scaleName:s||a,scaleType:fi,eventType:c},tournamentRecord:e,stageSequence:r,entries:o,stage:i}).scaledEntries}function vV(t){let{seedsCount:e}=t;t.seededParticipants&&(e=t.seededParticipants.length),e>t.drawSize&&(e=t.drawSize);let r=PV(t);e>r.length&&(e=r.length);let{seedLimit:n}=N_({enforcePolicyLimits:t.enforcePolicyLimits??!0,appliedPolicies:t.appliedPolicies,participantsCount:r.length,seedingProfile:t.seedingProfile,drawDefinition:t.drawDefinition,structureId:t.structureId,seedsCount:e});return n&&n<e&&(e=n),{seedsCount:e,stageEntries:r,seedLimit:n}}function M_(t){let e=wd({...t,modifyOriginal:!1});if(e.error)return e;let r=e.drawDefinition,{suppressDuplicateEntries:n=!0,ignoreStageSpace:o,appliedPolicies:i,qualifyingOnly:s,seedingProfile:a,participants:c,drawEntries:u,placeByes:p,drawSize:m,drawType:d,entries:l}=t,f=[],g=[],I=OV({suppressDuplicateEntries:n,ignoreStageSpace:o,drawDefinition:r,drawEntries:u,drawType:d,entries:l});if(I.error)return I;let h=d===ki?0:pt(t.seedsCount??0),S=FT({...t,qualifyingOnly:!m||s,appliedPolicies:i,drawDefinition:r,seedingProfile:a,participants:c,stage:nt,seedsCount:h,placeByes:p,drawSize:m,entries:l});if(S.error&&!S.conflicts)return S;S.positioningReport?.length&&f.push({[nt]:S.positioningReport});let T=S.structureId;return S.conflicts&&(g=S.conflicts),d===$r&&t.roundsCount&&D_({...t,drawDefinition:r,structureId:T}),{drawDefinition:r,positioningReports:f,conflicts:g,structureId:T}}function OV(t){let{ignoreStageSpace:e,drawDefinition:r,drawEntries:n,drawType:o,entries:i}=t;for(let s of i){if(n&&s.entryStage&&s.entryStage!==nt)continue;let a={...s,ignoreStageSpace:e??o===$r,entryStage:s.entryStage??nt,event:t.event,drawDefinition:r,drawType:o},c=fd(a);if(n&&c.error)return c}return{error:void 0}}var _V=()=>({matchUpType:void 0,drawName:void 0,drawId:void 0,structures:[],entries:[],links:[]});var R_=_V;function C_(t){let{drawId:e=Dt(),processCodes:r,matchUpType:n,drawType:o}=t??{},i=R_();return Object.assign(i,{processCodes:r,matchUpType:n,drawType:o,drawId:e})}function $d(t){let e=t.structureIds,{tournamentRecord:r,drawDefinition:n,matchUpFormat:o,structureId:i,matchUpId:s,event:a}=t,c=rt(t,[{[Ve]:!0,[Lm]:!0}]);if(c.error)return c;if(!Pr({matchUpFormat:o}))return{error:qa};let u="setMatchUpFormat";if(s){let p=Bt({drawDefinition:n,matchUpId:s,event:a});if(p.error)return p;let m=p.matchUp;if(m?.matchUpType===_e)return{info:"Cannot set matchUpFormat when { matchUpType: TEAM }",error:dr};m&&(m.matchUpFormat=o,gt({tournamentId:r?.tournamentId,eventId:a?.eventId,context:u,drawDefinition:n,matchUp:m}))}else if(Array.isArray(e)){if(a?.eventType===_e)return{error:Bn};for(let p of e){let m=at({drawDefinition:n,structureId:p});if(m.error)return m;m.structure&&(m.structure.matchUpFormat=o)}}else if(i){if(a?.eventType===_e)return{error:Bn};let p=at({drawDefinition:n,structureId:i});if(p.error)return p;p.structure&&(p.structure.matchUpFormat=o)}else n&&(n.matchUpFormat=o);return e=e??(i?[i]:void 0),Ot({drawDefinition:n,structureIds:e}),{...C}}function b_({tieFormat:t}){let e=ar({checkCollectionIds:!1,tieFormat:t});if(e.error)return e;for(let r of t.collectionDefinitions)r.collectionId||(r.collectionId=Dt());return{tieFormat:t}}function v_({tournamentRecord:t,drawDefinition:e,matchUpFormat:r,matchUpType:n,tieFormat:o,event:i}){if((r||o)&&!(r&&i?.matchUpFormat===r||i?.tieFormat&&o&&JSON.stringify(i.tieFormat)===JSON.stringify(o))){if(o){let a=b_({tieFormat:o});if(a.error)return a;e.tieFormat=a.tieFormat??o}else if(r){let a=$d({tournamentRecord:t,drawDefinition:e,matchUpFormat:r,event:i});if(a.error)return{info:"matchUpFormat or tieFormat error",error:a.error}}n&&(e.matchUpType=n)}return{error:void 0}}var nN={};Xt(nN,{attachPolicies:()=>Qi,findPolicy:()=>ei,getAppliedPolicies:()=>yt,getPolicyDefinitions:()=>vo,mutate:()=>eN,query:()=>rN,removePolicy:()=>tN});var eN={};Xt(eN,{attachPolicies:()=>Qi,removePolicy:()=>tN});function tN(t){let e=rt(t,[{[nb]:!0,_anyOf:{[Re]:!1,[ie]:!1,[Ve]:!1,[Do]:!1}}]);if(e.error)return e;let r,n=t.drawDefinition??t.event??((t.tournamentId||!t.tournamentRecords)&&t.tournamentRecord);if(n)return O_(t,n);if(t.tournamentRecords){let o=Object.keys(t.tournamentRecords);if(!o.length)return{error:Y};for(let i of o){let s=t.tournamentRecords[i],a=O_(t,s);if(a.error)return a;r=!0}}else return{error:Y};return r?{...C}:{error:Fc}}function O_(t,e){let r=yt(t).appliedPolicies??{};return r[t.policyType]?(delete r[t.policyType],Object.keys(r).length?At({element:e,extension:{name:nu,value:r}}):gr({element:e,name:nu}),{...C}):{error:Fc}}var rN={};Xt(rN,{findPolicy:()=>ei,getAppliedPolicies:()=>yt,getPolicyDefinitions:()=>vo});var oN={[xn]:{validSeedPositions:{ignore:!0},duplicateSeedNumbers:!0,drawSizeProgression:!0,seedingProfile:{drawTypes:{[Io]:{positioning:mi},[Nn]:{positioning:mi}},positioning:QC},policyName:"USTA SEEDING",seedsCountThresholds:[{drawSize:4,minimumParticipantCount:3,seedsCount:2},{drawSize:16,minimumParticipantCount:12,seedsCount:4},{drawSize:32,minimumParticipantCount:24,seedsCount:8},{drawSize:64,minimumParticipantCount:48,seedsCount:16},{drawSize:128,minimumParticipantCount:96,seedsCount:32},{drawSize:256,minimumParticipantCount:192,seedsCount:64}]}},Wg=oN;function __({appliedPolicies:t,policyDefinitions:e,drawDefinition:r,stack:n}){if(e&&typeof e!="object")return _({info:"policyDefinitions must be an object",result:{error:G},stack:n});let o={[ru]:t?.[ru]};return e?xV({policyDefinitions:e,appliedPolicies:t,policiesToAttach:o,drawDefinition:r}):o.avoidance&&Qi({drawDefinition:r,policyDefinitions:o}),!t?.[xn]&&!e?.[xn]&&(Qi({policyDefinitions:Wg,drawDefinition:r}),t&&Object.assign(t,Wg)),{error:void 0}}function xV({policyDefinitions:t,appliedPolicies:e,policiesToAttach:r,drawDefinition:n}){for(let o of Object.keys(t))JSON.stringify(e?.[o])!==JSON.stringify(t[o])&&(r[o]=t[o]);Object.keys(r).length&&(Qi({policyDefinitions:r,drawDefinition:n}),e&&Object.assign(e,r))}function x_(t){let{tournamentRecord:e,matchUpFormat:r,appliedPolicies:n,policyDefinitions:o,matchUpType:i,tieFormat:s,drawType:a,stack:c,event:u}=t,p=t.drawId?u?.drawDefinitions?.find(h=>h.drawId===t.drawId):void 0;p&&a!==p.drawType&&(p.drawType=a);let m=p??C_({processCodes:t.processCodes,drawId:t.drawId,drawType:a}),d=v_({tournamentRecord:e,drawDefinition:m,matchUpFormat:r,matchUpType:i,tieFormat:s,event:u});if(d.error)return _({result:d,stack:c});let l=__({appliedPolicies:n,policyDefinitions:o,drawDefinition:m,stack:c});if(l.error)return l;let f=p?.structures?.find(h=>h.stage===nt&&h.stageSequence===1)?.structureId,g=p?p.structures?.filter(h=>h.stage===ct):[],I=g?.length===1&&!g[0].matchUps?.length&&g[0].structureId;return{drawDefinition:m,structureId:f,existingDrawDefinition:p,existingQualifyingPlaceholderStructureId:I}}function w_(t){let e="generateOrGetExisting",r=[],n=[],o=x_(t);if(o.error)return _({result:o,stack:e});let i=o.existingDrawDefinition,s=o.drawDefinition??{},a=o.structureId,c=t.drawEntries??t.eventEntries??[],u=o.existingQualifyingPlaceholderStructureId&&E_({...t,...o})||M_({...t,...o,entries:c});return u.error?_({result:u,stack:e}):(u.positioningReports?.length&&r.push(...u.positioningReports??[]),u.conflicts?.length&&n.push(...u.conflicts??[]),s=u.drawDefinition,a=u.structureId,{existingDrawDefinition:i,positioningReports:r,drawDefinition:s,structureId:a,conflicts:n,entries:c})}function L_(t){let{qualifyingPlaceholder:e,qualifyingProfiles:r,existingDrawDefinition:n,positioningReports:o,appliedPolicies:i,qualifyingOnly:s,drawDefinition:a,seedingProfile:c,participants:u,structureId:p,entries:m,stack:d}=t,l=e&&!r?.length&&!n,f=[];if(r){let g=(T,y)=>T.stageSequence-y.stageSequence,I=(T,y)=>T.roundTarget-y.roundTarget,h=[],S=1;r.sort(I);for(let T of r){if(!Array.isArray(T.structureProfiles))return _({info:ii("structureProfiles"),result:{error:st},stack:d});S=T.roundTarget||S;let y=T.structureProfiles?.sort(g)||[],P=1;for(let U of y){let{qualifyingRoundNumber:E,qualifyingPositions:A,seededParticipants:N,seedingScaleName:D,seedsCount:M=0,seedByRanking:R,placeByes:b,drawSize:v}=U,O=FT({...t,seedingProfile:U.seedingProfile??c,stageSequence:P,qualifyingRoundNumber:E,preparedStructureIds:h,qualifyingPositions:A,seededParticipants:N,stage:ct,seedingScaleName:D,appliedPolicies:i,drawDefinition:a,qualifyingOnly:s,seedByRanking:R,participants:u,roundTarget:S,seedsCount:M,placeByes:b,drawSize:v,entries:m});if(O.error)return O;O.structureId&&h.push(O.structureId),P+=1,O.conflicts?.length&&f.push(...O.conflicts),O.positioningReport?.length&&o.push({[ct]:O.positioningReport})}S+=1}}else if(p&&l){let g=hn({structureName:Qe(ct),stage:ct}),{link:I}=Ma({sourceStructureId:g.structureId,targetStructureId:p,sourceRoundNumber:0,linkType:to});a.structures||(a.structures=[]),a.structures.push(g),a.links||(a.links=[]),a.links.push(I)}return{qualifyingConflicts:f,error:void 0}}var DN={};Xt(DN,{addGoesTo:()=>qi,allCompetitionMatchUps:()=>Un,allDrawMatchUps:()=>or,allEventMatchUps:()=>$n,allPlayoffPositionsFilled:()=>OS,allTournamentMatchUps:()=>Te,analyzeDraws:()=>Cu,analyzeMatchUp:()=>Xp,analyzeTournament:()=>KT,bulkUpdatePublishedEventIds:()=>XT,calculateWinCriteria:()=>Ps,categoryCanContain:()=>Yc,checkMatchUpIsComplete:()=>ds,checkValidEntries:()=>_d,compareTieFormats:()=>$o,competitionScheduleMatchUps:()=>Fu,courtGridRows:()=>nl,credits:()=>F_,drawMatchUps:()=>fy,eventMatchUps:()=>al,filterMatchUps:()=>Ni,filterParticipants:()=>yu,findDrawDefinition:()=>oT,findExtension:()=>dt,findVenue:()=>Wo,getAggregateTeamResults:()=>$T,getAllDrawMatchUps:()=>se,getAllEventData:()=>JT,getAllStructureMatchUps:()=>Ut,getAllowedDrawTypes:()=>Kd,getAllowedMatchUpFormats:()=>WT,getAppliedPolicies:()=>yt,getAssignedParticipantIds:()=>Ri,getAvailableMatchUpsCount:()=>vd,getAvailablePlayoffProfiles:()=>Pu,getCategoryAgeDetails:()=>Ls,getCheckedInParticipantIds:()=>us,getCompetitionDateRange:()=>Qd,getCompetitionMatchUps:()=>Qp,getCompetitionParticipants:()=>kT,getCompetitionPenalties:()=>jT,getCompetitionVenues:()=>$p,getCourtInfo:()=>ud,getCourts:()=>gy,getDrawData:()=>Zd,getDrawDefinitionTimeItem:()=>zh,getDrawParticipantRepresentativeIds:()=>rT,getDrawStructures:()=>gn,getDrawTypeCoercion:()=>bu,getEligibleVoluntaryConsolationParticipants:()=>eT,getEntriesAndSeedsCount:()=>ol,getEvent:()=>Sy,getEventData:()=>tl,getEventMatchUpFormatTiming:()=>iy,getEventProperties:()=>Iy,getEventPublishStatus:()=>Xr,getEventStructures:()=>Ig,getEventTimeItem:()=>du,getEvents:()=>hy,getFlightProfile:()=>Ht,getHomeParticipantId:()=>uy,getLinkedTournamentIds:()=>iu,getMatchUpCompetitiveProfile:()=>gu,getMatchUpContextIds:()=>py,getMatchUpDailyLimits:()=>ul,getMatchUpDailyLimitsUpdate:()=>sy,getMatchUpDependencies:()=>sn,getMatchUpFormat:()=>my,getMatchUpFormatTiming:()=>Iu,getMatchUpFormatTimingUpdate:()=>ny,getMatchUpScheduleDetails:()=>pd,getMatchUpType:()=>md,getMatchUpsMap:()=>Ne,getMatchUpsStats:()=>dy,getMatchUpsToSchedule:()=>el,getMaxEntryPosition:()=>ey,getModifiedMatchUpFormatTiming:()=>il,getPairedParticipant:()=>In,getParticipantEventDetails:()=>GT,getParticipantIdFinishingPositions:()=>nT,getParticipantMembership:()=>VT,getParticipantResults:()=>Mu,getParticipantScaleItem:()=>Nc,getParticipantSchedules:()=>BT,getParticipantSignInStatus:()=>HT,getParticipantTimeItem:()=>Qh,getParticipants:()=>Gt,getPersonRequests:()=>bi,getPolicyDefinitions:()=>vo,getPositionAssignments:()=>Gp,getPositionsPlayedOff:()=>yc,getPredictiveAccuracy:()=>cy,getProfileRounds:()=>rl,getPublishState:()=>gs,getRoundMatchUps:()=>Ke,getRounds:()=>ly,getScaleValues:()=>la,getScaledEntries:()=>ta,getScheduledRoundsDetails:()=>Lu,getSchedulingProfile:()=>Ko,getSchedulingProfileIssues:()=>ty,getSeedingThresholds:()=>ES,getSeedsCount:()=>vu,getStructureSeedAssignments:()=>on,getTeamLineUp:()=>ms,getTieFormat:()=>QT,getTimeItem:()=>rn,getTournamentIds:()=>Ip,getTournamentInfo:()=>Us,getTournamentPenalties:()=>zd,getTournamentPersons:()=>qT,getTournamentPoints:()=>Xd,getTournamentPublishStatus:()=>Su,getTournamentStructures:()=>vS,getTournamentTimeItem:()=>Jm,getValidGroupSizes:()=>Cp,getVenueData:()=>dc,getVenuesAndCourts:()=>Ao,isAdHoc:()=>cr,isCompletedStructure:()=>si,isValidForQualifying:()=>hT,isValidMatchUpFormat:()=>Pr,matchUpActions:()=>Od,participantScaleItem:()=>yo,participantScheduledMatchUps:()=>ay,positionActions:()=>IT,publicFindCourt:()=>lS,publicFindVenue:()=>dS,tallyParticipantResults:()=>Ca,tieFormatGenderValidityCheck:()=>Mm,tournamentMatchUps:()=>cl,validMatchUp:()=>Zf,validMatchUps:()=>Vr,validateCollectionDefinition:()=>qc,validateLineUp:()=>Td});function F_(){return`
|
|
@@ -23,5 +23,5 @@ var oL=Object.defineProperty;var Xt=(t,e)=>{for(var r in e)oL(t,r,{get:e[r],enum
|
|
|
23
23
|
`}var iN={};Xt(iN,{filterParticipants:()=>yu,getCompetitionParticipants:()=>kT,getPairedParticipant:()=>In,getParticipantEventDetails:()=>GT,getParticipantMembership:()=>VT,getParticipantScaleItem:()=>Nc,getParticipantSchedules:()=>BT,getParticipantSignInStatus:()=>HT,getParticipantTimeItem:()=>Qh,getParticipants:()=>Gt,getScaleValues:()=>la,participantScaleItem:()=>yo,validateLineUp:()=>Td});function kT(t){let{tournamentRecords:e}=t||{};if(typeof e!="object"||!Object.keys(e).length)return{error:wt};let r=[],n={},o={},i={},s=[],a={},c=[];for(let u of Object.values(e)){let{participantIdsWithConflicts:p,mappedMatchUps:m,participantMap:d,participants:l,matchUps:f,derivedEventInfo:g,derivedDrawInfo:I}=Gt({...t,tournamentRecord:u});Object.assign(a,m),Object.assign(n,d),Object.assign(o,g),Object.assign(i,I),r.push(...l??[]),s.push(...f??[]),p?.forEach(h=>{c.includes(h)||c.push(h)})}return{participantIdsWithConflicts:c,derivedEventInfo:o,derivedDrawInfo:i,participantMap:n,mappedMatchUps:a,participants:r,...C,matchUps:s}}function GT({tournamentRecord:t,participantId:e}){if(!t)return{error:Y};if(!e)return{error:oe};let r=[e].concat((t.participants??[]).filter(o=>o?.participantType&&[Lt,ft].includes(o.participantType)&&o.individualParticipantIds?.includes(e)).map(o=>o.participantId));return{eventDetails:(t.events??[]).filter(o=>{let i=(o?.entries??[]).map(s=>s.participantId);return Fe(i,r)}).map(o=>({eventName:o.eventName,eventId:o.eventId}))}}function VT({tournamentRecord:t,participantId:e}){if(!t)return{error:Y};if(!e)return{error:oe};let{participants:r}=Gt({participantFilters:{participantTypes:[Lt,ft,zr]},tournamentRecord:t});return(r??[]).filter(o=>o.individualParticipantIds?.includes(e)).reduce((o,i)=>{let s=i.participantType;return s&&(o[s]||(o[s]=[]),o[s].push(i)),o},{})}function BT({participantFilters:t={},tournamentRecord:e}){if(!e)return{error:Y};if(typeof t!="object")return{error:lo,context:{participantFilters:t}};let r={eventIds:t.eventIds},n=Te({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=sn({tournamentRecord:e,matchUps:n}).sourceMatchUpIds??[],a={};for(let p of i){let{sides:m}=p,d,l=m?.map(g=>{if(g.participant)return[g.participant].concat(...g.participant.individualParticipants||[]);s[p.matchUpId]&&!d&&(d=(s[p.matchUpId]||[]).map(I=>o[I]).filter(({winningSide:I,bye:h})=>!I&&!h))}).filter(Boolean).flat()??[];for(let g of l){let{participantId:I}=g;a[I]||(a[I]={potentialMatchUps:[],participant:g,matchUps:[]}),a[I].matchUps.push(p)}let f=d?.map(({sides:g})=>g).flat().map(({participant:g})=>g&&[g].concat(...g.individualParticipants||[])).filter(Boolean).flat()||[];for(let g of f){let{participantId:I}=g;a[I]||(a[I]={potentialMatchUps:[],participant:g,matchUps:[]}),a[I].potentialMatchUps.push(p)}}return{participantSchedules:Object.values(a).filter(({participant:p})=>!(t.participantIds&&!t.participantIds.includes(p.participantId)||t.participantTypes&&!t.participantTypes.includes(p.participantType))),...C}}function HT({tournamentRecord:t,participantId:e}){if(!t)return{error:Y};if(!e)return{error:oe};let{participant:r}=To({tournamentRecord:t,participantId:e});if(!r)return{error:te};let{timeItem:n}=rn({itemType:sc,element:r});return n&&n.itemValue===pu&&pu}var aN={};Xt(aN,{analyzeDraws:()=>Cu,analyzeTournament:()=>KT,getAggregateTeamResults:()=>$T,getAllowedDrawTypes:()=>Kd,getAllowedMatchUpFormats:()=>WT,getAppliedPolicies:()=>yt,getCompetitionDateRange:()=>Qd,getCompetitionPenalties:()=>jT,getPolicyDefinitions:()=>vo,getTournamentInfo:()=>Us,getTournamentPenalties:()=>zd,getTournamentPersons:()=>qT,getTournamentPoints:()=>Xd,getTournamentStructures:()=>vS,getTournamentTimeItem:()=>Jm});function WT({tournamentRecord:t,categoryName:e,categoryType:r}){if(!t)return{error:Y};let{appliedPolicies:n}=yt({tournamentRecord:t});return(n?.[en]?.matchUpFormats||[]).filter(({categoryNames:s,categoryTypes:a})=>!e&&!a||e&&s?.includes(e)||r&&a?.includes(r))}function Kd({tournamentRecord:t,categoryName:e,categoryType:r}){if(!t)return{error:Y};let{appliedPolicies:n}=yt({tournamentRecord:t});return(n?.[Vm]?.allowedDrawTypes||[]).filter(({categoryNames:s,categoryTypes:a})=>!e&&!a||e&&s?.includes(e)||r&&a?.includes(r))}function zd({tournamentRecord:t}){if(!t)return{error:Y};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 jT({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:wt};let e=[];for(let r of Object.values(t)){let{penalties:n}=zd({tournamentRecord:r});e.push(...n??[])}return{penalties:e}}function YT({event:t}){return{eventInfo:(({eventId:r,eventName:n,eventType:o,eventLevel:i,surfaceCategory:s,matchUpFormat:a,category:c,gender:u,startDate:p,endDate:m,ballType:d,discipline:l,onlineResources:f,notes:g})=>({eventId:r,eventName:n,eventType:o,eventLevel:i,surfaceCategory:s,matchUpFormat:a,category:c,gender:u,startDate:p,endDate:m,ballType:d,discipline:l,onlineResources:f,notes:g}))(t)}}var wV={[Vs]:{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}}}},k_=wV;function Us(t){let{tournamentRecord:e}=t??{};if(!e)return{error:Y};let r=(({tournamentId:c,tournamentRank:u,tournamentStatus:p,formalName:m,tournamentName:d,promotionalName:l,onlineResources:f,localTimeZone:g,activeDates:I,startDate:h,endDate:S,hostCountryCode:T,venues:y,notes:P,updatedAt:U})=>({tournamentId:c,tournamentRank:u,tournamentStatus:p,formalName:m,tournamentName:d,promotionalName:l,onlineResources:f,localTimeZone:g,activeDates:I,startDate:h,endDate:S,hostCountryCode:T,venues:y,notes:P,updatedAt:U}))(e),o=Gt({participantFilters:{participantRoles:[oP,ag,iP,sP,cP]},policyDefinitions:k_,tournamentRecord:e})?.participants??[];o&&(r.tournamentContacts=o);let i=gs({tournamentRecord:e})?.publishState,s=i?.tournament?.status?.publishedEventIds||[],a=[];for(let c of e.events??[])if(!t?.usePublishState||s.includes(c.eventId)){let u=YT({event:c}).eventInfo;u&&a.push(u)}return r.timeItemValues=ZS({element:e}),r.publishState=i?.tournament,r.eventInfo=a,{tournamentInfo:J(ot(r),!1,!0),...C}}function Qd({tournamentRecords:t}){if(!ht(t))return{error:wt};let r=Object.keys(t??{}).reduce((i,s)=>{let a=t[s],{tournamentInfo:{startDate:c,endDate:u}}=Us({tournamentRecord:a}),p=c&&new Date(Et(c));(!i.startDate||p&&p<i.startDate)&&(i.startDate=p);let m=u&&new Date(Et(u));return(!i.endDate||m&&m>i.endDate)&&(i.endDate=m),i},{startDate:void 0,endDate:void 0}),n=r.startDate&&Et(r.startDate.toISOString()),o=r.endDate&&Et(r.endDate.toISOString());return!n||!o?{error:ZA}:{startDate:n,endDate:o}}function qT({tournamentRecord:t,participantFilters:e}){if(!t)return{error:Y};let r=t.participants||[];e&&(r=yu({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 $T(t){let e=rt(t,[{[ie]:!0}]);if(e.error)return e;let r=t.finishingPositionRangeBounsPoints||{},n={},o=m=>{let d=m?.individualParticipants?.map(l=>l.teams?.length===1&&l.teams[0]);return m?.teams?.length===1&&m?.teams?.[0]||d?.[0].participantId===d?.[1].participantId&&d?.[0]},{matchUps:i,participants:s}=Gt({participantFilters:{participantTypes:[Tt]},withRankingProfile:!0,withStatistics:!0,...t});for(let m of s??[]){if(m.participantType===yr)continue;m.draws?.[0]?.drawId==="draw-0-3"&&console.log(m.participantType,m.draws[0].finishingPositionRange);let d=o(m);if(d)for(let l of m?.draws??[]){let f=l?.finishingPositionRange?.join("-");if(f&&r?.[f]){let g=d?.participantId,I=l?.drawId,h=`${g}|${I}|${f}`;n[h]=r[f]}}}let a=m=>({teamName:m,standingPoints:0,pointsPlayed:0,pointsPct:0,points:0,bonus:0,diff:0,loss:0,win:0}),c=(m,d,l)=>{m[d]===void 0&&(m[d]=0),m[d]+=l},u={},p={};for(let m of i??[]){let{sides:d,matchUpFormat:l}=m,f=l&&Ye(l);if(d?.length===2&&f.setFormat?.timed&&(!f.finalSetFormat||f.finalSetFormat?.timed))for(let g of d){let I=o(g.participant),h=I?.participantId,S=g.participant?.participantId,T=I?.participantName,y=g.sideNumber,P=g.participant?.individualParticipantIds||S&&[S]||[];if(P.forEach(U=>{U&&!u[U]&&(u[U]=a(T))}),h&&y){p[h]||(p[h]=a(T));let U=[...P.map(A=>u[A]),p[h]];m.winningSide&&(y===m.winningSide?U.forEach(A=>c(A,"win",1)):U.forEach(A=>c(A,"loss",1)));let E=m.score?.sets||[];for(let A of E){let N=A?.[`side${3-y}Score`]||0,D=A?.[`side${y}Score`]||0,M=D-N;U.forEach(R=>c(R,"pointsPlayed",D+N)),U.forEach(R=>c(R,"points",D)),U.forEach(R=>c(R,"diff",M))}}}}for(let m of Object.keys(n)){let[d]=m.split("|");p[d]&&(p[d].bonus+=n[m],p[d].pointsPct=parseFloat((p[d].points/p[d].pointsPlayed).toFixed(2)),p[d].standingPoints=p[d].win+p[d].bonus)}for(let m of Object.keys(u))u[m].pointsPct=parseFloat((u[m].points/u[m].pointsPlayed).toFixed(2));return{...C,individualResults:u,teamResults:p}}function G_(t){let r=t.participants?.filter(({participantType:a})=>a===Lt)?.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 KT({tournamentRecord:t}){if(!t)return{error:Y};let{drawsAnalysis:e}=Cu({tournamentRecord:t}),r={isDual:G_(t),drawsAnalysis:e},n=Gt({tournamentRecord:t});return n.missingParticipantIds?.length&&(r.missingParticipantIds=n.missingParticipantIds),{...C,analysis:r}}function zT(t,e){return t&&e&&Array.isArray(e)&&e[t-1]||typeof e=="object"&&e[t]}function V_(t){let{participation:e={},awardProfiles:r,startDate:n,eventType:o,drawSize:i,drawType:s,category:a,endDate:c,level:u}=t,{participationOrder:p,flightNumber:m,rankingStage:d}=e,l=g=>!n&&!c||!g.dateRanges?!0:g.dateRanges.some(I=>{let h=!n||!I.startDate||new Date(n)>new Date(I.startDate),S=!c||!I.endDate||new Date(c)<=new Date(I.endDate);return h&&S});return{awardProfile:r.find(g=>l(g)&&(!g.maxFlightNumber||m<=g.maxFlightNumber)&&(!g.drawTypes?.length||g.drawTypes?.includes(s))&&(!g.drawSizes?.length||g.drawSizes.includes(i))&&(!g.stages?.length||g.stages.includes(d))&&(!g.levels?.length||g.levels.includes(u))&&(!g.maxDrawSize||i<=g.maxDrawSize)&&(!g.drawSize||g.drawSize===i)&&(!g.maxLevel||u<=g.maxLevel)&&(!m||!g.flights?.flightNumbers?.length||g.flights.flightNumbers.includes(m))&&(!g.participationOrder||g.participationOrder===p)&&(!g.category?.ageCategoryCodes||g.category.ageCategoryCodes.includes(a?.ageCategoryCode))&&(!g.eventTypes?.length||g.eventTypes?.includes(o)))}}function sN({participantWon:t,flightNumber:e,valueObj:r,drawSize:n,flights:o,level:i}){let s=(f,g)=>{if(f){if(Array.isArray(g)){let I=g.find(h=>h.flight===f||h.f===f);return I.value||I.v}if(typeof g=="object"){let I=g.flights||g.f;if(Array.isArray(I))return I[f-1]}}},a=(f,g)=>{let I=f?.value||f?.v||(It(f)?f:0),h=zT(i,f?.level);return{value:s(g,h)||It(h)&&h||I}},c=0,u,p,m,d,l=t&&"won"||t===!1&&"lost"||void 0;if(Array.isArray(r)){let f=r.find(h=>h.drawSize===n||h.drawSizes?.includes(n)),g=r.find(h=>h.drawSize&&h.threshold&&n>h.drawSize),I=r.find(h=>!h.drawSize&&!h.drawSizes?.length);l!==void 0&&(f=f?.[l],g=g?.[l],I=I?.[l]),p=a(f,e).value,m=a(g,e).value,d=a(I,e).value,c=p||m||d,u=p&&f.requireWin||m&&g.requireWin||I?.requireWin}else if(typeof r=="object"){let f=r?.drawSizes?.[n],g=r;l!==void 0&&(f=f?.[l],g=g?.[l]),p=a(f,e).value,d=a(g,e).value,c=p||d,u=p?f.requireWin:g?.requireWin}else It(r)&&l===void 0&&(c=r);return e&&o?.pct?.[e]&&(c=Math.round(c*o.pct[e])),{awardPoints:c,requireWin:u}}function Xd({participantFilters:t,policyDefinitions:e,tournamentRecord:r,level:n}){if(!r)return{error:Y};let{policyDefinitions:o}=vo({policyTypes:[Rf],tournamentRecord:r}),i=e?.[Rf]??o?.[Rf];if(!i)return{error:$u};let s=i.awardProfiles,a=i.requireWinFirstRound,c=i.requireWinForPoints,{participants:u,derivedEventInfo:p,derivedDrawInfo:m,mappedMatchUps:d}=Gt({withRankingProfile:!0,participantFilters:t,tournamentRecord:r}),l=u?.filter(h=>h.draws?.length),f={},g={},I={};for(let h of l??[]){let{participantType:S,participantId:T,person:y,draws:P}=h;for(let U of P){let{drawId:E,structureParticipation:A,eventId:N}=U,D=p[N],M=m[E],R=M?.drawType,{category:b,eventType:v}=D||{},O=U.startDate||D.startDate||r.startDate,x=U.endDate||D.endDate||r.endDate;if(v===Cr&&T!==yr)continue;let F;if(s){let L=c,w=0,V=0,k=0,W;for(let H of A){let{finishingPositionRange:K,participationOrder:q,participantWon:B,flightNumber:$,rankingStage:z,winCount:j}=H;w+=j||0;let tt=M?.drawSize,{awardProfile:Q}=V_({awardProfiles:s,participation:H,eventType:v,startDate:O,category:b,drawSize:tt,drawType:R,endDate:x,level:n});if(Q){if(!tt)continue;let X=Array.isArray(K)&&Math.max(...K),lt=ut(K||[]).join("-"),it=X&&z!==ct&&K?.includes(tt);Q.requireWinForPoints!==void 0&&(L=Q.requireWinForPoints),Q.requireWinFirstRound!==void 0&&(a=Q.requireWinFirstRound);let{finishingPositionPoints:Rt={},finishingPositionRanges:Ft,finishingRound:Ue,pointsPerWin:fe,flights:Me}=Q,vr=Array.isArray(Q.perWinPoints)?Q.perWinPoints?.find(Pt=>Pt.participationOrders?.includes(q)):Q.perWinPoints,Zr=Rt.participationOrders,lr=0,Xe;if((!Zr||Zr.includes(q))&&Ft&&X){let Pt=Ft[X];Pt&&({awardPoints:lr,requireWin:Xe}=sN({flightNumber:$,valueObj:Pt,drawSize:tt,flights:Me,level:n}))}if(!lr&&Ue&&q===1&&X){let Pt=Ue[X];Pt&&({awardPoints:lr,requireWin:Xe}=sN({participantWon:B,flightNumber:$,valueObj:Pt,drawSize:tt,flights:Me,level:n}))}if(it&&a!==void 0&&(L=a),Xe!==void 0&&(L=Xe),lr>V&&(!L||j)&&(V=lr,W=X),!lr&&fe&&j&&(k+=j*fe,W=lt),!lr&&j&&vr){let Pt=zT(n,vr?.level);Pt?k+=j*Pt:vr.value&&(k+=j*vr.value)}}if(F=V+k,S===yr){let X=(h.matchUps||[]).filter(({structureId:lt})=>lt===H.structureId);for(let{matchUpId:lt}of X){let it=d[lt],Rt=it.sides.find(Ft=>Ft.participantId===T).sideNumber;if(it.winningSice===Rt)for(let Ft of it.tieMatchUps)Ft.winningSide}}}if(k||V){let H={winCount:w,positionPoints:V,rangeAccessor:W,perWinPoints:k,eventType:v,drawId:E,points:F},K=y?.personId;K?(f[K]||(f[K]=[]),f[K].push(H)):S===ft?(I[T]||(I[T]=[]),I[T].push(H)):S===yr&&(g[T]||(g[T]=[]),g[T].push(H))}}}}return{participantsWithOutcomes:l,personPoints:f,pairPoints:I,teamPoints:g,...C}}var uN={};Xt(uN,{compareTieFormats:()=>$o,getTieFormat:()=>QT,tieFormatGenderValidityCheck:()=>Mm,validateCollectionDefinition:()=>qc});function Jd(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===vi?"D":"S",p,s,u].join(";")}).join("|");return{tieFormatName:t&&r||"UNNAMED",matchUpFormats:e,tieFormatDesc:n}}function $o({considerations:t={},descendant:e,ancestor:r}){let n={},o={},{matchUpFormats:i,tieFormatDesc:s}=Jd(e),{matchUpFormats:a,tieFormatDesc:c}=Jd(r),u=ut((i??[]).filter(P=>!(a??[]).includes(P)).concat((a??[]).filter(P=>!(i??[]).includes(P)))),p=!!(t?.collectionName&&e.collectionDefinitions.map(({collectionName:P})=>P).join("|")!==r.collectionDefinitions.map(({collectionName:P})=>P).join("|")),m=!!(t?.collectionOrder&&e.collectionDefinitions.map(({collectionOrder:P})=>P).join("|")!==r.collectionDefinitions.map(({collectionOrder:P})=>P).join("|")),d=Object.assign({},...(e?.collectionDefinitions||[]).map(P=>({[P.collectionId]:P}))),l=Object.assign({},...(r?.collectionDefinitions||[]).map(P=>({[P.collectionId]:P})));n.collectionIds=PA(Object.keys(d),Object.keys(l)),o.collectionIds=PA(Object.keys(l),Object.keys(d)),n.collectionsValue=B_(d),o.collectionsValue=B_(l),n.groupsCount=r?.collectionGroups?.length??(0-(e?.collectionGroups?.length??0)||0),o.groupsCount=n.groupsCount?-1*n.groupsCount:0;let f=n.collectionsValue.totalValue-o.collectionsValue.totalValue,g=n.collectionsValue.totalMatchUps-o.collectionsValue.totalMatchUps,I=o.collectionsValue.assignmentValues.length!==n.collectionsValue.assignmentValues.length,h=o.collectionsValue.assignmentValues.some((P,U)=>{let E=n.collectionsValue.assignmentValues[U];return!E||P.valueKey!==E.valueKey||P.value!==E.value?!0:Array.isArray(P.value)?P.value.every((A,N)=>E.value[N]===A):!1}),S=p||m||c!==s||I||h||f!==0,T=[...o.collectionsValue.invalidValues,...n.collectionsValue.invalidValues],y=T.length&&T;return{matchUpFormatDifferences:u,matchUpCountDifference:g,descendantDifferences:n,ancestorDifferences:o,orderDifference:m,valueDifference:f,nameDifference:p,descendantDesc:s,ancestorDesc:c,...C,different:S,invalid:y}}function B_(t){let e=[],r=[],n=0;return{totalValue:Object.keys(t).sort(Tu).reduce((s,a)=>{let c=t[a],{collectionValueProfiles:u,collectionValue:p,matchUpCount:m,matchUpValue:d,scoreValue:l,setValue:f}=c,g={collectionValueProfiles:u,collectionValue:p,matchUpValue:d,scoreValue:l,setValue:f},I=Object.keys(g).filter(S=>![void 0,null].includes(g[S])&&(!Array.isArray(g[S])||g[S].length>0));I.length!==1&&e.push({collectionId:a});let h=I[0];if(h){let S=h==="collectionValueProfiles"?Object.values(u):g[h];r.push({valueKey:h,value:S})}return n+=m,u?.length?s+u.reduce((S,T)=>S+T.value,0):m?It(d)?s+d*m:It(l)?s+l*m:It(f)?s+f*m:s+p:s},0),totalMatchUps:n,invalidValues:e,assignmentValues:r}}function jg(t){Object.assign(t,{inContext:!0});let{matchUp:e,error:r}=cN(t);return{matchUp:J(e,!0,!0),error:r}}function cN({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:Y};if(typeof a!="string")return{error:sr};if(!i||!m){let g=(Te({tournamentRecord:r,nextMatchUps:s}).matchUps??[]).find(I=>I.matchUpId===a);if(!g)return{error:Le};({eventId:u,drawId:p}=g),{event:m,drawDefinition:i}=ze({tournamentRecord:r,eventId:u,drawId:p})}if(!i)return{error:Mr};o&&!n&&(n=qn({tournamentRecord:r,contextProfile:o}));let d={surfaceCategory:m?.surfaceCategory??r.surfaceCategory,indoorOutDoor:m?.indoorOutdoor??r.indoorOutdoor,endDate:m?.endDate??r.endDate,tournamentId:r.tournamentId,eventId:u??m?.eventId,drawId:p},{participants:l=[]}=Ai({participantsProfile:t,tournamentRecord:r,contextProfile:o,inContext:c});if(s){let g=(or({context:c?d:void 0,participants:l,afterRecoveryTimes:e,contextContent:n,contextProfile:o,drawDefinition:i,nextMatchUps:s,inContext:c,event:m}).matchUps??[]).find(h=>h.matchUpId===a);if(!g)return{error:Le};let I=i?.structures?.find(h=>h.structureId===g.structureId);return{drawDefinition:i,structure:I,matchUp:g}}else{let{matchUp:f,structure:g}=Bt({context:c?d:void 0,tournamentParticipants:l,afterRecoveryTimes:e,contextContent:n,drawDefinition:i,contextProfile:o,matchUpId:a,inContext:c,event:m});return{matchUp:f,structure:g,drawDefinition:i}}}function QT({tournamentRecord:t,drawDefinition:e,structureId:r,matchUpId:n,structure:o,eventId:i,drawId:s,event:a}){if(!t)return{error:Y};if(!s&&!a&&!r&&!n)return _({result:{error:st},stack:"getTieFormat"});i&&!a&&(a=t.events?.find(l=>l.eventId===i));let c=jg({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:an};let l=at({drawDefinition:e,structureId:r});if(l.error)return l;o=l.structure}let u=(o?.tieFormat||o?.tieFormatId)&&We({structure:o,drawDefinition:e,event:a})?.tieFormat,p=(e?.tieFormat||e?.tieFormatId)&&We({drawDefinition:e,event:a})?.tieFormat,m=We({event:a})?.tieFormat,d=We({matchUp:c?.matchUp,drawDefinition:e,structure:o,event:a})?.tieFormat;return{...C,matchUp:c?.matchUp,structureDefaultTieFormat:ir(u),eventDefaultTieFormat:ir(m),drawDefaultTieFormat:ir(p),tieFormat:ir(d),structure:o}}var lN={};Xt(lN,{bulkUpdatePublishedEventIds:()=>XT,getAllEventData:()=>JT,getCourtInfo:()=>ud,getDrawData:()=>Zd,getEventData:()=>tl,getEventPublishStatus:()=>Xr,getPublishState:()=>gs,getTournamentPublishStatus:()=>Su,getVenueData:()=>dc});function XT({tournamentRecord:t,outcomes:e}){if(!t)return{error:Y};if(!e?.length)return{error:st,info:"Missing outcomes"};let r=e.reduce((s,a)=>{let{drawId:c,eventId:u}=a;return u&&c&&(s[u]?s[u].includes(c)||s[u].push(c):s[u]=[c]),s},{}),n=Object.keys(r);return{publishedEventIds:(t.events?.filter(s=>n.includes(s.eventId))).filter(s=>{let a=Xr({event:s}),{drawDetails:c,drawIds:u}=a??{},{eventId:p}=s;return r[p].filter(d=>{let l=c?Object.keys(a.drawDetails).filter(f=>ld({drawId:f,drawDetails:c})):[];return u?.includes(d)||l.includes(d)}).length}).map(s=>s.eventId),eventIdPublishedDrawIdsMap:r}}function pN({dates:t=[],extension:e}){if(!e)return!1;if(typeof e.value=="boolean"&&e.value)return!0;if(!t.length)return!1;let r=ht(e.value)?e.value?.dates:void 0;if(Array.isArray(r))return r?.length?!!r.filter(o=>!t.length||t.includes(o)).length:!1}function mN({convertExtensions:t,ignoreDisabled:e,venue:r,court:n}){let o={...J(n,t,!0),venueId:r.venueId},{extension:i}=dt({name:no,element:n});if(e&&i){let s=ht(i.value)?i.value?.dates:void 0,a=i?.value===!0?[]:o.dateAvailability.map(c=>{let u=c.date;if(!(!u||s.includes(u)))return c}).filter(Boolean);o.dateAvailability=a}return{inContextCourt:o}}function Ao(t){let{convertExtensions:e,ignoreDisabled:r,venueIds:n=[],dates:o}=t,i=t.tournamentRecords||t.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord}||{},s=[],a=[],c=[],u=[];return Object.keys(i).filter(m=>!t.tournamentId||m===t.tournamentId).forEach(m=>{let d=i[m];for(let l of d.venues??[])if(!(n.length&&!n.includes(l.venueId))){if(r){let{extension:f}=dt({name:no,element:l});if(f?.value)continue}s.includes(l.venueId)||(u.push(J(l,e,!0)),s.push(l.venueId));for(let f of l.courts??[])if(!a.includes(f.courtId)){if(r){let{extension:I}=dt({name:no,element:f});if(pN({extension:I,dates:o}))continue}let{inContextCourt:g}=mN({convertExtensions:e,ignoreDisabled:r,venue:l,court:f});c.push(g),a.push(f.courtId)}}}),{courts:c,venues:u,...C}}function LV({convertExtensions:t,tournamentRecord:e,ignoreDisabled:r,dates:n}){if(!e)return{error:wt};let o=J(e.venues??[],t).filter(s=>{if(!r)return s;let{extension:a}=dt({name:no,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}=dt({name:no,element:u});return pN({extension:p,dates:n})}).filter(Boolean).map(u=>{let{inContextCourt:p}=mN({convertExtensions:t,ignoreDisabled:r,venue:a,court:u});return p});return c.length?s.concat(c):s},[]);return{venues:o,courts:i}}function $p({tournamentRecords:t,requireCourts:e,dates:r}){return typeof t!="object"||!Object.keys(t).length?{error:wt}:Object.keys(t).reduce((o,i)=>{let s=t[i],{venues:a}=LV({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 JT({tournamentRecord:t,policyDefinitions:e}){if(!t)return{error:Y};let r=t.events||[],n=t?.participants||[],{tournamentInfo:o}=Us({tournamentRecord:t}),{venues:i}=Ao({tournamentRecord:t}),s=r.map(c=>{let{eventId:u}=c,p=YT({event:c}).eventInfo,m=ya({tournamentRecord:t,event:c}).scheduleTiming,d=(c.drawDefinitions||[]).map(f=>{let g=(({drawId:y,drawName:P,matchUpFormat:U,updatedAt:E})=>({matchUpFormat:U,updatedAt:E,drawName:P,drawId:y}))(f),{abandonedMatchUps:I,completedMatchUps:h,upcomingMatchUps:S,pendingMatchUps:T}=js({requireParticipants:!0,tournamentParticipants:n,context:{eventId:u},policyDefinitions:e,tournamentRecord:t,inContext:!0,scheduleTiming:m,drawDefinition:f,event:c});return{drawInfo:g,matchUps:{abandonedMatchUps:I,completedMatchUps:h,upcomingMatchUps:S,pendingMatchUps:T}}}),l=Xr({event:c});return Object.assign(p,{drawsData:d,publish:l}),p});return{allEventData:{tournamentInfo:o,venuesData:i,eventsData:s}}}function ZT({publishStatus:t,drawId:e}){return t?.drawDetails?t.drawDetails?.[e]?.publishingDetail?.published:t?.drawIds?t.drawIds.includes(e):!0}var dN="PUBLIC",FV="ADMIN",H_={PUBLIC_DISPLAY:dN,ADMIN_DISPLAY:FV};function Zd(t){let{tournamentParticipants:e=[],includePositionAssignments:r,policyDefinitions:n,tournamentRecord:o,inContext:i=!0,usePublishState:s,status:a=Nr,pressureRating:c,refreshResults:u,drawDefinition:p,noDeepCopy:m,sortConfig:d,context:l,event:f}=t;if(!p)return{error:Z};let g=(({matchUpFormat:R,updatedAt:b,drawType:v,drawName:O,drawId:x})=>({matchUpFormat:R,updatedAt:b,drawName:O,drawType:v,drawId:x}))(p);g.display=dt({element:p,name:Wm}).extension?.value;let I={},h,{allStructuresLinked:S,sourceStructureIds:T,hasDrawFeedProfile:y,structureGroups:P}=Eu({drawDefinition:p});if(!S)return{error:BA};let U=t?.publishStatus??Xr({event:f,status:a}),E=t.eventPublished??!!gs({event:f}).publishState?.status?.published,A=!1,N=!1,M=P.map(R=>{let b={},v=R.map(O=>{let{structure:x}=at({drawDefinition:p,structureId:O}),{seedAssignments:F}=on({drawDefinition:p,structure:x});return x?.stage===nt&&x.stageSequence===1&&(h=F),x?.stage===ct&&(I[x.stageSequence??0]=F),x}).sort((O,x)=>Si(O,x,d)).map(O=>{if(!O)return;let x=O?.structureId,F=[];O.stage&&[nt,qe,de].includes(O.stage)&&(F=h),O?.stage===ct&&(F=I[O.stageSequence??0]);let{matchUps:L,roundMatchUps:w,roundProfile:V}=Ut({seedAssignments:O?.seedAssignments?.length?void 0:F,context:{drawId:g.drawId,...l},tournamentParticipants:e,policyDefinitions:n,tournamentRecord:o,usePublishState:s,publishStatus:U,drawDefinition:p,inContext:i,structure:O,event:f}),{positionAssignments:k}=bt({structure:O}),W=k?.filter(Br(ro)).map(B=>{let $=dt({element:B,name:Jo})?.extension?.value,{drawPosition:z,participantId:j}=B;return N=!0,{participantResult:$,participantId:j,drawPosition:z}});if(L.length&&(!W?.length&&t.allParticipantResults||u&&!O.structures)){let{subOrderMap:B}=KS({positionAssignments:k}),z=L.some(tt=>tt.matchUpType===xr)?L.filter(tt=>tt.matchUpType===xr):L,j=Ca({matchUpFormat:O.matchUpFormat,matchUps:z,policyDefinitions:n,pressureRating:c,subOrderMap:B});W=k?.filter(Br(ro)).map(tt=>{let{drawPosition:Q,participantId:X}=tt;return N=!0,{participantResult:X&&j?.participantResults?.[X],participantId:X,drawPosition:Q}})}let H=O?(({stageSequence:B,structureName:$,structureType:z,matchUpFormat:j,stage:tt})=>({stageSequence:B,structureName:$,structureType:z,matchUpFormat:j,stage:tt}))(O):{},K=dt({element:O,name:Wm}).extension?.value;H.display=K?.[dN]??K,H.sourceStructureIds=T[x],H.hasDrawFeedProfile=y[x],H.positionAssignments=k,H.structureActive=L.reduce((B,$)=>{let z=[he,Ce,Ln,le,oo,Mt,rr,Ct].includes($.matchUpStatus);return B||z||!!$.winningSide||!!$.score?.scoreStringSide1},!1);let q=L.reduce((B,$)=>B&&[Nt,le,rr,Ct,Mt,br].includes($.matchUpStatus),!!L.length);return H.structureCompleted=q,b[x]=q,H.structureActive&&(A=!0),{...H,participantResults:W,seedAssignments:F,roundMatchUps:w,roundProfile:V,structureId:x}});return v.forEach(O=>{r||delete O.positionAssignments,O.sourceStructuresComplete=O.sourceStructureIds?.every(x=>b[x])}),v}).flat();return g.drawActive=A,g.participantPlacements=N,g.drawGenerated=M?.reduce((R,b)=>R||!!b?.roundMatchUps,!1),g.drawCompleted=M?.reduce((R,b)=>R&&b.structureCompleted,!0),g.drawPublished=s?E&&ZT({publishStatus:U,drawId:g.drawId}):void 0,{structures:!s||g.drawPublished?m&&M||J(M,!1,!0):void 0,drawInfo:m?g:J(g,!1,!0),...C}}function tl(t){let{includePositionAssignments:e,participantsProfile:r,policyDefinitions:n,usePublishState:o,status:i=Nr,sortConfig:s}=t,a=rt(t,[{tournamentRecord:!0},{[km]:{event:!1,eventId:!1}}]);if(a.error)return a;let c=J(t.tournamentRecord,!1,!0),u=t.event?void 0:ze({tournamentRecord:c,eventId:t.eventId}).event,p=t.event?J(t.event,!1,!0):u&&J(u,!1,!0)||void 0;if(!p)return{error:jr};let{eventId:m}=p,{tournamentId:d,endDate:l}=c,f=Xr({event:p,status:i}),g=gs({event:p}).publishState??{},I=!!g?.status?.published,{participants:h}=Gt({withGroupings:!0,withEvents:!1,withDraws:!1,policyDefinitions:n,...r,tournamentRecord:c}),S=({stage:b,drawId:v})=>{if(!o)return!0;let O=f?.drawDetails?.[v]?.stageDetails;return!O||!Object.keys(O).length?!0:O[b]?.published},T=({structureId:b,drawId:v})=>{if(!o)return!0;let O=f?.drawDetails?.[v]?.structureDetails;return!O||!Object.keys(O).length?!0:O[b]?.published},y=({drawId:b})=>o?ZT({publishStatus:f,drawId:b}):!0,P=({drawId:b,structure:v})=>{if(!o)return v;let O=f?.drawDetails?.[b]?.structureDetails?.[v.structureId]?.roundLimit;if(It(O)){let x=et(1,O+1),F={},L={};for(let w of x)v.roundMatchUps[w]&&(F[w]=v.roundMatchUps[w],L[w]=v.roundProfile[w]);v.roundMatchUps=F,v.roundProfile=L}return v},U=p.drawDefinitions||[],E=!o||I?U.filter(y).map(b=>(({drawInfo:v,structures:O})=>({...v,structures:O}))(Zd({allParticipantResults:t.allParticipantResults,context:{eventId:m,tournamentId:d,endDate:l},pressureRating:t.pressureRating,refreshResults:t.refreshResults,includePositionAssignments:e,tournamentParticipants:h,noDeepCopy:!0,policyDefinitions:n,tournamentRecord:c,usePublishState:o,drawDefinition:b,publishStatus:f,sortConfig:s,event:p}))).map(({structures:b,...v})=>{let O=b?.filter(({stage:x,structureId:F})=>T({structureId:F,drawId:v.drawId})&&S({stage:x,drawId:v.drawId})).map(x=>P({drawId:v.drawId,structure:x}));return{...v,structures:O}}).filter(b=>b.structures?.length):void 0,N=(Array.isArray(c.venues)?c.venues:[]).map(b=>(({venueData:v})=>({...v}))(dc({venueId:b.venueId,tournamentRecord:c}))),D=(({eventId:b,eventName:v,eventType:O,eventLevel:x,surfaceCategory:F,matchUpFormat:L,category:w,gender:V,startDate:k,endDate:W,ballType:H,discipline:K})=>({eventId:b,eventName:v,eventType:O,eventLevel:x,surfaceCategory:F,matchUpFormat:L,category:w,gender:V,startDate:k,endDate:W,ballType:H,discipline:K}))(p);D.display=dt({element:p,name:Wm}).extension?.value;let{tournamentInfo:M}=Us({tournamentRecord:c}),R={tournamentInfo:M,venuesData:N,eventInfo:D,drawsData:E};return R.eventInfo.publishState=g,R.eventInfo.published=g?.status?.published,{...C,eventData:R,participants:h}}var hN={};Xt(hN,{courtGridRows:()=>nl,findVenue:()=>Wo,getMatchUpsToSchedule:()=>el,getPersonRequests:()=>bi,getProfileRounds:()=>rl,getScheduledRoundsDetails:()=>Lu,getSchedulingProfile:()=>Ko,getSchedulingProfileIssues:()=>ty,publicFindCourt:()=>lS});function ea({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:e,timeAfterRecovery:r,matchUp:n}){let{individualParticipantIds:o}=uu(n);r=r??n.schedule?.timeAfterRecovery;let i=u=>{t[u]||(t[u]=[]),t[u]=ut(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 el(t){let e=rt(t,[{[Df]:!0}]);if(e.error)return e;let{matchUpPotentialParticipantIds:r,dateScheduledMatchUpIds:n=[],scheduleCompletedMatchUps:o,matchUpNotBeforeTimes:i,matchUpScheduleTimes:s,orderedMatchUpIds:a,clearDate:c,matchUps:u}=t,p=s?Object.keys(s):[],m=(a??[]).map(l=>u.find(f=>f.matchUpId===l)).filter(Boolean).filter(l=>{let f=!c&&(n.includes(l.matchUpId)||p.includes(l.matchUpId)),g=[Nt,Mt,le,br,rr,Ct,he,Ce].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],ea({matchUpPotentialParticipantIds:r,matchUpNotBeforeTimes:i,matchUp:f}),l},{matchUpMap:{}}).matchUpMap:{};return{matchUpsToSchedule:m,matchUpMap:d}}function Kp({defaultRecoveryMinutes:t=0,defaultAverageMinutes:e,tournamentRecords:r,matchUpFormat:n,categoryName:o,categoryType:i,tournamentId:s,eventType:a,eventId:c}){if(!Pr({matchUpFormat:n}))return{error:qa};let u=Object.keys(r).filter(m=>!s||m===s),p;return u.forEach(m=>{if(p)return;let d=r[m],l=c?ze({tournamentRecord:d,eventId:c})?.event:void 0;return p=Iu({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 Lu(t){let e=rt(t,[{[km]:{tournamentRecords:!1,tournamentRecord:!1}},{rounds:!0,[He]:Be}]);if(e.error)return e;let{scheduleCompletedMatchUps:r,periodLength:n=30}=t,o=t.tournamentRecords||t.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord}||{};if(typeof o!="object")return{error:wt};let i={},s=[],a=[],c=t.rounds.toSorted((I,h)=>(I.sortOrder??0)-(h.sortOrder??0)),u=t.containedStructureIds??Object.assign({},...Object.values(o).map(I=>as({tournamentRecord:I}).containedStructures)),p=t.matchUps??Un({nextMatchUps:!0,tournamentRecords:o}).matchUps,m=0,d={},l={},f={};return{scheduledRoundsDetails:c.flatMap(I=>{let h=I.periodLength||n,S=[];u?.[I.structureId]?S.push(...u[I.structureId]):S.push(I.structureId);let T=p?Ni({tournamentIds:[I.tournamentId],roundNumbers:[I.roundNumber],matchUpIds:I.matchUpIds,eventIds:[I.eventId],drawIds:[I.drawId],processContext:!0,structureIds:S,matchUps:p}).sort(Mi):[],{segmentNumber:y,segmentsCount:P}=I.roundSegment||{};if(It(y)&&vn(T?.length)&&vn(P)&&y>0&&y<=P&&P<T?.length&&!I.matchUpIds?.length){let N=T.length/P,D=N*(y-1);T=T.slice(D,D+N)}let U=o[I.tournamentId],E=ze({drawId:I.drawId,tournamentRecord:U}).event,A=[];for(let N of T){let D=N.matchUpFormat;D&&(i[D]||(i[D]=[],i[D].push(N)),A.push(D))}for(let N of A){let{eventType:D,category:M}=E??{},{categoryName:R,ageCategoryCode:b}=M??{},{typeChangeRecoveryMinutes:v,recoveryMinutes:O,averageMinutes:x,error:F}=Kp({categoryName:R??b,categoryType:M?.categoryType,tournamentId:I.tournamentId,eventId:I.eventId,tournamentRecords:o,matchUpFormat:N,eventType:D});if(F)return{error:F,round:I};let L=T.filter(V=>(r||!ce.includes(V.matchUpStatus))&&V.matchUpStatus!==Nt).map(Ae);L.forEach(V=>{f[V]={typeChangeRecoveryMinutes:v,recoveryMinutes:O,averageMinutes:x},d[V]=O,l[V]=x}),a.push(...L),m=Math.max(x||0,m);let w=`${x}|${h}`;return s.includes(w)||s.push(w),{roundPeriodLength:h,recoveryMinutes:O,averageMinutes:x,matchUpIds:L,hash:w}}}),greatestAverageMinutes:m,matchUpFormatCohorts:i,recoveryMinutesMap:d,averageMinutesMap:l,orderedMatchUpIds:a,minutesMap:f,...C}}function fN({schedulingProfile:t,venueIds:e,eventIds:r,drawIds:n}){let o=[],i=t?.map(a=>{let c=Et(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 zp({tournamentRecords:t,schedulingProfile:e}){if(!e)return{valid:!0};if(!Array.isArray(e))return{valid:!1,error:G};let{venueIds:r,tournamentsMap:n}=GV({tournamentRecords:t}),o,i,s=e.every(a=>{let{scheduleDate:c,venues:u}=a;return Rr(c)?u.every(p=>{let{venueId:m,rounds:d}=p;return typeof m!="string"?(i="venueId should be a string",!1):Array.isArray(d)?r.includes(m)?!!d.every(f=>{if(!f)return i="empty round",!1;let{roundSegment:g,tournamentId:I,structureId:h,roundNumber:S,eventId:T,drawId:y}=f,U=n?.[I]?.[T]?.[y]?.[h]?.includes(S);U||(i="Invalid rounds");let{segmentNumber:E,segmentsCount:A}=g||{},N=!g||It(E)&&vn(A)&&E<=A;return N||(i="Invalid segment"),U&&N}):(o=Li,!1):(i="rounds should be an array",!1)}):!1});return!s&&!o&&(o=G),{valid:!!s,error:o,info:i}}function kV(t){let{tournamentRecord:e={},tournamentMap:r={},requireCourts:n}=t,o=[],i=[],s=[],a=[],c=(e?.venues||[]).map(({venueId:p,courts:m})=>(!n||m?.length)&&p),u=e?.tournamentId;return u&&(o.push(u),r[u]={},(e?.events||[]).forEach(m=>{let d=m.eventId;s.push(d),r[u][d]={},(m.drawDefinitions||[]).forEach(l=>{let f=l.drawId;a.push(f),r[u][d][f]={};let{structures:g}=gn({drawDefinition:l});(g||[]).forEach(I=>{let h=I.structureId,{matchUps:S}=Ut({structure:I}),{roundMatchUps:T}=Ke({matchUps:S}),y=T&&Object.keys(T).map(P=>parseInt(P));r[u][d][f][h]=y,i.push(h),I.structures?.length&&I.structures.forEach(P=>{i.push(P.structureId),r[u][d][f][P.structureId]=y})})})})),{tournamentMap:r,tournamentIds:o,structureIds:i,venueIds:c,eventIds:s,drawIds:a}}function GV(t){let e=t?.tournamentRecords&&Object.values(t?.tournamentRecords)||[],r={},{venueIds:n,eventIds:o,drawIds:i,structureIds:s,tournamentIds:a}=e.reduce((c,u)=>{let{tournamentIds:p,tournamentMap:m,structureIds:d,venueIds:l,eventIds:f,drawIds:g}=kV({tournamentRecord:u});return l.forEach(I=>{c.venueIds.includes(I)||c.venueIds.push(I)}),c.tournamentIds.push(...p),c.structureIds.push(...d),c.eventIds.push(...f),c.drawIds.push(...g),Object.assign(r,m),c},{tournamentIds:[],structureIds:[],venueIds:[],eventIds:[],drawIds:[]});return{tournamentsMap:r,tournamentIds:a,structureIds:s,venueIds:n,eventIds:o,drawIds:i}}function Ko({tournamentRecords:t,tournamentRecord:e}){if(typeof t!="object"||!Object.keys(t).length)return{error:wt};let{extension:r}=dt({element:e,name:Sa,tournamentRecords:t,discover:!0}),n=r?.value||[];if(n.length){let{venueIds:o}=$p({requireCourts:!0,tournamentRecords:t}),{eventIds:i,drawIds:s}=Mg({tournamentRecords:t}),{updatedSchedulingProfile:a,modifications:c,issues:u}=fN({schedulingProfile:n,venueIds:o,eventIds:i,drawIds:s});if(c){n=a;let p=Mc({tournamentRecords:t,tournamentRecord:e,schedulingProfile:n});return p.error?p:{schedulingProfile:n,modifications:c,issues:u}}}return{schedulingProfile:n,modifications:0}}function Mc({tournamentRecords:t,tournamentRecord:e,schedulingProfile:r}){let n=zp({tournamentRecords:t,schedulingProfile:r});return n.error?n:r?At({tournamentRecords:t,discover:!0,extension:{name:Sa,value:r}}):gr({element:e,name:Sa,tournamentRecords:t,discover:!0})}function Rc(t){let{tournamentRecord:e}=t,r=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!t.schedulingProfile){let{modifications:u,issues:p}=Ko({tournamentRecords:r,tournamentRecord:e});return{success:!u,modifications:u,issues:p}}let{venueIds:n}=$p({tournamentRecords:r}),{eventIds:o,drawIds:i}=Mg({tournamentRecords:r}),{updatedSchedulingProfile:s,modifications:a,issues:c}=fN({schedulingProfile:t.schedulingProfile,venueIds:n,eventIds:o,drawIds:i});return a?{...Mc({schedulingProfile:s,tournamentRecords:r}),modifications:a,issues:c}:{...C,modifications:a,issues:c}}function ty(t){let{scheduleDates:e=[],tournamentRecords:r,periodLength:n=30}=t??{};if(typeof r!="object")return{error:Ha};if(!Array.isArray(e))return{error:G};if(!e.every(Rr))return{error:je};let i=[],s=0,a={},{schedulingProfile:c}=Ko({tournamentRecords:r});if(!c)return{issues:i,...C};let{matchUps:u}=Un({nextMatchUps:!0,tournamentRecords:r});for(let m of c){let{scheduleDate:d,venues:l=[]}=m;if(!e?.length||e.includes(d)){for(let f of l||[])if(f){let{rounds:g}=f,I=[],{orderedMatchUpIds:h,scheduledRoundsDetails:S}=Lu({tournamentRecords:r,periodLength:n,matchUps:u,rounds:g}),{matchUpDependencies:T}=sn({tournamentRecords:r,matchUps:u}),y=P=>{let U;return S?.find((E,A)=>{let N=E.matchUpIds.includes(P);return N&&(U=A),N}),U};if(h?.forEach((P,U)=>{let E=h.slice(U+1),A=Yt(E,T?.[P]?.matchUpIds||[]);A.length&&I.push({matchUpId:P,shouldBeAfter:A})}),I.length){s+=I.length;let P=I.map(({matchUpId:U,shouldBeAfter:E})=>{let A=y(U),N=ut(E.map(y));return a[d]||(a[d]={}),a[d][A]||(a[d][A]=[]),N.forEach(D=>{a[d][A].includes(D)||a[d][A].push(D)}),{matchUpId:U,matchUpRoundIndex:A,earlierRoundIndices:N,shouldBeAfter:E}});i.push(...P)}}}}let p={matchUpIdShouldBeAfter:Object.assign({},...i.map(m=>{let{matchUpId:d,shouldBeAfter:l,earlierRoundIndices:f}=m;return{[d]:{earlierRoundIndices:f,shouldBeAfter:l}}}))};return{issuesCount:s,profileIssues:p,roundIndexShouldBeAfter:a,...C}}function bi(t){let{tournamentRecords:e,requestType:r}=t,n=rt(t,[{[Re]:!0}]);if(n.error)return n;let o={};for(let i of Object.values(e)){let{extension:s}=dt({element:i,name:ha}),a=s?.value||[];for(let c of a){let{personId:u,requests:p}=c||{};o[u]||(o[u]=[]);for(let m of p)r&&m.requestType!==r||o[u].push(m)}}return{personRequests:o,...C}}function Yg(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 ot({structureId:u,roundSegment:r,tournamentId:o,roundNumber:i,eventId:a,drawId:c,id:p})}function gN({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=Sr(e.map(({matchUpFormat:d})=>d)),m=0;return Object.keys(p).forEach(d=>{let l=p[d],f=Kp({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 W_(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 IN(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||ce.includes(m)).length||0,o=t.filter(({schedule:p,matchUpStatus:m})=>p?.scheduledDate&&p?.scheduledTime&&m!==Nt).length||0,i=e-r,s=i===n,a=i-o,c=i-o;return{unscheduledCount:a,incompleteCount:c,scheduledCount:o,completedCount:n,matchUpsCount:e,isScheduled:i===o,isComplete:s,byeCount:r}}function rl({tournamentRecords:t,schedulingProfile:e,tournamentRecord:r,withRoundId:n}){if(r&&!t){if(typeof r!="object")return{error:Ha};t={[r.tournamentId]:r}}if(e){let s=zp({tournamentRecords:t,schedulingProfile:e});if(s.error)return s}if(!e&&t){let s=Ko({tournamentRecords:t});if(s.error)return s;e=s.schedulingProfile}if(!e)return{error:ve};let o={};return{profileRounds:e.map(({venues:s,scheduleDate:a})=>s.map(({rounds:c})=>c.map(u=>{let p=Yg(u);return p.roundSegment?.segmentsCount&&(o[p.id]=p.roundSegment.segmentsCount),ot({id:n?p.id:void 0,scheduleDate:a,...p})}))).flat(1/0),segmentedRounds:o}}function nl({courtPrefix:t="C|",minRowsCount:e,courtsData:r}){if(!Array.isArray(r))return{error:G};let n=r?.reduce((s,a)=>{let c=a.matchUps||[],u=Math.max(0,...c.map(p=>p.schedule.courtOrder||0));return u>s?u:s},1),o=e?Math.max(e,n):n,i=et(0,o).map(s=>({matchUps:et(0,r.length).map(a=>{let c=r[a],{courtId:u,venueId:p}=c;return{schedule:{courtOrder:s+1,venueId:p,courtId:u}}})}));return r.forEach((s,a)=>{for(let c of s.matchUps){let u=c.schedule?.courtOrder;u&&(i[u-1].matchUps[a]=c)}}),{courtPrefix:t,rows:i.map((s,a)=>Object.assign({rowId:`rowId-${a+1}`},...s.matchUps.map((c,u)=>({[`${t}${u}`]:c}))))}}var SN={};Xt(SN,{getEntriesAndSeedsCount:()=>ol,getMaxEntryPosition:()=>ey});function ol({policyDefinitions:t,drawDefinition:e,drawSize:r,drawId:n,event:o,stage:i}){if(!o)return{error:vt};let{entries:s,stageEntries:a}=yS({drawDefinition:e,drawId:n,stage:i,event:o}),c=a.length,{drawSize:u}=ST({participantsCount:c}),p=vu({drawSize:r??u,participantsCount:c,policyDefinitions:t});if(p.error)return _({result:p,stack:"getEntriesAndSeedsCount"});let{seedsCount:m}=p;return{entries:s,seedsCount:m,stageEntries:a}}function ey(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})=>pt(o||0)),0)}var EN={};Xt(EN,{allCompetitionMatchUps:()=>Un,allDrawMatchUps:()=>or,allEventMatchUps:()=>$n,allTournamentMatchUps:()=>Te,analyzeMatchUp:()=>Xp,calculateWinCriteria:()=>Ps,checkMatchUpIsComplete:()=>ds,competitionScheduleMatchUps:()=>Fu,drawMatchUps:()=>fy,eventMatchUps:()=>al,filterMatchUps:()=>Ni,getAllDrawMatchUps:()=>se,getAllStructureMatchUps:()=>Ut,getCheckedInParticipantIds:()=>us,getCompetitionMatchUps:()=>Qp,getEventMatchUpFormatTiming:()=>iy,getHomeParticipantId:()=>uy,getMatchUpCompetitiveProfile:()=>gu,getMatchUpContextIds:()=>py,getMatchUpDailyLimits:()=>ul,getMatchUpDailyLimitsUpdate:()=>sy,getMatchUpDependencies:()=>sn,getMatchUpFormat:()=>my,getMatchUpFormatTiming:()=>Iu,getMatchUpFormatTimingUpdate:()=>ny,getMatchUpScheduleDetails:()=>pd,getMatchUpType:()=>md,getMatchUpsStats:()=>dy,getModifiedMatchUpFormatTiming:()=>il,getParticipantResults:()=>Mu,getPredictiveAccuracy:()=>cy,getRoundMatchUps:()=>Ke,getRounds:()=>ly,isValidMatchUpFormat:()=>Pr,matchUpActions:()=>Od,participantScheduledMatchUps:()=>ay,tallyParticipantResults:()=>Ca,tournamentMatchUps:()=>cl,validMatchUp:()=>Zf,validMatchUps:()=>Vr});function ry({tournamentRecords:t,extensionName:e}){if(typeof t!="object"||!Object.keys(t).length)return{error:wt};let r=[],n;for(let o of Object.values(t)){let{extension:i}=dt({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}=dt({name:e,element:a});u&&r.push({params:{eventId:c,extension:u},method:"addEventExtension"})}}return{methods:r}}function ny({tournamentRecords:t}){return ry({extensionName:Vo,tournamentRecords:t})}var TN="ADULT",yN="JUNIOR",oy="WHEELCHAIR",AN={[No]:{allowModificationWhenMatchUpsScheduled:{courts:!1,venues:!1},defaultTimes:{averageTimes:[{categoryNames:[],minutes:{default:90}}],recoveryTimes:[{minutes:{[_t]:30,default:60}}]},defaultDailyLimits:{[xt]:2,[_t]:2,total:3},matchUpAverageTimes:[{matchUpFormatCodes:[Dn],averageTimes:[{categoryNames:[],minutes:{default:90}},{categoryTypes:[oy],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:[TN,oy],minutes:{default:60,[_t]:30}},{categoryTypes:[yN],minutes:{default:60,[_t]: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:[TN,oy],minutes:{default:30}},{categoryTypes:[yN],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:[TN,yN],minutes:{default:30}},{categoryTypes:[oy],minutes:{default:15}}]},{matchUpFormatCodes:["SET1-S:TB10"],recoveryTimes:[{categoryNames:[],minutes:{default:15}}]}],matchUpDailyLimits:[]}},j_=AN;function iy({tournamentRecord:t,matchUpFormats:e,categoryType:r,event:n}){if(!n)return{error:vt};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)&&Pr({matchUpFormat:l?.matchUpFormat}))return m.push(l.matchUpFormat),l}).filter(Boolean)}else{let{policy:m}=ei({policyType:en,tournamentRecord:t,event:n});if(m?.matchUpFormats)o=m?.matchUpFormats;else{let{extension:d}=dt({name:Vo,element:n}),l,f;d?.value?{matchUpAverageTimes:l,matchUpRecoveryTimes:f}=d.value:{matchUpAverageTimes:l,matchUpRecoveryTimes:f}=j_[No],o=ut([...(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:vt};let p=o.map(({matchUpFormat:m,description:d})=>{let l=Iu({tournamentRecord:t,matchUpFormat:m,categoryName:u,categoryType:r,eventType:s,event:n});return{matchUpFormat:m,description:d,...l}});return ot({eventMatchUpFormatTiming:p,info:i})}function il(t){let e=rt(t,[{[ie]:!0},{[tr]:g=>Pr({matchUpFormat:g}),[Fr]:qa,[Lm]:!0}]);if(e.error)return e;let{tournamentRecord:r,matchUpFormat:n,event:o}=t,{extension:i}=dt({name:Vo,element:o}),s=i?.value,{extension:a}=dt({element:r,name:Vo}),c=a?.value,u=s?.matchUpAverageTimes&&Ep({...s,matchUpFormat:n}),p=c?.matchUpAverageTimes&&Ep({...c,matchUpFormat:n}),m=[u,p].find(g=>g),d=s?.matchUpRecoveryTimes&&Up({...s,matchUpFormat:n}),l=c?.matchUpRecoveryTimes&&Up({...c,matchUpFormat:n}),f=[d,l].find(g=>g);return{matchUpFormat:n,recoveryTimes:f,averageTimes:m}}function sy({tournamentRecords:t}){return ry({extensionName:ou,tournamentRecords:t})}var _a=({scheduleAttributes:t=["scheduledDate","scheduledTime"],schedule:e={}})=>!!Object.keys(e).filter(n=>t.includes(n)).filter(n=>e[n]).length;function ay({scheduleAttributes:t=["scheduledDate","scheduledTime"],matchUps:e=[]}){if(!Vr(e))return{error:Xn};if(!Array.isArray(t))return{error:G};let r=e.filter(Boolean).filter(({schedule:o})=>_a({schedule:o,scheduleAttributes:t})).reduce((o,i)=>{let{schedule:s}=i,a=Et(s?.scheduledDate),c=Kt(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)=>XI(Kt(i.schedule?.scheduledTime),Kt(s.schedule?.scheduledTime)))}),{...C,scheduledMatchUps:r}}function Y_({tournamentRecords:t}){let e={},r=[];for(let n of Object.values(t))for(let o of n.events??[]){let i=Xr({event:o}),s=i?.drawDetails;ht(s)?(Object.assign(e,s),r.push(...Object.keys(s).filter(a=>ld({drawId:a,drawDetails:s})))):i?.drawIds?.length&&r.push(...i.drawIds)}return{drawIds:r,detailsMap:e}}function sl({schedulingProfile:t,matchUps:e=[]}){let r={},n=({eventId:a,drawId:c,structureId:u,roundNumber:p})=>`${a}|${c}|${u}${p}`;t?.length&&t.map(({venues:c})=>c.map(({rounds:u})=>u)).flat().forEach(c=>{c.sort((p,m)=>(p.sortOrder||0)-(m.sortOrder||0)).forEach(({eventId:p,drawId:m,structureId:d,roundNumber:l},f)=>{let g=n({eventId:p,drawId:m,structureId:d,roundNumber:l});r[g]=f})});let o=[],i={noScheduledDate:[]};for(let a of e){let c=a.schedule||{},u=c.scheduledDate&&Et(c.scheduledDate)||c.scheduledTime&&Et(c.scheduledTime)||"noScheduledDate";i[u]||(i[u]=[]),i[u].push(a)}let s=Object.keys(i).sort();for(let a of s){let c=i[a],u={noScheduledTime:[]};for(let m of c){let d=m.schedule||{},l=d.scheduledTime&&Kt(d.scheduledTime)||"noScheduledTime";u[l]||(u[l]=[]),u[l].push(m)}let p=Object.keys(u).sort();for(let m of p){let d=u[m];d.sort((l,f)=>{let g=r[n(l)]||0,I=r[n(f)]||0;return g-I}),o.push(...d)}}return o}function al(t){let{participants:e,contextContent:r,participantMap:n}=t,{tournamentAppliedPolicies:o,scheduleVisibilityFilters:i,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,usePublishState:m,contextFilters:d,matchUpFilters:l,contextProfile:f,nextMatchUps:g,tournamentId:I,inContext:h,context:S,event:T}=t;if(!T)return{error:vt};let{eventId:y,eventName:P,endDate:U,eventType:E,category:A,gender:N}=T??{},D={...S,...ot({surfaceCategory:T.surfaceCategory??p?.surfaceCategory,indoorOutDoor:T.indoorOutdoor??p?.indoorOutdoor,tournamentId:I??p?.tournamentId,endDate:U??p?.endDate,eventName:P,eventType:E,category:A,eventId:y,gender:N})},M;!e&&p&&({participants:e,participantMap:n,groupInfo:M}=Ai({participantsProfile:s,policyDefinitions:c,useParticipantMap:u,tournamentRecord:p,contextProfile:f,inContext:h})),f&&!r&&(r=qn({policyDefinitions:c,tournamentRecord:p,contextProfile:f,event:T}));let R=Xr({event:T});return{...(T.drawDefinitions??[]).reduce((O,x)=>{let F=js({hydrateParticipants:t.hydrateParticipants,context:D,tournamentAppliedPolicies:o,scheduleVisibilityFilters:i,tournamentParticipants:e,participantsProfile:s,afterRecoveryTimes:a,policyDefinitions:c,tournamentRecord:p,usePublishState:m,contextContent:r,contextFilters:d,matchUpFilters:l,participantMap:n,publishStatus:R,contextProfile:f,drawDefinition:x,nextMatchUps:g,inContext:h,event:T});return Object.keys(F)?.forEach(w=>{Array.isArray(F[w])&&(O[w]||(O[w]=[]),O[w]=O[w].concat(F[w]))}),O},{}),...C,groupInfo:M}}function cl(t){if(!t?.tournamentRecord)return{error:Y};let e=t.contextContent,{scheduleVisibilityFilters:r,participantsProfile:n,afterRecoveryTimes:o,policyDefinitions:i,useParticipantMap:s,tournamentRecord:a,inContext:c=!0,usePublishState:u,contextFilters:p,matchUpFilters:m,contextProfile:d,nextMatchUps:l,context:f}=t,g=t.tournamentId??a.tournamentId,I=a?.events??[],{participants:h,participantMap:S,groupInfo:T}=Ai({participantsProfile:n,policyDefinitions:i,useParticipantMap:s,tournamentRecord:a,contextProfile:d,inContext:c});d&&!e&&(e=qn({policyDefinitions:i,tournamentRecord:a,contextProfile:d}));let{appliedPolicies:y}=yt({tournamentRecord:a}),P=p?.eventIds??[];return{...I.filter(A=>!P.includes(A.eventId)).map(A=>{let D={eventDrawsCount:Ht({event:A}).flightProfile?.flights?.length||A.drawDefinitions?.length||0,...f};return al({hydrateParticipants:t.hydrateParticipants,context:D,tournamentAppliedPolicies:y,scheduleVisibilityFilters:r,participantsProfile:n,afterRecoveryTimes:o,policyDefinitions:i,tournamentRecord:a,usePublishState:u,contextFilters:p,contextProfile:d,contextContent:e,matchUpFilters:m,participantMap:S,participants:h,tournamentId:g,nextMatchUps:l,inContext:c,event:A})}).reduce((A,N)=>((N&&Object.keys(N).filter(M=>!["success","matchUpsMap"].includes(M)))?.forEach(M=>{Array.isArray(N[M])&&(A[M]||(A[M]=[]),A[M]=A[M].concat(N[M]),A.matchUpsCount+=N[M].length)}),A),{matchUpsCount:0}),groupInfo:T}}function Qp({scheduleVisibilityFilters:t,hydrateParticipants: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:wt};let m=Object.keys(n).map(f=>{let g=n[f];return cl({scheduleVisibilityFilters:t,hydrateParticipants:e,participantsProfile:r,policyDefinitions:o,tournamentRecord:g,usePublishState:i,matchUpFilters:s,contextFilters:a,nextMatchUps:c,inContext:u})}),d={};return{...m.reduce((f,g)=>(Object.keys(g).forEach(h=>{Array.isArray(g[h])&&(f[h]||(f[h]=[]),f[h]=f[h].concat(g[h])),h==="groupInfo"&&Object.assign(d,g[h])}),f),{}),groupInfo:d}}function Fu(t){if(typeof t?.tournamentRecords!="object"||!Object.keys(t?.tournamentRecords).length)return{error:wt};let{courts:e,venues:r}=Ao(t),o=Ko(t).schedulingProfile,{sortDateMatchUps:i=!0,courtCompletedMatchUps:s,alwaysReturnCompleted:a,activeTournamentId:c,tournamentRecords:u,withCourtGridRows:p,minCourtGridRows:m,usePublishState:d,status:l=Nr,sortCourtsData:f}=t,g=c??ns()??Object.keys(u)[0],I=d?Su({tournamentRecord:u[g],status:l}):void 0,h=a?Qp({...t,matchUpFilters:{...t.matchUpFilters,matchUpStatuses:[le]},contextFilters:t.contextFilters}).completedMatchUps:[];if(d&&!I?.orderOfPlay?.published)return{completedMatchUps:h,dateMatchUps:[],courtsData:[],venues:r};let S,T;d&&({drawIds:S,detailsMap:T}=Y_({tournamentRecords:u})),S?.length&&(t.contextFilters||(t.contextFilters={}),t.contextFilters?.drawIds?t.contextFilters.drawIds=t.contextFilters.drawIds.filter(b=>S.includes(b)):t.contextFilters.drawIds=S),I?.eventIds?.length&&(t.matchUpFilters||(t.matchUpFilters={}),t.matchUpFilters?.eventIds&&t.matchUpFilters.eventIds.length?t.matchUpFilters.eventIds=t.matchUpFilters.eventIds.filter(b=>I.eventIds.includes(b)):t.matchUpFilters.eventIds=I.eventIds),I?.scheduledDates?.length&&(t.matchUpFilters||(t.matchUpFilters={}),t.matchUpFilters.scheduledDates&&t.matchUpFilters.scheduledDates.length?t.matchUpFilters.scheduledDates=t.matchUpFilters.scheduledDates.filter(b=>I.scheduledDates.includes(b)):t.matchUpFilters.scheduledDates=I.scheduledDates),a&&(t.matchUpFilters||(t.matchUpFilters={}),t.matchUpFilters?.excludeMatchUpStatuses?.length?t.matchUpFilters.excludeMatchUpStatuses.includes(le)||t.matchUpFilters.excludeMatchUpStatuses.push(le):t.matchUpFilters.excludeMatchUpStatuses=[le]);let{completedMatchUps:y,upcomingMatchUps:P,pendingMatchUps:U,groupInfo:E}=Qp({...t,matchUpFilters:t.matchUpFilters,contextFilters:t.contextFilters}),A=[...P??[],...U??[]];T&&(!S?.length||Object.keys(T).length)&&(A=A.filter(b=>{let{drawId:v,structureId:O,stage:x}=b;if(!T?.[v]?.publishingDetail?.published)return!1;if(T[v].stageDetails){let F=Object.keys(T[v].stageDetails),L=F.filter(V=>!T[v].stageDetails[V].published),w=F.filter(V=>T[v].stageDetails[V].published);return L.length&&L.includes(x)?!1:w.length&&w.includes(x)?!0:L.length&&!L.includes(x)&&!w.length}if(T[v].structureDetails){let F=Object.keys(T[v].structureDetails),L=F.filter(V=>!T[v].structureDetails[V].published),w=F.filter(V=>T[v].structureDetails[V].published);return L.length&&L.includes(O)?!1:w.length&&w.includes(O)?!0:L.length&&!L.includes(O)&&!w.length}return!0}));let N=i?sl({matchUps:A,schedulingProfile:o}):A,D=e?.map(b=>{let v=R(b);return{surfaceCategory:b?.surfaceCategory??"",matchUps:v,...b}}),M={completedMatchUps:a?h:y,dateMatchUps:N,courtsData:D,groupInfo:E,venues:r};if(p){let{rows:b,courtPrefix:v}=nl({minRowsCount:m,courtsData:D});M.courtPrefix=v,M.rows=b}return{...M,...C};function R({courtId:b}){let O=(s?N.concat(y??[]):N).filter(x=>x.schedule?.courtId===b||x.schedule?.allocatedCourts?.map(({courtId:F})=>F).includes(b));return f?sl({matchUps:O,schedulingProfile:o}):O}}function ul({tournamentRecords:t,tournamentId:e}){if(typeof t!="object"||!Object.keys(t).length)return{error:wt};let r=Object.keys(t).filter(o=>!e||o===e),n;return r.forEach(o=>{let i=t[o],{matchUpDailyLimits:s}=VV({tournamentRecord:i});n=s}),{matchUpDailyLimits:n}}function VV(t){let e=rt(t,[{[ie]:!0}]);if(e.error)return e;let{tournamentRecord:r}=t,{policy:n}=ei({policyType:No,tournamentRecord:r}),{extension:o}=dt({element:r,name:ou}),i=o?.value?.dailyLimits,s=n?.defaultDailyLimits;return{matchUpDailyLimits:i||s}}function cy(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:Y};if(c&&![xt,_t].includes(c))return{error:G,info:{matchUpType:c}};if(e&&!Vr(e))return{error:G,context:{matchUps:e}};let f=we[u],g=f?.ascending??t.ascending??!1,I=f?.accessor??t.valueAccessor,h=Array.isArray(f?.range)?Math.abs(f.range[0]-f.range[1]):0,S=It(m)&&h?(m??0/100)*h:t.zoneMargin??h,T={withScaleValues:!0,withCompetitiveness:!0},y={matchUpTypes:c?[c]:[xt,_t]},P=n?.participants;e?.[0]?.hasContext?d?e=e.filter(v=>v.drawId===d):p&&(e=e.filter(v=>v.eventId===p)):e===void 0&&(e=d&&!o&&[]||!d&&p&&!l&&[]||d&&or({inContext:!0,drawDefinition:o,contextFilters:y,contextProfile:T,participants:P})?.matchUps||!d&&p&&$n({inContext:!0,contextFilters:y,contextProfile:T,participants:P,event:l})?.matchUps||Te({tournamentRecord:n,contextFilters:y,contextProfile:T})?.matchUps||[]),c&&(e=e.filter(v=>v.matchUpType===c));let U=e.filter(({winningSide:v,score:O,sides:x,matchUpStatus:F})=>![rr,Mt,Ct,au,br].includes(F??"")&&Ie({score:O})&&x?.length===2&&v),E=HV({matchUps:U,excludeMargin:i,exclusionRule:s,valueAccessor:I,ascending:g,scaleName:u}),A=!a||ue(xt)(c)?S:(S||0)*2,N=S?U.map(({competitiveProfile:v,matchUpType:O,score:x,sides:F})=>{let L=$_({singlesForDoubles:r,valueAccessor:I,matchUpType:O,scaleName:u,sides:F}),w=Math.abs(L[0].value-L[1].value);return{competitiveness:v?.competitiveness,valuesGap:w,score:x}}).filter(({valuesGap:v})=>v<=A):[],D=BV({zoneData:N}),M=D&&[].concat(Object.values(D)).flat().length,R=M&&Object.assign({},...Object.keys(D).map(v=>({[v]:Math.round(1e4*D[v].length/M)/100}))),b=U.length-(N?.length||0);return{...C,relevantMatchUps:U,zoneDistribution:R,zoneData:N,accuracy:E,nonZone:b}}function BV({zoneData:t}){let e={[Zm]:[],[ac]:[],[cc]:[]};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 $_({singlesForDoubles:t,exclusionRule:e,valueAccessor:r,matchUpType:n,scaleName:o,sides:i}){let s=e?.range.sort(),a=c=>{let u=c?.[e?.valueAccessor];return{exclude:e&&u>=s[0]&&u<=s[1],exclusionValue:u}};return i.sort((c,u)=>c.sideNumber-u.sideNumber).map(({participant:c})=>{let u=[],p=c?.individualParticipants;if(p?.length){let m=[],d=0;for(let l of p){let{scaleValue:f,value:g}=q_({singlesForDoubles:t,valueAccessor:r,participant:l,matchUpType:n,scaleName:o}),{exclude:I,exclusionValue:h}=a(f);I&&u.push(h),m.push(f),g&&!isNaN(d)?d+=g:d=void 0}return{participantName:c.participantName,exclusionValues:u,scaleValues:m,value:d}}else if(c){let{scaleValue:m,value:d}=q_({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 q_({singlesForDoubles:t,valueAccessor:e,matchUpType:r,participant:n,scaleName:o}){let i=t?xt: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 HV({excludeMargin:t,exclusionRule:e,valueAccessor:r,ascending:n,scaleName:o,matchUps:i}){let s={affirmative:[],negative:[],excluded:[]};for(let u of i){let{matchUpType:p,sides:m,score:d,winningSide:l}=u;if(!l)continue;if(e&&(!e.valueAccessor||!e.range))return{info:"exclusionRule requires valueAccessor and range",error:st};let f=l-1,g=$_({exclusionRule:e,valueAccessor:r,matchUpType:p,scaleName:o,sides:m});if(e){let P=g.map(({exclusionValues:U})=>U).flat();if(P.length){s.excluded.push({scoreString:d?.scoreStringSide1,exclusionValues:P,winningSide:l,sideValues:g});continue}}if(g.filter(P=>![void 0,"",null].includes(P.value)).length<2){s.excluded.push({scoreString:d?.scoreStringSide1,missingValues:!0,winningSide:l,sideValues:g});continue}let I=g[f].value-g[1-f].value,h=parseFloat(t||0),S=h&&Math.abs(I)<h;if(S){s.excluded.push({scoreString:d?.scoreStringSide1,excludeMargin:t,winningSide:l,excludeGap:S,sideValues:g,valuesGap:I});continue}let T=n?I:I*-1,y=l===1?d?.scoreStringSide1:d?.scoreStringSide2;T>0?s.affirmative.push({winningScoreString:y,winningSide:l,sideValues:g,valuesGap:I,score:d}):s.negative.push({winningScoreString:y,winningSide:l,sideValues:g,valuesGap:I,score:d})}let a=s.affirmative.length+s.negative.length,c=a&&s.affirmative.length/a*100;return s.percent=c?Math.round(100*c)/100:0,s}function Ps({collectionDefinitions:t=[],collectionGroups:e=[]}){let r=0,{groupValueNumbers:n}=QS({collectionGroups:e}),o;for(let s of t||[]){let{collectionValueProfiles:a,collectionGroupNumber:c,collectionValue:u,matchUpCount:p,matchUpValue:m,scoreValue:d,setValue:l}=s,f=c&&n.includes(c);if(It(l||d))o=!0;else{if(f)continue;if(typeof u=="number"&&It(u))r+=u;else if(Array.isArray(a)&&a?.length)for(let g of a)r+=g.matchUpValue;else typeof m=="number"&&It(m)&&(r+=(p??0)*m)}}for(let s of e)r+=s.groupValue??0;return o||!r?{aggregateValue:!0,...C}:{valueGoal:Math.floor(r/2)+1,...C}}function uy(t){let{timeStamp:e,schedule:r,matchUp:n}=t,o=rt(t,[{[_n]:!0}]);if(o.error)return o;let{itemValue:i,timeStamp:s}=Ho({timeItems:n?.timeItems||[],itemType:cd});return!r||s&&e&&new Date(s).getTime()>new Date(e).getTime()?{homeParticipantId:i}:r}function py({matchUps:t,matchUpId:e}){if(!Vr(t))return{error:G};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 Ds(t,e){if(!ht(t))return{error:G};if(!Array.isArray(e))return{error:G};let r={};for(let{param:n,error:o,attr:i}of e){let s=WV({params:t,param:n,attr:i,error:o});if(s?.error)return s;r[n]=s}return r}function WV({params:t,param:e,attr:r,error:n}){if(e===mp&&ht(t.drawDefinition)&&Vt(t.structureId)){let o=(t.drawDefinition.structures??[]).find(({structureId:i})=>i===t.structureId);return!o.length&&n?{error:n}:{structure:o}}if(e===_n){let o=cN({...t,...r});return o.error&&n?{...o,error:n}:o}return{error:ve,info:{param:e}}}function my(t){let{structureId:e,matchUpId:r,event:n}=t,o=t.drawDefinition,i=rt(t,[{[ie]:!0},{[km]:{[Zc]:!1,[ln]:!1,[Ch]:!1,[Do]:!1}}]);if(i[fn])return i;let a=Ds(t,[{[is]:_n,[fn]:st}])?.matchUp;if(r&&a?.error)return a;!o&&a?.drawDefinition&&(o=a?.drawDefinition);let c=a?.structure;if(!c&&e&&!r){if(!o)return{error:an};let l=at({drawDefinition:o,structureId:e});if(l.error)return l;c=l.structure}let u=c?.matchUpFormat,p=o?.matchUpFormat,m=n?.matchUpFormat,d=a?.matchUp?.matchUpFormat||u||p||m;return{structureDefaultMatchUpFormat:u,eventDefaultMatchUpFormat:m,drawDefaultMatchUpFormat:p,matchUpFormat:d}}function dy({profileBands:t,tournamentRecord:e,matchUps:r}){if(!Vr(r))return{error:Xn};let n=!t&&ei({policyType:hi,tournamentRecord:e}).policy,o=t||n?.profileBands||ed[hi].profileBands,i=r.filter(({winningSide:d})=>d),s=i.map(nS),a=(d,l)=>{let f=rS(l,o);return d[f]+=1,d},c=oS(s).reduce((d,l)=>a(d,l),{[Zm]:0,[ac]:0,[cc]:0,[Jh]:0}),u=Object.keys(c).reduce((d,l)=>(c[l]||0)+d,0),p=Object.keys(c).map(d=>{let l=parseFloat((c[d]/u).toFixed(4));return{[d]:l*100}}),m=i.filter(({matchUpStatus:d})=>d===kU).length;return p.push({[kU]:parseFloat((m/u).toFixed(4))*100}),{competitiveBands:Object.assign({},...p),...C}}var{stageOrder:K_}=ZC;function z_(t,e){return t.eventName.localeCompare(e.eventName)||t.eventId.localeCompare(e.eventId)||(K_[t?.stage]||0)-(K_[e?.stage]||0)||e.matchUpsCount-t.matchUpsCount||`${t.stageSequence}-${t.roundNumber}-${t.minFinishingSum}`.localeCompare(`${e.stageSequence}-${e.roundNumber}-${e.minFinishingSum}`)}function ly({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:G,inContextMatchUps:n};if(s&&!o){if(typeof s!="object")return{error:Ha};o={[s.tournamentId]:s}}let l=typeof o!="object"||!Object.keys(o).length;if((m||u||!n||!i&&(t||r||i||a))&&l)return{error:wt};let g=Object.assign({},...Object.values(o??{}).map(({venues:E=[],tournamentId:A})=>({[A]:E?.map(({venueId:N})=>N)}))),I=Object.values(o??{}).map(({events:E=[],tournamentId:A,startDate:N,endDate:D})=>E.map(M=>({...M,validVenueIds:g[A],startDate:M.startDate??N,endDate:M.endDate??D}))).flat(),{segmentedRounds:h,profileRounds:S}=o&&(t||r||i||a)&&rl({tournamentRecords:o,schedulingProfile:i})||{},T=t&&Object.assign({},...S.map(E=>({[E.id]:E}))),y=n||o&&Un({tournamentRecords:o,matchUpFilters:c})?.matchUps||[],P=[],U=y&&Object.values(y.reduce((E,A)=>{let N=Yg(A).id,D=h?.[N],M=[...E[N]?.matchUps??[],A],{containerStructureId:R,stageSequence:b,structureName:v,tournamentId:O,isRoundRobin:x,matchUpType:F,roundNumber:L,roundOffset:w,structureId:V,eventName:k,roundName:W,drawName:H,eventId:K,drawId:q}=A,B=x?R:V;return{...E,[N]:{id:p?N:void 0,structureId:B,stageSequence:b,segmentsCount:D,structureName:v,tournamentId:O,matchUpType:F,roundNumber:L,roundOffset:w,eventName:k,roundName:W,drawName:H,matchUps:M,eventId:K,drawId:q}}},{})).map(E=>{let{minFinishingSum:A,winnerFinishingPositionRange:N}=W_(E.matchUps),D=E.segmentsCount;if(D){let L=E.matchUps.length/D;return ye(E.matchUps.sort((V,k)=>V.roundPosition-k.roundPosition),L).map((V,k)=>{let{unscheduledCount:W,incompleteCount:H,matchUpsCount:K,isScheduled:q,isComplete:B,byeCount:$}=IN(V),z=gN({matchUps:E.matchUps,tournamentRecords:o,events:I,round:E});return ot({...E,...d,roundSegment:{segmentsCount:D,segmentNumber:k+1},winnerFinishingPositionRange:N,unscheduledCount:W,incompleteCount:H,minFinishingSum:A,matchUpsCount:K,isScheduled:q,roundTiming:z,isComplete:B,byeCount:$,matchUps:V})})}let{unscheduledCount:M,incompleteCount:R,matchUpsCount:b,isScheduled:v,isComplete:O,byeCount:x}=IN(E.matchUps),F=gN({matchUps:E.matchUps,tournamentRecords:o,events:I,round:E});return ot({...E,...d,winnerFinishingPositionRange:N,unscheduledCount:M,incompleteCount:R,minFinishingSum:A,matchUpsCount:b,isScheduled:v,roundTiming:F,isComplete:O,byeCount:x})}).flat().filter(E=>{if(t){let V=Et(t),k=p?E.id:Yg(E).id;if(V&&T[k]&&Et(T[k].scheduleDate)===V)return!1}let{isComplete:A,isScheduled:N}=E,D=!r||!A,M=!e||!N,R=m||u?I?.find(({eventId:V})=>V===E.eventId):void 0,b=R?.startDate??s?.startDate,v=R?.endDate??s?.endDate,O=!u||!b||new Date(u)>=new Date(b),x=!u||!v||new Date(u)<=new Date(v),F=O&&x,L=!m||R?.validVenueIds.includes(m),w=D&&M&&L&&F;return w||P.push(E),w}).sort(z_)||[];return{...C,rounds:U,excludedRounds:P}}function Xp(t){let{matchUp:e,sideNumber:r,setNumber:n,isTiebreakValue:o,isPointValue:i}=t||{},{matchUpFormat:s}=t||{};if(!e)return{error:hr};s=s||e?.matchUpFormat;let a=Ye(s),c=!!e?.winningSide,u=e.score?.sets,p=u?.length,m=n&&n-1,d=!!u?.find((B,$)=>B.setNumber===n&&$===m),l=u?.filter(B=>B?.winningSide)||[],f=l?.length||0,g=n&&u?.slice(n)||[],I=!!(p&&n&&g?.reduce((B,$)=>(!$||!$.side1Score&&!$.side2Score&&!$.side1TiebreakScore&&!$.side2TiebreakScore&&!$.side1PointScore&&!$.side2PointScore)&&B,!0)),h=n<=p&&u.find(B=>B.setNumber===n),S=h&&wu({setObject:h,matchUpScoringFormat:a}),{isCompletedSet:T,sideGameScores:y,sideTiebreakScores:P}=S||{},U=!!(h&&!T&&I||n&&n===p+1&&!c),E=[1,2].includes(r),A=E?r-1:0,N=h&&E&&(!o&&!i&&y[A]!==void 0&&y[A]||o&&P[A]!==void 0&&P[A]),D=!!N,M=l?.map(B=>wu({setObject:B,matchUpScoringFormat:a}).isValidSetOutcome).reduce((B,$)=>B&&$,!0),R=l.reduce((B,$)=>{let{winningSide:z}=$,j=z-1;return B[j]++,B},[0,0]),b=e?.winningSide,v=b&&b-1,O=1-v,x=R[v],F=R[O],L=Math.max(...R),w=Sr(R)[L],{bestOf:V,exactly:k}=a??{},W=V&&Math.ceil(V/2)||k||1,H=L===W&&w===1&&R.indexOf(L)+1||void 0,K=x>F&&b===H;return{completedSetsHaveValidOutcomes:M,validMatchUpWinningSide:K,calculatedWinningSide:H,matchUpScoringFormat:a,validMatchUpOutcome:H&&M&&K,isLastSetWithValues:I,completedSetsCount:f,isCompletedMatchUp:c,isValidSideNumber:E,hasExistingValue:D,existingValue:N,isExistingSet:d,isActiveSet:U,...S}}function fy({participants:t,tournamentAppliedPolicies:e,scheduleVisibilityFilters:r,participantsProfile:n,afterRecoveryTimes:o,policyDefinitions:i,useParticipantMap:s,tournamentRecord:a,usePublishState:c,contextFilters:u,contextContent:p,matchUpFilters:m,participantMap:d,publishStatus:l,contextProfile:f,drawDefinition:g,nextMatchUps:I,tournamentId:h,inContext:S,context:T,event:y}){let{eventId:P,eventName:U,endDate:E,eventType:A,category:N,gender:D}=y??{},M={...T,...ot({surfaceCategory:y?.surfaceCategory??a?.surfaceCategory,indoorOutDoor:y?.indoorOutdoor??a?.indoorOutdoor,endDate:E??y?.endDate??a?.endDate,tournamentId:h??a?.tournamentId,eventName:U,eventType:A,category:N,eventId:P,gender:D})},R;return!t?.length&&a&&({participants:t,participantMap:d,groupInfo:R}=Ai({participantsProfile:n,policyDefinitions:i,useParticipantMap:s,tournamentRecord:a,contextProfile:f,inContext:S})),y&&f&&!p&&(p=qn({policyDefinitions:i,tournamentRecord:a,contextProfile:f,drawDefinition:g,event:y})),{...js({context:M,tournamentAppliedPolicies:e,scheduleVisibilityFilters:r,tournamentParticipants:t,participantsProfile:n,afterRecoveryTimes:o,policyDefinitions:i,tournamentRecord:a,usePublishState:c,participantMap:d,contextContent:p,contextFilters:u,matchUpFilters:m,publishStatus:l,contextProfile:f,drawDefinition:g,nextMatchUps:I,inContext:S,event:y}),groupInfo:R}}var UN={};Xt(UN,{getCompetitionVenues:()=>$p,getCourts:()=>gy,getVenuesAndCourts:()=>Ao,publicFindVenue:()=>dS});function gy({tournamentRecord:t,venueId:e,venueIds:r}){return t?{courts:(t.venues||[]).filter(o=>e?o.venueId===e:r?r.includes(o.venueId):!0).map(o=>{let{venueId:i}=o,s=J(o.courts||[]);return s.forEach(a=>Object.assign(a,{venueId:i})),s}).flat()}:{error:Y}}var PN={};Xt(PN,{categoryCanContain:()=>Yc,getCategoryAgeDetails:()=>Ls,getEvent:()=>Sy,getEventProperties:()=>Iy,getEventStructures:()=>Ig,getEventTimeItem:()=>du,getEvents:()=>hy,getFlightProfile:()=>Ht,getScaledEntries:()=>ta});function Iy({tournamentRecord:t,event:e}){if(!t)return{error:Y};if(!e)return{error:vt};let r=e.entries||[],n=t.participants||[],o=e.category?.categoryName||e.category?.ageCategoryCode,{eventType:i}=e,s=r.map(d=>d.participantId),a=n.filter(d=>s.includes(d.participantId)),c,u,p;return{entryScaleAttributes:a.map(d=>{let{participantId:l,participantName:f,name:g}=d,I={scaleType:rg,eventType:i,scaleName:o},h=yo({participant:d,scaleAttributes:I})?.scaleItem?.scaleValue;I={scaleType:WU,eventType:i,scaleName:o};let S=yo({participant:d,scaleAttributes:I})?.scaleItem?.scaleValue;I={scaleType:HU,eventType:i,scaleName:o};let T=yo({participant:d,scaleAttributes:I})?.scaleItem?.scaleValue;return c=!!(c||h),u=!!(u||S),p=!!(p||T),{participantId:l,participantName:f||g,seed:h,ranking:S,rating:T}}),hasSeededParticipants:c,hasRankedParticipants:u,hasRatedParticipants:p}}function hy({tournamentRecord:t,withScaleValues:e,scaleEventType:r,inContext:n,eventIds:o,drawIds:i,context:s}){if(!t)return{error:Y};let{tournamentId:a}=t,c=(t.events??[]).filter(({eventId:p})=>!o||Array.isArray(o)&&o.includes(p)).map(p=>{let m=p.drawDefinitions?.map(su);if(i?.length&&!Yt(i,m).length)return;let d=J(p);return n&&Object.assign(d,{tournamentId:a}),s&&Object.assign(d,s),d}).filter(Boolean),u={};if(e){let p=Gt({withScaleValues:!0,tournamentRecord:t}).participantMap,m=d=>d.reduce((l,f)=>l+parseFloat(f),0);for(let d of c){let l=r??d.eventType,f=d.eventId;u[f]||(u[f]={ratingsStats:{},ratings:{},ranking:{},draws:{}});let I=(d.entries??[]).filter(({entryStatus:E})=>Qr.includes(E)).map(St),h=E=>{if(E?.ratings?.[l])for(let A of E?.ratings?.[l]??[]){let N=A.scaleName;u[f].ratings[N]||(u[f].ratings[N]=[]);let D=we[N]?.accessor;if(D){let M=parseFloat(A.scaleValue?.[D]);M&&u[f].ratings[N].push(M)}}if(E?.rankings?.[l])for(let A of E?.rankings?.[l]??[]){let N=A.scaleName;u[f].ranking[N]||(u[f].ranking[N]=[]),A.scaleValue&&u[f].ranking[N].push(A.scaleValue)}};for(let E of I){let A=p?.[E]?.participant;if(A?.participantType!==Tt)for(let N of A?.individualParticipantIds??[]){let D=p?.[N]?.participant;h(D)}else h(A)}let S=u[f].ratings;for(let E of Object.keys(S)){let A=S[E];if(!A.length)continue;let N=AA(A)?.toFixed(2);u[f].ratingsStats[E]={avg:parseFloat((m(A)/A.length).toFixed(2)),median:N?parseFloat(N):void 0,max:Math.max(...A),min:Math.min(...A)}}let T=(E,A)=>{let N=D=>{if(u[f].draws?.[E]&&D?.ratings?.[l])for(let M of D?.ratings?.[l]??[]){let R=M.scaleName;u[f].draws[E]?.ratings[R]||(u[f].draws[E].ratings[R]=[]);let b=we[R]?.accessor;if(b){let v=parseFloat(M.scaleValue?.[b]);v&&u[f].draws[E].ratings[R].push(v)}}if(u[f].draws?.[E]&&D?.rankings?.[l])for(let M of D?.rankings?.[l]??[]){let R=M.scaleName;u[f].draws[E]?.ranking[R]||(u[f].draws[E].ranking[R]=[]);let b=M.scaleValue;b&&u[f].draws[E].ranking[R].push(b)}};for(let D of A.filter(Boolean)){let M=p?.[D]?.participant;if(M?.participantType!==Tt)for(let R of M?.individualParticipantIds??[]){let b=p?.[R]?.participant;N(b)}else N(M)}},y=[],P=E=>i?.length&&i.includes(E)||y.includes(E);for(let E of d.drawDefinitions??[]){let A=E.drawId;if(P(A))continue;let N=Ri({drawDefinition:E}).assignedParticipantIds??[];u[f].draws[A]||(u[f].draws[A]={ratingsStats:{},ratings:{},ranking:{}}),y.push(A),T(A,N)}let U=Ht({event:d}).flightProfile;for(let E of U?.flights??[]){let A=E.drawId;if(P(A))continue;let N=E.drawEntries.map(St);T(A,N)}for(let E of y){let A=u[f].draws[E].ratings;for(let N of Object.keys(A)){let D=A[N];if(!D.length)continue;let M=AA(D)?.toFixed(2);u[f].draws[E].ratingsStats[N]={avg:parseFloat((m(D)/D.length).toFixed(2)),median:M?parseFloat(M):void 0,max:Math.max(...D),min:Math.min(...D)}}}}}return ot({eventScaleValues:u,events:c,...C})}function Sy({tournamentRecord:t,drawDefinition:e,context:r,event:n}){if(!t)return{error:Y};if(!n)return{error:vt};let o=J(n);r&&Object.assign(o,r);let i=e&&o.drawDefinitions?.find(({drawId:s})=>e.drawId===s);return ot({drawDefinition:i,event:o})}function Q_(t){let e="validateAndDeriveDrawValues",{appliedPolicies:r,policyDefinitions:n}=qV(t),o=$V({...t,policyDefinitions:n,appliedPolicies:r}),i=YV(t),s=KV({...t,consideredEntries:i,appliedPolicies:r});if(s?.error)return _({result:s,stack:e});let a=zV({...t,consideredEntries:i}),c=jV({...t,appliedPolicies:r,policyDefinitions:n,drawSize:a});if(c.error)return _({result:c,stack:e});let u=c.drawType;if(isNaN(a)&&u!==$r)return _({result:{error:Ya},stack:e});let p=n?.[xn]??r?.[xn],m=t.seedingProfile??p?.seedingProfile?.drawTypes?.[u??""]??p?.seedingProfile;t.seedingProfile&&(n[xn]||(n[xn]={...Wg[xn]}),n[xn].seedingProfile=m);let d=QV({...t,drawType:u});return d?.error?_({result:d,stack:e}):{drawSize:a,drawType:u,enforceGender:o,seedingProfile:m,appliedPolicies:r,policyDefinitions:n}}function jV(t){let{policyDefinitions:e,appliedPolicies:r,enforceMinimumDrawSize:n=!0,drawSize:o}=t,i=t.drawTypeCoercion??bu({drawType:t.drawType,policyDefinitions:e,appliedPolicies:r}),s=yT({drawType:t.drawType,enforceMinimumDrawSize:n,drawTypeCoercion:i,drawSize:o});return s.error?s:{drawType:s.drawType}}function NN(t){return t?.filter(e=>e.entryStatus&&[...Qr,nd].includes(e.entryStatus))}function YV({considerEventEntries:t=!0,drawEntries:e,eventEntries:r,qualifyingOnly:n}){return(n&&[]||NN(e)||(t?r:[])).filter(({entryStage:o})=>!o||o===nt)}function qV(t){let{tournamentRecord:e,event:r}=t,n=yt({tournamentRecord:e,event:r}).appliedPolicies??{},o=J(t.policyDefinitions??{},!1,!0);return{appliedPolicies:n,policyDefinitions:o}}function $V({enforceGender:t,policyDefinitions:e,appliedPolicies:r}){return t??e?.[er]?.participants?.enforceGender??r?.[er]?.participants?.enforceGender}function KV(t){let{consideredEntries:e,appliedPolicies:r,policyDefinitions:n,enforceGender:o,participantMap:i,participants:s,event:a}=t;return a&&s&&_d({consideredEntries:e,policyDefinitions:n,appliedPolicies:r,participantMap:i,enforceGender:o,participants:s,event:a})}function zV(t){return!t.drawSize&&t.consideredEntries.length&&![$r,Xc,da,Nn,Io].includes(t.drawType??"")&&es(t.consideredEntries.length)||t.drawSize&&pt(t.drawSize)||!1}function QV(t){let{tournamentRecord:e,event:r,ignoreAllowedDrawTypes:n,drawType:o}=t,i=!n&&e&&Kd({tournamentRecord:e,categoryType:r?.category?.categoryType,categoryName:r?.category?.categoryName});return i?.length&&!i.includes(o)?{error:ym}:{...C}}function xa(t){let{voluntaryConsolation:e,tournamentRecord:r,event:n}=t,o="generateDrawDefinition",{participants:i,participantMap:s}=Gt({withIndividualParticipants:!0,convertExtensions:!0,internalUse:!0,tournamentRecord:r}),a=NN(n?.entries)??[],c=Q_({...t,participantMap:s,participants:i,eventEntries:a});if(c.error)return _({result:c,stack:o});let{appliedPolicies:u,policyDefinitions:p,drawSize:m,drawType:d,enforceGender:l,seedingProfile:f}=c,g=n?.eventType,I=t.matchUpType??g,h=A_({...t,enforceGender:l,eventType:g,matchUpType:I});if(h.error)return _({result:h,stack:o});let{matchUpFormat:S,tieFormat:T}=h;if(t.drawId&&typeof t.drawId!="string")return _({result:{error:G},stack:o});let P=w_({...t,policyDefinitions:p,tournamentRecord:r,appliedPolicies:u,matchUpFormat:S,seedingProfile:f,participants:i,eventEntries:a,matchUpType:I,tieFormat:T,drawSize:m,drawType:d,event:n});if(P.error)return _({result:P,stack:o});let{existingDrawDefinition:U,positioningReports:E,drawDefinition:A,structureId:N,conflicts:D,entries:M}=P;if(!A)return _({result:{error:G},stack:o});let R=L_({...t,existingDrawDefinition:U,positioningReports:E,appliedPolicies:u,drawDefinition:A,seedingProfile:f,participants:i,structureId:N,entries:M,params:t,stack:o});if(R.error)return R;let{qualifyingConflicts:b}=R;return A.drawName=t.drawName??(d&&Qe(d)),m&&typeof e=="object"&&m>=4&&pg({...e,drawDefinition:A,matchUpType:I}),{existingDrawDefinition:!!U,qualifyingConflicts:b,positioningReports:E,drawDefinition:A,structureId:N,...C,conflicts:D}}function Ty({scaleAttributes:t,scaledEntries:e,stageEntries:r,seedsCount:n,scaleName:o}){if(!t)return{error:st,info:"missing scaleAttributes"};let i=Object.assign({},...(e||[]).slice(0,n).map(({participantId:c},u)=>({[c]:u+1})));o=o||t.scaleName;let s=new Date().toISOString();return{scaleItemsWithParticipantIds:r.map(({participantId:c})=>({scaleItems:[{scaleValue:i[c],eventType:t.eventType,scaleType:ho,scaleName:o,scaleDate:s}],participantId:c}))}}function X_({tournamentRecord:t,drawDefinition:e,policyDefinitions:r,scaleAttributes:n,scaleName:o,drawSize:i,drawId:s,event:a,stage:c,sortDescending:u,scaleSortMethod:p}){let m=ol({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:G};let g=ta({tournamentRecord:t,scaleAttributes:n,scaleSortMethod:p,sortDescending:u,entries:d,stage:c}).scaledEntries??[],{scaleItemsWithParticipantIds:I}=Ty({scaleAttributes:n,scaledEntries:g,stageEntries:f,seedsCount:l,scaleName:o});return{scaleItemsWithParticipantIds:I}}var xN={};Xt(xN,{addDrawEntries:()=>sg,addEventEntries:()=>Fn,addEventEntryPairs:()=>vN,destroyPairEntries:()=>pP,destroyPairEntry:()=>ug,getEntriesAndSeedsCount:()=>ol,getMaxEntryPosition:()=>ey,modifyEntriesStatus:()=>dd,modifyEventEntries:()=>ON,mutate:()=>_N,promoteAlternate:()=>CN,promoteAlternates:()=>Ay,query:()=>SN,removeDrawEntries:()=>bN,removeEventEntries:()=>gc,setEntryPosition:()=>yy,setEntryPositions:()=>RN});var _N={};Xt(_N,{addDrawEntries:()=>sg,addEventEntries:()=>Fn,addEventEntryPairs:()=>vN,destroyPairEntries:()=>pP,destroyPairEntry:()=>ug,modifyEntriesStatus:()=>dd,modifyEventEntries:()=>ON,promoteAlternate:()=>CN,promoteAlternates:()=>Ay,removeDrawEntries:()=>bN,removeEventEntries:()=>gc,setEntryPosition:()=>yy,setEntryPositions:()=>RN});function yy({tournamentRecord:t,drawDefinition:e,participantId:r,entryPosition:n,skipRefresh:o,event:i}){let s="setEntryPositions";if(!t)return{error:Y};if(!r)return _({result:{error:oe},stack:s});if(n!==void 0&&!Number.isSafeInteger(n))return{error:G,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=Kn({entries:i.entries})),e?.entries&&(a(e),e.entries=Kn({entries:e.entries}))),{...C}}function RN({tournamentRecord:t,entryPositions:e,drawDefinition:r,event:n}){if(!t)return{error:Y};if(!Array.isArray(e))return{error:G};for(let o of e){let{participantId:i,entryPosition:s}=o,a=yy({skipRefresh:!0,tournamentRecord:t,drawDefinition:r,participantId:i,entryPosition:s,event:n});if(a.error)return a}return n?.entries&&(n.entries=Kn({entries:n.entries})),r?.entries&&(r.entries=Kn({entries:r.entries})),{...C}}function CN(t){let{participantId:e}=t;return e&&typeof e!="string"?{error:G,participantId:e}:Ay({...t,participantIds:[e].filter(Boolean)})}function Ay({tournamentRecord:t,drawDefinition:e,participantIds:r,stageSequence:n,stage:o=nt,eventId:i,event:s}){if(!t)return{error:Y};if(!Array.isArray(r))return{error:G,participantIds:r};if(!s)return{error:vt};let a="promoteAlternates";if(s){let c=J_({element:s,participantIds:r,stageSequence:n,stage:o});if(c.error)return c}if(e){let c=J_({element:e,participantIds:r,stageSequence:n,stage:o});if(c.error)return i?_({context:{drawPromotionError:c.error,drawId:e.drawId},result:{...C},stack:a}):c}return{...C}}function J_({participantIds:t,stageSequence:e,element:r,stage:n}){let o=(r.entries||[]).filter(m=>m.entryStatus===nn),i=(r.entries||[]).filter(m=>t.includes(m.participantId)),s=o.reduce((m,d)=>{let{entryPosition:l}=d;return isNaN(l)&&m||(!m||l<m.entryPosition)&&d||m},void 0),a=i.length?i:[s].filter(Boolean);if(!a?.length)return{error:VI};let c=a.filter(({entryStatus:m})=>m!==nn);if(c.length)return{error:zl,invalidEntryStatus:c};let u=a.filter(({entryStage:m})=>m&&m!==n);if(u.length)return{error:AC,invalidStage:u};let p=e&&a.filter(m=>m.stageSequence!==e);if(p?.length)return{error:EC,invalidStageSequence:p};for(let m of a){m.entryStatus=kr;let d=m?.entryPosition;isNaN(d)||r.entries.forEach(f=>{f.entryStatus===nn&&f.entryPosition>d&&(f.entryPosition=f.entryPosition-1)});let l=Math.max(...r.entries.filter(f=>f.entryStatus===kr&&!isNaN(f.entryPosition)).map(({entryPosition:f})=>pt(f||0)),0);m.entryPosition=l||0}return{...C}}function bN({autoEntryPositions:t=!0,participantIds:e,drawDefinition:r,drawId:n,stages:o,event:i}){if(!i)return{error:vt};if(!n)return{error:an};if(!e?.length)return{error:Uo};let s=Ri({drawDefinition:r,stages:o}).assignedParticipantIds??[];if(Fe(s,e))return{error:vs};let c=m=>{let d=m.participantId;return!e.includes(d)},{flightProfile:u}=Ht({event:i}),p=u?.flights?.find(m=>m.drawId===n);return p?.drawEntries&&(p.drawEntries=p.drawEntries.filter(c),t&&(p.drawEntries=Kn({entries:p.drawEntries}))),r?.entries&&(r.entries=r.entries.filter(c),t&&(r.entries=Kn({entries:r.entries}))),{...C}}function bn(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:Y};if(!s)return _({result:{error:wi},stack:e});s.participantId||(s.participantId=Dt()),a.participants||(a.participants=[]);let{participantId:c,individualParticipantIds:u}=s;if(a.participants.reduce((I,h)=>h.participantId===c||I,!1))return{error:aE};let{participantType:m,participantRole:d}=s;if(!m||!Object.keys(mu).includes(m))return{error:An,participantType:m};if(!d)return{error:sE};let l=a.participants||[],f=l.filter(I=>I.participantType===Tt).map(I=>I.participantId);if(m!==Tt&&s.person)return{error:G,person:s.person};if(u&&!Array.isArray(u))return{error:G,individualParticipantIds:u};if(m===ft){if(s.person)return{error:G,person:s.person};if(s.individualParticipantIds){if(s.individualParticipantIds.length!==2&&!i)return _({info:"PAIR must be 2 individualParticipantIds",result:{error:wr},stack:e});{let S=l.filter(y=>y.participantType===Tt).map(y=>y.participantId);if(!Array.isArray(s.individualParticipantIds))return _({result:{error:wr},stack:e});if(!s.individualParticipantIds.reduce((y,P)=>S.includes(P)&&y,!0))return _({result:{error:wr},stack:e})}}else return _({result:{error:Uo},stack:e});let I=l.filter(S=>S.participantType===ft).map(S=>({individualParticipantIds:S.individualParticipantIds,participant:S})),h=s.participantType===ft&&I.find(S=>Yt(S.individualParticipantIds,s.individualParticipantIds).length===2);if(h&&!r)return{...C,existingParticipant:!0,participant:n&&J(h.participant)};if(!s.participantName){let S=l.filter(y=>s.individualParticipantIds?.includes(y.participantId)),T=S.map(y=>y.person?.standardFamilyName).filter(Boolean).join("/");S.length===1&&(T+="/Unknown"),s.participantName=T}}else if(m===Tt){if(!s.person?.standardFamilyName||!s.person?.standardGivenName)return{error:mE};if(!s.participantName){let I=`${s.person.standardFamilyName.toUpperCase()}, ${s.person.standardGivenName}`;s.participantName=I}}else if(m&&[Lt,zr].includes(m)){if(u||(s.individualParticipantIds=[]),s.individualParticipantIds?.length)for(let I of s.individualParticipantIds){if(typeof I!="string")return _({result:{participantId:I,error:G},stack:e});if(!f.includes(I))return _({result:{participantId:I,error:te},stack:e})}}else return{error:An};a.participants.push(s),o||mt({payload:{tournamentId:a.tournamentId,participants:[s]},topic:Zo});let g={participant:n&&J(s),...C};return ot(g)}function Sn({allowDuplicateParticipantIdPairs:t,returnParticipants:e,tournamentRecord:r,participants:n=[]}){if(!r)return{error:Y};r.participants||(r.participants=[]);let i=r.participants.map(d=>d.participantId)||[];n.forEach(d=>{d.participantId||(d.participantId=Dt())});let s=n.filter(d=>!i.includes(d.participantId)),a=n.filter(d=>i.includes(d.participantId)),c=s.filter(d=>d.participantType===Tt),u=s.filter(d=>d.participantType!==Tt),p=c.concat(...u),m=[];if(p.length){for(let l of p){let f=bn({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&&mt({topic:Zo,payload:{tournamentId:r.tournamentId,participants:m}});let d={participants:e&&J(m),addedCount:m.length,...C};return a.length&&Object.assign(d,{notAdded:a,info:zu}),ot(d)}else return{info:"No new participants to add",addedCount:0,...C}}function vN(t){let e=rt(t,[{[ie]:!0,[Do]:!0}]);if(e.error)return e;let{allowDuplicateParticipantIdPairs:r,entryStatus:n=nn,participantIdPairs:o=[],entryStage:i=nt,tournamentRecord:s,drawDefinition:a,event:c,uuids:u}=t;if(c.eventType!==_t)return{error:Bn};let p=[],m=new Map;for(let y of s.participants??[]){let{participantType:P,participantId:U,person:E,individualParticipantIds:A}=y;P===Tt&&E?.sex?m.set(U,E.sex):P===ft&&A&&p.push(A)}let d=o.filter(y=>{if(y.length!==2)return!0;if(!c.gender||c.gender===Pn)return!1;if(!m.has(y[0])||!m.has(y[1]))return!0;let P=y.map(E=>m.get(E)),U=c.gender===$t&&(P[0]!==$t||P[1]!==$t)||c.gender===ne&&(P[0]!==ne||P[1]!==ne);return c.gender===Tr&&(P.sort(Tu),(P[0]!==ne||P[1]!==$t)&&(U=!0)),U});if(d.length)return{error:wr,invalidParticipantIdPairs:d};let l=o.map(y=>({participantId:u?.pop()??Dt(),participantRole:xe,individualParticipantIds:y,participantType:ft})),f=r?l:l.filter(y=>!p.find(P=>Yt(P,y.individualParticipantIds).length===2)),g,I=[];if(f){let y=Sn({allowDuplicateParticipantIdPairs:r,participants:f,returnParticipants:!0,tournamentRecord:s});if(y.error)return y;I=y.participants||[],g=y.info}let h=o.map(y=>{let P=I.find(E=>Yt(E.individualParticipantIds,y).length===2);if(P)return P;let{participant:U}=In({tournamentRecord:s,participantIds:y});return U}).map(y=>y.participantId),S=Fn({participantIds:h,tournamentRecord:s,drawDefinition:a,entryStatus:n,entryStage:i,event:c});f.length&&mt({payload:{participants:f},topic:Zo});let T=f.map(St);return{...S,info:g,newParticipantIds:T}}function ON({entryStatus:t=kr,unpairedParticipantIds:e=[],participantIdPairs:r=[],entryStage:n=nt,tournamentRecord:o,event:i}){if(!o)return{error:Y};if(!i)return{error:vt};let s=o.participants??[],a=s.filter(h=>h.participantType===Tt).map(h=>h.participantId),u=e.concat(...r).flat(1/0).filter(h=>!a.includes(h));if(u.length)return{error:wr,invalidParticipantIds:u};let p=r.filter(h=>h.length!==2);if(p.length)return{error:wr,invalidParticipantIdPairs:p};let m=s.filter(h=>h.participantType===ft).map(h=>h.individualParticipantIds),l=r.filter(h=>!m.find(S=>Yt(S,h).length===2)).map(h=>({participantType:ft,participantRole:xe,individualParticipantIds:h})),f=Sn({participants:l,tournamentRecord:o});if(f.error)return f;let g=r.map(h=>{let{participant:S}=In({tournamentRecord:o,participantIds:h});return S}).map(h=>({participantId:h,entryStatus:t,entryStage:n})),I=e.map(h=>({entryStatus:Gr,participantId:h,entryStage:n}));return i.entries=(i.entries??[]).filter(h=>h.entryStage===n),i.entries=i.entries.concat(...g,...I),{...C}}var $N={};Xt($N,{addDrawDefinition:()=>Cc,addEvent:()=>ra,addFlight:()=>Zp,assignSeedPositions:()=>HN,attachFlightProfile:()=>Xg,categoryCanContain:()=>Yc,deleteDrawDefinitions:()=>Jp,deleteEvents:()=>jN,deleteFlightAndFlightDraw:()=>VN,deleteFlightProfileAndFlightDraws:()=>kN,generate:()=>LN,generateEventsFromTieFormat:()=>wN,getCategoryAgeDetails:()=>Ls,getEvent:()=>Sy,getEventProperties:()=>Iy,getEventStructures:()=>Ig,getEventTimeItem:()=>du,getEvents:()=>hy,getFlightProfile:()=>Ht,getScaledEntries:()=>ta,modifyEvent:()=>YN,modifyEventMatchUpFormatTiming:()=>GN,modifyPairAssignment:()=>BN,mutate:()=>qN,query:()=>PN,refreshEventDrawOrder:()=>Qg,removeEventMatchUpFormatTiming:()=>pl,removeScaleValues:()=>Jg,removeSeeding:()=>WN,setEventDates:()=>Kg,setEventDisplay:()=>ml,setEventEndDate:()=>My,setEventStartDate:()=>Ny,updateDrawIdsOrder:()=>zg,validateCategory:()=>jc});var LN={};Xt(LN,{generateEventsFromTieFormat:()=>wN});function Z_({tournamentId:t,event:e}){return e?(mt({payload:{tournamentId:t,event:e},key:e.eventId,topic:CU}),{...C}):{error:vt}}var tx={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 ex={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 rx={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 Ey={COLLEGE_D3:tx,COLLEGE_DEFAULT:ex,COLLEGE_JUCO:rx,DOMINANT_DUO:mh,DOMINANT_DUO_MIXED:ah,LAVER_CUP:Ih,TEAM_DOUBLES_3_AGGREGATION:rh,TIME_TENNIS_DUAL:ch,TIME_TENNIS_PRO_CIRCUIT:sh,USTA_BREWER_CUP:uh,USTA_OZAKI_CUP:ph,USTA_COLLEGE:dh,USTA_GOLD_TEAM_CHALLENGE:eh,USTA_INTERSECTIONAL:ih,USTA_LEVEL_1:lh,USTA_SECTION_BATTLE:oh,USTA_SOUTHERN_LEVEL_5:nh,USTA_TOC:hh,USTA_WTT_ITT:fh,USTA_ZONAL:gh};function ra({suppressNotifications:t,tournamentRecord:e,internalUse:r,event:n}){if(!e)return{error:Y};if(e.events||(e.events=[]),!n)return{error:vt};let{startDate:o,endDate:i}=e;if(!r&&(n.entries?.length||n.drawDefinitions?.length)){let c=ot({drawDefinitions:!!n.drawDefinitions?.length,entries:!!n.entries?.length});return{info:"entries/drawDefinitions cannot exist",error:G,context:c}}let s={eventType:Fs,drawDefinitions:[],entries:[],startDate:o,endDate:i,...n};if(n.eventType===Cr){if(n.tieFormat){let c=ar({tieFormat:n.tieFormat});if(c.error)return c}else if(n.tieFormatName){if(!Ey[n.tieFormatName])return{context:{tieFormatName:n.tieFormatName},error:G};let c=Zn({isMock:e?.isMock,namedFormat:n.tieFormatName,event:n});s.tieFormat=c}}if(s.eventId||(s.eventId=Dt()),e.events.reduce((c,u)=>c||u.eventId===s.eventId,void 0))return{error:HA};{let c=s;if(e.events.push(c),!t){let{topics:u}=Lr();if(u.includes(hp)){let d=$n({event:n}).matchUps??[];Co({tournamentId:e?.tournamentId,eventId:n.eventId,matchUps:d})}let{drawDefinitions:p,...m}=n;for(let d of p||[])Ta({drawDefinition:d});Z_({tournamentId:e?.tournamentId,event:m})}return{...C,event:s}}}function wN(t){let e=rt(t,[{[Gs]:{[Fm]:!0,[Ph]:!0}},{[ie]:!0}]);if(e.error)return e;let r=t.tieFormat||Zn({namedFormat:t.tieFormatName}),n=t.uuids||[th(r.collectionDefinitions.length)],o={[$t]:[],[ne]:[]};if(t.addEntriesFromTeams){let a=t.tournamentRecord.participants?.filter(c=>c.participantType===yr)?.flatMap(c=>c.individualParticipantIds??[]);for(let c of t.tournamentRecord.participants??[])if(a?.includes(c.participantId)){let u=c.person?.sex;u&&[$t,ne].includes(u)&&o[u].push(c.participantId)}}let i=[];for(let s of r.collectionDefinitions??[]){let a=n?.pop()?.toString()||Dt(),c=s.matchUpType,u=s.gender,p={matchUpFormat:s.matchUpFormat,eventName:s.collectionName,category:s.category,gender:u,eventType:c,eventId:a};if(t.addEntriesFromTeams){let m=c===ko?Gr:t.entryStatus||kr,d=u===Tr?[...o[$t],...o[ne]]:o[u]??[];if(d.length){let l=Fn({participantIds:d,entryStatus:m,event:p});if(l.error)return l}}if(i.push(p),t.addEvents!==!1){let m=ra({internalUse:!0,tournamentRecord:t.tournamentRecord,event:p});if(m.error)return m}}return{...C,events:i}}var qN={};Xt(qN,{addDrawDefinition:()=>Cc,addEvent:()=>ra,addFlight:()=>Zp,assignSeedPositions:()=>HN,attachFlightProfile:()=>Xg,deleteDrawDefinitions:()=>Jp,deleteEvents:()=>jN,deleteFlightAndFlightDraw:()=>VN,deleteFlightProfileAndFlightDraws:()=>kN,modifyEvent:()=>YN,modifyEventMatchUpFormatTiming:()=>GN,modifyPairAssignment:()=>BN,refreshEventDrawOrder:()=>Qg,removeEventMatchUpFormatTiming:()=>pl,removeScaleValues:()=>Jg,removeSeeding:()=>WN,setEventDates:()=>Kg,setEventDisplay:()=>ml,setEventEndDate:()=>My,setEventStartDate:()=>Ny,updateDrawIdsOrder:()=>zg,validateCategory:()=>jc});function na({removePriorValues:t=!0,status:e=Nr,statusObject:r,event:n}){if(!ht(r))return{error:G};let o=Xr({event:n,status:e}),i=`${_o}.${xo}`,s={itemValue:{[e]:{...o,...r}},itemType:i};return zi({timeItem:s,removePriorValues:t,event:n})}function oa(t){let e=rt(t,[{[ie]:!0,[Do]:!0},{eventDataParams:!1,[He]:Kr}]);if(e.error)return e;let{includePositionAssignments:r,removePriorValues:n,tournamentRecord:o,status:i=Nr,event:s,drawIdsToRemove:a,drawIdsToAdd:c}=t,{appliedPolicies:u}=yt({tournamentRecord:o,event:s}),p={...u,...t.policyDefinitions},m=s?.drawDefinitions?.map(({drawId:P})=>P)??[],d=t.drawDetails?Object.keys(t.drawDetails):[],l=d.length?[]:t.drawIds,f=(c??[]).concat(...a??[],...l??[],...d),g=f.filter(P=>!m.includes(P));if(g.length)return _({result:{error:Mr},context:{invalidDrawIds:g}});let I=Xr({event:s,status:i}),h=Object.keys(I?.drawDetails||{}).filter(P=>m.includes(P)).reduce((P,U)=>(P[U]=I.drawDetails[U],P),{});for(let P of m)if((!f.length||f.includes(P))&&(a?.includes(P)||l?.length&&!l.includes(P)?h[P]={...h[P],publishingDetail:{published:!1}}:(c?.includes(P)||l?.includes(P)||!l?.length)&&(h[P]={...h[P],publishingDetail:{published:!0}})),t.drawDetails?.[P]){let U=t.drawDetails[P],E=U.structureDetails??h[P].structureDetails,A=U.stageDetails??h[P].stageDetails??{},{structureIdsToRemove:N=[],structureIdsToAdd:D=[],publishingDetail:M={},stagesToRemove:R=[],stagesToAdd:b=[]}=U;if((D||b)&&(M.published=!0),h[P]={publishingDetail:M,structureDetails:E,stageDetails:A},D.length||N.length){let O=(s?.drawDefinitions?.find(L=>L.drawId===P)?.structures??[]).map(({structureId:L})=>L),F=(D??[]).concat(N??[]).filter(L=>!O.includes(L));if(F.length)return _({result:{error:kt},context:{invalidStructureIds:F}});E=E??{};for(let L of O)N.includes(L)?E[L]={published:!1}:E[L]={published:!0};h[P].structureDetails=E}let v=(s?.drawDefinitions?.find(O=>O.drawId===P)?.structures??[]).map(({stage:O})=>O);if(b.length){for(let O of b)A[O]={published:!0};for(let O of v)A[O]||(A[O]={published:!1})}if(b.length||R.length){for(let O of R)A[O]={published:!1};for(let O of v)A[O]||(A[O]={published:!0})}(b.length||R.length)&&(h[P].stageDetails=A)}na({statusObject:{drawDetails:h},removePriorValues:n,status:i,event:s});let{topics:S}=Lr(),T=S.includes(jh),y=T||t.returnEventData?tl({includePositionAssignments:r,...t.eventDataParams,usePublishState:!0,tournamentRecord:o,policyDefinitions:p,event:s})?.eventData:void 0;return T&&mt({payload:{eventData:y,tournamentId:o.tournamentId},topic:jh}),{...C,eventData:y}}var FN="deleteDrawDefinitions",Uy="autoSchedulingAudit",qg="deleteEvents",nx={AUTO_SCHEDULING_AUDIT:Uy,DELETE_EVENTS:qg,DELETE_DRAW_DEFINITIONS:FN};function Jp(t){if(!t.tournamentRecord)return{error:Y};let e="deleteDrawDefinitions",r=t.drawIds??[],n=t.event,{autoPublish:o=!0,tournamentRecord:i,auditData:s,eventId:a,force:c}=t,{appliedPolicies:u}=yt({tournamentRecord:i,event:n}),p={...u,...t.policyDefinitions},m=Array.isArray(r)?r[0]:void 0;if(!n){let A=ze({tournamentRecord:i,eventId:a,drawId:m});if(A.error)return A;n=A.event}let d=[],l=[],f=[];if(!n?.drawDefinitions)return _({info:"event has no drawDefinition",result:{...C},stack:e});let g=n.drawDefinitions.map(({drawId:A})=>A);if(r.length||(r=g),r=r.filter(A=>g.includes(A)),!r.length)return _({info:"nothing to do; no matching drawIds in event.",result:{...C},stack:e});let I=J(Ht({event:n}).flightProfile,!1,!0),h=({participantId:A,drawPosition:N,qualifier:D,bye:M})=>({bye:M,qualifier:D,drawPosition:N,participantId:A}),S=c??u?.[en]?.allowDeletionWithScoresPresent?.drawDefinitions,T=Xr({event:n})??{},y=T.drawIds??(T.drawDetails&&Object.keys(T.drawDetails))??[],P,U=[],E=n.drawDefinitions.filter(A=>{if(r.includes(A.drawId)){let N=or({event:n,drawDefinition:A})?.matchUps??[];if(N.some(({score:k})=>Ie({score:k}))&&!S)return U.push(A.drawId),!0;let{drawId:M,drawType:R,drawName:b}=A,v=I?.flights?.find(k=>k.drawId===A.drawId);v&&(v.drawEntries=v.drawEntries?.filter(k=>Qr.includes(k.entryStatus))),y.includes(M)&&(y=y.filter(k=>k!==M),P=!0);let O=gn({stageSequence:1,drawDefinition:A,stage:nt})?.structures?.[0],F=(O?Gp({structureId:O.structureId,tournamentRecord:i,drawDefinition:A}):void 0)?.positionAssignments?.map(h),L=gn({stage:ct,drawDefinition:A})?.structures,w=L?.length?L.map(k=>{let W=k.stageSequence;return{positionAssignments:Gp({structureId:k.structureId,tournamentRecord:i,drawDefinition:A})?.positionAssignments.map(h),stageSequence:W}}):void 0,V={action:FN,payload:{drawDefinitions:[A],eventId:a??n?.eventId,auditData:s}};f.push(V),d.push(ot({tournamentId:i.tournamentId,eventId:a??n?.eventId,qualifyingPositionAssignments:w,positionAssignments:F,auditData:s,drawType:R,drawName:b,drawId:M})),N?.forEach(({matchUpId:k})=>l.push(k))}return!r.includes(A.drawId)});if(U.length&&!c)return _({context:{drawIdsWithScoresPresent:U},result:{error:tp},stack:e});if(n.drawDefinitions=E,I&&Mo({event:n,extension:{name:un,value:I}}),Rc({tournamentRecord:i}),P){let A={};for(let D of y)A[D]=T.drawDetails?.[D]??{published:!0};let N=na({statusObject:{drawDetails:A},event:n});if(N.error)return{error:N.error}}if(f.length)if(rp(Ti)){let A=i.tournamentId;mt({topic:Ti,payload:{tournamentId:A,detail:f}});let D=(rn({element:n,itemType:Ia})?.timeItem?.itemValue||0)+1;Qn({element:n,timeItem:{itemType:Ia,itemValue:D},removePriorValues:!0})}else t1({appliedPolicies:u,event:n,deletedDrawsDetail:d,auditData:s});if(l.length&&Yn({tournamentId:i?.tournamentId,matchUpIds:l}),r.forEach(A=>Tb({drawId:A})),o&&P){let A=oa({...t.eventDataParams,drawIdsToRemove:r,policyDefinitions:p,tournamentRecord:i,event:n});if(A.error)return{...C,info:A.error}}return{...C}}function t1({appliedPolicies:t,event:e,deletedDrawsDetail:r,auditData:n}){if(t?.audit?.[Ia]===!1)return;let{extension:o}=dt({name:Ia,element:e}),i={...n,deletedDrawsDetail:r},s={value:Array.isArray(o?.value)?o?.value.concat(i):[i],name:Ia};At({element:e,extension:s})}function kN({autoPublish:t=!0,tournamentRecord:e,auditData:r,event:n,force:o}){if(!e)return{error:Y};if(!n)return{error:vt};let{flightProfile:i}=Ht({event:n});if(i){let s=i.flights?.map(({drawId:c})=>c).filter(Boolean),a=Jp({eventId:n.eventId,tournamentRecord:e,autoPublish:t,auditData:r,drawIds:s,event:n,force:o});return a.error?a:gp({event:n,name:un})}return{...C}}function $g(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:wt};let a=Object.keys(s).filter(u=>!o||o===u);if(o&&!a.includes(o))return{error:G};let c;for(let u of a){let p=s[u],{event:m}=ze({tournamentRecord:p,eventId:i});i&&m&&(c=!0);let d=e1({tournamentRecord:p,event:m,matchUpFormat:e,averageTimes:n,recoveryTimes:r});if(d.error)return d}return!i||c?{...C}:{error:jr}}function e1({tournamentRecord:t,recoveryTimes:e,matchUpFormat:r,averageTimes:n,event:o}){if(!t)return{error:Y};if(n&&!Array.isArray(n))return{error:G};if(e&&!Array.isArray(e))return{error:G};let i=Vo;if(o){let{extension:s}=dt({element:o,name:i}),a=s?.value||{},c=ox({...a,matchUpFormat:r,averageTimes:n,recoveryTimes:e});At({element:o,extension:{name:i,value:c}})}else{let{extension:s}=dt({element:t,name:i}),a=s?.value||{},c=ox({...a,matchUpFormat:r,averageTimes:n,recoveryTimes:e});At({extension:{name:i,value:c},element:t})}return{...C}}function ox(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 GN(t){let{tournamentRecord:e,recoveryMinutes:r,averageMinutes:n,matchUpFormat:o,categoryType:i,eventId:s,event:a}=t;if(!e)return{error:Y};if(!Pr({matchUpFormat:o}))return{error:G};if(!a)return{error:vt};let{averageTimes:c=[],recoveryTimes:u=[]}=il({tournamentRecord:e,matchUpFormat:o,event:a}),p=a.category,m=p?.categoryName||p?.ageCategoryCode||a?.eventId,d={categoryNames:[m],minutes:{}},l={categoryNames:[m],minutes:{}},f=T=>{if(T.categoryTypes?.includes(i)&&console.log("encountered:",{categoryType:i}),!(T.categoryNames?.includes(m)&&(T.categoryNames=T.categoryNames.filter(y=>y!==m),d={minutes:T.minutes,categoryNames:[m]},!T.categoryNames.length)))return T},g=n&&!isNaN(pt(n)),I=r&&!isNaN(pt(r)),h=c.map(f).filter(T=>T?.categoryNames?.length),S=u.map(f).filter(T=>T?.categoryNames?.length);return g&&(Object.assign(d.minutes,{[a?.eventType||xt]:n}),h.push(d)),I&&(Object.assign(l.minutes,{[a?.eventType||xt]:r}),S.push(l)),!g&&!I?{error:G}:$g({averageTimes:g&&h,recoveryTimes:I&&S,tournamentRecord:e,matchUpFormat:o,eventId:s,event:a})}function pl(t){if(t.event)return ix({event:t.event});{t.tournamentRecord&&!t.tournamentRecords&&(t.tournamentRecords={[t.tournamentRecord.tournamentId]:t.tournamentRecord});let e=rt(t,[{[Re]:!0,[Rh]:!0}]);if(e.error)return e;let{tournamentRecords:r,eventId:n}=t;for(let o of Object.values(r??{})){let{event:i}=ze({tournamentRecord:o,eventId:n});if(i)return ix({event:i})}}return{error:jr}}function ix({event:t}){return gp({event:t,name:Vo})}var r1="MON",n1="TUE",o1="WED",i1="THU",s1="FRI",a1="SAT",c1="SUN",Py={MON:r1,TUE:n1,WED:o1,THU:i1,FRI:s1,SAT:a1,SUN:c1};function Dy(t){return!Array.isArray(t)||ut(t).length!==t.length?!1:t.every(e=>Object.keys(Py).includes(e))}function Ny({tournamentRecord:t,event:e,startDate:r}){if(!t)return{error:Y};if(!e)return{error:vt};if(!Po.test(r))return{error:je};let n=sx(t);if(n.error)return n;let{tournamentStartDate:o,tournamentEndDate:i}=n,s=new Date(Et(r)).getTime();if(!o||!i||s<o||s>i)return{error:je};let a=e.endDate&&new Date(Et(e.endDate)).getTime();return a&&s>a&&(e.endDate=r),e.startDate=r,{...C}}function My(t){let{tournamentRecord:e,event:r,endDate:n}=t;if(!e)return{error:Y};if(!r)return{error:vt};if(!Po.test(n))return{error:je};let o=sx(e);if(o.error)return o;let{tournamentStartDate:i,tournamentEndDate:s}=o,a=new Date(Et(n)).getTime();if(!i||!s||a<i||a>s)return{error:je};let c=r.startDate&&new Date(Et(r.startDate)).getTime();return c&&a<c&&(r.startDate=n),r.endDate=n,{...C}}function Kg(t){let e=rt(t,[{tournamentRecord:!0,event:!0},{[tr]:c=>Po.test(c),[Fr]:je,startDate:!1,endDate:!1},{[tr]:c=>c.filter(Boolean).every(u=>Po.test(u)),[Fr]:je,activeDates:!1},{[tr]:Dy,weekdays:!1}]);if(e.error)return e;let{tournamentRecord:r,weekdays:n,event:o,startDate:i,endDate:s}=t,a=t.activeDates?.filter(Boolean);if(i&&s){let c=new Date(Et(i)).getTime(),u=new Date(Et(s)).getTime();if(c>u)return{error:G}}if(a){let c=i||r.startDate,u=s||r.endDate,p=!c||a.every(d=>new Date(d)>=new Date(c)),m=!u||a.every(d=>new Date(d)<=new Date(u));if(!p||!m)return{error:je}}if(i){let c=Ny({tournamentRecord:r,event:o,startDate:i});if(c.error)return c}if(s){let c=My({tournamentRecord:r,event:o,endDate:s});if(c.error)return c}return a&&(o.activeDates=a),n&&(o.weekdays=n),{...C}}function sx(t){let{startDate:e,endDate:r}=t;return!Po.test(e)||!Po.test(r)?_({result:{error:rE},context:{startDate:e,endDate:r}}):{tournamentStartDate:new Date(Et(e)).getTime(),tournamentEndDate:new Date(Et(r)).getTime()}}function zg({event:t,orderedDrawIdsMap:e}){if(typeof t!="object")return{error:vt};if(!e)return{error:st,info:"Missing drawIdsOrderMap"};if(typeof e!="object")return{error:G,info:"orderedDrawIdsMap must be an object"};let r=Object.values(e);if(!r.every(i=>!isNaN(i)))return{error:G,info:"drawOrder must be numeric"};if(ut(r).length!==r.length)return{error:G,info:"drawOrder values must be unique"};if(t.drawDefinitions?.length){let i=(t.drawDefinitions||[]).map(({drawId:a})=>a),s=Object.keys(e);if(s?.length&&Yt(i,s).length!==i.length)return{error:G,info:"Missing drawIds"};t.drawDefinitions.forEach(a=>{a.drawOrder=e[a.drawId]})}let{flightProfile:o}=Ht({event:t});return o?.flights?.forEach(i=>{i.flightNumber=e[i.drawId]}),{...C}}function Qg({tournamentRecord:t,event:e}){if(!t)return{error:Y};if(!e)return{error:vt};let{flightProfile:r}=Ht({event:e}),n=r?.flights&&Object.assign({},...r.flights.sort((o,i)=>o.flightNumber-i.flightNumber).map((o,i)=>({[o.drawId]:i+1})))||e.drawDefinitions?.length&&Object.assign({},...e.drawDefinitions.sort((o,i)=>o.drawOrder-i.drawOrder).map((o,i)=>({[o.drawId]:i+1})))||void 0;return n?zg({event:e,orderedDrawIdsMap:n}):{...C}}function VN({autoPublish:t=!0,tournamentRecord:e,auditData:r,drawId:n,event:o,force:i}){if(!e)return{error:Y};if(!n)return{error:an};if(!o)return{error:vt};let{flightProfile:s}=Ht({event:o});if(s&&s.flights?.find(u=>u.drawId===n)){let u=s.flights.filter(m=>m.drawId!==n),p={name:un,value:{...s,flights:u}};Mo({event:o,extension:p})}if(o.drawDefinitions?.find(c=>c.drawId===n)){let c=Jp({drawIds:[n],eventId:o.eventId,tournamentRecord:e,autoPublish:t,auditData:r,event:o,force:i});if(c.error)return c}return Qg({tournamentRecord:e,event:o})}function BN(t){let e=rt(t,[{[Do]:!0,[ie]:!0,[Nf]:!1},{replacementIndividualParticipantId:!0,[tr]:h=>Vt(h),existingIndividualParticipantId:!0,[fn]:oe,participantId:!0}]),{replacementIndividualParticipantId:r,existingIndividualParticipantId:n,tournamentRecord:o,drawDefinition:i,participantId:s,event:a,uuids:c}=t;if(e.error)return e;if(a?.eventType!==qr)return{error:Bn};if(!(a?.entries?.filter(({entryStatus:h})=>[Gr,Ei].includes(h)).map(({participantId:h})=>h)||[]).includes(r))return{error:mn};let p=(o.participants||[]).find(h=>h.participantId===s);if(p?.participantType!==ft)return{error:xi,participant:p};let m=p.individualParticipantIds,d=[r,...m.filter(h=>h!==n)],{participant:l}=In({participantIds:d,tournamentRecord:o}),f;if(l)f=l.participantId;else{let h={participantId:c?.pop(),participantRole:xe,individualParticipantIds:d,participantType:ft},S=bn({participant:h,returnParticipant:!0,tournamentRecord:o});if(S.error)return S;f=S.participant.participantId}let{flightProfile:g}=Ht({event:a});if(i){let h=g?.flights?.find(({drawId:S})=>S===i.drawId);h&&(h.drawEntries=h.drawEntries.map(S=>S.participantId===s?{...S,participantId:f}:S)),i.entries=i.entries.map(S=>S.participantId===s?{...S,participantId:f}:S);for(let S of i.structures||[])if(S.structures){S.positionAssignments=void 0;for(let T of S.structures)T.positionAssignments=T.positionAssignments.map(y=>y.participantId===s?{...y,participantId:f}:y)}else S.positionAssignments&&(S.positionAssignments=S.positionAssignments.map(T=>T.participantId===s?{...T,participantId:f}:T))}a.entries=a.entries.map(h=>h.participantId===s&&{...h,participantId:f}||h.participantId===r&&{...h,participantId:n}||h);let I=o.events.some(({entries:h,eventId:S,drawDefinitions:T})=>a.eventId===S?T.some(({drawId:y,entries:P})=>y===i?.drawId?!1:P?.find(U=>U.participantId===s)):h?.find(y=>y.participantId===s));if(!I){let h=$i({addIndividualParticipantsToEvents:!1,participantIds:[s],tournamentRecord:o});if(h.error)return h}return{...C,participantOtherEntries:I,newPairParticipantId:f}}function Cc(t){let{flight:e,suppressNotifications:r,modifyEventEntries:n,existingDrawCount:o,allowReplacement:i,checkEntryStatus:s,tournamentRecord:a,drawDefinition:c,event:u}=t;if(!c)return{error:Z};if(!u)return{error:vt};u.drawDefinitions||(u.drawDefinitions=[]);let{drawId:p,drawName:m,entries:d}=c,{entries:l}=u,f=0;if(o!==void 0&&o!==u.drawDefinitions.length)return{error:G,info:"drawDefintions count mismatch"};let{flightProfile:g}=Ht({event:u}),I=e&&g?.flights?.find(v=>v.flightNumber===e.flightNumber),h=g?.links?.find(v=>v?.target?.drawId===p)?.source?.drawId;if(h&&!u.drawDefinitions.find(v=>v.drawId===h))return _({result:{error:Z},info:{sourceDrawId:h}});if(I&&I.drawId!==c.drawId)return _({result:{error:ua},info:{relevantFlight:I}});let y=d?.every(({participantId:v,entryStatus:O})=>{let x=I?.drawEntries.find(F=>F.participantId===v);return!O||x?.entryStatus===O}),P=!s||l&&d?.every(({participantId:v,entryStatus:O,entryStage:x})=>l.find(L=>L.participantId===v&&(!L.entryStage||L.entryStage===x))?.entryStatus===O);if(I&&!y)return _({result:{error:ua},context:{drawEntriesPresentInFlight:y,matchingEventEntries:P,relevantFlight:I},info:"Draw entries are not present in flight or do not match entryStatuses"});if(n&&d?.filter(Boolean).forEach(v=>{if(v?.entryStatus&&Qr.includes(v?.entryStatus)){let O=l?.filter(Boolean).find(x=>x.participantId===v.participantId);O&&v.entryStatus&&O?.entryStatus!==v.entryStatus&&(O.entryStatus=v.entryStatus,f+=1)}}),l&&!P)return _({result:{info:"Draw entries do not match event entryStatuses",context:{matchingEventEntries:P,eventEntries:l},error:ua}});let U=g?.flights?.map(({flightNumber:v})=>!isNaN(v)&&pt(v))?.filter(Boolean)||[],E=u.drawDefinitions.map(({drawOrder:v})=>v&&pt(v))?.filter(Boolean)||[],A=Math.max(0,...E,...U)+1,N=g?.flights?.find(v=>v.drawId===p),D;if(N){N.drawName=c.drawName,D={name:un,value:{...g,flights:g.flights}};let v=N.flightNumber;v&&!E.includes(v)?A=v:N.flightNumber=A}else{let v=g?.flights||[];v.push({manuallyAdded:!0,flightNumber:A,drawEntries:d,drawName:m,drawId:p}),D={name:un,value:{...g||{},flights:v}}}Mo({event:u,extension:D}),Object.assign(c,{drawOrder:A});let M=u.drawDefinitions.find(v=>v.drawId===p),R=a?.tournamentId,b=u.eventId;if(M){if(!i)return{error:OA};let O=or({drawDefinition:M})?.matchUps?.map(Ae)??[],x=or({drawDefinition:c})?.matchUps;if(!r){O?.length&&Yn({matchUpIds:O,action:"modifyDrawDefinition",tournamentId:R,eventId:b}),x?.length&&Co({matchUps:x,tournamentId:R,eventId:b}),u.drawDefinitions=u.drawDefinitions.map(L=>L.drawId===p?c:L);let F=c.structures?.map(({structureId:L})=>L);Ot({drawDefinition:c,tournamentId:R,structureIds:F,eventId:b})}}else if(u.drawDefinitions.push(c),!r){let{matchUps:v}=or({drawDefinition:c,event:u});v&&Co({tournamentId:a?.tournamentId,matchUps:v}),Ta({drawDefinition:c,tournamentId:R,eventId:b})}return{...C,modifiedEventEntryStatusCount:f}}function HN(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:Vl};if(!n)return{error:Y};if(!c)return{error:an};let m=on({provisionalPositioning:e,drawDefinition:o,structureId:s});if(m.error)return m;let{seedAssignments:d,seedLimit:l}=m,f=Object.assign({},...(d??[]).filter(h=>h.seedNumber).map(h=>({[h.seedNumber]:h})));a.forEach(h=>{let{seedNumber:S}=h;l&&S<=l&&(!r||f[S])&&(f[S]=h)});let g=Object.values(f),I=g.map(h=>h?.participantId).filter(Boolean);if(I.length!==PI(I).length)return{error:_A};for(let h of g){let S=$s({...h,provisionalPositioning:e,tournamentRecord:n,drawDefinition:o,seedingProfile:i,structureId:s,event:u});if(S?.error)return S;S?.success&&p++}return p?{...C,modifications:p}:{error:_s}}function Xg({deleteExisting:t,event:e,flightProfile:r}){let n="attachFlightProfile";if(!r)return _({result:{error:st},stack:n});if(!e)return _({result:{error:vt},stack:n});let{flightProfile:o}=Ht({event:e});return o&&!t?_({result:{error:nf},stack:n}):e.drawDefinitions?.length?_({result:{error:CA},stack:n}):(Mo({event:e,extension:{name:un,value:r}}),{flightProfile:J(r,!1,!0),...C})}function ax({tournamentRecord:t,scaleAttributes:e,participantIds:r}){if(!t)return{error:Y};if(!r)return{error:Uo};if(!e)return{error:st,info:"scaleAttributes required"};let{scaleType:n,eventType:o,scaleName:i}=e,s=[BU,n,o,i].join(".");return t.participants?.forEach(a=>{r.includes(a.participantId)&&a.timeItems&&(a.timeItems=a.timeItems.filter(c=>c&&c?.itemType!==s))}),{...C}}function Jg({tournamentRecord:t,scaleAttributes:e,drawDefinition:r,entryStatuses:n,drawId:o,event:i,stage:s}){if(!i)return{error:vt};if(n&&!Array.isArray(n))return _({result:{error:G},info:ii("entryStatus"),stack:"removeScaleValues"});let a=i.entries;if(o){let{flightProfile:p}=Ht({event:i}),m=p?.flights?.find(d=>d.drawId===o);m?a=m.drawEntries:a=r?.entries}let u=(a||[]).filter(p=>(!s||!p.entryStage||p.entryStage===s)&&(!n||n.includes(p.entryStatus))).map(St);return ax({tournamentRecord:t,scaleAttributes:e,participantIds:u})}function ml({removePriorValues:t,tournamentRecord:e,displaySettings:r,status:n=Nr,event:o}){if(!e)return _({result:{error:Y}});if(!o)return _({result:{error:vt}});if(!ht(r))return _({result:{error:st}});if(ht(r.draws))for(let s of Object.keys(r.draws)){let a=r.draws[s].scheduleDetails??[];if(a.length){let c=[];for(let u of a){let p=c.find(m=>gC(m.attributes,u.attributes));p?.dates&&u.dates?p.dates.push(...u.dates):c.push(u)}r.draws[s].scheduleDetails=c}}let i=na({statusObject:{displaySettings:r},removePriorValues:t,status:n,event:o});return i.error?i:{...C}}function WN({tournamentRecord:t,drawDefinition:e,entryStatuses:r,scaleName:n,drawId:o,event:i,stage:s}){if(!t)return{error:Y};if(!i)return{error:vt};n=n||i.category?.categoryName||i.category?.ageCategoryCode;let a={eventType:i.eventType,scaleType:ho,scaleName:n};return Jg({tournamentRecord:t,scaleAttributes:a,drawDefinition:e,entryStatuses:r,drawId:o,event:i,stage:s})}function jN(t){let e=rt(t,[{[ie]:!0},{eventIds:!0,[He]:Be}]);if(e.error)return e;let{removePairParticipants:r,tournamentRecord:n,eventIds:o}=t,i=[],s=[],a=[],c=[];if(n.events=(n.events||[]).filter(u=>{if(o.includes(u.eventId)){let d={action:qg,payload:{events:[u]}};i.push(d),s.push({tournamentId:n.tournamentId,eventName:u.eventName,eventType:u.eventType,category:u.category,eventId:u.eventId,gender:u.gender})}let p=u.eventType===qr?(u.entries||[]).map(({entryStatus:d,participantId:l})=>d!==Gr&&l).filter(Boolean):[],m=o.includes(u.eventId);return m?c.push(...p):a.push(...p),!m}),r){let u=c.filter(p=>!a.includes(p));n.participants=n.participants.filter(({participantId:p})=>!u.includes(p))}if(Rc({tournamentRecord:n}),i.length)if(rp(Ti)){let u=n.tournamentId;mt({topic:Ti,payload:{type:qg,tournamentId:u,detail:i}})}else Pc({tournamentRecord:n,timeItem:{itemValue:s,itemType:qg}});return{...C}}function YN(t){let e=rt(t,[{tournamentRecord:!0,eventId:!0,event:!0},{eventUpdates:!0,_ofType:Kr}]);if(e.error)return e;let{eventUpdates:r,event:n}=t,o="modifyEvent",i=m1(t),s=d1({enteredParticipants:i}),{enteredParticipantGenders:a,enteredParticipantTypes:c}=s,u=Ht({event:n})?.flightProfile?.flights,p=!n.drawDefinitions?.length&&!u?.length,m=l1({noFlightsNoDraws:p,enteredParticipantGenders:a,eventUpdates:r,stack:o});if(m.error)return m;let d=f1({enteredParticipantTypes:c,eventUpdates:r,stack:o});if(d.error)return d;let l=u1({...t,...s,enteredParticipants:i,stack:o});if(l.error)return l;let f=p1({...t,stack:o});return f.error?f:(r.eventType&&(n.eventType=r.eventType),r.eventName&&(n.eventName=r.eventName),r.gender&&(n.gender=r.gender),{...C})}function u1(t){let e=t.eventUpdates?.category;if(!e)return{...C};let r=jc({category:e});if(r.error)return r;if(t.event.eventType===_e){let n=t.event?.drawDefinitions?.map(u=>ni(u))??[],o=ni(t.event),s=($n(t)?.matchUps??[]).map(u=>ni(u))??[];if(![o,...n,...s].filter(Boolean).every(u=>u.collectionDefinitions.every(p=>!p.category||Yc({category:t.eventUpdates.category,childCategory:p.category}))))return _({result:{error:Vc},stack:t.stack})}if(t.enteredParticipants?.length){let n=t.eventUpdates.startDate||t.event.startDate||t.tournamentRecord.startDate,o=t.eventUpdates.endDate||t.event.endDate||t.tournamentRecord.endDate,i=t.enteredParticipants.map(c=>c.participantType===Tt?c:c.individualParticpants??[]).flat(),s=Ls({category:e,consideredDate:n}),a=Ls({category:e,consideredDate:o});if(s?.ageMinDate||s?.ageMaxDate||a?.ageMinDate||a?.ageMaxDate)for(let c of i){let u=c.person?.birthDate;if(!u)return _({result:{error:JA},stack:t.stack});let p=new Date(u).getTime();if(s.ageMinDate||s.ageMaxDate){let m=new Date(s.ageMinDate).getTime(),d=new Date(s.ageMaxDate).getTime();if(p<m||p>d)return _({result:{error:GI},stack:t.stack})}if(a.ageMin||a.ageMax){let m=new Date(a.ageMinDate).getTime(),d=new Date(a.ageMaxDate).getTime();if(p<m||p>d)return _({result:{error:GI},stack:t.stack})}}}return{...C}}function p1(t){let{tournamentRecord:e,eventUpdates:r,event:n,stack:o}=t;if(r.startDate||r.endDate){let i=Kg({startDate:r.startDate,endDate:r.endDate,tournamentRecord:e,event:n});if(i.error)return _({result:i,stack:o})}return{...C}}function m1(t){let{tournamentRecord:e,event:r}=t,n=r?.entries?.filter(({entryStatus:o})=>{let i=o;return[...Qr,nn].includes(i)}).map(({participantId:o})=>o)??[];return n?Gt({participantFilters:{participantIds:n},withIndividualParticipants:!0,tournamentRecord:e}).participants??[]:[]}function d1({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=ut(e);return{enteredParticipantTypes:r,enteredParticipantGenders:n}}function l1({noFlightsNoDraws:t,enteredParticipantGenders:e,eventUpdates:r,stack:n}){let o=!e.length||!r.gender||r.gender===Pn||e.length===1&&e[0]===r.gender||t&&r.gender===Tr;return r.gender&&!o?_({context:{gender:r.gender,validGender:o},result:{error:Xu},stack:n}):{...C}}function f1({enteredParticipantTypes:t,eventUpdates:e,stack:r}){let o=(t.includes(_e)&&[_e]||t.includes(Tt)&&[jn]||t.includes(ft)&&[qr]||[qr,jn,_e]).includes(e.eventType??"");return e.eventType&&!o?_({context:{participantType:e.eventType,validEventType:o},result:{error:Bn},stack:r}):{...C}}function Zp({qualifyingPositions:t,drawEntries:e=[],drawName:r,drawId:n,event:o,stage:i}){let s="addFlight";if(!o)return _({result:{error:vt},stack:s});if(!r)return _({result:{error:st},stack:s});if(e?.length){let g=(o.entries??[]).map(St),I=e.map(St);if(Yt(I,g).length!==I.length)return _({result:{error:G},stack:s})}let a=Ht({event:o})?.flightProfile,c=a?.flights?.map(({flightNumber:g})=>!isNaN(g)&&pt(g))?.filter(Boolean)||[],u=Math.max(0,...c)+1,m={drawId:n||Dt(),flightNumber:u,drawEntries:e,drawName:r};if(i&&(m.stage=i),t&&(m.qualifyingPositions=t),(a?.flights||[]).find(({drawId:g})=>g===m.drawId))return _({result:{error:bE},stack:s});let l=(a?.flights||[]).concat(m),f={name:un,value:{...a||{},flights:l}};return Mo({event:o,extension:f})}var ZN={};Xt(ZN,{drawMatic:()=>qd,garman:()=>JN,generateAdHocMatchUps:()=>Ou,generateAdHocRounds:()=>Yd,generateAndPopulatePlayoffStructures:()=>Cd,generateCourts:()=>Zg,generateDrawDefinition:()=>xa,generateDrawMaticRound:()=>Fd,generateDrawStructuresAndLinks:()=>xd,generateDrawTypeAndModifyDrawDefinition:()=>wd,generateFlightProfile:()=>ux,generateLineUps:()=>Cy,generateQualifyingStructure:()=>Pd,generateSeedingScaleItems:()=>Ty,generateStatCrew:()=>lx,generateVoluntaryConsolation:()=>PT,roundRobinGroups:()=>gv});var g1="splitLevelBased",KN="splitWaterfall",zN="splitShuttle",cx={SPLIT_LEVEL_BASED:g1,SPLIT_WATERFALL:KN,SPLIT_SHUTTLE:zN};function ux(t){let{drawNameRoot:e="Flight",attachFlightProfile:r,tournamentRecord:n,scaleAttributes:o,scaleSortMethod:i,deleteExisting:s,sortDescending:a,drawNames:c=[],flightsCount:u,splitMethod:p,uuids:m=[],event:d,stage:l}=t;if(!d)return{error:vt};let f=d.entries??[],{flightProfile:g}=Ht({event:d});if(g&&r&&!s)return{error:nf};let I=t.scaledEntries??ta({tournamentRecord:n,scaleAttributes:o,scaleSortMethod:i,sortDescending:a,event:d,stage:l}).scaledEntries,h=I.map(St),S=Ir(f.filter(({participantId:D})=>!h.includes(D)).filter(D=>(!l||!D.entryStage||D.entryStage===l)&&(!D.entryStatus||ri.includes(D.entryStatus)))),T=I.concat(...S),y=T.length,P=Math.ceil(y/u),U=ye(T,P);p===KN?U=xl(T,u):p===zN&&(U=xl(T,u,!0));function E(D){return(D||[]).map(({participantId:M,scaleValue:R})=>{let b=f.find(v=>v.participantId===M);return b?.scaleValue&&R&&(b.scaleValue=R),b}).sort((M,R)=>M.scaleValue-R.scaleValue).map((M,R)=>(M.scaleValue&&(M.seedNumber=R+1),M))}let A=et(0,u).map(D=>{let M=D+1;return{flightNumber:M,drawId:m?.pop()??Dt(),drawEntries:E(U[D]),drawName:c?.length&&c[D]||`${e} ${M}`}}),N={scaleAttributes:o,splitMethod:p,flights:A};if(r){let D=Xg({flightProfile:N,deleteExisting:s,event:d});return{splitEntries:Ur()&&U||void 0,...D}}else return{flightProfile:N,...C}}function QN({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 px({tagName:e,attributes:o,childArrays:r,childObjects:n})}function px(t){let{tagName:e,attributes:r=[],childArrays:n=[],childObjects:o}=t,i=`\r
|
|
24
24
|
`,s=l=>{let f=Object.keys(l)[0],g=l[f];return{key:f,value:g}},a=n?.map(({key:l,value:f})=>px({tagName:l,childObjects:f.map(s)})).join(`\r
|
|
25
25
|
`),c=o?.map(({key:l,value:f})=>QN({tagName:l,json:f??[]})).join(`\r
|
|
26
|
-
`),u=r?.map(({key:l,value:f})=>`${l}="${f}"`).join(" "),p=u?` ${u}`:"";if(e==="childArray")return c;let m=c?.length?`${i}${c}${i}`:"",d=a?.length?`${i}${a}${i}`:"";return`<${e}${p}>${m}${d}</${e}>`}function lx(t){let e=rt(t,[{[ie]:!0}]);if(e.error)return e;let{tournamentRecord:r}=t,{startDate:n,tournamentId:o,tournamentName:i}=r,{participantMap:s,matchUps:a,mappedMatchUps:c}=Gt({withMatchUps:!0,withEvents:!0,tournamentRecord:r}),u=r.participants.filter(y=>y.participantType===Lt),p=a?.filter(y=>y.matchUpType===Lt)??[],m=p?.reduce((y,P)=>{let U=P?.tieMatchUps??[];return U&&[...y,...U]},[])??[],d=a?.filter(y=>y.matchUpType===xt)??[],l=a?.filter(y=>y.matchUpType===_t)??[],f=m.length===d.length+l.length,g=p.length===1&&f,h={mappedMatchUps:c,participantMap:s,tournamentName:i,tournamentId:o,tournament:f?"N":"Y",startDate:n},S=[],T=[];if(g){let y=p[0],{json:P,xml:U}=mx({teamParticipants:u,teamMatchUp:y,...h,doubles:l,singles:d});T.push(P),S.push(U)}else for(let y of p){let P=y?.sides?.map(({participant:N})=>N?.participantId).filter(Boolean);if(P?.length!==2)continue;let U=P.map(N=>N&&s?.[N]?.participant),{xml:E,json:A}=mx({doubles:y.tieMatchUps?.filter(N=>N.matchUpType===_t),singles:y.tieMatchUps?.filter(N=>N.matchUpType===xt),teamParticipants:U,teamMatchUp:y,...h});T.push(A),S.push(E)}return{json:T,xml:S,...C}}function mx({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=Hn(a,"/","MDY"),l=p?.participantName||m?.[1]?.participantName,f=p?.participantId||m?.[1]?.participantId,g=m?.[0]?.participantName,I=m?.[0]?.participantId,h={},S=t.map(y=>({team:{...S1({teamParticipant:y,teamMatchUp:i,uniValues:h,participantMap:r,mappedMatchUps:e,homeid:f})}})),T=ot({venue:{tournamentname:s?n:void 0,neutralgame:p?"N":"Y",gameid:o,officials:{},tournament:s,rules:{},homename:l,visname:g,homeid:f,visid:I,date:d},childArray:S,singles_matches:u?.map(y=>dx({matchUp:y,homeid:f,uniValues:h})),doubles_matches:c?.map(y=>dx({matchUp:y,homeid:f,uniValues:h}))});return{json:T,xml:QN({json:T,tagName:"tngame"})}}function I1({homeid:t,uniValues:e,participant:r}){if(!r)return{};let n=r.individualParticipants?.length===2,o=n?ut(r.individualParticipants?.map(g=>g.teams?.[0]?.participantId)):[],i=n?ut(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 ot({vh:m,uni:d,uni_1:l,uni_2:f,team:a,name:c,name_1:u,name_2:p})}function h1({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 S1({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:P})=>P.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 P of p??[]){let U=n?.[P],E=U.sides.find(({participant:N})=>N.participantId===s)?.sideNumber,A=U.score?.sets?.[0]?.[`side${E}Score`]??0;I+=A;for(let N of U.tieMatchUps??[]){let{matchUpType:D,winningSide:M}=N,R=M&&(M===E?"w":"l")||"";R&&(l[D][R]+=1);let b=R==="w"?"1":"0",v=R==="l"?"1":"0";if(D===xt){let O=g.length+1;g.push({singles_pair:{pair:O,won:b,lost:v,tied:"0"}})}else if(D===_t){let O=f.length+1;f.push({doubles_pair:{pair:O,won:b,lost:v,tied:"0"}})}}}let h=[{singles:{childArray:g,won:l.SINGLES.w,lost:l.SINGLES.l}},{doubles:{childArray:f,won:l.DOUBLES.w,lost:l.DOUBLES.l}}],S=[],T=1;for(let P of t.individualParticipantIds){let U=r?.[P];if(U){let{participant:E,counters:A}=U,N={won:A?.DOUBLES?.wins||0,lost:A?.DOUBLES?.losses||0},D={won:A?.SINGLES?.wins||0,lost:A?.SINGLES?.losses||0},{participantName:M,participantId:R}=E;i[s][R]=T,S.push({player:{name:M,uni:T,singles:D,doubles:N}})}T+=1}return{vh:c,id:s,name:a,score:d||I,totals:h,childArray:S}}function dx({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=h1({sets:t.score?.sets,sideNumber:p});return{[i===xt?"singles_score":"doubles_score"]:{...I1({homeid:e,uniValues:r,participant:m}),...d}}});return{[i===xt?"singles_match":"doubles_match"]:{match:n,order:o,childArray:a}}}var T1="ASC",XN="ASC",y1="DESC",Ry="DESC",fx={ASC:T1,ASCENDING:XN,DESC:y1,DESCENDING:Ry};function Cy(t){let{tieFormat:e}=t,{useDefaultEventRanking:r,tournamentRecord:n,drawDefinition:o,scaleAccessor:i,singlesOnly:s,attach:a,event:c}=t;if(c?.eventType!==Cr)return{error:Bn};if(!n)return{error:Y};if(!e&&!o)return{error:Mr};if(e=e??We({drawDefinition:o,event:c})?.tieFormat,ar({tieFormat:e}).error)return{error:Lo};if(typeof i!="object"&&!r)return{error:G,context:{scaleAccessor:i}};let u={},m=(o?.entries??c?.entries??[]).filter(R=>R?.entryStatus===kr).map(St),{participants:d=[]}=Gt({withIndividualParticipants:!0,withScaleValues:!0,tournamentRecord:n}),l=d.filter(({participantId:R})=>m.includes(R)),f=R=>R===fi?"rankings":"ratings",g=c?.category?.categoryName??c?.category?.ageCategoryCode,{scaleName:I=g,scaleType:h=fi,sortOrder:S,accessor:T}=i||{},y=f(h),P=(R,b)=>{let v=R[y]?.[b];if(!v&&r&&(v=R[y]?.[aa]),Array.isArray(v)){let O=v.find(x=>x.scaleName===I)?.scaleValue;if(Zt(O))return O;if(T&&typeof O=="object")return O[T]}return 0},U=(R,b,v)=>{let O=S===Ry?b:R,x=S===Ry?R:b;return P(O,v)-P(x,v)},E=(R,b)=>U(R,b,aa),A=(R,b)=>U(R,b,vi),N=[],D=e?.collectionDefinitions??[];for(let R of l){let b=R.individualParticipants?.sort(E)??[],v=s?b:R.individualParticipants?.sort(A)??[],O={};for(let F of D){let L=[],{collectionId:w,matchUpCount:V,matchUpType:k,gender:W}=F,H=ue(aa)(k);et(0,V).forEach(K=>{let q=H?b:v??[],B=K+1,$=[];et(0,H?1:2).forEach(z=>{let j=q?.find(tt=>{let Q=W&&([$t,ne].includes(W)&&W||W===Tr&&[$t,ne][z]);return(!Q||Q===tt.person?.sex)&&!L.includes(tt.participantId)})?.participantId;j&&($.push(j),L.push(j),O[j]||(O[j]=[]),O[j].push({collectionPosition:B,collectionId:w}))}),H||N.push($)})}let x=Object.keys(O).map(F=>({collectionAssignments:O[F],participantId:F}));u[R.participantId]=x}let M=[];for(let R of N){let{participant:b}=In({tournamentParticipants:d,participantIds:R});if(!b){let v={individualParticipantIds:R,participantRole:xe,participantType:ft};M.push(v)}}if(a){for(;M.length;)bn({participant:M.pop(),tournamentRecord:n});At({element:o,extension:{name:Ro,value:u}})}return{...C,lineUps:u,participantsToAdd:M}}function Zg(t){if(!t)return{error:st};let e=rt(t,[{dates:!1,[tr]:s=>Array.isArray(s)&&s.every(Rr)},{uuids:!1,[tr]:s=>Array.isArray(s)&&s.every(Vt)},{startTime:!1,endTime:!1,[tr]:QI},{idPrefix:!1,namePrefix:!1,[tr]:Vt},{count:!0,[tr]:Zt}]);if(e.error)return e;let{startDate:r,endDate:n}=t.tournamentRecord??{},o=t.dates||r&&n&&ws(r,n)||[],i=et(1,t.count+1).map(s=>ot({courtId:t.uuids?.pop()??(t.idPrefix&&`${t.idPrefix}-${s}`)??Dt(),courtName:t.courtNames?.pop()??(t.namePrefix&&`${t.namePrefix} ${s}`),dateAvailability:o.map(a=>({startTime:t.startTime??"08:00",endTime:t.endTime??"20:00",date:a}))}));return{...C,courts:i}}var JN={};Xt(JN,{default:()=>A1,garman:()=>hx});function wa({court:t,date:e}){let r=e&&t.dateAvailability.find(o=>Wn(o.date,e)),n=t.dateAvailability.find(o=>!o.date);return r||n}function Ns(t){let e=rt(t,[{courtDate:!0,_ofType:Kr}]);if(e.error)return e;let{includeBookingTypes:r=[],courtDate:n}=t,o=[],i=ke(n.startTime);(n.bookings||[]).filter(a=>!a.bookingType||!r.includes(a.bookingType)).sort((a,c)=>gf(a.startTime).localeCompare(gf(c.startTime))).forEach(a=>{let c={startTime:Kt(i.toISOString()),endTime:a.startTime};ke(a.startTime)>i&&o.push(c),ke(a.endTime)>i&&(i=ke(a.endTime))});let s={startTime:Kt(i.toISOString()),endTime:n.endTime};return ke(n.endTime)>i&&o.push(s),{timeSlots:o}}function gx({averageMatchUpMinutes:t,includeBookingTypes:e,periodStartTime:r,periodEndTime:n}){let o=s=>{let{timeSlots:a}=Ns({includeBookingTypes:e,courtDate:s});return!!a?.filter(i)?.length};function i(s){let a=ke(s.startTime),c=ke(s.endTime);return a>r||c<n?!1:ma(r,c)>=t}return{enoughTime:o}}function by(t){let e=rt(t,[{periodStart:!0,date:!0},{courts:!0,_ofType:Be}]);if(e.error)return e;let{averageMatchUpMinutes:r,includeBookingTypes:n,periodStart:o,date:i}=t,s=t.courts,a=ke(o),c=hf(a,r),{enoughTime:u}=gx({averageMatchUpMinutes:r,includeBookingTypes:n,periodStartTime:a,periodEndTime:c});return{availableToScheduleCount:(s?.filter(m=>{if(!Array.isArray(m.dateAvailability))return!1;let d=wa({date:i,court:m});return!!(d&&u(d))})||[]).length,...C}}function tm(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:G,courts:i};if(!Array.isArray(s))return{error:Am};if(!Rr(o))return{error:je};r&&(Array.isArray(r)?r.includes(o)&&(s=[]):s=[]);let{courtBookings:a,unassignedBookings:c}=s.reduce((l,f)=>{let{courtId:g}=f;return g?l.courtBookings[g]?l.courtBookings[g].push(f):l.courtBookings[g]=[f]:l.unassignedBookings.push(f),l},{courtBookings:{},unassignedBookings:[]}),u=i.map((l,f)=>{let{courtId:g,courtName:I}=l,h=a[g]||[],S=wa({date:o,court:l})||{},{bookings:T=[],startTime:y,endTime:P,date:U}=S,A=[e[f]&&{startTime:y,endTime:e[f]},...J(T,!1,!0),...h].filter(Boolean);return{courtId:g,courtName:I,dateAvailability:{bookings:A,startTime:y,endTime:P,date:U}}});c.sort((l,f)=>qt(l.startTime)-qt(f.startTime));let p=()=>u.map(l=>{let f=l.dateAvailability,{timeSlots:g=[]}=Ns({courtDate:f});return{courtName:l.courtName,courtId:l.courtId,timeSlots:g}}).flat(),m=[];for(let l of c){let{startTime:f,endTime:g,averageMinutes:I,recoveryMinutes:h,matchUpId:S}=l,T=qt(f),y=qt(g),U=p().reduce((E,{courtId:A,courtName:N,timeSlots:D})=>{let M;return D.find(({startTime:b,endTime:v})=>{M=qt(b)-T;let O=T>=qt(b);return y<=qt(v)&&E.startDifference!==0&&((M===0||M+n>=0)&&(E.startDifference===void 0||M<E.startDifference)||O)})?{courtName:N,courtId:A,startDifference:M}:E},{});if(U.courtId){let E={averageMinutes:I,recoveryMinutes:h,matchUpId:S,startTime:f,endTime:g};m.push(E),u.find(({courtId:N})=>N===U.courtId)?.dateAvailability.bookings.push(E)}else console.log({unassignedBooking:l})}return{virtualCourts:u.map(({courtId:l,courtName:f,dateAvailability:g})=>({dateAvailability:[g],courtName:f,courtId:l})),assignedBookings:m}}function ku({averageMatchUpMinutes:t,periodLength:e=30,recoveryMinutes:r}){let n=(t||90)+(r||0);return e>n?n:e||30}function vy(t){let{startTime:e="8:00",endTime:r="20:30",count:n=10,date:o}=t??{};return et(0,n).map(()=>({dateAvailability:[{date:o,startTime:e,endTime:r}]}))}function bc({scheduleDate:t,startTime:e,endTime:r,courts:n}){let o=e&&"startTime"||r&&"endTime"||void 0;return n.reduce((i,s)=>{let a=wa({date:t,court:s}),c=o&&(a?.[o]||s[o]);return c&&(!i||e&&qt(c)<qt(i)||r&&qt(c)>qt(i))?c:i},void 0)}function Ix({averageMinutes:t,startTime:e,endTime:r,courts:n,date:o}){e=e||bc({courts:n,scheduleDate:o,startTime:!0}),r=r||bc({courts:n,scheduleDate:o,endTime:!0});let i;if(e&&r){let s=ke(e),a=ke(r);for(let c of n||[]){if(!Array.isArray(c.dateAvailability))continue;let u=wa({court:c,date:o}),{timeSlots:p}=Ns({courtDate:u});p?.forEach(m=>{let d=ke(m.startTime),l=ke(m.endTime);if(d>a||d<s||l<s)return!1;if(ma(d,l)>=t){let I=Kt(d.toISOString());(!i||I<i)&&(i=I)}})}}return{firstTimeSlotStartTime:i}}function dl(t){let e=rt(t,[{courts:!0,_ofType:Be}]);if(e.error)return e;let{date:r=If(),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||ku({averageMatchUpMinutes:u}),r=Et(r),n=Kt(n),o=Kt(o);let l=0,f=0,g=0,I=0,h=0;!s&&m&&(s=vy({startTime:n,endTime:o,count:m,date:r}));let{virtualCourts:S}=tm({remainingScheduleTimes:c,clearScheduleDates:p,scheduleDate:r,periodLength:i,bookings:d,courts:s}),{firstTimeSlotStartTime:T}=Ix({averageMinutes:u,courts:S,startTime:n,endTime:o,date:r});a&&T&&(n=T||n);let y=qt(n),U=qt(o)-y,E=Math.floor(U/i),N=et(0,E+1).map(M=>{let R=y+M*i,b=BC(R),v=by({courts:S??[],averageMatchUpMinutes:u,periodStart:b,date:r});if(v.error)return{error:v.error};let{availableToScheduleCount:O=0}=v,x=O>f?O-f:0;h+=M?O:0;let F=M?h/M:O,w=i*F/u,V=M?w*(M-1)+F:F,k=O?f&&V-l||x:0;l=V,f=O,g+=k;let W=pt(g)-I;return I+=W,{periodStart:b,add:W,availableToScheduleCount:O,newCourts:x,totalMatchUps:I}});return{scheduleTimes:N.reduce((M,R)=>{let v=et(0,R.add).map(()=>({scheduleTime:R.periodStart}));return M.concat(...v)},[]).flat(),timingProfile:N,totalMatchUps:I}}var hx={getCourtsAvailableAtPeriodStart:by,generateTimeSlots:Ns,getScheduleTimes:dl,courtGenerator:vy},A1=hx;var Oy={};Xt(Oy,{isValid:()=>Pr,isValidMatchUpFormat:()=>Pr,parse:()=>Ye,stringify:()=>ip});var yM={};Xt(yM,{allCompetitionMatchUps:()=>Un,allDrawMatchUps:()=>or,allEventMatchUps:()=>$n,allTournamentMatchUps:()=>Te,analyzeMatchUp:()=>Xp,applyLineUps:()=>SM,assignMatchUpSideParticipant:()=>tM,assignTieMatchUpParticipantId:()=>gl,bulkMatchUpStatusUpdate:()=>fM,calculateWinCriteria:()=>Ps,checkInParticipant:()=>eI,checkMatchUpIsComplete:()=>ds,checkOutParticipant:()=>tI,competitionScheduleMatchUps:()=>Fu,disableTieAutoCalc:()=>dM,drawMatchUps:()=>fy,enableTieAutoCalc:()=>uM,eventMatchUps:()=>al,filterMatchUps:()=>Ni,findMatchUp:()=>jg,getAllDrawMatchUps:()=>se,getAllStructureMatchUps:()=>Ut,getCheckedInParticipantIds:()=>us,getCompetitionMatchUps:()=>Qp,getEventMatchUpFormatTiming:()=>iy,getHomeParticipantId:()=>uy,getMatchUpCompetitiveProfile:()=>gu,getMatchUpContextIds:()=>py,getMatchUpDailyLimits:()=>ul,getMatchUpDailyLimitsUpdate:()=>sy,getMatchUpDependencies:()=>sn,getMatchUpFormat:()=>my,getMatchUpFormatTiming:()=>Iu,getMatchUpFormatTimingUpdate:()=>ny,getMatchUpScheduleDetails:()=>pd,getMatchUpType:()=>md,getMatchUpsStats:()=>dy,getModifiedMatchUpFormatTiming:()=>il,getParticipantResults:()=>Mu,getPredictiveAccuracy:()=>cy,getRoundMatchUps:()=>Ke,getRounds:()=>ly,isValidMatchUpFormat:()=>Pr,matchUpActions:()=>Od,mutate:()=>TM,participantScheduledMatchUps:()=>ay,query:()=>EN,removeDelegatedOutcome:()=>pM,removeMatchUpSideParticipant:()=>nI,removeTieMatchUpParticipantId:()=>rM,replaceTieMatchUpParticipantId:()=>rI,resetAdHocMatchUps:()=>IM,resetMatchUpLineUps:()=>iI,resetScorecard:()=>aI,resetTieFormat:()=>sI,setDelegatedOutcome:()=>gM,setMatchUpFormat:()=>lM,setMatchUpStatus:()=>Gu,setOrderOfFinish:()=>hM,substituteParticipant:()=>mM,tallyParticipantResults:()=>Ca,toggleParticipantCheckInState:()=>ll,tournamentMatchUps:()=>cl,updateTieMatchUpScore:()=>co,validMatchUp:()=>Zf,validMatchUps:()=>Vr});var TM={};Xt(TM,{applyLineUps:()=>SM,assignMatchUpSideParticipant:()=>tM,assignTieMatchUpParticipantId:()=>gl,bulkMatchUpStatusUpdate:()=>fM,checkInParticipant:()=>eI,checkOutParticipant:()=>tI,disableTieAutoCalc:()=>dM,enableTieAutoCalc:()=>uM,findMatchUp:()=>jg,removeDelegatedOutcome:()=>pM,removeMatchUpSideParticipant:()=>nI,removeTieMatchUpParticipantId:()=>rM,replaceTieMatchUpParticipantId:()=>rI,resetAdHocMatchUps:()=>IM,resetMatchUpLineUps:()=>iI,resetScorecard:()=>aI,resetTieFormat:()=>sI,setDelegatedOutcome:()=>gM,setMatchUpFormat:()=>lM,setMatchUpStatus:()=>Gu,setOrderOfFinish:()=>hM,substituteParticipant:()=>mM,toggleParticipantCheckInState:()=>ll,updateTieMatchUpScore:()=>co});function tM({tournamentRecord:t,drawDefinition:e,participantId:r,sideNumber:n,matchUpId:o,event:i}){if(r&&typeof r!="string")return{error:mn};if(!e)return{error:Z};if(!o)return{error:sr};let s=n===void 0;if(s&&(n=1),![1,2].includes(n))return _({result:{error:G,context:{sideNumber:n}}});let{matchUp:a,structure:c}=Bt({drawDefinition:e,matchUpId:o,event:i});if(!a)return{error:Le};if(!(!c?.structures&&!(e.drawType&&e.drawType!==$r)&&!c?.matchUps?.find(({roundPosition:p})=>!!p)))return{error:ym};if(!r&&(a?.score?.scoreStringSide1||ce.includes(a?.matchUpstatus)||a?.matchUpStatus&&[he,Ce].includes(a.matchUpStatus)))return{error:Ku,info:"matchUp has completed status or score"};if(a){if(a.sides=[1,2].map(p=>{let m=a.sides?.find(d=>d.sideNumber===p)??{sideNumber:p};return n===p?{...m,participantId:r}:m}),s)for(let p of a.sides)p.sideNumber&&(p.sideNumber=3-p.sideNumber);gt({tournamentId:t?.tournamentId,context:"assignSideParticipant",drawDefinition:e,matchUp:a})}return{...C,sidesSwapped:s}}function Jr({removePriorValues:t,tournamentRecord:e,duplicateValues:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:s,event:a}){let{matchUp:c}=Bt({drawDefinition:n,event:a,matchUpId:i});if(!c)return{error:Le};let u=Qn({removePriorValues:t,element:c,duplicateValues:r,timeItem:s});return o||gt({tournamentId:e?.tournamentId,eventId:a?.eventId,context:"addTimeItem",drawDefinition:n,matchUp:c}),u}function tI(t){let e=[{[ie]:!0},{[Ve]:!0},{[ro]:!0},{[ln]:!0}],r=rt(t,e);if(r.error)return r;let n=Ds(t,[{[is]:_n,attr:{[tu]:!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&&Km.includes(u)||u&&ce.includes(u)||Ie({score:p}))return{error:LA};let m=us({matchUp:c});if(m?.error)return m;let{checkedInParticipantIds:d,allRelevantParticipantIds:l}=m??{};if(!l?.includes(s))return{error:mn};if(!d?.includes(s))return{error:pE};let f=iS({matchUp:c});if(f?.error)return f;let{sideParticipantIds:g,nestedIndividualParticipantIds:I}=f??{},h=g?.indexOf(s);return h!==void 0&&[0,1].includes(h)&&(I?.[h]??[]).forEach(T=>{Jr({drawDefinition:i,matchUpId:a,timeItem:{itemType:ad,itemValue:T}})}),Jr({tournamentRecord:o,drawDefinition:i,matchUpId:a,timeItem:{itemValue:s,itemType:ad}}),{...C,checkedOut:!0}}function eI(t){let e=[{[ie]:!0},{[Ve]:!0},{[ro]:!0},{[ln]:!0}],r=rt(t,e);if(r[fn])return r;let n=Ds(t,[{[is]:_n,attr:{[tu]:!0}}]);if(n[fn])return n;let{tournamentRecord:o,drawDefinition:i,participantId:s,matchUpId:a}=t,c=us({matchUp:n?.matchUp?.matchUp});if(c?.error)return c;let{checkedInParticipantIds:u,allRelevantParticipantIds:p}=c??{};if(!p?.includes(s))return{[fn]:mn};let m={...C,checkedIn:!0};return u?.includes(s)||Jr({tournamentRecord:o,drawDefinition:i,matchUpId:a,timeItem:{itemValue:s,itemType:sd}}),m}function ll(t){let e=rt(t,[{[ro]:!0,[Ve]:!0,[ln]:!0}]);if(e.error)return e;let r=t.tournamentId??t.activeTournamentId,n=t.tournamentRecord??(r&&t.tournamentRecords?.[r]);if(!n)return{error:Y};let i=Ds(t,[{[is]:_n,attr:{[tu]:!0},[fn]:Le}]).matchUp?.matchUp;if(!i)return{error:Le};let{checkedInParticipantIds:s=[]}=us({matchUp:i}),{participantId:a,matchUpId:c,drawDefinition:u}=t;return a&&s.includes(a)?tI({tournamentRecord:n,drawDefinition:u,participantId:a,matchUpId:c,matchUp:i}):eI({tournamentRecord:n,drawDefinition:u,participantId:a,matchUpId:c,matchUp:i})}function fl({tournamentRecord:t,drawDefinition:e,tieMatchUpId:r,event:n}){if(!t)return{error:Y};if(!e)return{error:an};if(!n)return{error:jr};let o=Ne({drawDefinition:e}),{matchUp:i}=Bt({matchUpId:r,drawDefinition:e,matchUpsMap:o});if(!i)return{error:Le};let{matchUp:s,structure:a}=Bt({tournamentParticipants:t.participants,matchUpId:r,inContext:!0,drawDefinition:e,matchUpsMap:o,event:n});if(!s)return{error:Le};let{collectionPosition:c,drawPositions:u,collectionId:p,matchUpTieId:m,matchUpType:d}=s;if(d&&!Lc([xt,_t],d))return{error:dr};let{positionAssignments:l}=bt({structure:a}),f=l?.filter(U=>u?.includes(U.drawPosition)),{matchUp:g}=Bt({matchUpId:m,drawDefinition:e,matchUpsMap:o}),I=g?.sides?.map(St)??[],h=f?.map(St)??[],S=[...I,...h],{participants:T}=Gt({tournamentRecord:t,participantFilters:{participantTypes:[Lt],participantIds:S}}),{matchUp:y}=Bt({matchUpId:m,inContext:!0,drawDefinition:e,matchUpsMap:o}),P=We({matchUp:g,drawDefinition:e,structure:a,event:n})?.tieFormat;return{inContextDualMatchUp:y,inContextTieMatchUp:s,relevantAssignments:f,collectionPosition:c,teamParticipants:T,collectionId:p,matchUpType:d,dualMatchUp:g,tieMatchUp:i,tieFormat:P,structure:a,...C}}function rI(t){let e=fl(t);if(e.error)return e;let r="replaceTieMatchUpParticipantid",{existingParticipantId:n,tournamentRecord:o,newParticipantId:i,drawDefinition:s,substitution:a,event:c}=t;if(!n||!i)return _({result:{error:oe},stack:r});if(n===i)return{...C};let{inContextDualMatchUp:u,inContextTieMatchUp:p,collectionPosition:m,collectionId:d,dualMatchUp:l,tieMatchUp:f,tieFormat:g}=e,I=p?.matchUpType,h=p?.sides?.find(V=>V.participant?.participantId===n||V.participant?.individualParticipantIds?.includes(n));if(!h)return{error:te};let S=Gt({tournamentRecord:o,participantFilters:{participantIds:[n,i]}})?.participants??[];if(S.length!==2)return _({result:{error:oe},stack:r});if(S[0].participantType!==S[1].participantType)return _({result:{error:An},stack:r});let{appliedPolicies:T}=yt({tournamentRecord:o,drawDefinition:s,event:c}),y=t.policyDefinitions?.[er]??T?.[er]??hs[er],P=S.find(({participantId:V})=>V===i);if((t.enforceGender??y?.participants?.enforceGender)!==!1&&[$t,ne].includes(p?.gender)&&p?.gender!==P?.person?.sex)return{error:xi,info:"Gender mismatch"};let E=y?.processCodes?.substitution;ba({tournamentId:o.tournamentId,eventId:c.eventId,inContextDualMatchUp:u,drawDefinition:s,dualMatchUp:l});let A=l?.sides?.find(({sideNumber:V})=>V===h.sideNumber);if(!A)return _({result:{sideNumber:h.sideNumber,existingParticipantId:n,error:ve},stack:r});if(p?.sides?.flatMap(V=>V.participant?.individualParticipantIds||V.participant?.participantId||[])?.includes(i))return _({result:{error:zu},stack:r});let D=u?.sides?.find(({sideNumber:V})=>V===h.sideNumber)?.participantId,M=A.lineUp,R=M?.find(({participantId:V})=>i===V),b=M?.reduce((V,k)=>k.substitutionOrder>V?k.substitutionOrder:V,0),v=M?.map(V=>{let k=J(V,!1,!0);if(![n,i].includes(k.participantId))return k;if(!a&&[n,i].includes(k.participantId)&&(k.collectionAssignments=k.collectionAssignments?.filter(W=>!(W.collectionPosition===m&&W.collectionId===d))),a&&n===k.participantId&&(k.collectionAssignments=k.collectionAssignments.map(W=>W.collectionPosition===m&&W.collectionId===d&&W.substitutionOrder===void 0?{...W,substitutionOrder:b}:W)),k.participantId===i){k.collectionAssignments||(k.collectionAssignments=[]);let W={collectionId:d,collectionPosition:m};a&&(W.previousParticipantId=n,W.substitutionOrder=(b??0)+1),k.collectionAssignments.push(W)}return k})??[];if(!R){let V={collectionId:d,collectionPosition:m};a&&(V.substitutionOrder=(b??0)+1,V.previousParticipantId=n);let k={collectionAssignments:[V],participantId:i};v.push(k)}let O=I===_t,{assignedParticipantIds:x}=Np({lineUp:M,collectionPosition:m,collectionId:d}),{assignedParticipantIds:F}=Np({lineUp:v,collectionPosition:m,collectionId:d});if(A.lineUp=v,D&&g){let V=Ki({participantId:D,lineUp:v,drawDefinition:s,tieFormat:g});if(V.error)return _({result:V,stack:r})}else console.log("team participantId not found");let L,w;if(O){let{tournamentRecord:V}=t,k=In({participantIds:F,tournamentRecord:V});if(!k.participant){let K=bn({returnParticipant:!0,pairOverride:!0,tournamentRecord:V,participant:{participantRole:xe,individualParticipantIds:F,participantType:ft}});if(K.error)return _({result:K,stack:r});L=K.participant?.participantId}k=In({participantIds:x,tournamentRecord:V});let W=k.participant?.participantId;W&&$i({participantIds:[W],tournamentRecord:V}).success&&(w=W)}if(a||h.substitutions?.length===1){if(a)E&&f&&(f.processCodes=ut([...f?.processCodes??[],...E]));else for(let V of E||[]){let k=f?.processCodes?.lastIndexOf(V);k!==void 0&&f?.processCodes?.splice(k,1)}f&>({tournamentId:o?.tournamentId,matchUp:f,context:r,drawDefinition:s})}return l&>({tournamentId:o?.tournamentId,matchUp:l,context:r,drawDefinition:s}),{...C,modifiedLineUp:v,participantRemoved:w,participantAdded:L}}function _y({collectionPosition:t,teamParticipantId:e,dualMatchUpSide:r,drawDefinition:n,participantIds:o,collectionId:i}){if(!i||!t||!Array.isArray(o))return{modifiedLineUp:r?.lineUp||[],error:G};let s=r?.lineUp||ms({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 Sx({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:r}){let n=(r.events||[]).filter(i=>i?.eventType===_e&&i?.entries?.some(s=>s.participantId===e)),o=i=>!t.includes(i.participantId);for(let i of n){i.entries=(i.entries||[]).filter(o);let{flightProfile:s}=Ht({event:i});s?.flights?.forEach(a=>{a.drawEntries=(a.drawEntries||[]).filter(o)}),i?.drawDefinitions?.forEach(a=>{a.entries=(a.entries||[]).filter(o)})}return{...C}}function em({individualParticipantIds:t,groupingParticipantId:e,removeFromOtherTeams:r,tournamentRecord:n}){let o="addIndividualParticipantIds";if(!n)return _({result:{error:Y},stack:o});if(!e||!t)return _({result:{error:st},stack:o});let i=n.participants??[],s=i.find(m=>m.participantId===e);if(!s)return _({result:{error:te},stack:o});if(s?.participantType&&![Lt,zr].includes(s.participantType))return _({context:{participantType:s.participantType},result:{error:An},stack:o});let a=t.filter(m=>i.find(l=>l.participantId===m)?.participantType!==Tt);if(a.length)return _({result:{error:wr,invalidParticipantIds:a},stack:o});s.individualParticipantIds||(s.individualParticipantIds=[]);let c=s.individualParticipantIds,u=t.filter(m=>!c.includes(m));u.length&&(r&&Rp({individualParticipantIds:u,tournamentRecord:n}),s.individualParticipantIds=s.individualParticipantIds.concat(...u));let{topics:p}=Lr();if(p.includes(nr)){let m=i.find(({participantId:d})=>d===e);mt({topic:nr,payload:{participants:[m]}})}return Sx({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:n}),{groupingParticipant:J(s,!1,!0),added:u.length,...C}}function rm(t){let{updateParticipantName:e=!0,groupingParticipantId:r,removeFromOtherTeams:n,tournamentRecord:o,pairOverride:i,participant:s}=t;if(!o)return{error:Y};if(!s)return{error:wi};if(!s.participantId)return bn({tournamentRecord:o,participant:s});let{participant:a}=To({participantId:s.participantId,tournamentRecord:o});if(!a)return bn({tournamentRecord:o,participant:s});let{participantRoleResponsibilties:c,individualParticipantIds:u,participantOtherName:p,participantName:m,participantRole:d,participantType:l,onlineResources:f,contacts:g,person:I}=s;if(l&&a.participantType!==l)return{error:oE};let h={};if(g&&(h.contacts=g),f&&(h.onlineResources=f),p&&Vt(p)&&(h.participantOtherName=p),m&&Vt(m)&&(h.participantName=m),Array.isArray(u)){let{participants:S}=Gt({participantFilters:{participantTypes:[Tt]},tournamentRecord:o}),T=S?.map(St);if(T){let y=u.filter(P=>Vt(P)&&T.includes(P));([zr,jt].includes(l||a.participantType)||l===ft&&(y.length===2||i))&&(h.individualParticipantIds=y),a.participantType===mu.PAIR&&e&&(h.participantName=E1({individualParticipants:S,newValues:h}))}}return Object.keys(gd).includes(d)&&(h.participantRole=d),Object.keys(mu).includes(l)&&(h.participantType=l),Array.isArray(c)&&(h.participantRoleResponsibilties=c),a.participantType===mu.INDIVIDUAL&&I&&U1({updateParticipantName:e,existingParticipant:a,newValues:h,person:I}),Object.assign(a,ot(h)),r&&em({individualParticipantIds:[a.participantId],groupingParticipantId:r,removeFromOtherTeams:n,tournamentRecord:o}),mt({topic:nr,payload:{tournamentId:o.tournamentId,participants:[a]}}),{participant:J(a),...C}}function E1({individualParticipants:t,newValues:e}){let r=e.individualParticipantIds,n=t.filter(({participantId:o})=>r.includes(o)).map(({person:o})=>o?.standardFamilyName).filter(Boolean).sort().join("/");return r.length===1&&(n+="/Unknown"),n}function U1({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(Nm).includes(m)&&(o.sex=m);let d;if(Vt(c)&&(o.personId=c),a&&Vt(a)&&(P1(a)||a==="")&&(o.nationalityCode=a),i&&typeof Vt(i)&&i.length>1&&(o.standardFamilyName=i,d=!0),s&&typeof Vt(s)&&s.length>1&&(o.standardGivenName=s,d=!0),d&&t){let l=`${o.standardGivenName} ${o.standardFamilyName}`;r.participantName=l}u&&Rr(u)&&(o.birthdate=u),p&&Vt(p)&&(o.tennisId=p),Object.assign(e.person,o)}function P1(t){return ti.flatMap(({iso:e,ioc:r})=>[e,r]).filter(Boolean).includes(t)}function gl(t){let e=fl(t);if(e.error)return e;let r="assignTieMatchUpParticipantId",n=t.teamParticipantId,{tournamentRecord:o,drawDefinition:i,participantId:s,event:a}=t;if(!s)return _({result:{error:oe},stack:r});if(t.sideNumber&&![1,2].includes(t.sideNumber))return _({result:{error:jl},stack:r});let{inContextDualMatchUp:c,inContextTieMatchUp:u,relevantAssignments:p,collectionPosition:m,teamParticipants:d,collectionId:l,matchUpType:f,dualMatchUp:g,tieFormat:I}=e;if(u?.sides?.flatMap(B=>B.participant?.individualParticipantIds||B.participant?.participantId||[])?.includes(s))return _({result:{...C},stack:r});n=n??(t.sideNumber?c?.sides?.find(B=>B.sideNumber===t.sideNumber)?.participantId:void 0);let S=Gt({participantFilters:{participantIds:[s]},tournamentRecord:o})?.participants?.[0];if(!S)return _({result:{error:te},stack:r});let{appliedPolicies:T}=yt({tournamentRecord:o,drawDefinition:i,event:a}),y=t.policyDefinitions?.[er]??T?.[er]??hs[er];if((t.enforceGender??y?.participants?.enforceGender)!==!1&&[$t,ne].includes(u?.gender)&&u?.gender!==S.person?.sex)return{error:xi,info:"Gender mismatch"};let{individualParticipantIds:U,participantType:E}=S;if(ue(xt)(f)&&E!==Tt)return{error:An};let A=E===Tt?[s]:U,N=n&&d?.find(({participantId:B})=>B===n)||d?.find(({individualParticipantIds:B})=>Fe(A,B));if(!N)return{error:ef};if(n||(n=N.participantId),!n)return{error:te};let M=p?.find(B=>B.participantId===N?.participantId)?.drawPosition,R=g?.sides?.find(B=>B.participantId===n)?.sideNumber,b=u?.sides?.find(B=>M&&B.drawPosition===M)?.sideNumber,v=R??b??t.sideNumber;if(!I)return{error:bs};if(!I.collectionDefinitions?.find(B=>B.collectionId===l))return{error:zA};ba({tournamentId:o.tournamentId,eventId:a.eventId,inContextDualMatchUp:c,drawDefinition:i,dualMatchUp:g});let x=g?.sides?.find(B=>B.sideNumber===v),F=u?.sides?.find(B=>B.sideNumber===v),V=(x?.lineUp??ms({participantId:n,drawDefinition:i})?.lineUp)?.filter(B=>B.collectionAssignments?.find($=>$.collectionPosition===m&&$.collectionId===l&&!$.previousParticipantId))?.map(B=>B?.participantId),k=V?.length>1&&V||(E===ft?S.individualParticipantIds:[s]),W=_y({collectionPosition:m,teamParticipantId:n,dualMatchUpSide:x,drawDefinition:i,participantIds:k,collectionId:l});if(W.error)return _({result:W,stack:r});let{modifiedLineUp:H}=W,K;if(f===_t){if(E!==ft){let B=eM({collectionPosition:m,teamParticipantId:n,drawDefinition:i,modifiedLineUp:H,participantId:s,collectionId:l,tieFormat:I});if(B?.error)return _({result:B,stack:r});if(B=q({side:F}),B.error)return B;K=B.deletedParticipantId,x&&(x.lineUp=H),g&>({tournamentId:o?.tournamentId,matchUp:g,context:r,drawDefinition:i})}else if(E===ft)for(let B of k)eM({collectionPosition:m,teamParticipantId:n,drawDefinition:i,modifiedLineUp:H,participantId:B,collectionId:l,tieFormat:I})}else{let B=eM({collectionPosition:m,teamParticipantId:n,drawDefinition:i,modifiedLineUp:H,participantId:s,collectionId:l,tieFormat:I});if(B?.error)return B}if(x&&(x.lineUp=H),g&>({tournamentId:o?.tournamentId,matchUp:g,context:r,drawDefinition:i}),K){let{error:B}=$i({participantIds:[K],tournamentRecord:o});B&&console.log("cleanup")}return{...C,modifiedLineUp:H};function q({side:B}){let $;if(B.participant){let z=B.participant.individualParticipantIds||[];if(z.filter(Boolean).length===1){let{participant:tt}=In({participantIds:z,tournamentRecord:o});z.push(s);let{participant:Q}=In({participantIds:z,tournamentRecord:o});if(!Q&&tt){tt.individualParticipantIds=z;let X=rm({pairOverride:!0,tournamentRecord:o,participant:tt});if(X.error)return X}else $=tt?.participantId}}else{let j=bn({participant:{individualParticipantIds:[s],participantRole:xe,participantType:ft},pairOverride:!0,tournamentRecord:o});if(j.error)return j}return{...C,deletedParticipantId:$}}}function eM({collectionPosition:t,teamParticipantId:e,drawDefinition:r,modifiedLineUp:n,participantId:o,collectionId:i,tieFormat:s}){let a=ms({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 Ki({participantId:e,lineUp:n,drawDefinition:r,tieFormat:s})}function rM(t){let{tournamentRecord:e,drawDefinition:r,participantId:n,event:o}=t,i="removeTieMatchUpParticiapantId";if(!n)return _({result:{error:oe},stack:i});let s=fl(t);if(s.error)return s;let{appliedPolicies:a}=yt({tournamentRecord:e,drawDefinition:r,event:o}),u=(t.policyDefinitions?.[er]??a?.[er]??hs[er])?.processCodes?.substitution,{inContextDualMatchUp:p,inContextTieMatchUp:m,relevantAssignments:d,collectionPosition:l,teamParticipants:f,collectionId:g,matchUpType:I,dualMatchUp:h,tieMatchUp:S,tieFormat:T}=s;if(!h)return _({result:{error:hr},stack:i});let y=m?.sides?.find(R=>R.participant?.participantId===n||R.participant?.individualParticipantIds?.includes(n));if(!y)return _({result:{error:te},stack:i});let P=t.policyDefinitions?.[en]??a?.[en];if(!y.substitutions?.length&&(Ie({score:m?.score})||m?.winningSide)&&P?.requireParticipantsForScoring!==!1)return _({result:{error:vE},stack:i});let U=p?.sides?.find(({sideNumber:R})=>R===y.sideNumber)?.participantId;if(!U)return _({result:{error:te},stack:i});let E=Gt({participantFilters:{participantIds:[n]},tournamentRecord:e})?.participants?.[0];if(!E)return _({result:{error:te},stack:i});if(I===xt&&E.participantType===ft)return _({result:{error:xi},stack:i});let A=E.participantType===Tt?[n]:E.individualParticipantIds;ba({tournamentId:e.tournamentId,eventId:o.eventId,inContextDualMatchUp:p,drawDefinition:r,dualMatchUp:h});let N=h.sides?.find(({sideNumber:R})=>R===y.sideNumber);if(!N&&(h.sides?.filter(({lineUp:R})=>!R).length||0)<2){let R=f?.map(({participantId:b})=>({drawPosition:d?.find(v=>v.participantId===b)?.drawPosition,teamParticipantId:b}));N=h.sides?.find(b=>R?.find(({drawPosition:v})=>v===b.drawPosition)?.teamParticipantId===U)}if(!N)return _({result:{error:te,context:{participantId:n}}});let{modifiedLineUp:D,previousParticipantIds:M}=_y({collectionPosition:l,teamParticipantId:U,dualMatchUpSide:N,participantIds:A,drawDefinition:r,collectionId:g});if(N.lineUp=D,U&&T&&Ki({participantId:U,lineUp:D,drawDefinition:r,tieFormat:T}),I===_t&&E.participantType===Tt){let R=m?.sides?.find(O=>O.sideNumber===N?.sideNumber),{participantId:b}=R??{},v=b&&Gt({participantFilters:{participantIds:[b]},tournamentRecord:e,withDraws:!0})?.participants?.[0];if(v){let O=v?.individualParticipantIds?.filter(x=>x!==n)??[];if(M&&O.push(...M),O.length>2)return _({result:{error:wr},stack:i});if(v.draws?.length){if(O.length===1){let{participant:x}=In({participantIds:O,tournamentRecord:e});if(!x){let L=bn({participant:{participantRole:xe,individualParticipantIds:O,participantType:ft},pairOverride:!0,tournamentRecord:e});if(L.error)return _({result:L,stack:i})}}}else if(O.length){v.individualParticipantIds=O;let x=rm({participant:v,pairOverride:!0,tournamentRecord:e});if(x.error)return _({result:x,stack:i})}else{let x=$i({participantIds:[b],tournamentRecord:e});x.error&&console.log("cleanup",{result:x})}}else return _({result:{error:te},stack:i})}if(y.substitutions?.length===1&&!m?.sides?.find(b=>b.sideNumber!==y.sideNumber)?.substitutions?.length&&S?.processCodes?.length){for(let b of u||[]){let v=S.processCodes.lastIndexOf(b);S.processCodes.splice(v,1)}gt({tournamentId:e?.tournamentId,matchUp:S,context:i,drawDefinition:r})}return gt({tournamentId:e?.tournamentId,matchUp:h,context:i,drawDefinition:r}),{...C,modifiedLineUp:D}}function nI(t){let e=rt(t,[{[ie]:!0,[Ve]:!0,[ln]:!0}]);if(e.error)return e;let{drawDefinition:r,sideNumber:n,matchUpId:o,event:i}=t;if(n&&![1,2].includes(n))return{error:G,sideNumber:n};let{matchUp:s,structure:a}=Bt({drawDefinition:r,matchUpId:o,event:i});return s?cr({structure:a})?(s.sides?.forEach(c=>{(!n||c.sideNumber===n)&&delete c.participantId}),gt({tournamentId:t.tournamentRecord?.tournamentId,context:"assignSideParticipant",drawDefinition:r,matchUp:s}),{...C}):{error:ym}:{error:Le}}function Tx({matchUpStatuses:t=[Nt,Ct,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=Fe(s||[],t),u=Fe(a||[],t);return{sourceMatchUp:o,winnerHadMatchUpStatus:c,winnerMatchUpStatuses:s,loserHadMatchUpStatus:u,loserMatchUpStatuses:a}}function yx({inContextDrawMatchUps:t,sourceMatchUpStatus:e,targetDrawPosition:r,tournamentRecord:n,sourceMatchUpId:o,drawDefinition:i,structureId:s,dualMatchUp:a,roundNumber:c,matchUpsMap:u,event:p}){let{structure:m}=at({drawDefinition:i,structureId:s});if(m?.structureType===Ge)return{...C};u=u??Ne({drawDefinition:i});let l=(u?.mappedMatchUps||{})[s].matchUps,{initialRoundNumber:f}=fs({drawPosition:r,matchUps:l}),g=l?.filter(h=>h.roundNumber>=c&&h.roundNumber!==f&&h.drawPositions?.includes(r)),{positionAssignments:I}=bt({drawDefinition:i,structureId:s});for(let h of g??[])D1({inContextDrawMatchUps:t,sourceMatchUpStatus:e,positionAssignments:I,targetDrawPosition:r,tournamentRecord:n,sourceMatchUpId:o,drawDefinition:i,dualMatchUp:a,matchUpsMap:u,matchUp:h,event:p});return{...C}}function D1({inContextDrawMatchUps:t,positionAssignments:e,sourceMatchUpStatus:r,targetDrawPosition:n,tournamentRecord:o,sourceMatchUpId:i,drawDefinition:s,dualMatchUp:a,matchUpsMap:c,matchUp:u,event:p}){let m="removeSubsequentDrawPosition";if(a){let g=t.find(({matchUpId:h})=>u.matchUpId===h).sides?.find(h=>h.drawPosition===n)?.sideNumber,I=u.sides?.find(h=>h.sideNumber===g);I&&delete I.lineUp}u.drawPositions=(u.drawPositions||[]).map(f=>f===n?void 0:f).filter(Boolean);let l=e.filter(({drawPosition:f})=>u.drawPositions?.includes(f)).filter(f=>f.bye).length;return u.matchUpStatus=l&&Nt||[Mt,Ct].includes(u.matchUpStatus)&&u.matchUpStatus||Qt,[Ct,Mt].includes(u.matchUpStatus)&&(u.winningSide=void 0),u.matchUpStatusCodes&&NS({inContextDrawMatchUps:t,sourceMatchUpStatus:r,sourceMatchUpId:i,matchUpsMap:c,matchUp:u}),gt({tournamentId:o?.tournamentId,eventId:p?.eventId,context:`${m}-${n}`,drawDefinition:s,matchUp:u}),{...C}}function vc(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=cr({structure:p}),{drawPositions:f,winningSide:g}=c.matchUp||{};if(!l&&!f)return{error:ja};let{targetLinks:{loserTargetLink:I,winnerTargetLink:h,byeTargetLink:S},targetMatchUps:{loserMatchUp:T,winnerMatchUp:y,byeMatchUp:P}}=c,U=Gn({...t,matchUpStatus:i||Qt,removeWinningSide:!0});if(U.error)return U;let E;if(d){let{matchUpTieId:L,matchUpsMap:w}=t;if(E=co({appliedPolicies:t.appliedPolicies,matchUpId:L,tournamentRecord:n,drawDefinition:o,matchUpsMap:w,event:m}),!e&&!E.removeWinningSide)return{...C}}if(l)return{...C};let{matchUps:A}=Ut({afterRecoveryTimes:!1,inContext:!0,drawDefinition:o,matchUpsMap:s,structure:p}),{positionAssignments:N}=Se({structure:p}),D=g-1,M=1-D,R=f[D],b=f[M],{winnerParticipantId:v,loserParticipantId:O}=N?.reduce((L,w)=>(w.drawPosition===b&&(L.loserParticipantId=w.participantId),w.drawPosition===R&&(L.winnerParticipantId=w.participantId),L),{winnerParticipantId:void 0,loserParticipantId:void 0})||{},x=A.filter(L=>L.drawPositions?.includes(b));if(y&&nM({sourceMatchUpStatus:i,sourceMatchUpId:u,inContextDrawMatchUps:r,winningDrawPosition:R,winnerParticipantId:v,tournamentRecord:n,winnerTargetLink:h,drawDefinition:o,winnerMatchUp:y,dualMatchUp:a,matchUpsMap:s}),T){let{winnerHadMatchUpStatus:L}=Tx({drawPositionMatchUps:x,loserDrawPosition:b,sourceMatchUps:A}),V=I.linkCondition===On;if(L&&V){let W=Math.min(...T.drawPositions);xy({targetLink:I,inContextDrawMatchUps:r,drawDefinition:o,drawPosition:W,matchUpsMap:s,event:m})}let k=N1({sourceMatchUpStatus:i,sourceMatchUpId:u,loserParticipantId:O,tournamentRecord:n,loserTargetLink:I,drawDefinition:o,loserMatchUp:T,dualMatchUp:a,matchUpsMap:s,event:m});if(k.error)return k}if(P){let L=Math.min(...P.drawPositions);xy({sourceMatchUpId:u,targetLink:S,inContextDrawMatchUps:r,drawDefinition:o,drawPosition:L,matchUpsMap:s,event:m})}return{...C,...E&&{tieMatchUpResult:E}}}function nM({inContextDrawMatchUps:t,winningDrawPosition:e,sourceMatchUpStatus:r,winnerParticipantId:n,tournamentRecord:o,winnerTargetLink:i,sourceMatchUpId:s,drawDefinition:a,winnerMatchUp:c,matchUpsMap:u,dualMatchUp:p,event:m}){let{structureId:d,roundNumber:l}=c,f="removeDirectedWinner";if(i){let g=i.target.structureId,{structure:I}=at({drawDefinition:a,structureId:g});if(!I)return{error:kt};let{positionAssignments:h}=Se({structure:I});I.seedAssignments=(I.seedAssignments??[]).filter(N=>N.participantId!==n);let T=h?.find(N=>N.participantId===n)?.drawPosition,{matchUps:y}=Ut({drawDefinition:a,structure:I,event:m}),P=y.map(N=>N.drawPositions).flat(1/0).filter(Boolean),U=Sr(P);if((T?U[T]:void 0)===1)h?.forEach(N=>{N.participantId===n&&delete N.participantId});else{let N=y.filter(({drawPositions:D})=>D.includes(T));console.log("not removing from position assignments since instances > 1",{drawPositionMatchUps:N,winnerTargetLink:i})}let A=u?.drawMatchUps?.find(({matchUpId:N})=>N===c.matchUpId);A&>({tournamentId:o?.tournamentId,eventId:m?.eventId,matchUp:A,context:f,drawDefinition:a})}return l&&yx({targetDrawPosition:e,inContextDrawMatchUps:t,sourceMatchUpStatus:r,tournamentRecord:o,sourceMatchUpId:s,drawDefinition:a,dualMatchUp:p,matchUpsMap:u,roundNumber:l,structureId:d}),{...C}}function N1({sourceMatchUpStatus:t,loserParticipantId:e,tournamentRecord:r,loserTargetLink:n,sourceMatchUpId:o,drawDefinition:i,loserMatchUp:s,matchUpsMap:a,dualMatchUp:c,event:u}){let p="removeDirectedLoser",m=n.target.structureId,{structure:d}=at({drawDefinition:i,structureId:m});if(!d)return{error:kt};let{positionAssignments:l}=Se({structure:d}),f=l?.find(g=>g.participantId===e)?.drawPosition;if(l?.forEach(g=>{g.participantId===e&&delete g.participantId}),d.seedAssignments=(d.seedAssignments??[]).filter(g=>g.participantId!==e),c){let g=s?.sides.reduce((S,T,y)=>T.drawPosition===f?y:S,void 0),I=a?.drawMatchUps?.find(({matchUpId:S})=>S===s.matchUpId),h=I?.sides?.[g];h&&(delete h.lineUp,gt({tournamentId:r?.tournamentId,eventId:u?.eventId,matchUp:I,context:p,drawDefinition:i}))}return{...C}}function xy({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,matchUpsMap:o,targetLink:i,event:s}){let a=i.target.structureId,c="removeDirectedBye";Rn({color:"brightyellow",method:c,drawPosition:n});let u=lc({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,matchUpsMap:o,structureId:a,event:s});return _({result:u,stack:c})}function Ax(t){let{matchUpFormat:e,score:r}=t,n=r?.sets?.length,o=e&&Ye(e),{setFormat:i,finalSetFormat:s,bestOf:a}=o??{};return(a&&n===a&&s||i)?.timed||!1}function Ex({tournamentRecord:t,drawDefinition:e,structure:r,matchUp:n}){let o="attemptToSetMatchUpStatusBYE";if(n?.winningSide)return _({result:{error:pa},context:{matchUpStatus:Nt},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=Nt,n.matchUpStatusCodes=[],gt({tournamentId:t?.tournamentId,context:o,drawDefinition:e,matchUp:n}),{...C}):_({result:{error:KA},info:"matchUp does not include BYE",stack:o})}function Il(t){let{tournamentRecord:e,appliedPolicies:r,drawDefinition:n,matchUpsMap:o,targetData:i,structure:s,event:a}=t,c="doubleExitAdvancement";if(s.structureType===Ge)return _({result:{...C},stack:c});let{matchUp:u,targetMatchUps:p,targetLinks:m}=i,{loserMatchUp:d,winnerMatchUp:l,loserTargetDrawPosition:f}=p,g=[Ct,Mt].includes(d?.matchUpStatus)&&!d.sides?.map(I=>I.participantId??I.participant).filter(Boolean).length;if(d&&d.matchUpStatus!==Nt){let{loserTargetLink:I}=m;if(r?.progression?.doubleExitPropagateBye){let h=Px({loserTargetDrawPosition:f,tournamentRecord:e,loserTargetLink:I,drawDefinition:n,loserMatchUp:d,matchUpsMap:o,event:a});if(h.error)return _({result:h,stack:c})}else if(!g){let{feedRound:h,drawPositions:S,matchUpId:T}=d,y=h?2:2-S.indexOf(f),P=Ux({...t,targetMatchUp:d,walkoverWinningSide:y,tournamentRecord:e,sourceMatchUp:u,matchUpId:T});if(P.error)return _({result:P,stack:c})}}if(l){let I=Ux({...t,matchUpId:l.matchUpId,targetMatchUp:l,tournamentRecord:e,sourceMatchUp:u});if(I.error)return _({result:I,stack:c})}return _({result:{...C},stack:c})}function Ux(t){let{inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,sourceMatchUp:o,targetMatchUp:i,matchUpsMap:s}=t,a=n.structures.find(({structureId:q})=>q===i.structureId),c=t.matchUpStatus===Ce?Ce:he,u=t.matchUpStatus===Ce?Mt:Ct,p="conditionallyAdvanceDrawPosition",m=s.drawMatchUps.find(q=>q.matchUpId===i.matchUpId);if(!m)return{error:hr};let d=o?.drawPositions||[],l=m.drawPositions?.filter(Boolean),f=o?.structureId===i.structureId;if(f&&Fe(d,l)&&(l=l.filter(q=>!d.includes(q))),f&&l.length>1)return _({result:{error:Wa},stack:p});let{pairedPreviousMatchUpIsDoubleExit:g,pairedPreviousMatchUp:I}=PS(t),h=ur({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),{targetMatchUps:S,targetLinks:T}=h,{loserTargetDrawPosition:y,winnerMatchUp:P,loserMatchUp:U}=S;if(U){let{loserTargetLink:q}=T,B=Px({loserTargetDrawPosition:y,loserMatchUp:U,tournamentRecord:r,loserTargetLink:q,drawDefinition:n,matchUpsMap:s});if(B.error)return _({result:B,stack:p})}let E=m.drawPositions?.filter(Boolean)||[],A=E.length===1,N=t.walkoverWinningSide||A&&hd({drawPosition:E[0],matchUpId:i.matchUpId,inContextDrawMatchUps:e})||void 0,D=[Ct,Mt].includes(m.matchUpStatus)&&!E.length,M=m.finishingRound===1,R=D&&!M?c:u,b=e.find(q=>q.matchUpId===I.matchUpId),v=[],O;o&&(o?.structureId===b?.structureId?o.roundPosition<I?.roundPosition?O=1:O=2:i.feedRound?o.structureId===i.structureId?O=2:O=1:N&&(O=3-N));let x=t.matchUpStatus,F=I?.matchUpStatus;O===1?v=[{matchUpStatus:wy(x),previousMatchUpStatus:x,sideNumber:1},{matchUpStatus:wy(F),previousMatchUpStatus:F,sideNumber:2}]:O===2&&(v=[{matchUpStatus:wy(F),previousMatchUpStatus:F,sideNumber:1},{matchUpStatus:wy(x),previousMatchUpStatus:x,sideNumber:2}]),v.length&&(v=v.map(q=>ot(q)));let L=Gn({...t,winningSide:N,matchUp:m,matchUpStatusCodes:v,context:p,matchUpStatus:R});if(L.error)return _({result:L,stack:p});if(D)return Il({...t,matchUpStatus:R,targetData:h});if(!P)return _({result:{...C},stack:p});let w=l.length===2?l[N-1]:l[0],{positionAssignments:V}=bt({structure:a}),k=V?.find(q=>q.drawPosition===w),W=s.drawMatchUps.find(q=>q.matchUpId===P.matchUpId),H=W?.drawPositions?.filter(Boolean),K=H.length===1;if(w){if(k?.bye){let q=ur({matchUpId:W.matchUpId,inContextDrawMatchUps:e,drawDefinition:n});if(K){let B=H.filter(Boolean)[0],$=hd({drawPosition:B,matchUpId:W.matchUpId,inContextDrawMatchUps:e}),z=Gn({appliedPolicies:t.appliedPolicies,matchUpId:W.matchUpId,matchUp:W,matchUpStatus:u,matchUpStatusCodes:[],removeScore:!0,context:p,drawDefinition:n,winningSide:$});return z.error?_({result:z,stack:p}):hS({drawPositionToAdvance:B,matchUpId:W.matchUpId,inContextDrawMatchUps:e,drawDefinition:n,matchUpsMap:s})}else if([Ct,Mt].includes(P.matchUpStatus)){let B=Il({...t,matchUpId:W.matchUpId,matchUpStatus:R,targetData:q});if(B.error)return _({result:B,stack:p})}return _({result:{...C},stack:p})}return hc({matchUpId:P.matchUpId,drawPosition:w,inContextDrawMatchUps:e,drawDefinition:n})}else if(g){if(!W)return{error:hr};if(K){let $=H[0],z=hd({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawPosition:$});console.log("existing drawPosition is winningSide",{walkoverWinningSide:z})}let q=[Ct,Mt].includes(W.matchUpStatus)?u:c,B=Gn({matchUpId:W.matchUpId,appliedPolicies:t.appliedPolicies,matchUp:W,matchUpStatusCodes:[],removeScore:!0,context:p,drawDefinition:n,matchUpStatus:q});if(B.error)return _({result:B,stack:p});if(q===c){let $=Il({...t,matchUpId:i.matchUpId,matchUpStatus:q,targetData:h});if($.error)return $}}return _({result:{...C},stack:p})}function Px(t){let{loserTargetDrawPosition:e,tournamentRecord:r,loserTargetLink:n,drawDefinition:o,matchUpsMap:i,event:s}=t,a=n?.target?.structureId,{structure:c}=at({drawDefinition:o,structureId:a});return c?Hr({drawPosition:e,tournamentRecord:r,drawDefinition:o,structureId:a,matchUpsMap:i,event:s}):{error:pi}}function wy(t){return t===he?Ct:t===Ce?Mt:t}function Dx(t){let{tournamentRecord:e,drawDefinition:r,matchUpStatus:n,structure:o,matchUp:i}=t,s=!!(i.tieMatchUps&&!i.rondPosition&&t.inContextDrawMatchUps.find(h=>h.matchUpId===i.matchUpId).containerStructureId),a="attemptToSetMatchUpStatus",c=n===Nt,u=i.winningSide,p=[he,Ce].includes(n),m=Ua({matchUpStatus:n}),d=og({matchUpStatus:n}),l=!m&&!d,f=t.matchUpTieId||u&&m&&!p,g=u&&p,I=()=>Gn({...t,removeScore:[oo,Ct].includes(n),matchUpStatus:n||Qt});return l&&{error:xI}||f&&oM(t)||g&&M1(t)||u&&vc(t)||d&&I()||c&&Ex({tournamentRecord:e,drawDefinition:r,structure:o,matchUp:i})||!m&&{error:xI}||p&&R1(t)||s&&oM(t)||_({result:{error:pa},stack:a})}function M1(t){let e=vc(t);return e.error?e:Il(t)}function R1(t){let e=oM({...t,removeScore:!0});return e.error?e:Il(t)}function oM(t){let e="scoreModification";if(t.isCollectionMatchUp&&t.dualMatchUp?.winningSide&&!t.projectedWinningSide){let i=vc(t);if(i.error)return _({result:i,stack:e})}let n=!!t.matchUp.collectionId,o=Gn({...t,context:e});if(n){let{matchUpTieId:i,drawDefinition:s,matchUpsMap:a}=t,c=co({tournamentRecord:t.tournamentRecord,appliedPolicies:t.appliedPolicies,matchUpId:i,event:t.event,drawDefinition:s,matchUpsMap:a});if(c.error)return _({result:c,stack:e});Object.assign(o,{tieMatchUpResult:c})}return _({result:o,stack:e})}function Nx({drawDefinition:t,structure:e,matchUp:r}){let{drawPositions:n}=r,{positionAssignments:o}=bt({drawDefinition:t,structure:e}),s=o?.filter(({drawPosition:m})=>n?.includes(m))?.map(m=>{let{extension:d}=dt({element:m,name:Jo});return d?.value?.groupOrder}),{containerStructures:a}=as({drawDefinition:t}),c=a[e.structureId];return{structureIds:Ws({drawDefinition:t,structureId:c})?.links?.source?.filter(m=>Fe(s,m.source?.finishingPositions||[])).map(m=>m.source.structureId)}}function Ly({drawDefinition:t,structure:e,matchUp:r}){let n=[];if(e.finishingPosition===li&&si({drawDefinition:t,structure:e})){let{structureIds:i}=Nx({drawDefinition:t,structure:e,matchUp:r});i?.length&&n.push(...i)}return{connectedStructureIds:n}}function Mx(t){let e,{inContextDrawMatchUps:r,inContextMatchUp:n,drawDefinition:o,winningSide:i}=t,s=t.targetData.targetLinks?.winnerTargetLink;if(s.target.feedProfile===dn){let a=n.sides.find(({sideNumber:u})=>u!==i).participantId,c=r.find(u=>u.structureId===s.target.structureId&&u.roundNumber===s.target.roundNumber&&u.sides.some(({participantId:p})=>p===a));if(c?.matchUpStatus===Qt){let u=ur({matchUpId:c.matchUpId,inContextDrawMatchUps:r,drawDefinition:o});if(!Ci({inContextDrawMatchUps:r,drawDefinition:o,targetData:u})){let{structure:m}=at({structureId:c.structureId,drawDefinition:o}),d=bt({structure:m}).positionAssignments;for(let l of d||[])if(l.participantId===a){let f=n.sides.find(({sideNumber:g})=>g===i).participantId;if(l.participantId=f,m?.positionAssignments)m.positionAssignments=d;else if(m?.structures){let g=Object.assign({},...(d||[]).map(I=>({[I.drawPosition]:I.participantId})));for(let I of m.structures)I.positionAssignments?.forEach(h=>h.participantId=g[h.drawPosition])}bo({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:o,structure:m}),e=!0}}}}return{...C,qualifierReplaced:e}}function Rx(t){let e,{inContextDrawMatchUps:r,inContextMatchUp:n,drawDefinition:o,winningSide:i}=t,s=t.targetData.targetLinks?.winnerTargetLink;if(s.target.feedProfile===dn){let a=n.sides.find(({sideNumber:p})=>p===i)?.participantId,c=r.filter(p=>p.structureId===s.target.structureId&&p.roundNumber===s.target.roundNumber&&p.sides.some(({participantId:m,qualifier:d})=>d&&!m)),u=yn(c);if(u?.matchUpStatus===Qt){let p=ur({matchUpId:u.matchUpId,inContextDrawMatchUps:r,drawDefinition:o});if(!Ci({inContextDrawMatchUps:r,drawDefinition:o,targetData:p})){let d=u.sides.find(g=>g.qualifier&&!g.participantId)?.drawPosition,{structure:l}=at({structureId:u.structureId,drawDefinition:o});if(!l)return{error:kt};let f=bt({structure:l}).positionAssignments;for(let g of f||[])if(g.drawPosition===d&&!g.participantId){if(g.participantId=a,l.positionAssignments)l.positionAssignments=f;else if(l.structures){let I=Object.assign({},...(f||[]).map(h=>({[h.drawPosition]:h.participantId})));for(let h of l.structures)h.positionAssignments?.forEach(S=>S.participantId=I[S.drawPosition])}bo({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:o,structure:l}),e=!0}}}}return{...C,qualifierPlaced:e}}function Cx(t){let e="attemptToSetWinningSide",r,{appliedPolicies:n,disableAutoCalc:o,drawDefinition:i,dualMatchUp:s,winningSide:a,structure:c,matchUp:u}=t;if(s?._disableAutoCalc&&o!==!1)return Rd(t);if(u.winningSide&&u.winningSide!==a){let{connectedStructureIds:l}=Ly({drawDefinition:i,structure:c,matchUp:u});l.length&&(console.log({connectedStructureIds:l}),r=!0);let f=vc(t);if(f.error)return f}let p=JS(t);if(p.error)return _({result:p,stack:e});let m,d;return t.qualifierChanging&&n?.[eu]?.autoReplaceQualifiers&&(m=Mx(t).qualifierReplaced),t.qualifierAdvancing&&n?.[eu]?.autoPlaceQualifiers&&(d=Rx(t).qualifierPlaced),_({result:ot({...C,...p,connectedStructures:r,qualifierReplaced:m,qualifierPlaced:d}),stack:e})}var Fy={drawPositionToRemove:"green",iteration:"brightred",winner:"green",loser:"brightred"};function iM(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";Rn({color:"brightyellow",method:u,matchUpId:a,iteration:c,keyColors:Fy});let{targetMatchUps:{loserMatchUp:p,winnerMatchUp:m,loserTargetDrawPosition:d},targetLinks:{loserTargetLink:l}}=i;if(m&&m.matchUpStatus!==Nt){let{stage:I,roundNumber:h,roundPosition:S,structureName:T}=m;Rn({winner:"winner",roundPosition:S,structureName:T,roundNumber:h,keyColors:Fy,stage:I}),bx({...t,targetMatchUp:m,sourceMatchUp:s,iteration:c})}let f=p?.matchUpStatus===Nt&&(p?.feedRound||p?.roundNumber===1),g=i?.targetLinks?.loserTargetLink?.linkCondition===On;if(f&&g){let I=e.filter(({roundNumber:P,structureId:U})=>U===s.structureId&&P===1),h=I.map(({roundPosition:P})=>P),S=ye(h.sort(),2).find(P=>P.includes(s.roundPosition));if((I.filter(({roundPosition:P})=>S.includes(P))?.map(({matchUpStatus:P})=>P)).every(P=>[Ce,he].includes(P)))return _({result:{...C},stack:u})}if(p&&(p.matchUpStatus!==Nt||f)){let I=e.find(({matchUpId:E})=>E===p.matchUpId),{structure:h}=at({drawDefinition:n,structureId:I.structureId}),{stage:S,roundNumber:T,roundPosition:y,feedRound:P,structureName:U}=p;if(Rn({loser:"loser",roundPosition:y,structureName:U,roundNumber:T,keyColors:Fy,feedRound:P,stage:S}),r?.progression?.doubleExitPropagateBye||f)xy({drawPosition:d,targetLink:l,inContextDrawMatchUps:e,drawDefinition:n,matchUpsMap:o});else{let E=bx({...t,targetMatchUp:p,structure:h,iteration:c});if(E.error)return _({result:E,stack:u})}}return _({result:{...C},stack:u})}function bx(t){let{inContextDrawMatchUps:e,appliedPolicies:r,drawDefinition:n,sourceMatchUp:o,targetMatchUp:i,matchUpsMap:s,structure:a,iteration:c}=t,u="conditionallyRemoveDrawPosition";Rn({method:u,structureName:a?.structureName,iteration:c});let p=ur({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),{targetMatchUps:{winnerMatchUp:m}}=p,d=s?.drawMatchUps.find(y=>y.matchUpId===i.matchUpId),l=[],f,g,I;if(i.feedRound)I=m?.drawPositions?.filter(Boolean)?.find(P=>i.drawPositions.includes(P));else if(!o)I=Yt(i?.drawPositions||[],m?.drawPositions||[])?.[0];else if(g=DS({structureId:a.structureId,matchUp:o,matchUpsMap:s})?.pairedPreviousMatchUp,f=[he,Ce].includes(g?.matchUpStatus),l=g?.drawPositions?.filter(Boolean)||[],[...ce,Nt].includes(g?.matchUpStatus)||g?.winningSide){let P=o.drawPositions||[],U=i.drawPositions?.filter(Boolean);Fe(P,U)&&(U=U?.filter(A=>!P.includes(A))),I=P.concat(l).find(A=>U?.includes(A))}if(m&&I){let{stage:y,roundNumber:P,roundPosition:U,structureName:E}=m;Rn({method:"removeDirectedWinner",drawPositionToRemove:I,color:"brightgreen",roundPosition:U,structureName:E,roundNumber:P,keyColors:Fy,stage:y}),nM({winningDrawPosition:I,winnerMatchUp:m,inContextDrawMatchUps:e,drawDefinition:n,matchUpsMap:s})}let h=iM({targetData:p,matchUp:i,inContextDrawMatchUps:e,appliedPolicies:r,drawDefinition:n,matchUpsMap:s,structure:a,iteration:c});if(h.error)return _({result:h,stack:u});let S=C1({pairedPreviousDoubleExit:f,noContextTargetMatchUp:d}),T=!f;return h=Gn({...t,matchUpId:i.matchUpId,matchUp:d,removeWinningSide:!0,matchUpStatusCodes:[],context:u,matchUpStatus:S,removeScore:T,score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0}}),h.error?_({result:h,stack:u}):{...C}}function C1({pairedPreviousDoubleExit:t,noContextTargetMatchUp:e}){return e.matchUpStatus===Nt?Nt:t?[Ce,Mt].includes(e?.matchUpStatus)?Mt:Ct:Qt}function vx(t){let e,{inContextDrawMatchUps:r,inContextMatchUp:n,drawDefinition:o}=t,i=t.targetData.targetLinks?.winnerTargetLink;if(i.target.feedProfile===dn){let s=n.sides?.find(({sideNumber:c})=>c===n.winningSide)?.participantId,a=r.find(c=>c.structureId===i.target.structureId&&c.roundNumber===i.target.roundNumber&&c.sides?.some(({participantId:u})=>u===s));if(a&&a.matchUpStatus===Qt){let c=ur({matchUpId:a.matchUpId,inContextDrawMatchUps:r,drawDefinition:o});if(!Ci({inContextDrawMatchUps:r,drawDefinition:o,targetData:c})){let{structure:p}=at({structureId:a.structureId,drawDefinition:o}),m=bt({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])}bo({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:o,structure:p}),e=!0}}}}return{qualifierRemoved:e}}function _x(t){let{matchUp:e,matchUpStatus:r,score:n,winningSide:o}=t,i="noDownStreamDependencies";if([he,Ce].includes(e?.matchUpStatus)&&![he,Ce].includes(r)){let I=iM(t);if(I.error)return _({result:I,stack:i})}let a=r===he,c=Ie({score:n})&&!a&&(t.isCollectionMatchUp&&!t.projectedWinningSide||!o),u=t?.inContextMatchUp?.collectionId&&Ax(t.inContextMatchUp),p=t.removeScore||!u&&![pn,br].includes(r||pn),m=t.isCollectionMatchUp&&t.dualMatchUp.winningSide&&!t.projectedWinningSide||e.winningSide&&!o&&!Ie({score:n}),d=r&&r!==Qt,l=I=>{let h,{structure:S,drawDefinition:T,dualMatchUp:y,disableAutoCalc:P}=t;if(y?._disableAutoCalc&&P!==!1)return Rd({...t,removeWinningSide:m});let{connectedStructureIds:U}=Ly({drawDefinition:T,structure:S,matchUp:e});U.length&&(console.log({connectedStructureIds:U}),h=!0),Object.assign(t,{removeScore:I});let E=vc(t);if(E.error)return E;if(t.removingQualifier&&t.appliedPolicies?.[eu]?.autoRemoveQualifiers){let A=vx(t);return{...C,connectedStructures:h,...A}}return{...C,connectedStructures:h}};if(m&&o&&t.isCollectionMatchUp)return Ox(t);let f=[oo,br].includes(r)&&t.dualWinningSideChange,g=(o||f)&&Cx(t)||c&&l(p)||d&&Dx(t)||m&&l(p)||e&&Ox({...t,removeScore:!0})||{...C};return _({result:g,stack:i})}function Ox(t){let e="ndd:scoreModification";if(t.isCollectionMatchUp&&t.dualMatchUp?.winningSide&&!t.projectedWinningSide&&!t.autoCalcDisabled){let o=vc(t);if(o.error)return o}let n=Gn({...t,context:e});if(t.isCollectionMatchUp){let{matchUpTieId:o,drawDefinition:i,event:s,matchUpsMap:a}=t,{removeWinningSide:c}=co({tournamentRecord:t.tournamentRecord,appliedPolicies:t.appliedPolicies,matchUpId:o,drawDefinition:i,matchUpsMap:a,event:s});c&&console.log("REMOVE WINNING SIDE")}return _({result:n,stack:e})}function oI(t){let e=rt(t,[{[ie]:!0,[Ve]:!0,[ln]:!0},{homeParticipantId:!0,[fn]:oe}]);if(e.error)return e;let r=Ds(t,[{[is]:_n,attr:{[tu]:!0}}]);if(r.error)return r;let n=r?.matchUp?.matchUp?.sides?.map(m=>m?.participantId);if(t.homeParticipantId&&!n?.includes(t.homeParticipantId))return{error:mn};let{disableNotice:o=!0,homeParticipantId:i,removePriorValues:s,tournamentRecord:a,drawDefinition:c,matchUpId:u}=t;return Jr({duplicateValues:!1,removePriorValues:s,tournamentRecord:a,drawDefinition:c,disableNotice:o,matchUpId:u,timeItem:{itemType:cd,itemValue:i}})}function sM({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Ho({timeItems:r?.timeItems||[],itemType:Ap});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{timeModifiers:n}:e}function zo(t){let e="addMatchUpScheduledTime",r=t.matchUp,{removePriorValues:n,tournamentRecord:o,drawDefinition:i,disableNotice:s,scheduledTime:a,matchUpId:c}=t;if(!c)return _({result:{error:sr},stack:e});if(!Wc(a))return _({result:{error:Eo},stack:e});if(!r){let I=Bt({drawDefinition:i,matchUpId:c});if(I.error)return _({result:I,stack:e});r=I.matchUp}let u=Et(a),p=Hs({matchUp:r}).scheduledDate,m=u&&!p;if((sM({matchUp:r}).timeModifiers||[])?.length){let I=aM({disableNotice:!0,removePriorValues:n,tournamentRecord:o,timeModifiers:[],drawDefinition:i,matchUpId:c,matchUp:r});if(I?.error)return _({result:I,stack:e})}let f=Xa(a,!0,m);return Jr({duplicateValues:!1,removePriorValues:n,tournamentRecord:o,drawDefinition:i,disableNotice:s,matchUpId:c,timeItem:{itemType:ji,itemValue:f}})}function aM({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,timeModifiers:o,matchUpId:i,matchUp:s}){let a="addMatchUpTimeModifiers";if(!i)return _({result:{error:sr},stack:a});if(o!==void 0&&!Array.isArray(o))return _({info:ii("timeModifiers"),result:{error:G},stack:a});if(!s){let l=Bt({drawDefinition:r,matchUpId:i});if(l.error)return _({result:l,stack:a});s=l.matchUp}let c=sM({matchUp:s}).timeModifiers||[],u=o.filter(l=>!c.includes(l));if(o.length&&!u.length)return{...C};if(u.some(l=>sS.includes(l))){c=c.filter(f=>!sS.includes(f));let l=zo({disableNotice:!0,removePriorValues:t,scheduledTime:"",tournamentRecord:e,drawDefinition:r,matchUpId:i});if(l.error)return _({result:l,stack:a})}let m=o?.length?[...u,...c]:void 0;return Jr({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:i,timeItem:{itemType:Ap,itemValue:m}})}function nm({scheduledDate:t,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i}){if(!i)return{error:sr};let s=t&&Po.test(t);if(t&&!s)return{error:je};let c={itemValue:Et(t),itemType:Wi};return Jr({duplicateValues:!1,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:c})}function om({removePriorValues:t,tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,courtDayDate:i,matchUpId:s,courtIds:a}){if(!r&&!e)return{error:Y};if(!s)return{error:sr};let c=Bt({drawDefinition:n,matchUpId:s});if(c.error)return c;if(c?.matchUp?.matchUpType!==xr)return{error:dr};if(!(a===void 0||Array.isArray(a)&&a.length&&a.every(d=>typeof d=="string")))return{error:G,context:{courtIds:a}};let p;if(a){let d=e||r&&{[r.tournamentId]:r},l=Ao({tournamentRecords:d});if(l.error)return l;let f=l.courts?.filter(g=>a.includes(g.courtId));if(f?.length!==a.length)return{error:G,context:{courtIds:a}};p=f?.map(g=>({venueId:g.venueId,courtId:g.courtId}))}return Jr({duplicateValues:!1,removePriorValues:t,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:s,timeItem:{itemType:so,itemDate:i,itemValue:p}})}function ia({removePriorValues:t,tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,venueId:s}){if(!r)return{error:Y};if(!i)return{error:sr};if(s){let c=Wo({tournamentRecords:e,tournamentRecord:r,venueId:s});if(c.error)return c}return Jr({duplicateValues:!1,removePriorValues:t,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:{itemType:Hi,itemValue:s}})}function Xi({removePriorValues:t,tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,courtDayDate:i,matchUpId:s,courtId:a}){if(!r&&!e)return{error:Y};if(!s)return{error:sr};if(a){let u=ps({tournamentRecords:e,tournamentRecord:r,courtId:a});if(u.error)return u;let p=u.venue?.venueId;ia({tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:s,venueId:p})}return Jr({duplicateValues:!1,removePriorValues:t,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:s,timeItem:{itemType:Bo,itemDate:i,itemValue:a}})}function Ms(t,e){let r=$I.test(t)?t:Kt(t),n=Et(t)||Et(e)||Hn(new Date);return new Date(`${n}T${r}`).getTime()}function im(t){let e="addMatchUpScheduleItems",r=rt(t,[{drawDefinition:!0,matchUpId:!0},{schedule:!0,[He]:Kr}],e);if(r.error)return r;let{matchUpDependencies:n,inContextMatchUps:o}=t,{errorOnAnachronism:i=!1,checkChronology:s=!0,removePriorValues:a,tournamentRecords:c,tournamentRecord:u,drawDefinition:p,disableNotice:m,drawMatchUps:d,matchUpId:l,schedule:f,event:g}=t,I,h;if(d)I=d.find(O=>O.matchUpId===l);else{let O=Bt({drawDefinition:p,event:g,matchUpId:l});if(O.error)return O;I=O.matchUp}let{endTime:S,courtId:T,courtIds:y,courtOrder:P,resumeTime:U,homeParticipantId:E,scheduledDate:A,scheduledTime:N,startTime:D,stopTime:M,timeModifiers:R,venueId:b}=f;s&&(!n||!o)&&({matchUpDependencies:n,matchUps:o}=sn({drawDefinition:p}));let v=n?.[l]?.matchUpIds;if(f.scheduledDate&&s&&v){let O=o?.filter(x=>(x.schedule?.scheduledDate||Et(x.schedule?.scheduledTime))&&v.includes(x.matchUpId)).map(({schedule:x})=>{let F=bm(x);return new Date(F).getTime()});if(O?.length){let x=bm(f),F=new Date(x).getTime();if(Math.max(...O)>=F){if(i)return _({result:{error:bI},stack:e});h=bI}}}if(A!==void 0){let O=nm({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,scheduledDate:A,matchUpId:l});if(O?.error)return _({result:O,stack:e,context:{scheduledDate:A}})}if(N!==void 0){let O=zo({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,scheduledTime:N,matchUpId:l,matchUp:I});if(O?.error)return _({result:O,stack:e,context:{scheduledTime:N}})}if(D!==void 0){let O=Gy({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,matchUpId:l,startTime:D,event:g});if(O?.error)return _({result:O,stack:e,context:{startTime:D}})}if(M!==void 0){let O=By({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,matchUpId:l,stopTime:M,event:g});if(O?.error)return _({result:O,stack:e,context:{stopTime:M}})}if(U!==void 0){let O=Hy({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,resumeTime:U,matchUpId:l,event:g});if(O?.error)return _({result:O,stack:e,context:{resumeTime:U}})}if(S!==void 0){let O=Vy({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,matchUpId:l,endTime:S,event:g});if(O?.error)return _({result:O,stack:e,context:{endTime:S}})}if(y!==void 0){let O=om({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,matchUpId:l,courtIds:y});if(O?.error)return _({result:O,stack:e,context:{courtIds:y}})}if(T!==void 0&&A!==void 0){let O=Xi({courtDayDate:A,disableNotice:!0,removePriorValues:a,tournamentRecords:c,tournamentRecord:u,drawDefinition:p,matchUpId:l,courtId:T});if(O?.error)return _({result:O,stack:e,context:{courtId:T}})}if(b!==void 0){let O=ia({disableNotice:!0,removePriorValues:a,tournamentRecords:c,tournamentRecord:u,drawDefinition:p,matchUpId:l,venueId:b});if(O?.error)return _({result:O,stack:e,context:{venueId:b}})}if(P!==void 0&&It(P)){let O=ky({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,courtOrder:P,matchUpId:l});if(O?.error)return _({result:O,stack:e,context:{courtOrder:P}})}if(R!==void 0){let O=aM({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,timeModifiers:R,matchUpId:l,matchUp:I});if(O?.error)return _({result:O,stack:e,context:{timeModifiers:R}})}return Vt(E)&&oI({disableNotice:!0,homeParticipantId:E,removePriorValues:a,tournamentRecord:u,drawDefinition:p,matchUpId:l}),m||gt({tournamentId:u?.tournamentId,eventId:g?.eventId,context:e,drawDefinition:p,matchUp:I}),h?{...C,warnings:[h]}:{...C}}function ky({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,courtOrder:o,matchUpId:i}){if(!i)return{error:sr};if(o&&!It(o))return{error:G,info:"courtOrder must be numeric"};let s=o&&pt(o);return Jr({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:i,timeItem:{itemType:yp,itemValue:s}})}function cM({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,participantId:o,officialType:i,matchUpId:s}){if(!s)return{error:sr};if(!o)return{error:oe};if(e){let c=Gt({tournamentRecord:e,participantFilters:{participantTypes:[Tt],participantRoles:[ag]}}).participants??[];if(!Go({tournamentParticipants:c,participantId:o}))return{error:te}}let a={itemType:"SCHEDULE.ASSIGNMENT.OFFICIAL",itemValue:o};return i&&(a.itemSubTypes=[i]),Jr({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:s,timeItem:a})}function Gy({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,startTime:i,event:s}){if(!o)return{error:sr};if(!Wc(i))return{error:Eo};let{matchUp:a}=Bt({drawDefinition:r,event:s,matchUpId:o}),{scheduledDate:c}=Hs({matchUp:a}),p=(a?.timeItems??[]).filter(m=>[Yi,Pi,Di].includes(m?.itemType)).map(m=>Ms(m.itemValue,c)).reduce((m,d)=>!m||d<m?d:m,void 0);if(!p||Ms(i,c)<p){a?.timeItems&&(a.timeItems=a.timeItems.filter(l=>l.itemType!==Oo));let m=Xa(i,!0,!0);return Jr({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,timeItem:{itemType:Oo,itemValue:m}})}else return{error:AE}}function Vy({validateTimeSeries:t=!0,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,endTime:s,event:a}){if(!i)return{error:sr};if(!Wc(s))return{error:Eo};let{matchUp:c}=Bt({drawDefinition:n,event:a,matchUpId:i}),{scheduledDate:u}=Hs({matchUp:c}),m=(c?.timeItems??[]).filter(d=>[Oo,Pi,Yi].includes(d?.itemType)).map(d=>Ms(d.itemValue,u)).reduce((d,l)=>!d||l>d?l:d,void 0);if(!t||!m||Ms(s,u)>m){c?.timeItems&&(c.timeItems=c.timeItems.filter(f=>f.itemType!==Di));let d=Xa(s,!0,!0);return Jr({duplicateValues:!1,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:{itemType:Di,itemValue:d}})}else return{error:TE}}function By({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,stopTime:i,event:s}){if(!o)return{error:sr};if(!Wc(i))return{error:Eo};let{matchUp:a}=Bt({drawDefinition:r,event:s,matchUpId:o}),{scheduledDate:c}=Hs({matchUp:a}),u=a?.timeItems??[];if(u.reduce((g,I)=>I.itemType===Di||g,void 0))return{error:HI};let m=u.filter(g=>[Oo,Pi,Yi].includes(g?.itemType)).sort((g,I)=>Ms(g.itemValue,c)-Ms(I.itemValue,c)),d=m[m.length-1],l=d&&d.itemType===Yi,f=m.filter(g=>!l||g.createdAt!==d.createdAt).map(g=>Ms(g.itemValue,c)).reduce((g,I)=>!g||I>g?I:g,void 0);if(Ms(i,c)>f){if(a?.timeItems&&l){let h=d.createdAt;a.timeItems=a.timeItems.filter(S=>S.createdAt!==h)}let I={itemValue:Xa(i,!0,!0),itemType:Yi};return Jr({duplicateValues:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,timeItem:I})}else return{error:yE}}function Hy({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,resumeTime:o,matchUpId:i,event:s}){if(!i)return{error:sr};if(!Wc(o))return{error:Eo};let{matchUp:a}=Bt({drawDefinition:r,event:s,matchUpId:i}),{scheduledDate:c}=Hs({matchUp:a}),u=a?.timeItems??[];if(u.reduce((g,I)=>I.itemType===Di||g,void 0))return{error:HI};let m=u.filter(g=>[Oo,Pi,Yi].includes(g?.itemType)).sort((g,I)=>Ms(g.itemValue,c)-Ms(I.itemValue,c)),d=m[m.length-1],l=d&&d.itemType===Pi,f=m.filter(g=>!l||g.createdAt!==d.createdAt).map(g=>Ms(g.itemValue,c)).reduce((g,I)=>!g||I>g?I:g,void 0);if(Ms(o,c)>f){if(a?.timeItems&&l){let h=d.createdAt;a.timeItems=a.timeItems.filter(S=>S.createdAt!==h)}let I={itemValue:Xa(o,!0,!0),itemType:Pi};return Jr({duplicateValues:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:i,timeItem:I})}else return{error:UC}}function xx({drawDefinition:t,matchUpStatus:e,matchUpsMap:r,winningSide:n,dualMatchUp:o,tieFormat:i,structure:s,matchUp:a,event:c,score:u}){let p=J(o,void 0,!0);for(let d of p?.tieMatchUps||[])d.matchUpId===a.matchUpId&&(d.winningSide=n,d.score=u,!Ie({score:u})&&!e?Object.assign(d,{...Ru}):e&&(d.matchUpStatus=e));i=i??We({matchUp:a,structure:s,drawDefinition:t,event:c})?.tieFormat;let{winningSide:m}=Uc({matchUp:p,drawDefinition:t,matchUpsMap:r,structure:s,tieFormat:i,event:c});return{projectedWinningSide:m}}function wx(t){let{tournamentRecord:e,inContextMatchUp:r,structure:n,drawDefinition:o}=t,i=r.roundNumber,s=r.sides.find(U=>U.sideNumber===r.winningSide),a=r.sides.find(U=>U.sideNumber!==r.winningSide),{drawPosition:c,participantId:u}=s,{drawPosition:p,participantId:m}=a,d="swapWinnerLoser",{matchUps:l}=Ut(t),f=l.filter(({drawPositions:U,roundNumber:E})=>U?.includes(c)&&E>i);Ur({changeWinner:!0})&&console.log({existingWinnerSubsequentMatchUps:f}),f.forEach(U=>{U.drawPositions=U.drawPositions?.map(E=>E===c?p:E)||[],gt({tournamentId:e?.tournamentId,eventId:t.event?.eventId,context:d,drawDefinition:o,matchUp:U})});let{stage:g,stageSequence:I}=n,h=o.structures.filter(({stage:U,stageSequence:E})=>U===g&&E>I).map(({structureId:U})=>U),{targetLinks:{loserTargetLink:S,winnerTargetLink:T}}=t.targetData,y=[S?.target.structureId,T?.target?.structureId].filter(Boolean);return o.structures.filter(({stage:U,structureId:E})=>U!==g&&y.includes(E)).forEach(({stage:U,stageSequence:E,structureId:A})=>{h.includes(A)||h.push(A),o.structures.filter(({stage:N,stageSequence:D})=>N===U&&D>E).forEach(({structureId:N})=>{h.includes(N)||h.push(N)})}),o.structures.filter(({structureId:U})=>h.includes(U)).forEach(U=>{let{positionAssignments:E}=bt({structure:U}),A=E?.find(({participantId:D})=>D===u),N=E?.find(({participantId:D})=>D===m);A&&(A.participantId=m),N&&(N.participantId=u)}),Gn({...t,context:d})}function La(t){let e="setMatchUpStatus";t.matchUpStatus&&[Ct,he].includes(t.matchUpStatus)&&(t.score=void 0);let{allowChangePropagation:r,disableScoreValidation:n,tournamentRecords:o,tournamentRecord:i,disableAutoCalc:s,enableAutoCalc:a,drawDefinition:c,matchUpStatus:u,winningSide:p,matchUpId:m,event:d,score:l}=t;if(!c)return{error:Z};if(u&&[oo,pn,br,Qt].includes(u)&&p)return{error:G,winningSide:p,matchUpStatus:u};if(![void 0,...Lh].includes(u))return _({result:{error:pa},info:"matchUpStatus does not exist",stack:"setMatchUpStatus"});let f=Ne({drawDefinition:c}),{matchUps:g}=se({nextMatchUps:!0,tournamentRecord:i,inContext:!0,drawDefinition:c,matchUpsMap:f,event:d}),I=f.drawMatchUps.find(k=>k.matchUpId===m),h=g?.find(k=>k.matchUpId===m);if(!I||!g)return{error:Le};if((I.winningSide||p)&&u===Nt)return{context:"Cannot have Bye with winningSide",error:Bl,matchUpStatus:u};let S=h?.structureId,{structure:T}=at({drawDefinition:c,structureId:S}),y=ue(jt)(I.matchUpType),P=h?.drawPositions?.filter(Boolean),U=h?.matchUpTieId,E=ur({matchUpId:U||m,inContextDrawMatchUps:g,drawDefinition:c});Object.assign(t,{inContextDrawMatchUps:g,inContextMatchUp:h,matchUpTieId:U,matchUpsMap:f,targetData:E,structure:T,matchUp:I});let A=Ci(t),N;if(y){if(s)At({extension:{name:ga,value:!0},element:I});else if(a){let k=I.winningSide,{winningSide:W,scoreStringSide1:H,scoreStringSide2:K,set:q}=Uc({drawDefinition:c,matchUpsMap:f,structure:T,matchUp:I,event:d}),B={scoreStringSide1:H,scoreStringSide2:K,sets:q?[q]:[]};if(N=W!==k,A&&N)return _({stack:"winningSideWithDownstreamDependencies",result:{error:Um},context:{winningSide:p,matchUp:I}});gr({name:ga,element:I}),Object.assign(t,{winningSide:W,dualWinningSideChange:N,projectedWinningSide:W,score:B})}ba({tournamentId:i?.tournamentId,inContextDualMatchUp:h,eventId:d?.eventId,dualMatchUp:I,drawDefinition:c})}if(y&&u&&[ic].includes(u))return{info:"Not supported for matchUpType: TEAM",error:G};if(l&&!y&&!n){let k=I.matchUpFormat??T?.matchUpFormat??c?.matchUpFormat??d?.matchUpFormat,W=Vg({existingMatchUpStatus:I.matchUpStatus,matchUpFormat:k,matchUpStatus:u,winningSide:p,score:l});if(W.error)return W}let D=yt({policyTypes:[eu,en],tournamentRecord:i,drawDefinition:c,event:d})?.appliedPolicies??{};ht(t.policyDefinitions)&&Object.assign(D,t.policyDefinitions);let M=v1({assignedDrawPositions:P,inContextMatchUp:h,appliedPolicies:D,drawDefinition:c,matchUpStatus:u,structure:T,matchUp:I});if(M?.error)return M;let R=h?.stage===ct&&h.finishingRound===1,b=R&&p,v=R&&I.winningSide&&!p&&(!t.matchUpStatus||t.matchUpStatus&&og({matchUpStatus:t.matchUpStatus}))&&(!t.outcome||!Ie({outcome:t.outcome})),O=b&&p!==I.winningSide&&I.winningSide;if(Object.assign(t,{qualifierAdvancing:b,qualifierChanging:O,removingQualifier:v,appliedPolicies:D}),U){let{matchUp:k}=Bt({matchUpId:U,inContext:!0,drawDefinition:c,matchUpsMap:f,event:d});if(k){let W=We({matchUp:k,drawDefinition:c,structure:T,event:d})?.tieFormat,{projectedWinningSide:H}=xx({drawDefinition:c,matchUpStatus:u,dualMatchUp:k,matchUpsMap:f,winningSide:p,tieFormat:W,structure:T,matchUp:I,event:d,score:l}),K=k.winningSide;N=H!==K;let q=k._disableAutoCalc;Object.assign(t,{isCollectionMatchUp:!0,dualWinningSideChange:N,projectedWinningSide:H,autoCalcDisabled:q,matchUpTieId:U,dualMatchUp:k,tieFormat:W})}}let x=Ua({matchUpStatus:u});if(!U){if(A&&!p&&(u&&og({matchUpStatus:u})||u&&[he,Ce].includes(u)))return{error:Bl,activeDownstream:A,winningSide:p};if(p&&p===I.winningSide&&u&&!x)return{context:"winningSide must include directing matchUpStatus",error:Bl,directingMatchUpStatus:x,matchUpStatus:u}}let{schedule:F}=t;if(F){let k=im({disableNotice:!0,tournamentRecords:o,tournamentRecord:i,drawDefinition:c,matchUpId:m,schedule:F});if(k.error)return k}let L=!y&&!N&&p&&I.winningSide&&I.winningSide!==p;if(r&&L&&I.roundPosition)return wx(t);let w=p&&!U||t.projectedWinningSide;Rn({activeDownstream:A,matchUpWinner:w,method:e,winningSide:p});let V=!A&&_x(t)||w&&b1(t)||(x||t.autoCalcDisabled)&&Lx(t)||{error:CE};return _({result:V,stack:e})}function b1(t){let{matchUp:e,winningSide:r,matchUpTieId:n,dualWinningSideChange:o}=t;return r===e.winningSide||n&&!o?Lx(t):_({stack:"winningSideWithDownstreamDependencies",result:{error:Um},context:{winningSide:r,matchUp:e}})}function Lx(t){let{tournamentRecord:e,matchUp:r,event:n}=t,o=t.isCollectionMatchUp&&r.winningSide&&!t.winningSide&&!Ie({score:t.score}),i=t.isCollectionMatchUp?t.matchUpStatus||o&&Qt||t.winningSide&&le||pn:t.matchUpStatus||le,s=t.removeScore||[oo,Ct].includes(i)&&![pn,br].includes(i),a=Gn({...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=co({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 v1({assignedDrawPositions:t,inContextMatchUp:e,appliedPolicies:r,drawDefinition:n,matchUpStatus:o,structure:i,matchUp:s}){if(r?.[en]?.requireParticipantsForScoring===!1)return{...C};let a=e?.sides?.map(p=>p.participantId).filter(Boolean).length,c=s?.sides?[]:bt({structureId:i?.structureId,drawDefinition:n}).positionAssignments,u=a&&a===2||s.collectionId&&cr({structure:i})&&a&&a>=1||t?.length===2&&c?.filter(p=>t.includes(p.drawPosition)).every(p=>p.participantId);return o&&wh.includes(o)&&!u?_({info:"matchUpStatus requires assigned participants",context:{matchUpStatus:o,requiredParticipants:u},result:{error:pa}}):{...C}}function uM({tournamentRecord:t,drawDefinition:e,matchUpId:r,event:n}){if(!e)return{error:Z};let{matchUp:o}=Bt({drawDefinition:e,matchUpId:r,event:n});return o?.matchUpType!==xr?{error:dr}:La({enableAutoCalc:!0,tournamentRecord:t,drawDefinition:e,matchUpId:r,event:n})}function pM({drawDefinition:t,event:e,matchUpId:r}){if(!t)return{error:Z};if(!r)return{error:sr};let{matchUp:n}=Bt({drawDefinition:t,event:e,matchUpId:r});return n?gr({name:Bm,element:n}):{error:Le}}function Fx({substituteParticipantId:t,existingParticipantId:e,tournamentRecord:r,drawDefinition:n,sideNumber:o,matchUpId:i,event:s}){let a="substituteParticipant";if(!n)return{error:Z};if(!i)return{error:sr};if(!e||!t)return _({result:{error:oe},stack:a});let{matchUp:c}=Bt({drawDefinition:n,matchUpId:i,event:s});if(!c)return{error:Le};if(!c.collectionId)return _({result:{error:dr},stack:a});let u=Ne({drawDefinition:n}),{matchUps:p}=se({tournamentParticipants:r?.participants,inContext:!0,drawDefinition:n,matchUpsMap:u}),m=p?.find(g=>g.matchUpId===i),l=p?.find(g=>g.matchUpId===m?.matchUpTieId)?.sides?.find(g=>g.participant.individualParticipants.some(({participantId:I})=>I===e));return!l||o&&l.sideNumber!==o?{error:mn}:l.participant?.individualParticipants?.map(St).filter(g=>g!==e)?.includes(t)?rI({newParticipantId:t,tieMatchUpId:i,existingParticipantId:e,substitution:!0,tournamentRecord:r,drawDefinition:n,event:s}):_({result:{error:mn},stack:a})}function mM(t){return Fx(t)}function dM({drawDefinition:t,matchUpId:e,event:r}){if(!t)return{error:Z};let{matchUp:n}=Bt({drawDefinition:t,matchUpId:e,event:r});return At({extension:{name:ga,value:!0},element:n})}function lM(t){let e="setMatchUpFormat",r=rt(t,[{tournamentRecord:!0},{[tr]:P=>Pr({matchUpFormat:P}),[Fr]:qa,matchUpFormat:!0}]);if(r.error)return _({result:r,stack:e});let{tournamentRecord:n,drawDefinition:o,scheduledDates:i,stageSequences:s,matchUpFormat:a,structureId:c,eventType:u,matchUpId:p,eventId:m,stages:d,drawId:l,event:f,force:g}=t;if(i&&!Array.isArray(i))return _({result:{error:G,scheduledDates:i},stack:e});if(u&&!Lc([jn,qr],u))return _({result:{error:Bn},stack:e});let I=0,h=t.structureIds||c&&[c].filter(Boolean)||[],S=t.eventIds||m&&[m].filter(Boolean)||[],T=t.drawIds||l&&[l].filter(Boolean)||[];if((c||h?.length)&&!o)return _({result:{error:Z},stack:e});if(l&&p&&o){let P=$d({tournamentRecord:n,drawDefinition:o,matchUpFormat:a,structureIds:h,structureId:c,matchUpId:p});if(P.error)return P;I+=1}let y=P=>{let U=[];for(let E of P.structures||[]){if(Array.isArray(d)&&!d.includes(E.stage)||Array.isArray(s)&&!s.includes(E.stageSequence)||h?.length&&!h.includes(E.structureId))continue;h?.length&&E.matchUpFormat!==a&&(E.matchUpFormat=a,U.push(E.structureId),I+=1);let A=((g||i)&&Ut({matchUpFilters:{matchUpStatuses:[Qt]},structure:E}).matchUps)??[],N=(i&&Ut({matchUpFilters:{matchUpStatuses:[Qt]},contextFilters:{scheduledDates:i},afterRecoveryTimes:!1,inContext:!0,structure:E}).matchUps)??[];if(A?.length){let D=N?N.map(Ae):A.map(Ae);for(let M of A)D.includes(M.matchUpId)&&(M.matchUpFormat=i?.length?a:void 0,gt({tournamentId:n?.tournamentId,eventId:f?.eventId,context:e,drawDefinition:P,matchUp:M}))}}return!U.length&&P.matchUpFormat!==a&&(P.matchUpFormat=a,I+=1),U};for(let P of n?.events||[])if(!(S?.length&&!S.includes(P.eventId)||u&&u!==P.eventType||u===_e))if(Array.isArray(s)||Array.isArray(d)||h?.length||T?.length)for(let U of P.drawDefinitions||[]){if(Array.isArray(T)&&!T.includes(U.drawId))continue;let E=y(U);Ot({structureIds:E,drawDefinition:U})}else P.matchUpFormat!==a&&(P.matchUpFormat=a,I+=1);return I?{...C,modificationsCount:I}:{...C,info:_s}}function iI({inheritance:t=!0,tournamentRecord:e,drawDefinition:r,matchUpId:n,event:o}){if(!r)return{error:Z};let i=Bt({drawDefinition:r,matchUpId:n})?.matchUp;if(!i?.tieMatchUps)return{error:dr};let s=Bt({inContext:!0,drawDefinition:r,matchUpId:n,event:o})?.matchUp,a=0;return(i?.sides||[]).forEach(c=>{c.lineUp&&delete c.lineUp}),(s?.sides||[]).forEach(c=>{if(a+=1,t===!1){let u=s?.tieFormat,p=c.participantId;u&&p&&Ki({drawDefinition:r,participantId:p,lineUp:[],tieFormat:u})}gt({tournamentId:e?.tournamentId,context:"resetMatchUpLineUps",eventId:o?.eventId,drawDefinition:r,matchUp:i})}),{...C,modificationsCount:a}}function Wy(t){let{matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}=t;if(!o)return{sets:[]};let i=o.sets||[],s=jo({winnerFirst:!1,matchUpFormat:e,matchUpStatus:r,sets:i}),a=jo({winnerFirst:!1,reversed:!0,matchUpFormat:e,matchUpStatus:r,sets:i}),c=jo({matchUpFormat:e,matchUpStatus:r,winningSide:n,sets:i}),u=s===c?a:s;return n&&(s=n===1?c:u,a=n===2?c:u),{score:{sets:i,scoreStringSide1:s,scoreStringSide2:a}}}function Gu(t){let e=rt(t,[{[ln]:!0,[Ve]:!0}]);if(e.error)return e;let r=Dr(t);if(!t.drawDefinition){let h=t.tournamentRecord??(t.tournamentId&&r[t.tournamentId]);t.tournamentRecord||(t.tournamentRecord=h);let S=ze({eventId:t.eventId,drawId:t.drawId,tournamentRecord:h});if(S.error)return S;S.drawDefinition&&(t.drawDefinition=S.drawDefinition),t.event=S.event}let{disableScoreValidation:n,policyDefinitions:o,tournamentRecord:i,disableAutoCalc:s,enableAutoCalc:a,drawDefinition:c,matchUpId:u,schedule:p,event:m,notes:d}=t,l=t.matchUpFormat||t.outcome?.matchUpFormat,{policy:f}=ei({policyType:en,tournamentRecord:i,event:m}),g=t.allowChangePropagation!==void 0&&t.allowChangePropagation||f?.allowChangePropagation!==void 0&&f.allowChangePropagation||void 0,{outcome:I}=t;if(I?.winningSide&&![1,2].includes(I.winningSide))return{error:Em};if(l){let h=$d({tournamentRecord:i,drawDefinition:c,matchUpFormat:l,matchUpId:u,event:m});if(h.error)return h}if(I?.score?.sets&&!I.score.scoreStringSide1){let{score:h}=Wy(I);I.score=h,I.score.sets=I.score.sets.filter(S=>S.side1Score||S.side2Score||S.side1TiebreakScore||S.side2TiebreakScore)}return La({matchUpStatusCodes:I?.matchUpStatusCodes,matchUpStatus:I?.matchUpStatus,winningSide:I?.winningSide,allowChangePropagation:g,disableScoreValidation:n,score:I?.score,tournamentRecords:r,policyDefinitions:o,tournamentRecord:i,disableAutoCalc:s,enableAutoCalc:a,drawDefinition:c,matchUpFormat:l,matchUpId:u,schedule:p,event:m,notes:d})}function fM(t){if(!t?.outcomes)return{error:st};if(!Array.isArray(t.outcomes))return{error:st,info:{outcomes:t.outcomes}};let e=t.tournamentRecords||t.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord}||{},r=t.outcomes??[],n=r.reduce((o,i)=>o.includes(i.tournamentId)?o:o.concat(i.tournamentId),[]);for(let o of n){let i=e[o];if(!i)return{error:Y};let s=r.filter(a=>a.tournamentId===o);if(s.length){let a=O1({outcomes:s,tournamentRecord:i});if(a.error)return a}}return{...C}}function O1(t){let{tournamentRecords:e,tournamentRecord:r,outcomes:n,policyDefinitions:o}=t,i={};n.forEach(s=>{let{eventId:a}=s;i[a]||(i[a]=[]),i[a].push(s)});for(let s of Object.keys(i)){let{event:a}=ze({tournamentRecord:r,eventId:s});for(let c of i[s]){let{drawId:u}=c,p=a?.drawDefinitions?.find(m=>m.drawId===u);if(p&&u){let{matchUpFormat:m,matchUpId:d}=c,l=Gu({schedule:c?.schedule,tournamentRecords:e,policyDefinitions:o,tournamentRecord:r,drawDefinition:p,matchUpFormat:m,matchUpId:d,outcome:c,drawId:u,event:a});if(l.error)return l}}}return{...C}}function kx({drawDefinition:t,matchUpId:e,outcome:r,matchUp:n}){if(!n&&!t)return{error:Z};if(!r)return{error:st,info:"missing outcome"};if(!n&&!e)return{error:hr};if(!n){let i=Bt({drawDefinition:t,matchUpId:e});if(i.error)return i;n=i.matchUp}return typeof r!="object"||!r.score?.scoreStringSide1||!r.score?.scoreStringSide2?{error:G}:At({element:n,extension:{name:Bm,value:r}})}function gM(t){return kx(t)}function sI(t){let e="resetTieFormat",{drawDefinition:r,event:n,uuids:o}=t,i=rt(t,[{[ie]:!0,[ln]:!0}],e);if(i.error)return i;let s=Ds(t,[{[is]:_n}]);if(s[fn])return s;let a=t.tournamentRecord?.tournamentId,{matchUp:c,structure:u}=s?.matchUp??{};if(!c?.tieMatchUps)return _({result:{error:dr},info:"Must be a TEAM matchUp",stack:e});if(!c.tieFormat)return{...C};let p=We({structure:u,drawDefinition:r,event:n})?.tieFormat;if(!p)return _({result:{error:ve},info:"No inherited tieFormat",stack:e});let m=[],d=[],l=[],f=[];for(let g of p.collectionDefinitions){let{matchUpCount:I,collectionId:h}=g;d.push(h);let S=(c.tieMatchUps||[]).filter(T=>T.collectionId===h);if(S.length>I)S.sort((T,y)=>(T.matchUpStatus===Qt?1:0)-(y.matchUpStatus===Qt?1:0)),l.push(...S.slice(0,I)),m.push(...S.slice(3).map(Ae));else if(l.push(...S),S.length<I){let T=I-S.length,y=Du({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),Co({eventId:n?.eventId,matchUps:f,drawDefinition:r,tournamentId:a})),m.length&&Yn({matchUpIds:m,eventId:n?.eventId,drawDefinition:r,tournamentId:a}),c&&(c.tieMatchUps=l,c.tieFormatId=void 0,c.tieFormat=void 0,gt({structureId:u?.structureId,eventId:n?.eventId,context:e,drawDefinition:r,tournamentId:a,matchUp:c})),{...C,newMatchUps:f,deletedMatchUpIds:m}}function aI(t){let{tournamentRecord:e,drawDefinition:r,matchUpId:n,event:o}=t,i="resetScorecard";if(!r)return _({result:{error:Z},stack:i});if(!n)return _({result:{error:sr},stack:i});if(!Vt(n))return _({result:{error:G,matchUpId:n},stack:i});let s=Ne({drawDefinition:r}),{matchUps:a}=se({nextMatchUps:!0,inContext:!0,drawDefinition:r,matchUpsMap:s}),c=s.drawMatchUps.find(I=>I.matchUpId===n),u=a?.find(I=>I.matchUpId===n);if(!c||!a)return{error:Le};if(c.matchUpType!==Cr)return{error:dr};let p=ur({inContextDrawMatchUps:a,drawDefinition:r,matchUpId:n}),m=u?.structureId,{structure:d}=at({drawDefinition:r,structureId:m});if(Object.assign(t,{inContextDrawMatchUps:a,inContextMatchUp:u,matchUpsMap:s,targetData:p,structure:d,matchUp:c}),Ci(t))return{error:Um};if(c.tieMatchUps?.length)for(let I of c.tieMatchUps){let h=La({matchUpId:I.matchUpId,matchUpTieId:n,winningSide:void 0,removeScore:!0,tournamentRecord:e,drawDefinition:r,event:o});if(h.error)return _({result:h,stack:i})}let f=yt({tournamentRecord:e,drawDefinition:r,event:o})?.appliedPolicies,g=co({event:t.event,removeScore:!0,tournamentRecord:e,appliedPolicies:f,drawDefinition:r,matchUpsMap:s,matchUpId:n});if(g.error)return _({result:g,stack:i});if(t.tiebreakReset&&!g.tieFormatRemoved){let I=We({drawDefinition:r,structure:d,event:o})?.tieFormat;if(c.tieFormat&&I){let{matchUpCountDifference:h,descendantDifferences:S,ancestorDifferences:T,valueDifference:y}=$o({descendant:c.tieFormat,ancestor:I});if(S.collectionIds.length===1&&!T.collectionIds.length&&!T.groupsCount&&h===1&&y===1){let P=sI({tournamentRecord:e,drawDefinition:r,matchUpId:n,event:o});if(P.error)return P}}}return{...C}}function IM(t){let e=rt(t,[{[Ve]:!0,[Do]:!0},{[Gs]:{[ec]:!1,roundNumbers:!1},[bh]:"At least one must be provided",[He]:Be}]);if(e.error)return e;let r=tT(t);if(r.error)return r;let{matchUpIds:n}=r,o=ue(Cr)(t.event.eventType),{tournamentRecord:i,drawDefinition:s,event:a}=t;for(let c of n){if(o){let p=aI({tiebreakReset:!0,tournamentRecord:i,drawDefinition:s,matchUpId:c,event:a});if(p.error||t.removeAssignments&&iI({inheritance:!1,drawDefinition:s,matchUpId:c}).error)return p}let u=La({winningSide:void 0,removeScore:!0,tournamentRecord:i,drawDefinition:s,matchUpId:c,event:a});if(u.error)return u;if(t.removeAssignments){let p=nI({...t,matchUpId:c});if(p.error)return p}}return{...C}}function Gx({tournamentRecord:t,drawDefinition:e,finishingOrder:r}){if(!e)return{error:Z};let n="setOrderOfFinish";if(!Array.isArray(r))return _({info:ii("finishingOrder"),result:{error:G},stack:n});let{completedMatchUps:o,matchUpsMap:i}=js({inContext:!0,drawDefinition:e}),s=o?.map(Ae)??[],a=r.map(Ae),{matchUpTypes:c,roundNumbers:u,structureIds:p,matchUpTieIds:m}=(o??[]).filter(({matchUpId:T})=>a.includes(T)).reduce((T,y)=>{let{matchUpTieId:P,matchUpType:U,roundNumber:E,structureId:A}=y;return T.matchUpTypes.includes(U)||T.matchUpTypes.push(U),T.roundNumbers.includes(E)||T.roundNumbers.push(E),T.structureIds.includes(A)||T.structureIds.push(A),T.matchUpTieIds.includes(P)||T.matchUpTieIds.push(P),T},{matchUpTypes:[],roundNumbers:[],structureIds:[],matchUpTieIds:[]});if(c.length>1||m.length>1||u.length>1||p.length>1)return _({info:"matchUpType, structureId and roundNumber must be equivalent",result:{error:G},stack:n});let d,l,f={},g=[],I=[];if(!r.every(({orderOfFinish:T,matchUpId:y})=>(g.push(y),T&&I.push(T),f[y]=T,d=s.includes(y),l=T===void 0||It(T)&&Math.floor(T)>0,d&&l)))return _({result:{error:d?G:pa},info:!d&&"matchUps must be completed"||!l&&"orderOfFinish must be integer > 0 or undefined"||void 0,stack:n});let S=o?.filter(T=>T.structureId===p[0]&&T.roundNumber===u[0]&&T.matchUpType===c[0]&&T.matchUpTieId===m[0]&&!g.includes(T.matchUpId));for(let T of S??[]){let{orderOfFinish:y}=T||{};if(y){if(!It(y))return _({context:{orderOfFinish:y,matchUp:T},result:{error:G},stack:n});I.push(y)}}if(PI(I).length!==I.length||Math.max(...I)>I.length)return _({info:"Values not unique or greater than expected number of values",result:{error:G},stack:n});if(p.length){let T=hu({matchUpFilters:{matchUpIds:a},structureId:p[0],drawDefinition:e,matchUpsMap:i});if(T.error)return _({result:T,stack:n});T.completedMatchUps?.forEach(y=>{y.orderOfFinish=f[y.matchUpId],gt({tournamentId:t.tournamentId,context:"setOrderOfFinish",drawDefinition:e,matchUp:y})})}return{...C}}function hM(t){return Gx(t)}function SM(t){let{tournamentRecord:e,drawDefinition:r,matchUpId:n,lineUps:o,event:i}=t,s="applyLineUps",a=rt(t,[{[ie]:!0,[Ve]:!0,[ln]:!0},{lineUps:!0,[He]:Be}],s);if(a.error)return a;let c=e.participants||[],u=Bt({tournamentParticipants:c,inContext:!0,drawDefinition:r,matchUpId:n});if(u.error)return u;if(!u.matchUp)return{error:Le};let{matchUp:p,structure:m}=u,{drawPositions:d,matchUpType:l}=p;if(l!==jt)return{error:dr};if(!d?.length)return{error:ja};let f=We({matchUp:p,drawDefinition:r,structure:m,event:i})?.tieFormat,g={};for(let h of o){if(!Array.isArray(h))return{error:G,lineUp:h};let S={},T=[];for(let A of h){if(typeof A!="object")return{error:G,lineUpAssignment:A};let{participantId:N,collectionAssignments:D=[]}=A;if(!Array.isArray(D))return{error:G,collectionAssignments:D};let M=c.find(b=>b.participantId===N);if(!M)return{error:te};if(M.participantType!==Tt)return{error:An};let R=p.sides?.find(b=>b.participant?.individualParticipantIds?.includes(N))?.sideNumber;R&&T.push(R);for(let b of D){if(typeof b!="object")return{error:G,collectionAssignment:b};let{collectionId:v,collectionPosition:O}=b,x=f?.collectionDefinitions?.find(w=>w.collectionId===v);if(!x)return{error:G,collectionId:v};let F=`${v}-${O}`;S[F]||(S[F]=[]);let L=S[F].length;if(ue(xt)(x.matchUpType)&&L||x.matchUpType===_t&&L>1)return{info:"Excessive collectionPosition assignments",error:G};S[F].push(N)}}let y=Object.values(S);for(let A of y)if(A.length===2){let{participant:N}=In({tournamentParticipants:c,participantIds:A});if(!N){let M=bn({participant:{participantType:ft,participantRole:xe,individualParticipantIds:A},pairOverride:!0,tournamentRecord:e});if(M.error)return M}}let P=Sr(T),U=(P[1]||0)>(P[2]||0)&&1||(P[2]||0)>(P[1]||0)&&2||void 0,E=Object.keys(g).map(A=>parseInt(A));U&&!E.includes(U)&&(g[U]=h)}if(!Object.keys(g).length)return{error:rf};if(u=Bt({drawDefinition:r,matchUpId:n}),u.error)return u;if(!u.matchUp)return{error:Le};let{matchUp:I}=u;I.sides||(I.sides=[]);for(let h of[1,2]){let S=I.sides.find(y=>y.sideNumber===h),T=g[h];if(T)S?S.lineUp=T:I.sides.push({lineUp:T,sideNumber:h});else continue}return gt({tournamentId:e?.tournamentId,context:s,drawDefinition:r,matchUp:I}),{...C}}var fI={};Xt(fI,{anonymizeTournamentRecord:()=>MM,generate:()=>NM,generateEventWithDraw:()=>dm,generateOutcome:()=>mI,generateOutcomeFromScoreString:()=>cI,generateParticipants:()=>sa,generateTournamentRecord:()=>DM,modifyTournamentRecord:()=>RM,mutate:()=>CM});var NM={};Xt(NM,{generateEventWithDraw:()=>dm,generateOutcome:()=>mI,generateOutcomeFromScoreString:()=>cI,generateParticipants:()=>sa,generateTournamentRecord:()=>DM});function cI(t){let{matchUpFormat:e,matchUpStatus:r,winningSide:n,scoreString:o}=t;if(!o)return{outcome:{...Ru,winningSide:n,matchUpStatus:r}};if(n&&![1,2,void 0].includes(n))return{error:G,winningSide:n};let i=o&&jd({scoreString:o}),s={},a=jo({sets:i,matchUpFormat:e}),c=jo({sets:i,reversed:!0,matchUpFormat:e});return n===2?(s.scoreStringSide1=c,s.scoreStringSide2=a):(s.scoreStringSide1=a,s.scoreStringSide2=c),s.sets=jd({scoreString:s.scoreStringSide1}),ot({outcome:{matchUpStatus:r,winningSide:n,score:s}})}function hl({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 Fa({individualParticipantProfiles:t,participantId:e}){t[e]||(t[e]={typeChangeTimeAfterRecovery:void 0,timeAfterRecovery:void 0,priorMatchUpType:void 0,potentialRecovery:{},potentialCounted:{},potentialBookings:{},bookings:[],counters:{}})}function Vx({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 Oc({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,typeChangeRecoveryMinutes:r,averageMatchUpMinutes:n=0,matchUpNotBeforeTimes:o,matchUpDependencies:i,recoveryMinutes:s=0,scheduleTime:a,matchUp:c}){let u=Kt(c?.schedule?.endTime),p=u?Yr(u,pt(s)):Yr(a,pt(n)+pt(s)),m=r&&(u?Yr(Kt(u),r):Yr(a,pt(n)+pt(r))),d=i?.[c.matchUpId]?.participantIds||[],l=(c.roundPosition&&t[c.matchUpId]||[]).flat();d.forEach(f=>{Fa({individualParticipantProfiles:e,participantId:f});let I=e[f].priorMatchUpType!==c.matchUpType&&m||p;l.includes(f)?Vx({individualParticipantProfiles:e,drawId:c.drawId,recoveryValue:I,participantId:f,scheduleTime:a}):(e[f].timeAfterRecovery=I,e[f].bookings.push({scheduleTime:a,timeAfterRecovery:I}))}),ea({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:o,timeAfterRecovery:p,matchUp:c})}function jy({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||qt(f)<qt(d.scheduleTime)?g:d},{});m.scheduleTime&&qt(u)>qt(m.scheduleTime)&&(i=m)}return{scheduledDependent:i}}function Bx(t){let{sides:e,matchUpType:r}=t||{};return(e||[]).map(n=>r===_t&&(n?.participant?.individualParticipants||[])||n?.participant&&[n.participant]||[]).flat()}var _c="DO_NOT_SCHEDULE",Hx={DO_NOT_SCHEDULE:_c};function Sl({averageMatchUpMinutes:t=90,requestConflicts:e={},potentials:r=!0,personRequests:n,scheduleTime:o,scheduleDate:i,matchUp:s}){let a=Bx(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===_c&&Wn(i,l.date)),u=[],p=s?.matchUpId,m=ke(Kt(o),Et(i)),d=Kt(hf(m,t).toISOString());for(let l of c){let{requestId:f,startTime:g,endTime:I}=l;(o>g&&o<I||d>g&&d<I)&&(u.push({matchUpId:p,request:l,scheduleTime:o}),e[f]?(e[f].scheduleTimes.includes(o)||e[f].scheduleTimes.push(o),e[f].matchUpIds.includes(p)||e[f].matchUpIds.push(p)):e[f]={request:l,scheduleTimes:[o],matchUpIds:[p]})}return{conflicts:u}}function uI({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,matchUp:r,value:n}){let{matchUpType:o}=r,{individualParticipantIds:i}=uu(r),a=(t[r.matchUpId]||[]).filter(u=>!Fe(u,i)).flat();[...i,...a].forEach(u=>{if(Fa({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[ao]?p[ao]+=n:n>0&&(p[ao]=n),a.includes(u)&&(e[u].potentialCounted[r.drawId]=!0)}})}function Wx({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,dateScheduledMatchUpIds:r,greatestAverageMinutes:n,dateScheduledMatchUps:o,matchUpNotBeforeTimes:i,matchUpScheduleTimes:s,matchUpDependencies:a,clearScheduleDates:c,scheduleDate:u,minutesMap:p,matchUps:m}){let d=[];r||(o=m?.filter(g=>{let I=g.schedule||{},h=g.matchUpStatus===Nt;return h&&d.push({tournamentId:g.tournamentId,matchUpId:g.matchUpId}),!h&&_a({schedule:I})&&(!u||g.schedule.scheduledDate===u)}),r=o.map(Ae));let l=Array.isArray(c)?c.includes(u):c,f=l?[]:m.filter(({matchUpId:g})=>r.includes(g));for(let g of f){uI({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,value:1,matchUp:g});let I=g.schedule?.scheduledTime;if(I){s[g.matchUpId]=I;let h=p?.[g.matchUpId]?.recoveryMinutes;Oc({individualParticipantProfiles:e,matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:i,matchUpDependencies:a,averageMatchUpMinutes:n,recoveryMinutes:h,scheduleTime:I,matchUp:g})}}return{dateScheduledMatchUpIds:r,byeScheduledMatchUpDetails:d,dateScheduledMatchUps:o,clearDate:l}}function sm({defaultRecoveryMinutes:t=0,averageMatchUpMinutes:e=90,dateScheduledMatchUps:r,tournamentRecords:n,venueIds:o=[],periodLength:i,scheduleDate:s,matchUps:a}){if(typeof n!="object")return{error:wt};if(!Vr(a)&&!Array.isArray(r))return{error:Xn};i=i??ku({recoveryMinutes:t,averageMatchUpMinutes:e});let c=Object.assign({},...Object.values(n).map(d=>(d.events??[]).map(l=>{let{scheduleTiming:f}=ya({tournamentRecord:d,event:l});return{[l.eventId]:{event:l,scheduleTiming:f}}})).flat()),u={averageTimes:[{minutes:{default:e}}],recoveryTimes:[{minutes:{default:t}}]};r||(r=a?.filter(d=>{let l=d.schedule;return _a({schedule:l})&&(!s||d.schedule.scheduledDate===s)}));let p=r?.filter(d=>(!o.length||o.includes(d.schedule.venueId))&&d.matchUpStatus!==Nt);return{bookings:p?.map(({eventId:d,schedule:l,matchUpFormat:f})=>{let{event:g,scheduleTiming:I}=c[d],h=g?.eventType,S={...I,defaultTiming:u,matchUpFormat:f},{averageMinutes:T,recoveryMinutes:y}=Pp({timingDetails:S,eventType:h}),{courtId:P,venueId:U}=l,E=Kt(l.scheduledTime),A=Yr(E,T);return{recoveryMinutes:y,averageMinutes:T,periodLength:i,startTime:E,courtId:P,endTime:A,venueId:U}}).filter(Boolean),relevantMatchUps:p,dateScheduledMatchUps:r}}function jx({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:wt};a=a??ku({recoveryMinutes:r,averageMatchUpMinutes:n});let{courts:l,venues:f}=Ao({dates:[c],ignoreDisabled:!0,tournamentRecords:i}),g=l?.filter(U=>!p||p.includes(U.venueId))??[];u=u??bc({courts:g,scheduleDate:c,startTime:!0}),d=d??bc({courts:g,scheduleDate:c,endTime:!0});let{bookings:I,dateScheduledMatchUps:h}=sm({defaultRecoveryMinutes:r,averageMatchUpMinutes:n,tournamentRecords:i,scheduleDate:c,periodLength:a,venueIds:p,matchUps:m}),S={calculateStartTimeFromCourts:t,remainingScheduleTimes:e,averageMatchUpMinutes:n,clearScheduleDates:o,date:c,periodLength:a,startTime:u,bookings:I,endTime:d,courts:g},{scheduleTimes:T}=dl(S),y=p?.length===1&&p[0]||f?.length===1&&f[0].venueId||void 0;return{dateScheduledMatchUpIds:h?.map(Br("matchUpId")),dateScheduledMatchUps:h,scheduleTimes:T,venueId:y}}function Yx({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 Yy({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,scheduleCompletedMatchUps:r,containedStructureIds:n,matchUpNotBeforeTimes:o,matchUpScheduleTimes:i,matchUpDependencies:s,clearScheduleDates:a,tournamentRecords:c,periodLength:u,scheduleDate:p,useGarman:m,matchUps:d,courts:l,venues:f}){let g={},I=[],h=[],S=[];for(let T of f){let{rounds:y=[],venueId:P}=T,{scheduledRoundsDetails:U,greatestAverageMinutes:E,orderedMatchUpIds:A,minutesMap:N}=Lu({scheduleCompletedMatchUps:r,containedStructureIds:n,tournamentRecords:c,periodLength:u,matchUps:d,rounds:y});S.push(...A??[]);let{groupedRounds:D}=Yx({scheduledRoundsDetails:U,greatestAverageMinutes:E,garmanSinglePass:!0}),M,R=[];m&&({scheduleTimes:R,dateScheduledMatchUpIds:M}=jx({averageMatchUpMinutes:D[0]?.averageMinutes,scheduleDate:Et(p),venueIds:[T.venueId],clearScheduleDates:a,tournamentRecords:c,periodLength:u,matchUps:d}));let b=Wx({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,dateScheduledMatchUpIds:M,greatestAverageMinutes:E,matchUpNotBeforeTimes:o,matchUpScheduleTimes:i,matchUpDependencies:s,clearScheduleDates:a,scheduleDate:p,minutesMap:N,matchUps:d});({dateScheduledMatchUpIds:M}=b);let v=b,{byeScheduledMatchUpDetails:O,clearDate:x}=b;O?.length&&h.push(...O);let{matchUpsToSchedule:F,matchUpMap:L}=el({matchUpPotentialParticipantIds:t,scheduleCompletedMatchUps:r,dateScheduledMatchUpIds:M,matchUpNotBeforeTimes:o,matchUpScheduleTimes:i,orderedMatchUpIds:A,clearDate:x,matchUps:d}),w=l.filter(V=>V.venueId===P);g[P]={previousRemainingScheduleTimes:[],courtsCount:w.length,greatestAverageMinutes:E,scheduledRoundsDetails:U,dateScheduledMatchUps:v,matchUpsToSchedule:F,scheduleTimes:R,groupedRounds:D,venueCourts:w,minutesMap:N,matchUpMap:L},a||I.push(...M)}return{allDateScheduledByeMatchUpDetails:h,allDateScheduledMatchUpIds:I,venueScheduledRoundDetails:g,allDateMatchUpIds:S}}function qx(t,e){let r=qt(t.scheduleTime),n=qt(t.timeAfterRecovery),o=qt(e.scheduleTime),i=qt(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 ot({hasOverlap:s||a||u||c||p,startAisContained:a,endAisContained:u,startBisContained:c,endBisContained:p},!0)}function Tl({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=>{Fa({individualParticipantProfiles:t,participantId:f});let g=t[f];if(!g.timeAfterRecovery)return!0;let I=Kt(o?.schedule?.endTime),h=I?Yr(I,pt(c)):Yr(n,pt(a)+pt(c));return!!![...Object.keys(g.potentialBookings).filter(P=>P!==o.drawId).map(P=>g.potentialBookings[P]).flat(),...g.bookings].find(P=>qx({scheduleTime:n,timeAfterRecovery:h},P).hasOverlap)}),p=e[o.matchUpId],d=(p?ma(ke(p),ke(n),!1):0)>=0;return{enoughTime:u&&d}}function qy({autoSchedulingAudit:t,tournamentRecords:e}){mt({topic:Ti,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:Uy,itemValue:o};for(let s of Object.values(e)){let a=s.tournamentId;rp(Ti)?mt({payload:{type:Uy,tournamentId:a,detail:o},topic:Ti}):Pc({tournamentRecord:s,timeItem:i})}}function yl({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,matchUpDailyLimits:r={},matchUp:n}){let{enteredIndividualParticipantIds:o}=uu(n),{matchUpId:i,matchUpType:s}=n,a=(n.roundPosition&&t[i]||[]).flat(),c=ut(o.concat(...a));return c.forEach(p=>{Fa({individualParticipantProfiles:e,participantId:p})}),{participantIdsAtLimit:c.filter(p=>{let m=e[p];if(m)return[s,ao].find(d=>{let l=m.counters?.[d]||0,f=r[d]||0;return l&&f&&l>=f})}),relevantParticipantIds:c}}function Vu({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:Y};if(!c&&(!u||!Array.isArray(u)))return{error:rs};if(!c&&(!p||typeof p!="object"))return{error:UE};let m,d=[],l=0;if(n&&!o){let I=sn({tournamentRecords:s,tournamentRecord:a});o=I.matchUpDependencies,m=I.matchUps}m||(m=Te({tournamentRecord:a})?.matchUps??[]);let f=m.reduce((I,h)=>{let{matchUpId:S,drawId:T,matchUpStatus:y}=h;return(e||y!==Nt)&&(t||!ce.includes(y))&&(I[T]?I[T].push(S):I[T]=[S]),I},{}),g=c?.map(I=>I.matchUpId);for(let I of Object.keys(f)){let{drawDefinition:h}=wo({tournamentRecord:a,drawId:I});if(!h)continue;let S=f[I].filter(y=>u?.includes(y)??g?.includes(y)),T=or({inContext:!1,drawDefinition:h}).matchUps;for(let y of S){let P=c?.find(E=>E.matchUpId===y)?.schedule||p,U=im({schedule:P,matchUpDependencies:o,errorOnAnachronism:r,removePriorValues:i,inContextMatchUps:m,tournamentRecords:s,tournamentRecord:a,checkChronology:n,drawDefinition:h,drawMatchUps:T,matchUpId:y});if(U?.warnings?.length&&d.push(...U.warnings),U?.success&&(l+=1),U.error)return U}}return d.length?{...C,scheduled:l,warnings:d}:{...C,scheduled:l}}function xc(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 Vu(t);let p=rt(t,[{[Re]:!0},{[Gs]:{matchUpContextIds:!1,matchUpDetails:!1},[Fr]:G,[He]:Be}]);if(p.error)return p;if((!c||o)&&!u)return{error:st,info:"schedule is required"};let m=[],d=0,{matchUpDependencies:l}=sn({tournamentRecords:s});for(let f of Object.values(s)){let{tournamentId:g}=f,I=o?.filter(S=>S.tournamentId===g).map(Ae),h=c?.filter(S=>S?.tournamentId===g);if(I?.length||h?.length){let S=Vu({matchUpDetails:h,scheduleCompletedMatchUps:e,scheduleByeMatchUps:r,matchUpDependencies:l,errorOnAnachronism:n,removePriorValues:i,tournamentRecords:s,tournamentRecord:f,checkChronology:a,matchUpIds:I,schedule:u});if(S.warnings?.length&&m.push(...S.warnings),S.scheduled&&(d+=S.scheduled),S.error)return S}}return m.length?{...C,scheduled:d,warnings:m}:{...C,scheduled:d}}function $x({schedulingProfileModifications:t,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:r,schedulingProfileIssues:n,dateSchedulingProfiles:o,containedStructureIds:i,matchUpDependencies:s,matchUpDailyLimits:a,clearScheduleDates:c,tournamentRecords:u,schedulingProfile:p,personRequests:m,periodLength:d,matchUps:l,courts:f,dryRun:g}){let I={},h={},S={},T={},y={},P={},U={},E={},A={},N={};for(let R of o){let b=Et(R?.scheduleDate),v=R?.venues||[],O={},x={},F=(B,$)=>{B.forEach(z=>{let j=x[z].counters;j[$]?j[$]+=1:j[$]=1,j[ao]?j[ao]+=1:j[ao]=1})};S[b]={},T[b]={},I[b]={},h[b]={},U[b]=[],E[b]=[],A[b]=[],N[b]=[];let L={};l.forEach(B=>{B.schedule?.scheduledDate&&Wn(b,Et(B.schedule.scheduledDate))&&ea({matchUpPotentialParticipantIds:O,matchUpNotBeforeTimes:L,matchUp:B})});let{allDateScheduledByeMatchUpDetails:w,venueScheduledRoundDetails:V,allDateMatchUpIds:k}=Yy({matchUpPotentialParticipantIds:O,individualParticipantProfiles:x,scheduleCompletedMatchUps:r,containedStructureIds:i,matchUpNotBeforeTimes:L,matchUpScheduleTimes:P,matchUpDependencies:s,clearScheduleDates:c,tournamentRecords:u,useGarman:!0,periodLength:d,scheduleDate:b,matchUps:l,courts:f,venues:v}),W=10,H=0,K,q=10;for(;!K;){for(let{venueId:B}of v){let $=0,z=V[B];for(;z.courtsCount&&z.scheduleTimes?.length&&z.matchUpsToSchedule?.length&&$<=z.courtsCount;){let{scheduleTime:j,attempts:tt=0}=z.scheduleTimes.shift(),Q=z.matchUpsToSchedule.find(X=>{let{matchUpId:lt,matchUpType:it}=X,{participantIdsAtLimit:Rt,relevantParticipantIds:Ft}=yl({matchUpPotentialParticipantIds:O,individualParticipantProfiles:x,matchUpDailyLimits:a,matchUp:X});if(Rt.length)return E[b].includes(lt)||E[b].push(lt),!1;let{scheduledDependent:Ue}=jy({matchUpScheduleTimes:P,matchUpDependencies:s,scheduleTime:j,matchUpId:lt,details:z});if(Ue)return!1;let{dependenciesScheduled:fe,remainingDependencies:Me}=hl({matchUpScheduleTimes:P,matchUpDependencies:s,allDateMatchUpIds:k,matchUp:X});if(!fe)return T[b][lt]||(T[b][lt]=[]),T[b][lt].push({scheduleTime:j,remainingDependencies:Me}),!1;let{enoughTime:vr}=Tl({individualParticipantProfiles:x,matchUpNotBeforeTimes:L,matchUpDependencies:s,scheduleTime:j,details:z,matchUp:X});if(!vr)return S[b][lt]||(S[b][lt]=[]),S[b][lt].push({scheduleTime:j}),!1;let Zr=z.greatestAverageMinutes,{conflicts:lr}=Sl({potentials:e,averageMatchUpMinutes:Zr,requestConflicts:N,personRequests:m,scheduleTime:j,scheduleDate:b,matchUp:X});if(lr?.length)return y[b]||(y[b]=[]),y[b].push(...lr),!1;F(Ft,it);let Xe=z.minutesMap?.[lt]?.recoveryMinutes;return Oc({matchUpPotentialParticipantIds:O,individualParticipantProfiles:x,matchUpNotBeforeTimes:L,averageMatchUpMinutes:Zr,matchUpDependencies:s,recoveryMinutes:Xe,scheduleTime:j,matchUp:X}),P[lt]=j,!0});z.matchUpsToSchedule=z.matchUpsToSchedule.filter(({matchUpId:X})=>X!==Q?.matchUpId),Q?$+=1:(h[b][B]||(h[b][B]=[]),h[b][B].push({scheduleTime:j,attempts:tt+1}))}z.matchUpsToSchedule?.length&&(h[b][B]=h[b][B]?.filter(j=>{let tt=j.attempts<W;return tt&&z.scheduleTimes.push(j),!tt})),(!z.scheduleTimes?.length||!z.matchUpsToSchedule?.length)&&(z.complete=!0)}H+=1,K=v.every(({venueId:B})=>V[B].complete)||H===q}for(let{venueId:B}of v){let $=V[B].matchUpMap;Object.keys($).forEach(z=>{let j=u[z];j&&Object.keys($[z]).forEach(tt=>{let{drawDefinition:Q}=wo({tournamentRecord:j,drawId:tt});Q&&$[z][tt].forEach(({matchUpId:lt})=>{let it=P[lt];if(it){let Rt=it.split(":").map(Jn).join(":"),Ft=`${Et(b)}T${Rt}`;g?U[b].push(lt):(zo({drawDefinition:Q,scheduledTime:Ft,matchUpId:lt}).success&&U[b].push(lt),B&&ia({tournamentRecord:j,drawDefinition:Q,matchUpId:lt,venueId:B}))}})})}),A[b]=V[B].matchUpsToSchedule.map(Ae),I[b][B]=V[B].scheduleTimes.sort((z,j)=>qt(z.scheduleTime)-qt(j.scheduleTime))}!g&&w?.length&&xc({matchUpDetails:w,scheduleByeMatchUps:!0,removePriorValues:!0,tournamentRecords:u,schedule:{scheduledDate:"",scheduledTime:"",courtOrder:"",courtId:"",venueId:""}});for(let B of R.venues)for(let $ of B.rounds){let j=($.matchUps?.map(({matchUpId:Q})=>Q)||[]).filter(Q=>U[b].includes(Q));$.canScheduledMatchUpIds=j;let tt=Math.round(j.length/$.matchUpsCount*1e4)/100;(tt===1/0||isNaN(tt))&&(tt=0),$.possibleToSchedulePct=tt,$.matchUpsCount===j.length&&($.possibleToSchedule=!0)}}let D=o.map(({scheduleDate:R})=>R),M={timeStamp:Date.now(),overLimitMatchUpIds:E,scheduledMatchUpIds:U,schedulingProfile:p,noTimeMatchUpIds:A,requestConflicts:N,scheduledDates:D};return qy({tournamentRecords:u,autoSchedulingAudit:M}),{...C,schedulingProfileModifications:t,schedulingProfileIssues:n,scheduleTimesRemaining:I,dateSchedulingProfiles:o,skippedScheduleTimes:h,recoveryTimeDeferredMatchUpIds:S,dependencyDeferredMatchUpIds:T,matchUpScheduleTimes:P,overLimitMatchUpIds:E,scheduledMatchUpIds:U,noTimeMatchUpIds:A,requestConflicts:N,scheduledDates:D}}function AM({averageMinutes:t,startTime:e,endTime:r,court:n,date:o}){if(!Array.isArray(n.dateAvailability))return{error:st,stack:"getEarliestCourtTime"};let i=bc({scheduleDate:o,courts:[n],startTime:!0}),s=bc({scheduleDate:o,courts:[n],endTime:!0});e=e||i,r=r||s;let a=wa({court:n,date:o}),{timeSlots:c}=Ns({courtDate:a}),u=ke(e),p=ke(r);return{earliestCourtTime:c?.reduce((d,l)=>{let f=ke(l.startTime),g=ke(l.endTime);if(f>p||g<u)return d;let I=u>f?u:f;if(ma(I,g)>=t){let T=Kt(I.toISOString());(!d||T<d)&&(d=T)}return d},void 0),courtStartTime:i,courtEndTime:s}}function Kx({schedulingProfileModifications:t,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:r,schedulingProfileIssues:n,dateSchedulingProfiles:o,containedStructureIds:i,matchUpDependencies:s,matchUpDailyLimits:a,clearScheduleDates:c,tournamentRecords:u,periodLength:p=30,schedulingProfile:m,personRequests:d,matchUps:l=[],courts:f,dryRun:g}){let I={},h={},S={},T={},y={},P={},U={},E={},A={};for(let M of o??[]){let R=Et(M?.scheduleDate),b=M?.venues||[],v={},O={},x=(Q,X)=>{Q.forEach(lt=>{let it=O[lt].counters;it[X]?it[X]+=1:it[X]=1,it[ao]?it[ao]+=1:it[ao]=1})};I[R]={},h[R]={},P[R]=[],U[R]=[],E[R]=[],A[R]=[];let F={};l?.forEach(Q=>{Q.schedule?.scheduledDate&&Wn(R,Et(Q.schedule.scheduledDate))&&ea({matchUpPotentialParticipantIds:v,matchUpNotBeforeTimes:F,matchUp:Q})});let{allDateScheduledByeMatchUpDetails:L,allDateScheduledMatchUpIds:w,venueScheduledRoundDetails:V,allDateMatchUpIds:k}=Yy({matchUpPotentialParticipantIds:v,individualParticipantProfiles:O,scheduleCompletedMatchUps:r,containedStructureIds:i,matchUpNotBeforeTimes:F,matchUpScheduleTimes:y,matchUpDependencies:s,clearScheduleDates:c,tournamentRecords:u,periodLength:p,scheduleDate:R,matchUps:l,courts:f,venues:b}),W=l?.filter(({matchUpId:Q})=>w.includes(Q)),{bookings:H}=sm({dateScheduledMatchUps:W,tournamentRecords:u,scheduleDate:R,periodLength:p}),{virtualCourts:K}=tm({scheduleDate:R,periodLength:p,bookings:H,courts:f}),q=K?.reduce((Q,X)=>{let{earliestCourtTime:lt,courtEndTime:it}=AM({date:R,averageMinutes:0,court:X});return(!Q.startTime||ke(lt)<ke(Q.startTime))&&(Q.startTime=lt),(!Q.endTime||ke(it)>ke(Q.endTime))&&(Q.endTime=it),Q},{}),B=q.startTime,$=({courtId:Q,booking:X})=>K?.find(lt=>lt.courtId===Q)?.dateAvailability[0].bookings.push(X),z=10,j=0,tt;for(;!tt;){for(let{venueId:Q}of b){let X=V[Q],lt=X.matchUpsToSchedule.length,it=[],Rt=[],Ft,Ue=0;for(;!Ft;){for(let fe of X.matchUpsToSchedule){if(Rt.length===X.courtsCount||it.length===X.courtsCount){Ft=!0;break}let{matchUpId:Me,matchUpType:vr}=fe,{participantIdsAtLimit:Zr,relevantParticipantIds:lr}=yl({matchUpPotentialParticipantIds:v,individualParticipantProfiles:O,matchUpDailyLimits:a,matchUp:fe});if(Zr.length){U[R].includes(Me)||U[R].push(Me);continue}let{dependenciesScheduled:Xe,remainingDependencies:ee}=hl({matchUpScheduleTimes:y,matchUpDependencies:s,allDateMatchUpIds:k,matchUp:fe});if(!Xe){h[R][Me]||(h[R][Me]=[]),h[R][Me].push({remainingDependencies:ee});continue}let Pt=[],ae=K?.reduce((re,pr)=>{if(Rt.includes(pr.courtId))return re;let{earliestCourtTime:Jt}=AM({averageMinutes:X.greatestAverageMinutes,startTime:B,date:R,court:pr});if(re.scheduleTime&&qt(Jt)>=qt(re.scheduleTime))return re;let{scheduledDependent:Wt}=jy({matchUpScheduleTimes:y,matchUpDependencies:s,scheduleTime:Jt,matchUpId:Me,details:X});if(Wt)return re;let{enoughTime:mr}=Tl({individualParticipantProfiles:O,matchUpNotBeforeTimes:F,matchUpDependencies:s,scheduleTime:Jt,details:X,matchUp:fe});if(!mr)return I[R][Me]||(I[R][Me]=[]),I[R][Me].includes(Jt)||I[R][Me].push(Jt),re;let zt=X.minutesMap?.[Me]?.averageMinutes||X.greatestAverageMinutes,{conflicts:pe}=Sl({potentials:e,averageMatchUpMinutes:zt,requestConflicts:A,personRequests:d,scheduleTime:Jt,scheduleDate:R,matchUp:fe});if(pe?.length)return Pt.push(...pe),!1;x(lr,vr);let Pe=X.minutesMap?.[Me]?.recoveryMinutes;return Oc({matchUpPotentialParticipantIds:v,individualParticipantProfiles:O,matchUpNotBeforeTimes:F,averageMatchUpMinutes:zt,matchUpDependencies:s,recoveryMinutes:Pe,scheduleTime:Jt,matchUp:fe}),(!re.scheduleTime||qt(Jt)<qt(re.scheduleTime))&&(re.averageMatchUpMinutes=zt,re.recoveryMinutes=Pe,re.scheduleTime=Jt,re.courtName=pr.courtName,re.courtId=pr.courtId),re},{});if(ae.scheduleTime){let{averageMatchUpMinutes:re,recoveryMinutes:pr,scheduleTime:Jt,courtId:Wt}=ae;y[Me]=Jt,T[Me]=Wt,it.push(Me),Rt.push(Wt);let mr=Jt,zt=Yr(mr,re);$({courtId:Wt,booking:{averageMatchUpMinutes:re,recoveryMinutes:pr,periodLength:p,matchUpId:Me,startTime:mr,courtId:Wt,endTime:zt,venueId:Q}}),X.matchUpsToSchedule=X.matchUpsToSchedule.filter(Pe=>Pe.matchUpId!==Me)}else Pt?.length&&(S[R]||(S[R]=[]),S[R].push(...Pt))}(Rt.length===X.courtsCount||it.length===X.courtsCount||!X.matchUpsToSchedule.length)&&(Ft=!0),X.matchUpsToSchedule.length&&it<X.courtsCount&&(ke(B)<ke(q.endTime)?B=Yr(B,p):(Ft=!0,X.complete=!0)),Ue+=1,!Ft&&Ue>=lt&&(Ft=!0)}X.matchUpsToSchedule?.length||(X.complete=!0)}j+=1,tt=b.every(({venueId:Q})=>V[Q].complete)||j===z}for(let{venueId:Q}of b){let X=V[Q].matchUpMap;Object.keys(X).forEach(lt=>{let it=u[lt];it&&Object.keys(X[lt]).forEach(Rt=>{let{drawDefinition:Ft}=wo({tournamentRecord:it,drawId:Rt});Ft&&X[lt][Rt].forEach(({matchUpId:fe})=>{let Me=y[fe],vr=T[fe];if(Me){let Zr=Me.split(":").map(Jn).join(":"),lr=`${Et(R)}T${Zr}`;g||(zo({drawDefinition:Ft,scheduledTime:lr,matchUpId:fe}),Xi({courtDayDate:R,tournamentRecords:u,tournamentRecord:it,drawDefinition:Ft,matchUpId:fe,courtId:vr})),P[R].push(fe)}})})}),E[R]=V[Q].matchUpsToSchedule.map(Ae)}!g&&L?.length&&xc({matchUpDetails:L,scheduleByeMatchUps:!0,removePriorValues:!0,tournamentRecords:u,schedule:{scheduledDate:"",scheduledTime:"",courtOrder:"",courtId:"",venueId:""}});for(let Q of M.venues)for(let X of Q.rounds){let it=(X.matchUps??[]).map(({matchUpId:Ft})=>Ft)?.filter(Ft=>P[R].includes(Ft));X.canScheduledMatchUpIds=it;let Rt=Math.round((it?.length||0)/X.matchUpsCount*1e4)/100;(Rt===1/0||isNaN(Rt))&&(Rt=void 0),X.possibleToSchedulePct=Rt,X.matchUpsCount===it?.length&&(X.possibleToSchedule=!0)}}let N=(o??[]).map(({scheduleDate:M})=>M),D={timeStamp:Date.now(),overLimitMatchUpIds:U,scheduledMatchUpIds:P,schedulingProfile:m,noTimeMatchUpIds:E,requestConflicts:A,scheduledDates:N};return qy({tournamentRecords:u,autoSchedulingAudit:D}),{...C,schedulingProfileModifications:t,schedulingProfileIssues:n,dateSchedulingProfiles:o,recoveryTimeDeferredMatchUpIds:I,dependencyDeferredMatchUpIds:h,matchUpScheduleTimes:y,overLimitMatchUpIds:U,scheduledMatchUpIds:P,noTimeMatchUpIds:E,requestConflicts:A,scheduledDates:N}}function am(t){let{scheduleAttributes:e=["scheduledDate","scheduledTime","courtOrder"],ignoreMatchUpStatuses:r=ce,scheduledDates:n,venueIds:o}=t,i=Dr(t),s=ht(i)?Object.values(i).map(({tournamentId:c})=>c).filter(Boolean):[];if(!s?.length)return{error:wt};let a=0;for(let c of s){let u=i[c],p=_1({ignoreMatchUpStatuses:r,scheduleAttributes:e,tournamentRecord:u,scheduledDates:n,venueIds:o});if(p.error)return p;a+=p.clearedScheduleCount??0}return{...C,clearedScheduleCount:a}}function _1({scheduleAttributes:t=["scheduledDate","scheduledTime","courtOrder"],ignoreMatchUpStatuses:e=ce,tournamentRecord:r,scheduledDates:n,venueIds:o=[]}){if(typeof r!="object")return{error:Y};if(!Array.isArray(e)||!Array.isArray(o))return{error:G};o.length&&t.push("venueId");let i=Te({matchUpFilters:{scheduledDates:n},tournamentRecord:r}).matchUps??[],s={};i.forEach(({matchUpStatus:u,schedule:p,drawId:m,matchUpId:d})=>{(!u||!e.includes(u))&&_a({schedule:p,scheduleAttributes:t})&&(!o?.length||o.includes(p.venueId))&&(s[m]||(s[m]=[]),s[m].push(d))});let a=r.tournamentId,c=0;for(let u in s){let{event:p,drawDefinition:m}=ze({tournamentRecord:r,drawId:u}),d=or({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&&![so,Bo,Hi,yp,Wi,ji].includes(g?.itemType);return I||(f=!0),I}),f&&(gt({context:"clear schedules",eventId:p?.eventId,drawDefinition:m,tournamentId:a,matchUp:l}),c+=1)}}return{...C,clearedScheduleCount:c}}function cm(t){let{checkPotentialRequestConflicts:e=!0,scheduleCompletedMatchUps:r,clearScheduleDates:n,scheduleDates:o=[],tournamentRecords:i,periodLength:s,useGarman:a,dryRun:c,pro:u}=t,p=rt(t,[{[Re]:!0},{[tr]:N=>!N||Array.isArray(N)&&N.every(Rr),[Dh]:!1,[He]:Be}]);if(p.error)return p;let m=Ko({tournamentRecords:i});if(m.error)return m;if(!m.schedulingProfile.length)return{...C};let{modifications:d,issues:l=[],schedulingProfile:f=[]}=m,g=Object.assign({},...Object.values(i).map(N=>as({tournamentRecord:N}).containedStructures)),I=o.map(N=>{if(Rr(N))return Et(N)}).filter(Boolean),h=f.map(N=>N.scheduleDate).map(N=>Rr(N)&&Et(N)).filter(N=>N&&(!o.length||I.includes(N)));if(!h.length)return{error:tE};if(n&&!c){let N=Array.isArray(n)?n:[];am({tournamentRecords:i,scheduledDates:N})}let S=Ao({ignoreDisabled:!1,tournamentRecords:i}).courts,{matchUps:T}=Un({matchUpFilters:{matchUpTypes:[xt,_t]},afterRecoveryTimes:!0,nextMatchUps:!0,tournamentRecords:i}),{matchUpDependencies:y}=sn({includeParticipantDependencies:!0,tournamentRecords:i,matchUps:T}),{matchUpDailyLimits:P}=ul({tournamentRecords:i}),{personRequests:U}=bi({requestType:_c,tournamentRecords:i}),E=f.filter(N=>{let D=Et(N?.scheduleDate);return h.includes(D)}).sort((N,D)=>new Date(N.scheduleDate).getTime()-new Date(D.scheduleDate).getTime()),A={schedulingProfileModifications:d,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:r,schedulingProfileIssues:l,dateSchedulingProfiles:E,containedStructureIds:g,matchUpDependencies:y,matchUpDailyLimits:P,clearScheduleDates:n,tournamentRecords:i,schedulingProfile:f,personRequests:U,periodLength:s,useGarman:a,matchUps:T,dryRun:c,courts:S};return u?Kx(A):$x(A)}function um(t){let{tournamentRecord:e,tournamentRecords:r,activeTournamentId:n,...o}=t||{};return o.tournamentId||(o.tournamentId=Dt()),o.startDate&&!Qa(o.startDate)&&!Cm.test(o.startDate)?{error:je}:o.endDate&&!Qa(o.endDate)&&!Cm.test(o.endDate)?{error:je}:(o.extensions&&(o.extensions=o.extensions.filter(wn)),{...o})}function pI({addParticipants:t=!0,participantAttribute:e,tournamentRecord:r,personAttribute:n,teamNames:o,accessor:i,uuids:s}){if(!r)return{error:Y};let a={},c=(r.participants??[]).filter(({participantType:f,participantRole:g})=>f===Tt&&g===xe),u=0;for(let f of c){let I=i&&ls({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()??Dt(),individualParticipantIds:[],participantRole:xe,participantType:Lt};let h={value:n??e,name:Oh};At({element:a[I],extension:h}),u+=1}a[I].individualParticipantIds.push(f.participantId)}}let p=Object.keys(a),m=(r.participants??[]).map(f=>{if(f.participantType!==Lt||f.participantRole!==xe)return;let{extension:g}=dt({name:Oh,element:f}),I=g?.value;if(p.includes(I))return f.participantId}).filter(Boolean),d=0,l=[];return Object.keys(a).forEach(f=>{let g=a[f],{participantId:I}=g;m.includes(I)||(r.participants||(r.participants=[]),t&&r.participants.push(g),l.push(g),d++)}),t&&d?(mt({payload:{tournamentId:r.tournamentId,participants:l},topic:Zo}),{...C,participantsAdded:d}):l.length?{...C,newParticipants:l}:{error:yC}}var zx=[{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 Qx=["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 $y({count:t=1,participantsCount:e=32}={}){let r=Ir(Qx),n=r.slice(0,t);return{cities:et(0,e).map(i=>i<Math.min(t,r.length)?n[i]:yn(n))}}function Ky({count:t=1,participantsCount:e=32}={}){let r=Ir(zx),n=r.slice(0,t).map(i=>Object.keys(i)).flat();return{states:et(0,e).map(i=>i<Math.min(t,r.length)?n[i]:yn(n))}}function zy({count:t=1,participantsCount:e=32}={}){let r=et(0,t).map(()=>et(0,5).map(()=>po(0,9)).join(""));return{postalCodes:et(0,e).map(o=>o<t?r[o]:yn(r))}}function pm({idPrefix:t,participantType:e,index:r,uuids:n}){let o=Vt(e)?e[0]:"X";return t?`${t}-${o}-${r}`:n?.pop()||Dt()}function Qy(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 Xx={lastNames:["Abbey","Ahern","Ampleforth","Ananiadis","Andelic","Assange","Atreides","Austen","Bach","Banks","Barrington","Batty","Bauers","Beals","Beer","Bennett","Berry","Bonaparte","Brewer","Brockovich","Bukowski","Cassidy","Catton","Calvino","Carlin","Carson","Chip","Constant","Crane","Crowne","Cummings","Curie","Dallas","Diamond","Deckard","Drazic","Dunbar","Earhart","Eisenstein","Eldritch","Elliot","Ellul","Escher","Eyre","Faulkner","Fulcher","Fukuoka","Godel","Goldstein","Greer","Hedges","Herbert","Holmgren","Humperdinck","Huxley","Illich","Jeffers","Jensen","Jevons","Johnson","Johnstone","Jovovich","Kingsnorth","Langer","Fernwright","Fuller","Le Guin","Lem","Lovelace","Mander","McLuhan","Midgely","Mond","Montoya","Moore","Murry","Nagle","Nearing","Ogden","Ophuls","Parks","Paz","Peet","Perfect","Pendejo","Pevensie","Postman","Ripley","Rodda","Rumfoord","Runciter","Rugen","Sale","Schumacher","Shaftoe","Shelley","Shepard","Smith","Stratton","Stewart","Swift","Tillich","Turing","Tyrell","Twain","Yeats","Veblen","Yates","Vonnegut","Waterhouse","Watson","Wolin","Wirt","Waschuk","Wormwood"],firstFemale:["Ada","Amelia","Amelie","America","Anne","Antonia","Aravis","Astrid","Beatrice","Brienne","Buttercup","Caitlin","Cimorene","Cordelia","Desdemona","Ellen","Elizabeth","Emily","Emmie","Erin","Eva","Evelyn","Heather","Helen","Hermia","Hypatia","Imogen","Jane","Jasmine","Juliana","Juliet","Katniss","Leeloo","Lenina","Lilith","Linda","Lizzie","Louise","Lucy","Marie","Mary","Martha","Matilda","Milla","Miranda","Meg","Melba","Nicole","Ola","Portia","Pris","Rachael","Rachel","Rebecca","River","Rosa","Rosalind","Scout","Sharn","Susanne","Titania","Uhura","Ursula","Valentina","Viola","Virginia","Xena","Zoe"],firstMale:["Alan","Aldous","August","Axel","Barda","Barry","Bill","Bruce","Charles","Chris","Constantine","Darwin","David","Derrick","Edward","Emmanuel","Ernst","Estlin","Fezzik","Filby","Frank","Frito","George","Glen","Helmholtz","Inigo","Italo","Ivan","Jacques","James","Jared","Jerry","Joe","Johann","Julian","John Michael","Jonathan","Korben","Kirkpatrick","Kurt","Lief","Malachi","Mark","Marhsall","Masanobu","Maurits","Michael","Mustapha","Neil","Nikola","Octavio","Palmer","Paul","Pierre","Robinson","Rick","Rincewind","Roy","Shannon","Sheldon","Stafford","Stanislaw","Stanley","Syme","Thorstein","Thomas","Tyrone","Vizzini","Walton","Walker","Warren","Wendell","Westley","William","Winston","Zoran"]};function Xy(t){let{count:e=100,sex:r}=t||{};if(!e||r&&![$t,ne].includes(r))return{personData:[],error:G};let n=Math.ceil(e*1.3),{lastNames:o,firstFemale:i,firstMale:s}=Xx,a=ti.map(({iso:I})=>I).filter(Boolean),c=Math.ceil(n/o.length),u=Math.ceil(n/i.length),p=Math.ceil(n/s.length),m=et(0,c).flatMap(()=>{let I=J(o,!1,!0);return et(0,o.length).map(()=>tn(I))}),d=et(0,u).flatMap(()=>{let I=J(i,!1,!0);return et(0,i.length).map(()=>tn(I))}),l=et(0,p).flatMap(()=>{let I=J(s,!1,!0);return et(0,s.length).map(()=>tn(I))}),f={};for(let I=0;I<n;I++){let h=m.pop(),S=r||yn([$t,ne]),T=S===$t?l.pop():d.pop(),y=yn(a);f[`${T}${h}`]={nationalityCode:y,sex:S,firstName:T,lastName:h}}return{personData:Object.values(f).slice(0,e)}}function Jy(t){let e=t?.count||1,{personExtensions:r,consideredDate:n,isMock:o=!0,gendersCount:i,personData:s,category:a,sex:c}=t||{};if(isNaN(e))return{error:G};let u=i?.[$t]||c===$t&&e||0,p=i?.[ne]||c===ne&&e||0;e=Math.max(e,u+p);let m=e-(u+p),d=u&&Xy({count:u,sex:$t}).personData||[],l=p&&Xy({count:p,sex:ne}).personData||[],f=[...d,...l,...m&&Xy({count:m}).personData||[]],g=f.filter(A=>!c||u&&p||A.sex===c),I=[];if(Array.isArray(s)){let A=s.filter(N=>typeof N.firstName!="string"||typeof N.lastName!="string"||N.sex&&![$t,ne].includes(N.sex)||N.nationalityCode&&(typeof N.nationalityCode!="string"||N.nationalityCode.length>3||!ti.find(({iso:D,ioc:M})=>[D,M].includes(N.nationalityCode)))?!1:(N.nationalityCode&&I.push(N.nationalityCode),!0));if(A.length)g=A;else return{error:G}}let h=s?g:Ir(g);if(h.length<e){let{maleFirstNames:A,maleLastNames:N,femaleFirstNames:D,femaleLastNames:M,nationalityCodes:R}=f.reduce((b,v)=>{let{firstName:O,lastName:x,nationalityCode:F}=v;return v.sex===$t?(b.maleFirstNames.includes(O)||b.maleFirstNames.push(O),b.maleLastNames.includes(x)||b.maleLastNames.push(x)):(b.femaleFirstNames.includes(O)||b.femaleFirstNames.push(O),b.femaleLastNames.includes(x)||b.femaleLastNames.push(x)),b.nationalityCodes.includes(F)||b.nationalityCodes.push(F),b},{maleFirstNames:[],maleLastNames:[],femaleFirstNames:[],femaleLastNames:[],nationalityCodes:[]});et(0,e-h.length).forEach(()=>{let b=c||yn([$t,ne]),v=yn(R),O=b===$t?yn(A):yn(D),x=b===$t?yn(N):yn(M),F={firstName:O,lastName:x,sex:b,nationalityCode:v};h.push(F)})}let{ageMinDate:S,ageMaxDate:T}=Ls({consideredDate:n,category:a}),y=pt(S?.slice(0,4)||0)||pt(T?.slice(0,4)||0)-3,P=pt(T?.slice(0,4)||0)||pt(S?.slice(0,4)||0)+3,U=(S||T)&&[y,P],E=h.slice(0,e).map((A,N)=>{let[D,M]=U||[],R=U&&tn(et(D,M)),b=tn(et(0,365)),v=R&&HC(R,b);return Object.assign(ot({extensions:r||[{name:"regionCode",value:N+1}],birthDate:v,isMock:o}),A)});return{persons:E.length&&E||h[0],nationalityCodes:I}}var Jx=["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 mm({nameRoot:t="TEAM",count:e=1}={}){let n=Ir(Jx).slice(0,e);return n.length<e&&et(0,e-n.length).forEach(o=>n.push(`${t} ${o+1}`)),{names:n}}function sa(t){let{scaledParticipantsCount:e,rankingRange:r}=t,{ratingsParameters:n=we,valuesInstanceLimit:o,ratingsValues:i=[],consideredDate:s,categories:a,category:c,nationalityCodesCount:u,nationalityCodeType:p,nationalityCodes:m,participantsCount:d=32,participantType:l,teamSize:f=8,personIds:g,idPrefix:I,uuids:h,personExtensions:S,addressProps:T,gendersCount:y,matchUpType:P,personData:U,sex:E,inContext:A,withISO2:N,withIOC:D,scaleAllParticipants:M}=t,R=l===ft||P===vi,b=l===Lt||P===Lt;r&&(!Array.isArray(r)||!r.every(ee=>Zt(ee))||r.length!==2)&&(r=void 0),e=M?d:e;let v=1e3,O=e&&e>v?e:v;r=r||[1,O],r[1]+=1;let x=d*(R&&2||b&&(f??8)||1),F=Jy({count:x,personExtensions:S,consideredDate:s,gendersCount:y,personData:U,category:c,sex:E});if(F.error)return F;let{nationalityCodes:L,persons:w}=F,V={},k={},W={},H={},K=ee=>{Object.assign(V,ee.doublesRankings),Object.assign(k,ee.singlesRankings),Object.assign(H,ee.doublesRatings),Object.assign(W,ee.singlesRatings)};if(ht(c)){let ee=Zx({scaledParticipantsCount:e,ratingsParameters:n,participantType:l,ratingsValues:i,rankingRange:r,category:c});K(ee)}Array.isArray(a)&&a.forEach(ee=>{let Pt=Zx({scaledParticipantsCount:e,ratingsParameters:n,participantType:l,ratingsValues:i,rankingRange:r,category:ee});K(Pt)});let q=ti.filter(ee=>p==="IOC"&&ee.ioc||ee.iso);function B(ee){let Pt=Math.ceil(x/ee);return o&&Pt>o?Math.ceil(x/o):ee}let{postalCodesProfile:$,postalCodesCount:z,statesProfile:j,citiesProfile:tt,citiesCount:Q,statesCount:X}=T||{},lt=ee=>Object.keys(ee).map(Pt=>et(0,j[Pt]).map(()=>Pt)).flat(),it=tt&<(tt)||T?.cities||$y({count:Q||x,participantsCount:x}).cities,Rt=j&<(j)||T?.states||Ky({count:X||x,participantsCount:x}).states,Ft=$&<($)||T?.postalCodes||zy({count:z||x,participantsCount:x}).postalCodes,Ue={cities:it,states:Rt,postalCodes:Ft},fe=B(u),Me=fe?Ir(q).slice(0,u):m&&q.filter(ee=>m.includes(ee.iso))||q,vr=Ir(et(0,Math.ceil(x/(fe||1))).map(()=>Me).flat(1/0)),Zr=mm({count:d}).names;return{participants:et(0,d).map(ee=>{let Pt=R&&2||b&&(f??8)||1,ae=et(0,Pt).map(mr=>{let zt=ee*Pt+mr;return Xe(zt)}),re=ae.map(mr=>mr.participantId),pr=ae.map(mr=>mr.person.standardFamilyName).join("/"),Jt=R?ft:Lt,Wt={participantId:pm({participantType:Jt,index:ee,idPrefix:I,uuids:h}),participantName:R?pr:Zr[ee],participantRole:xe,individualParticipantIds:re,participantType:Jt};return A&&(Wt.individualParticipants=ae),R||b?[Wt,...ae]:ae}).flat(),...C};function Xe(ee){let Pt=w[ee],{nationalityCode:ae,participantExtensions:re,participantTimeItems:pr,extensions:Jt,firstName:Wt,birthDate:mr,lastName:zt,personId:pe,sex:Pe}=Pt||{},Or=Wt||"GivenName",Je=zt||"FamilyName",De=`${Or} ${Je}`,Ee=vr[ee],ge=L?.length&&ae||Ee&&(p==="IOC"?Ee.ioc||Ee.iso:Ee.iso||Ee.ioc)||ae;vr?.length&&!ge&&!ae&&console.log("%c Invalid Nationality Code",{participantIndex:ee,country:Ee});let _r=Qy({...Ue,participantIndex:ee,nationalityCode:ge}),fr=ot({participantId:pm({participantType:Tt,index:ee,idPrefix:I,uuids:h}),extensions:re,timeItems:pr,participantRole:xe,participantType:Tt,participantName:De,person:{personId:pe||g?.length&&g[ee]||Dt(),birthDate:Rr(mr)?mr:void 0,addresses:[_r],standardFamilyName:Je,standardGivenName:Or,nationalityCode:ge,extensions:Jt,sex:Pe}});if(D&&ge){let be=ti.find(({iso:Ar})=>Ar===ge);be?.ioc&&(fr.person.iocNationalityCode=be.ioc),be?.label&&(fr.person.countryName=be.label)}if(N&&ge){let be=ti.find(({iso:Ar})=>Ar===ge);be?.iso2&&(fr.person.iso2NationalityCode=be.iso2),be?.label&&(fr.person.countryName=be.label)}let uo=be=>{let Ar=be.categoryName||be.ratingType||be.ageCategoryCode,Zi=k[Ar]?.[ee],Tn=V[Ar]?.[ee];Zy({scaleValue:Zi,eventType:Fs,scaleType:fi,participant:fr,category:be}),Zy({scaleValue:Tn,eventType:ko,scaleType:fi,participant:fr,category:be});let ts=W[Ar]?.[ee],ju=H[Ar]?.[ee];Zy({scaleValue:ts,eventType:Fs,scaleType:gi,participant:fr,category:be}),Zy({scaleValue:ju,eventType:ko,scaleType:gi,participant:fr,category:be})};return Array.isArray(a)?a.forEach(be=>uo(be)):c&&uo(c),fr}}function Zy({scaleValue:t,participant:e,eventType:r,scaleType:n,category:o}){let i=o.categoryName||o.ratingType||o.ageCategoryCode,s=[Ii,n,r,i].join("."),a={itemValue:t,itemType:s};i&&t&&(e.timeItems||(e.timeItems=[]),e.timeItems.push(a))}function Zx(t){let{category:e,scaledParticipantsCount:r,ratingsParameters:n,participantType:o,ratingsValues:i=[]}=t,s=e.rankingRange||t.rankingRange||[1,1e3],a={},c={},u={},p={},{categoryName:m,ageCategoryCode:d,ratingType:l}=e,f=e.categoryName||e.ratingType||e.ageCategoryCode;if((m||d)&&!l){let[g,I]=s||[];if(c[f]=Ir(et(g,I)).slice(0,r||po(20,30)),[ft,Lt].includes(o)){let[h,S]=s||[];a[f]=Ir(et(h,S)).slice(0,r||po(20,30))}}if(l&&n[l]){let{ratingMax:g,ratingMin:I,ratingAttributes:h}=e,S={...n[l],...h||{}},{attributes:T={},decimalsCount:y,accessors:P,range:U,step:E}=S,A=O=>{let x={},F=Object.keys(O||{});for(let L of F){let w=O[L];if(typeof w=="object"&&w.generator){let{range:V}=w,[k,W]=V.slice().sort();x[L]=po(k,W)}else x[L]=w}return x},D=U[0]>U[1]?2:.7,[M,R]=U.slice().sort(),v=et(0,2e3).map(()=>EA(M,R,D,E,y)).filter(x=>(!g||x<=g)&&(!I||x>=I)).slice(0,r||po(20,30)).map(x=>P?Object.assign({},...P.map(F=>({[F]:x})),A(T)):x);u[f]=[...i,...v],[ft,Lt].includes(o)&&(p[f]=[...i,...v])}return{singlesRankings:c,doublesRankings:a,singlesRatings:u,doublesRatings:p}}function Al(t){let{alternatesCount:e=0,tieFormatName:r,drawSize:n}=t,o=0,i=0,s=0,a=0,c={},u={[$t]:0,[ne]:0,[Tr]:0,[os]:0,[Pn]:0};(ht(t.tieFormat)?t.tieFormat:Zn({namedFormat:r}))?.collectionDefinitions?.filter(Boolean).forEach(f=>{let{category:g,collectionId:I,matchUpType:h,matchUpCount:S,gender:T}=f;if([$t,ne].includes(T)){let y=S*(h===_t?2:1);u[T]<y&&(u[T]=y)}else T===Tr&&(u[$t]<S&&(u[$t]=S),u[ne]<S&&(u[ne]=S));if(g){let y=JSON.stringify(g);c[y]=g}if(I||(f.collectionId=Dt()),ue(_t)(h)){let y=S;a+=S,o=Math.max(o,y)}if(ue(xt)(h)){let y=S;s+=S,i=Math.max(i,y)}});let m=Object.keys(c).length?Math.max(s,a*2):Math.max(i,o*2),d=o*(n+e),l=i*(n+e);return{maxDoublesDraw:d,maxSinglesDraw:l,teamSize:m,genders:u}}function tw({participantsProfile:t,eventProfiles:e,drawProfiles:r}){let{participantsCount:n,participantType:o=Tt}=t||{},i=n||0,s={[ne]:0,[Tr]:0,[os]:0,[$t]:0,[Pn]:0},a=0,c=0,u=0,p=0,m=0,d=({alternatesCount:f=0,uniqueParticipants:g,tieFormatName:I,drawSize:h=0,eventType:S,tieFormat:T,category:y,gender:P,stage:U})=>{let E=S===qr,A=S===_e,N=!!(g||U===ct||y||P);if(A){p=Math.max(p,h+f),T=typeof T=="object"?T:Zn({namedFormat:I});let{teamSize:D,maxDoublesDraw:M,maxSinglesDraw:R,genders:b}=Al({alternatesCount:f,tieFormatName:I,tieFormat:T,drawSize:h});u=Math.max(u,D),c=Math.max(c,R),N||(a=Math.max(a,M)),Object.keys(b).forEach(v=>s[v]+=b[v])}else if(E)if(N){let D=(h+f)*2;m+=D,P&&(s[P]+=D)}else h+f&&h+f>a&&(a=h+f);else if(N){let D=h+f;P&&(s[P]+=D),m+=D}else h&&h>c&&(c=h+f)};if(e?.forEach(f=>{let{tieFormatName:g,tieFormat:I,drawProfiles:h,eventType:S,category:T,gender:y}=f;if(h)for(let P of h){let{tieFormatName:U,tieFormat:E}=P;d({...P,tieFormatName:U||g,tieFormat:E||I,eventType:S,category:T,gender:y})}}),Array.isArray(r))for(let f of r)d(f);let l=Math.max(p*u,a*2,c);return a&&(o=ft),(n||i)<l&&(n=l),n&&a&&[ft,_e].includes(o)&&(c&&Math.floor(c/2)>a?n=Math.floor(c/2):(!c||a*2>=c)&&(n=Math.ceil(n/2))),n===void 0&&(n=!e?.length&&!r?.length?32:0),n<i&&(n=i),{uniqueParticipantsCount:m,participantsCount:n,largestTeamDraw:p,largestTeamSize:u,participantType:o,gendersCount:s}}function tA({participantsProfile:t,tournamentRecord:e,eventProfiles:r,drawProfiles:n,startDate:o,uuids:i}){if(t?.participantsCount===0)return{addedCount:0,...C};let{participantsCount:s,participantType:a,largestTeamDraw:c,largestTeamSize:u,gendersCount:p}=tw({participantsProfile:t,eventProfiles:r,drawProfiles:n}),m=t?.teamKey,d=sa({consideredDate:o,...t,participantsCount:s,participantType:a,gendersCount:p,uuids:i}).participants,l=0,f=Sn({tournamentRecord:e,participants:d});if(f.error)return f;if(l+=f.addedCount,m){let S=pI({tournamentRecord:e,...m});if(S.error)return S}let g=d.filter(({participantType:S})=>S===Tt).map(St),I=t?.idPrefix?`${Lt}-${t.idPrefix}`:void 0,h=et(0,c).map(S=>{let T=g.slice(S*u,(S+1)*u),y=pm({index:S,participantType:a,idPrefix:I,uuids:i});return{participantName:`Team ${S+1}`,participantRole:xe,individualParticipantIds:T,participantType:Lt,participantId:y}});return f=Sn({participants:h,tournamentRecord:e}),f.error?f:(l+=f.addedCount,{addedCount:l,...C})}function eA({drawProfiles:t,category:e,gender:r}){let n={},o=t?.reduce((s,a)=>{let{qualifyingPositions:c=0,participantsCount:u=0,uniqueParticipants:p,stage:m=nt,drawSize:d=0}=a||{};Object.keys(s).includes(m)||(s[m]=0);let l=(u||d)-c;return p||r||e||m===ct?(Object.keys(n).includes(m)||(n[m]=0),n[m]+=l):s[m]=Math.max(s[m],l),s},{}),i=Object.keys(n);return i.forEach(s=>o[s]+=n[s]),{stageParticipantsCount:o,uniqueParticipantsCount:n,uniqueParticipantStages:i}}function rA({allUniqueParticipantIds:t,stageParticipantsCount:e,eventParticipantType:r,targetParticipants:n}){let o=e[nt]||0,i=e[ct]||0;return{stageParticipants:{QUALIFYING:n?.filter(({participantType:a})=>a===r).filter(({participantId:a})=>!t.includes(a)).slice(0,i),MAIN:n?.filter(({participantType:a})=>a===r).filter(({participantId:a})=>!t.includes(a)).slice(i,i+o)}}}var k1={[Ct]:2,[he]:1,[Ce]:1,[rr]:1,[Mt]:4};function mI(t){let{defaultWithScorePercent:e=2,winningSide:r}=t,{matchUpStatusProfile:n=k1,matchUpFormat:o=Dn,pointsPerMinute:i=1,sideWeight:s=4}=t;if(!Pr({matchUpFormat:o}))return{error:Hl};if(typeof n!="object")return{error:G};if(e>100&&(e=100),isNaN(e)||isNaN(i)||isNaN(s))return{error:G};let a=Object.keys(n).filter(b=>Object.keys(Vh).includes(b)&&b!==le);if(Object.keys(a).reduce((b,v)=>b+n[v],0)>100)return{error:G,matchUpStatusProfile:n};let u=a.reduce((b,v)=>(b.pointer=b.pointer+n[v],b.valueMap.push([b.pointer,v]),b),{pointer:0,valueMap:[]}),p=po(1,100),m=(u.valueMap.find(b=>p<=b[0])??[100,le])[1],d={sets:[],scoreStringSide1:"",side2ScoreString:""};if([Ct,Mt].includes(m)){r=r||po(1,2);let b={score:d,matchUpStatus:m,winningSide:r};if(!(m===Mt&&po(1,100)>100-e))return{outcome:b}}else if([he,Ce].includes(m))return{outcome:{score:d,matchUpStatus:m}};let l=Ye(o),{bestOf:f=1,exactly:g,setFormat:I,finalSetFormat:h}=l??{},S=[],T=po(0,1),y=r?[r-1]:[...et(0,s).map(()=>T),1-T],U=[rr,Mt,pn,ss].includes(m)&&(tn(et(1,g||f))||1),E,A=et(1,(g??f)+1);for(let b of A){let v=b===(g??f),{set:O,incomplete:x,winningSideNumber:F}=G1({setFormat:v&&h||I,incomplete:U===b,pointsPerMinute:i,matchUpStatus:m,weightedRange:y,setNumber:b});if(S.push(O),x){E=F;break}if(Xp({matchUp:{score:{sets:S},matchUpFormat:o}}).calculatedWinningSide)break}let N=Xp({matchUp:{score:{sets:S},matchUpFormat:o,winningSide:r}}),D=E?r||E:N.calculatedWinningSide,{score:M}=Wy({winningSide:D,score:{sets:S},matchUpStatus:m});return{outcome:{winningSide:D,matchUpStatus:m,score:M}}}function G1({weightedRange:t=[0,1],pointsPerMinute:e,matchUpStatus:r,incomplete:n,setFormat:o,setNumber:i}){let s={setNumber:i},{setTo:a,tiebreakFormat:c,tiebreakAt:u,tiebreakSet:p,timed:m,minutes:d}=o,l=po(0,t.length-1),f=t[l],g;if(m){let I=d*e,h=Math.round(I*.2),S=I+tn([1,-1])*h,T=cC(S,2),y=[T,S-T];f&&y.reverse(),g=t[l]+1;let P=y[0]>y[1]&&1||y[1]>y[0]&&2||0;if(n){let[A,N]=y;return Object.assign(s,{side1Score:A,side2Score:N}),ce.includes(r)?{set:s,incomplete:n,winningSideNumber:g}:{set:s,incomplete:n}}P||(y[po(0,1)]+=1),P=y[0]>y[1]?1:2,P!==g&&y.reverse();let[U,E]=y;return Object.assign(s,{side1Score:U,side2Score:E,winningSide:g}),{set:s}}else{if(n)return s.side1Score=po(0,u),s.side2Score=po(0,u),ce.includes(r)&&(g=t[l]+1),{set:s,incomplete:n,winningSideNumber:g};{let I=et(1,a+1).map(E=>et(0,a+2-E).map(()=>E)).flat(),h=I[po(0,I.length-1)],S=a&&Bg({isSide1:!0,tiebreakAt:u,lowValue:h,setTo:a}),T=!S,y=t.length===1&&t[l]+1;if(!T){y?(S[0]>S[1]?1:2)!==y&&S.reverse():f&&S.reverse();let[E,A]=S;Object.assign(s,{side1Score:E,side2Score:A})}let P=wu({matchUpScoringFormat:{setFormat:o},setObject:s}),U;if(P.hasTiebreakCondition||T){let{NoAD:E,tiebreakTo:A}=c||p||{},N=et(1,A+1).map(R=>et(0,A+2-R).map(()=>R)).flat(),D=N[po(0,N.length-1)],M=qp({isSide1:!0,tiebreakNoAd:E,tiebreakTo:A,lowValue:D});if(M)if(T){let R=M[0]>M[1]?1:2;y?R!==y&&M.reverse():f&&M.reverse(),[s.side1TiebreakScore,s.side2TiebreakScore]=M,U=M[0]>M[1]&&1||M[1]>M[0]&&2||void 0}else P.leadingSide===2?[s.side1TiebreakScore,s.side2TiebreakScore]=M:[s.side2TiebreakScore,s.side1TiebreakScore]=M}s.winningSide=P.winningSide||P.leadingSide||y||U}}return{set:s}}function El(t){let{matchUpStatusProfile:e,completeAllMatchUps:r,randomWinningSide:n,tournamentRecord:o,completionGoal:i,drawDefinition:s,event:a}=t;if(!s)return{error:Z};let c=t.matchUpFormat||s.matchUpFormat||a?.matchUpFormat,u=s.structures.slice().sort(Si),p=0,{matchUps:m,matchUpsMap:d}=se({matchUpFilters:{matchUpTypes:[jt],roundNumbers:[1]},contextFilters:{stages:[nt,ct]},inContext:!0,drawDefinition:s});if(m?.length){let h=a?.category?.ageCategoryCode||a?.category?.categoryName;if(h){let T=Cy({singlesOnly:!0,tournamentRecord:o,drawDefinition:s,scaleAccessor:{scaleName:h,sortOrder:XN,scaleType:fi},event:a});if(T.error)return T;let{lineUps:y,participantsToAdd:P}=T;Sn({tournamentRecord:o,participants:P}),At({element:s,extension:{name:Ro,value:y}})}else{let S=m[0]?.structureId,{positionAssignments:T}=bt({drawDefinition:s,structureId:S});if(T?.length){let{participants:y}=Gt({participantFilters:{participantTypes:[jt]},tournamentRecord:o}),P=U=>{let E=U.tieMatchUps.filter(ue(xt)),A=U.tieMatchUps.filter(ue(_t));E.forEach((N,D)=>{let M=N.matchUpId;N.sides.forEach(R=>{let{drawPosition:b}=R,v=y?.find(O=>{let{participantId:x}=O;return T.find(L=>L.participantId===x)?.drawPosition===b});if(v){let O=v.individualParticipantIds?.[D];O&&gl({teamParticipantId:v.participantId,participantId:O,tournamentRecord:o,drawDefinition:s,tieMatchUpId:M,event:a})}})}),A.forEach((N,D)=>{let M=N.matchUpId;N.sides.forEach(R=>{let{drawPosition:b}=R,v=y?.find(O=>{let{participantId:x}=O;return T.find(L=>L.participantId===x)?.drawPosition===b});v&&v.individualParticipantIds?.slice(D*2,D*2+2)?.forEach(x=>{gl({teamParticipantId:v.participantId,participantId:x,tournamentRecord:o,drawDefinition:s,tieMatchUpId:M,event:a})})})})};m.forEach(P)}}}let l=typeof r=="string"&&r,f=l&&le,g=u.length===2&&u[0].finishingPosition===li&&Yt(u.map(({stage:h})=>h),[nt,de]).length===2,I=u.map(({structureId:h})=>h);for(let h of I){if(p>=i)break;let S=s.structures.find(P=>P.structureId===h),T=Ut({contextFilters:{matchUpTypes:[_t,xt]},afterRecoveryTimes:!1,tournamentRecord:o,inContext:!0,drawDefinition:s,matchUpsMap:d,structure:S,event:a}).matchUps;T.length;let y=T.filter(({winningSide:P})=>!P).sort(Mi).map(Ae);for(let P of y){if(!isNaN(i)&&p>=i)break;let{matchUps:U}=Ut({matchUpFilters:{matchUpTypes:[_t,xt]},afterRecoveryTimes:!1,tournamentRecord:o,inContext:!0,drawDefinition:s,matchUpsMap:d,structure:S,event:a}),E=U.find(N=>N.matchUpId===P),A=[he,Ce].includes(E.matchUpStatus);if(E?.readyToScore&&!A){let D=V1({matchUpStatusProfile:e,tournamentRecord:o,drawDefinition:s,targetMatchUp:E,matchUpFormat:c,matchUpStatus:f,scoreString:l,winningSide:!n&&1,event:a});if(D?.error)return D;p+=1}}g&&S.finishingPosition===li&&t.completeRoundRobinPlayoffs&&Ks({structureId:S.structureId,applyPositioning:!0,drawDefinition:s})}return{...C,completedCount:p}}function EM(t){let{matchUpStatusCodes:e,policyDefinitions:r,tournamentRecord:n,drawDefinition:o,targetMatchUp:i,matchUpStatus:s,matchUpFormat:a,scoreString:c,winningSide:u,event:p}=t;if(!i||i.matchUpStatus===Nt)return;let{matchUpId:m}=i||{},{outcome:d}=cI({matchUpFormat:a,matchUpStatus:s,scoreString:c,winningSide:u});return e&&(d.matchUpStatusCodes=e),Gu({tournamentRecord:n,policyDefinitions:r,drawDefinition:o,matchUpFormat:a,matchUpId:m,outcome:d,event:p})}function V1(t){let{matchUpStatusProfile:e={},tournamentRecord:r,policyDefinitions:n,drawDefinition:o,matchUpStatus:i,matchUpFormat:s,targetMatchUp:a,scoreString:c,winningSide:u,event:p}=t;if(c||i)return EM(t);let{matchUpId:m}=a||{},{outcome:d}=mI({matchUpStatusProfile:e,matchUpFormat:s,winningSide:u});return Gu({policyDefinitions:n,tournamentRecord:r,drawDefinition:o,matchUpFormat:s,matchUpId:m,outcome:d,event:p})}function nA({matchUpStatusProfile:t,completeAllMatchUps:e,randomWinningSide:r,tournamentRecord:n,drawProfiles:o,isMock:i,event:s}){let a=Ht({event:s}).flightProfile,{eventName:c,eventType:u,category:p}=s,{startDate:m}=n,d=[],l=p?.categoryName||p?.ageCategoryCode||p?.ratingType,f=s.drawDefinitions?.map(({drawId:g})=>g);if(Array.isArray(a?.flights))for(let[g,I]of a.flights.entries()){let{drawId:h,stage:S,drawName:T,drawEntries:y}=I;d.push(I.drawId);let P=o[g],{seedsCount:U,generate:E=!0}=P||{};if(E){let A=y.filter(Br(ro)).map(Br(ro)),N=l||c;if(n&&U&&U<=A.length&&et(1,U+1).forEach((x,F)=>{let L={scaleValue:x,scaleName:N,scaleType:ho,eventType:u,scaleDate:m},w=A[F];Dc({tournamentRecord:n,participantId:w,scaleItem:L})}),f?.includes(h))break;let D=xa({...P,matchUpType:u,seedingScaleName:N,tournamentRecord:n,drawEntries:y,drawName:T,drawId:h,isMock:i,event:s,stage:S});if(D.error)return{error:D.error,drawIds:[]};let{drawDefinition:M}=D;if(!M)return{error:Mr};let R=o[g]?.drawExtensions;if(Array.isArray(R)&&R.filter(wn).forEach(O=>At({element:M,extension:O})),D=Cc({suppressNotifications:!0,tournamentRecord:n,drawDefinition:M,event:s}),D.error)return{error:D.error,drawIds:[]};if(P?.withPlayoffs){let O=M.structures?.[0].structureId,x=kp({idPrefix:P.idPrefix,...P.withPlayoffs,tournamentRecord:n,drawDefinition:M,structureId:O,isMock:i,event:s});if(x?.error)return x}let b=P?.completionGoal;if(!(P?.automated===!1)&&(e||b)){let O=P?.matchUpFormat,x=El({completeAllMatchUps:!b&&e,matchUpStatusProfile:t,randomWinningSide:r,tournamentRecord:n,completionGoal:b,drawDefinition:M,matchUpFormat:O,event:s});if(x.error)return{error:x.error,drawIds:[]};let F=x.completedCount;if(P?.drawType===Io){let L=M.structures?.find(k=>k.stage===nt);if(!L)return{error:kt};let w=Ks({structureId:L.structureId,tournamentRecord:n,drawDefinition:M,event:s});if(w.error)return{error:w.error,drawIds:[]};let V=b?b-(F??0):void 0;if(w=El({completeAllMatchUps:!b&&e,completionGoal:b?V:void 0,matchUpStatusProfile:t,randomWinningSide:r,tournamentRecord:n,drawDefinition:M,matchUpFormat:O,event:s}),w.error)return{error:w.error,drawIds:[]}}}}}return{...C,drawIds:d}}function oA(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=ue(jn)(m)&&Tt||ue(qr)(m)&&ft||m,l=r[nt]||0,f=r[ct]||0,g=i.drawProfiles?.length?l+f:i.participantsProfile?.participantsCount??0,I=[$t,ne].includes(p)?p:void 0,h=e?.idPrefix?`E-${s}-${e?.idPrefix}`:void 0,{participants:S}=sa({uuids:i.uuids||c,...e,scaledParticipantsCount:i.scaledParticipantsCount,consideredDate:o?.startDate,rankingRange:i.rankingRange,participantType:d,participantsCount:g,ratingsParameters:n,category:u,idPrefix:h,sex:I}),y=Sn({tournamentRecord:o,participants:S});if(y.error)return y;let P=S?.filter(({participantType:E})=>E===d),U=S?.map(St);return{uniqueDrawParticipants:P,uniqueParticipantIds:U}}function ew({autoEntryPositions:t,tournamentRecord:e,drawParticipants:r,drawProfile:n,event:o}){let{drawType:i=go,qualifyingPositions:s=0,stage:a=nt,drawSize:c=0,drawName:u,drawId:p}=n,m=c-s,d=r.slice(0,m).map(St);if(d.length){let g=Fn({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=Zp({drawName:u||i,qualifyingPositions:s,drawEntries:l,drawId:p,event:o,stage:a});return f.error?f:{...C}}function iA({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=nt,drawSize:l=0}=u,f=l-p,g=m||s||i||d===ct,I=g?t.slice(c,c+f):r[d||nt]||[];g&&(c+=f);let h=ew({autoEntryPositions:e,drawParticipants:I,tournamentRecord:n,drawProfile:u,event:a});if(h.error)return h}return{...C}}function sA(t){let{allUniqueParticipantIds:e,matchUpStatusProfile:r,participantsProfile:n,completeAllMatchUps:o,autoEntryPositions:i,hydrateCollections:s,randomWinningSide:a,ratingsParameters:c,tournamentRecord:u,eventProfile:p,eventIndex:m,publish:d,isMock:l,uuids:f}=t,g=p.gender,I=p.eventName,{eventType:h=jn,policyDefinitions:S,drawProfiles:T=[],eventExtensions:y,surfaceCategory:P,tieFormatName:U,processCodes:E,discipline:A,eventLevel:N,timeItems:D,ballType:M,category:R}=p,b=p.eventId||Dt(),v=p.tieFormat||(h===_e?Zn({namedFormat:U,event:{eventId:b,category:R,gender:g},hydrateCollections:s,isMock:l}):void 0),O=u.participants;for(let j of T)!g&&j.gender&&(g=j?.gender);let{stageParticipantsCount:x,uniqueParticipantsCount:F,uniqueParticipantStages:L}=eA({drawProfiles:T,category:R,gender:g}),w=ue(jn)(h)&&Tt||ue(qr)(h)&&ft||h,{uniqueDrawParticipants:V=[],uniqueParticipantIds:k=[]}=L?oA({event:{eventType:h,category:R,gender:g},uniqueParticipantsCount:F,participantsProfile:n,ratingsParameters:c,tournamentRecord:u,eventProfile:p,eventIndex:m,uuids:f}):{},{eventAttributes:W}=p;typeof W!="object"&&(W={});let H=R?.categoryName||R?.ageCategoryCode||R?.ratingType;I=I||H||"Generated Event";let K={...W,surfaceCategory:P,processCodes:E,discipline:A,eventLevel:N,eventName:I,eventType:h,tieFormat:v,ballType:M,category:R,eventId:b,gender:g};if(y?.length&&Array.isArray(y)){let j=y.filter(wn);j?.length&&Object.assign(K,{extensions:j})}if(Array.isArray(D)&&D.forEach(j=>zi({event:$,timeItem:j})),typeof S=="object")for(let j of Object.keys(S))Qi({policyDefinitions:{[j]:S[j]},event:K});K.category&&(K.category.categoryName=H);let q,B=ra({suppressNotifications:!1,internalUse:!0,tournamentRecord:u,event:K});if(B.error)return B;let $=B?.event,{stageParticipants:z}=rA({allUniqueParticipantIds:e,stageParticipantsCount:x,eventParticipantType:w,targetParticipants:O});if(T?.length){let j=iA({uniqueDrawParticipants:V,autoEntryPositions:i,stageParticipants:z,tournamentRecord:u,drawProfiles:T,category:R,gender:g,event:$});if(j.error)return j;let tt=nA({matchUpStatusProfile:r,completeAllMatchUps:o,randomWinningSide:a,tournamentRecord:u,drawProfiles:T,isMock:l,event:$});if(tt.error)return tt;q=tt.drawIds}else if(p?.participantsProfile?.participantsCount){let j=V.map(St);if(j.length){let tt=Fn({participantIds:j,autoEntryPositions:i,tournamentRecord:u,entryStage:nt,event:$});if(tt.error)return tt}}return d&&oa({tournamentRecord:u,event:$}),{drawIds:q,eventId:b,uniqueParticipantIds:k}}function dI({tournamentRecords:t,scheduleDate:e,venueId:r,round:n}){if(!Rr(e))return{error:je};let o="addSchedulingProfileRound",{extension:i}=dt({name:Sa,tournamentRecords:t,discover:!0}),s=i?.value||[],a=s.find(l=>Wn(e,l.scheduleDate));if(!a){let{startDate:l,endDate:f}=Qd({tournamentRecords:t}),g=new Date(e);if(l&&g<new Date(l)||f&&g>new Date(f))return{error:je};a={scheduleDate:e,venues:[]},s.push(a)}let c=a.venues.find(l=>l.venueId===r);c||(c={venueId:r,rounds:[]},a.venues.push(c));let u=["notBeforeTime"],p=l=>Object.keys(l).filter(f=>!u.includes(f)).sort().map(f=>ht(l[f])?p(l[f]):l[f]).flat().join("|");if(c.rounds.find(l=>p(l)===p(n)))return _({result:{error:VA},stack:o});c.rounds.push(n);let d=Mc({tournamentRecords:t,schedulingProfile:s});return d.error?d:{...C}}function rw({schedulingProfile:t,tournamentRecord:e}){if(typeof t!="object")return{error:G};let r=as({tournamentRecord:e}).containedStructures,n=Te({tournamentRecord:e}).matchUps??[],{tournamentId:o}=e,i=[];for(let s of t){let{scheduleDate:a,venues:c=[]}=s;for(let u of c){let{rounds:p,venueId:m}=u;for(let d of p){let{drawId:l,winnerFinishingPositionRange:f,roundSegment:g}=d,h=n.filter(S=>{let T=f?.indexOf("-")>0&&f.split("-").map(P=>+P),y=S.finishingPositionRange?.winner;return S.drawId===l&&(!d.roundNumber||S.roundNumber===d.roundNumber)&&(!y||!T||Yt(y,T).length===2||ut(y).length===ut(T).length&&Yt(y,T).length===ut(y).length)})[0];if(h){let{eventId:S,roundNumber:T,drawName:y,structureName:P,roundName:U}=h,E=h.structureId;T&&!f&&(E=Object.keys(r).find(D=>r[D].includes(E))??E);let A={tournamentId:o,structureId:E,roundNumber:T,roundSegment:g,eventId:S,drawId:l},N=dI({tournamentRecords:{[o]:e},round:A,scheduleDate:a,venueId:m});if(N.error)return N;i.push({structureName:P,roundName:U,drawName:y,...A})}}}}return{scheduledRounds:i}}function dm(t){let e=rt(t,[{drawProfile:!0,_ofType:Kr}]);if(e.error)return e;let{allUniqueParticipantIds:r=[],participantsProfile:n={},matchUpStatusProfile:o,completeAllMatchUps:i,autoEntryPositions:s,hydrateCollections:a,randomWinningSide:c,ratingsParameters:u,tournamentRecord:p,isMock:m=!0,drawProfile:d,startDate:l,drawIndex:f,uuids:g}=t,I=J(d,!1,!0),{excessParticipantAlternates:h=!0,matchUpFormat:S=Dn,drawType:T=go,tournamentAlternates:y=0,alternatesCount:P=0,qualifyingPositions:U,qualifyingProfiles:E,generate:A=!0,eventExtensions:N,drawExtensions:D,completionGoal:M,tieFormatName:R,buildTeams:b,seedsCount:v,timeItems:O,drawName:x,category:F,idPrefix:L,publish:w,gender:V,stage:k}=I,W=I.drawSize||(I.ignoreDefaults?void 0:32),H=I.eventId||Dt(),K=d.eventType||d.matchUpType||jn,q=K===qr?ft:Tt,B=ht(d.tieFormat)&&d.tieFormat||K===Lt&&Zn({event:{eventId:H,category:F,gender:V},namedFormat:R,hydrateCollections:a,isMock:m})||void 0,$=F?.categoryName||F?.ageCategoryCode||F?.ratingType,z=d.eventName||$||`Generated ${K}`,j=p?.participants||[],tt=(E?.map(Pt=>Pt.structureProfiles||[]).flat().reduce((Pt,ae)=>{let re=!ae.participantsCount||ae.participantsCount>ae.drawSize?ae.drawSize:ae.participantsCount||0;return Pt+re},0)||0)*(q===ft?2:1),Q=(!d.participantsCount||d.participantsCount>W?W:d.participantsCount)||0,X={eventName:z,eventType:K,tieFormat:B,category:F,eventId:H,gender:V};Array.isArray(O)&&O.forEach(Pt=>zi({event:X,timeItem:Pt}));let{eventAttributes:lt}=d;if(typeof lt!="object"&&(lt={}),Object.assign(X,lt),N?.length&&Array.isArray(N)){let Pt=N.filter(wn);Pt?.length&&Object.assign(X,{extensions:Pt})}let it=[];if(n?.participantsCount===0||d.uniqueParticipants||tt||!p||V||F){let Pt=(Q||0)+P+tt,ae=Pt,re={[$t]:0,[ne]:0},pr,Jt;K===Lt&&({teamSize:pr,genders:Jt}=Al({alternatesCount:P,tieFormatName:R,tieFormat:B,drawSize:W}),Object.keys(Jt).forEach(pe=>{[$t,ne].includes(pe)&&Jt[pe]&&(re[pe]=W*Jt[pe])}),ae=pr*((W||0)+tt));let Wt=n?.idPrefix?`D-${f}-${n?.idPrefix}`:void 0,zt=sa({...n,scaledParticipantsCount:d.scaledParticipantsCount||n.scaledParticipantsCount,participantsCount:ae,consideredDate:p?.startDate,sex:V||n?.sex,rankingRange:d.rankingRange,uuids:d.uuids||g,ratingsParameters:u,participantType:q,gendersCount:re,idPrefix:Wt,category:F}).participants;if(X.category&&(X.category.categoryName=$),p){let pe=Sn({participants:zt,tournamentRecord:p});if(pe.error)return pe}if(zt.forEach(({participantId:pe})=>it.push(pe)),j=zt,K===Lt){let pe=Jt[$t]?zt.filter(({participantType:be,person:Ar})=>be===Tt&&Ar?.sex===$t).map(St):[],Pe=Jt[ne]?zt.filter(({participantType:be,person:Ar})=>be===Tt&&Ar?.sex===ne).map(St):[],Or=zt.filter(({participantType:be})=>be===Tt).map(St).filter(be=>!pe.includes(be)&&!Pe.includes(be)),Je=[...I.teamNames??[],...mm({count:Pt}).names],De=pr-(Jt[$t]+Jt[ne]),Ee=0,ge=0,_r=0,fr=et(0,Pt).map(be=>{let Ar=Pe.slice(Ee,Ee+Jt[ne]),Zi=pe.slice(ge,ge+Jt[$t]),Tn=Or.slice(_r,_r+De);Ee+=Jt[ne],ge+=Jt[$t],_r+=De;let ts=b!==!1?[...Ar,...Zi,...Tn]:[];return{participantName:Je[be]||`Team ${be+1}`,participantOtherName:`TM${be+1}`,participantRole:xe,individualParticipantIds:ts,participantType:Lt,participantId:Dt()}}),uo=Sn({participants:fr,tournamentRecord:p});if(!uo.success)return uo;j=fr}}let Rt=Pt=>{let{participantType:ae}=Pt;return ue(jn)(K)&&ae===Tt||ue(qr)(K)&&ae===ft?!0:K===Lt&&ae===Lt},Ft=Pt=>!d.gender||Pt.person?.sex===d.gender?!0:Pt.individualParticipantIds?.some(ae=>{let re=j.find(pr=>pr.participantId===ae);return re&&Ft(re)}),Ue=j.filter(Rt).filter(Ft).filter(({participantId:Pt})=>!r.includes(Pt)),fe=Ue.slice(0,Q).map(Pt=>Pt.participantId);if(m&&fe?.length){let Pt=Fn({autoEntryPositions:s,entryStage:k,tournamentRecord:p,participantIds:fe,event:X});if(Pt.error)return Pt}let Me=tt?Ue.slice(Q,Q+tt).map(Pt=>Pt.participantId):0;if(m&&Me?.length){let Pt=0,ae=1,re=(Jt,Wt)=>Jt.stageSequence-Wt.stageSequence,pr=(Jt,Wt)=>Jt.roundTarget-Wt.roundTarget;for(let Jt of E.sort(pr)){ae=Jt.roundTarget||ae;let Wt=1,mr;for(let zt of Jt.structureProfiles.sort(re)){let Pe=(zt.drawSize||hm(zt.participantsCount))-(mr||0),Or=Me.slice(Pt,Pt+Pe),Je=Fn({entryStage:ct,entryStageSequence:Wt,autoEntryPositions:s,tournamentRecord:p,participantIds:Or,roundTarget:ae,event:X});if(Je.error)return Je;mr=zt.qualifyingPositions,Pt+=Pe,Wt+=1}ae+=1}}let vr=h&&p?.participants?.filter(({participantId:Pt})=>!fe.includes(Pt)).filter(Rt).filter(Ft).slice(0,P||W-Q||y).map(Pt=>Pt.participantId);if(m&&vr?.length){let Pt=Fn({participantIds:vr,autoEntryPositions:!1,entryStatus:nn,tournamentRecord:p,event:X});if(Pt.error)return Pt.error}let Zr=$||z;p&&v&&v<=fe.length&&et(1,v+1).forEach((ae,re)=>{let pr={scaleName:Zr,scaleDate:l,scaleType:rg,scaleValue:ae,eventType:K},Jt=fe[re];Dc({tournamentRecord:p,participantId:Jt,scaleItem:pr})});let lr=xa({...J(d,!1,!0),tournamentRecord:p,seedingScaleName:Zr,matchUpFormat:S,eventId:H,isMock:m,event:X});if(lr.error)return lr;if(!lr.drawDefinition)return{error:Mr};let{drawDefinition:Xe}=lr,ee=Xe.drawId;if(Array.isArray(D)&&D.filter(wn).forEach(Pt=>At({element:Xe,extension:Pt})),A){if(Cc({drawDefinition:Xe,event:X,suppressNotifications:!0}),d.withPlayoffs){let ae=Xe.structures?.[0].structureId,re=kp({...d.withPlayoffs,tournamentRecord:p,drawDefinition:Xe,structureId:ae,idPrefix:L,isMock:m,event:X});if(re?.error)return re}let Pt=d.automated===!1;if(m&&!Pt){let ae=re=>{let pr=El({completeAllMatchUps:re.completeAllMatchUps,completionGoal:re.completionGoal,matchUpStatusProfile:o,randomWinningSide:c,tournamentRecord:p,drawDefinition:Xe,matchUpFormat:S,event:X});if(pr.error)return pr;let Jt=pr.completedCount;if(T===Io){let Wt=Xe.structures?.find(pe=>pe.stage===nt);if(!Wt)return{error:kt};Ks({structureId:Wt.structureId,tournamentRecord:p,drawDefinition:Xe,event:X});let mr=M?M-(Jt??0):void 0,zt=El({completionGoal:M?mr:void 0,matchUpStatusProfile:o,completeAllMatchUps:i,randomWinningSide:c,tournamentRecord:p,drawDefinition:Xe,matchUpFormat:S,event:X});if(zt.error)return zt}};if(M&&ae({completionGoal:M}),d.outcomes){let{matchUps:re}=or({inContext:!0,drawDefinition:Xe,event:X});for(let pr of d.outcomes){let{matchUpStatus:Jt=le,matchUpStatusCodes:Wt,stageSequence:mr=1,matchUpIndex:zt=0,structureOrder:pe,matchUpFormat:Pe,drawPositions:Or,roundPosition:Je,stage:De=nt,roundNumber:Ee,winningSide:ge,scoreString:_r}=pr,fr=re?.reduce((Tn,ts)=>{let{structureId:ju,matchUpId:iC}=ts;return Tn[ju]?Tn[ju].push(iC):Tn[ju]=[iC],Tn},{})??[],uo=Object.assign({},...Object.keys(fr).map((Tn,ts)=>({[Tn]:ts+1}))),Ar=re?.filter(Tn=>(!De||Tn.stage===De)&&(!mr||Tn.stageSequence===mr)&&(!Ee||Tn.roundNumber===Ee)&&(!Je||Tn.roundPosition===Je)&&(!pe||uo[Tn.structureId]===pe)&&(!Or||Yt(Or,Tn.drawPositions).length===2))?.[zt],Zi=EM({matchUpStatusCodes:Wt,tournamentRecord:p,drawDefinition:Xe,targetMatchUp:Ar,matchUpFormat:Pe,matchUpStatus:Jt,scoreString:_r,winningSide:ge});if(Zi?.error)return Zi}}i&&ae({completeAllMatchUps:i})}w&&oa({tournamentRecord:p,event:X})}else{let Pt=Zp({drawEntries:Xe.entries,drawName:x||T,qualifyingPositions:U,drawId:ee,event:X,stage:k});if(Pt.error)return Pt}return{...C,event:ot(X),uniqueParticipantIds:it,targetParticipants:j,drawDefinition:Xe,eventId:H,drawId:ee}}var UM=()=>({altitude:void 0,courtId:void 0,courtName:"",courtDimensions:void 0,latitude:void 0,longitude:void 0,surfaceCategory:void 0,surfaceType:void 0,surfacedDate:void 0,dateAvailability:[],onlineResources:[],pace:void 0,notes:void 0}),nw=UM;function aA(t){return parseInt(t)}function PM({startTime:t="",endTime:e=""}={}){if(!t||!e||!xs.test(t)||!xs.test(e))return!1;let[r,n]=t.split(":").map(aA),[o,i]=e.split(":").map(aA);return o<r?!1:!(r===o&&i<n)}function ow(t,e){let[r,n]=t.startTime.split(":").map(aA),[o,i]=e.startTime.split(":").map(aA);return r<o?-1:r>o?1:n<i?-1:n>i?1:0}function cA({dateAvailability:t}){if(!t)return{error:eE};if(!Array.isArray(t))return{error:ql};let e="Dates must be formated => YYYY-MM-DD",r="Times must be 24 hour => 00:00";for(let n of t){if(typeof n!="object")return{error:ql};let{date:o,startTime:i,endTime:s,bookings:a=[]}=n;if(!i||!s)return{error:ql};if(o&&!Po.test(o))return{error:je,dateAvailability:{date:o},info:e};if(!xs.test(i))return{error:Eo,dateAvailability:{startTime:i},info:r};if(!xs.test(s))return{error:Eo,dateAvailability:{endTime:s},info:r};if(i===s)return{error:Eo,dateAvailability:{startTime:i,endTime:s},info:"startTime and endTime are equivalent"};if(!PM({startTime:i,endTime:s}))return{error:Eo,dateAvailability:{startTime:i,endTime:s},info:"endTime must be after startTime"};if(a){if(!Array.isArray(a))return{error:Am};for(let c of a){if(typeof c!="object")return{error:Am};let{startTime:u,endTime:p}=c;if(!xs.test(u))return{error:Eo,booking:{startTime:u},info:r};if(!xs.test(p))return{error:Eo,booking:{endTime:p},info:r};if(u===p)return{error:Eo,dateAvailability:{startTime:u,endTime:p},info:"startTime and endTime are equivalent"};if(!PM({startTime:u,endTime:p}))return{error:Eo,dateAvailability:{startTime:u,endTime:p},info:"endTime must be after startTime"}}}}return{valid:!0}}function Ul({tournamentRecord:t,disableNotice:e,venueId:r,courtId:n,court:o}){let{venue:i}=Wo({tournamentRecord:t,venueId:r});if(!i)return{error:Li};i.courts||(i.courts=[]);let s={...UM(),venueId:r,courtId:n};if(s.courtId||(s.courtId=Dt()),i.courts.some(c=>c.courtId===s.courtId))return{error:hE};{let c=(o?.dateAvailability||[]).map(m=>({...m,date:Et(m.date),startTime:Kt(m.startTime),endTime:Kt(m.endTime),bookings:m.bookings?.map(({startTime:d,endTime:l,bookingType:f})=>({startTime:Kt(d),endTime:Kt(l),bookingType:f}))})),u=Object.keys(s);for(let m of u)if(o?.[m])if(m==="dateAvailability"){let d=cA({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||mt({payload:{venue:i,tournamentId:t.tournamentId},topic:yi,key:i.venueId}),{...C,court:J(s),venueId:r}}}function lI(t){let{tournamentRecord:e,venueId:r}=t;if(typeof r!="string"||!r)return{error:Xo};let n=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},o=[],i;for(let s of Object.values(n)){let{venue:a}=Wo({tournamentRecord:s,venueId:r});if(a){let c=B1({...t,tournamentRecord:s});for(let u of c?.courts??[])o.push(u?.courtId);if(c.error)return c;i=!0}}return i?{...C,courtIds:o}:{error:Li}}function B1({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:Xo};let l=Wo({tournamentRecord:n,venueId:m});if(l.error)return l;let{venue:f}=l;if(!Zt(s)||!o)return{error:IE};s=s??o.length;let h=et(0,s).map(S=>{let T=i?.[S],y=T?d.map(P=>({date:Hn(P),startTime:a,endTime:u,...T})):e;return T&&a&&u&&y.push({startTime:a,endTime:u}),{courtName:o[S]||r&&f?.venueAbbreviation&&`${f?.venueAbbreviation} ${S+1}`||`${t} ${S+1}`,dateAvailability:y}}).map((S,T)=>{let y=c?.pop()||p&&`${p}-${T+1}`;return Ul({disableNotice:!0,tournamentRecord:n,courtId:y,venueId:m,court:S})}).map(S=>S.court).filter(Boolean);return h.length!==s?_({info:"not all courts could be generated",result:{error:G}}):(f&&mt({payload:{venue:f,tournamentId:n.tournamentId},topic:yi,key:f.venueId}),{...C,courts:J(h)})}function Pl({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()??Dt(),dateAvailability:m,startTime:d="07:00",endTime:l="19:00",courtTimings:f,courtsCount:g,courtNames:I,venueName:h,idPrefix:S,courtIds:T}=c,y={venueName:h||`Venue ${a+1}`,venueAbbreviation:u,venueId:p},P=mc({tournamentRecord:t,venue:y});if(P.error){if(e)continue;return P}s.push(p);let U=ws(o,i),E=!Array.isArray(m)&&[{startTime:d,endTime:l}].concat(U.map(A=>({date:Hn(A),startTime:d,endTime:l})));if(g||I){let A=lI({dateAvailability:m||E,tournamentRecord:t,courtTimings:f,courtsCount:g,courtNames:I,startTime:d,idPrefix:S,courtIds:T,endTime:l,venueId:p,dates:U});if(A.error)return A}}return s}function iw(t){let{tournamentRecord:e,leagueProfiles:r,eventIds:n,venueIds:o,drawIds:i,allUniqueParticipantIds:s,uuids:a}=t,c=0;for(let p of r){let m=[],{tieFormatName:d=vm,teamProfiles:l=[],teamsCount:f=0,category:g,idPrefix:I,gender:h}=p,S=p.leagueName??p.eventName??`League ${c+1}`,T=p.leagueId??p.eventId??a?.pop()??Dt();n.push(T);let y=ht(p.tieFormat)&&p.tieFormat||Zn({event:{eventId:T,category:g,gender:h},namedFormat:d,isMock:t.isMock})||void 0;if(!y)return{error:bs};let P=Math.max(f,l.length),U=et(0,P),{genders:E,teamSize:A}=Al({tieFormat:y,drawSize:P}),N={[ne]:0,[Tr]:0,[os]:0,[$t]:0,[Pn]:0};Object.keys(E).forEach(R=>N[R]+=E[R]);for(let R of U){let b=l?.[R]?.teamName??`Team ${R+1}`,v=l?.[R]?.teamId||a?.pop()||Dt(),O=p.startDate??t.startDate,x=sa({...p?.participantsProfile,participantsCount:A,consideredDate:O,gendersCount:N,category:g,gender:h,uuids:a}).participants,F=x.map(H=>H.participantId),L=Lt,w=v??pm({participantType:L,idPrefix:I,index:R,uuids:a});m.push({participantId:w,entryStatus:kr,entryStage:nt});let V=l?.[R]?.venueIds??[],k={participantId:w,participantRole:xe,participantName:b,individualParticipantIds:F,participantType:L,homeVenueIds:V};V.forEach(H=>!o.includes(H)&&o.push(H)),s.push(...F),s.push(w);let W=Sn({participants:[k,...x],tournamentRecord:e});if(W.error)return W}let M={eventName:S,entries:m,eventType:Lt,tieFormat:y,category:g,eventId:T,gender:h};if(e.events||(e.events=[]),e.events.push(M),m.length){let R=(Zt(p.roundsCount)&&p.roundsCount)??p.roundsCount===JC?(P-1)*2:P-1,b=xa({automated:p.automated,tournamentRecord:e,drawType:$r,roundsCount:R,drawSize:P,event:M});if(b.error)return b;let{drawDefinition:v}=b;if(v){let O=v?.drawId;Cc({drawDefinition:v,event:M,suppressNotifications:!0}),i.push(O)}}c++}let u=o.map(p=>({venueId:p}));Pl({tournamentRecord:e,ignoreExistingVenues:!0,venueProfiles:u,uuids:a})}var H1=["Generated Tournament","CourtHive Challenge","Replication Crisis","Open Competition","Factory Follies","Mock Tournament","Atomic Culture","Racket Rally","Stats Fail"];function DM(t){let{startDate:e,endDate:r}=t??{},{tournamentName:n=tn(H1),ratingsParameters:o=we,tournamentExtensions:i,policyDefinitions:s,schedulingProfile:a,venueProfiles:c,uuids:u}=t??{},p=t?.isMock===!1?void 0:!0;if(e&&!Rr(e)||r&&!Rr(r))return{error:je};if(t.leagueProfiles&&!Array.isArray(t.leagueProfiles)||t.eventProfiles&&!Array.isArray(t.eventProfiles)||t.drawProfiles&&!Array.isArray(t.drawProfiles))return{error:G};if(!e){let S=new Date;e=Hn(r??S),r=Hn(S.setDate(S.getDate()+7))}if(!r){let S=new Date(e);r=Hn(S.setDate(S.getDate()+7))}let m=um({...t.tournamentAttributes??{},tournamentName:n,startDate:e,endDate:r,isMock:p}),d=c?.length?Pl({tournamentRecord:m,venueProfiles:c,uuids:u}):[];if(i?.length&&Array.isArray(i)){let S=i.filter(T=>wn({extension:T}));S?.length&&Object.assign(m,{extensions:S,isMock:p})}if(typeof s=="object")for(let S of Object.keys(s))Qi({policyDefinitions:{[S]:s[S]},tournamentRecord:m});if(!t?.leagueProfiles?.length||t.eventProfiles?.length||t.drawProfiles?.length||t.participantsProfile){let S=tA({tournamentRecord:m,...t});if(!S.success)return S}let l=[],f=[],g=[];if(t.leagueProfiles){let S=iw({allUniqueParticipantIds:l,tournamentRecord:m,...t,eventIds:f,venueIds:d,drawIds:g});if(S?.error)return S}if(t.drawProfiles){let S=W1({allUniqueParticipantIds:l,ratingsParameters:o,tournamentRecord:m,...t,eventIds:f,drawIds:g});if(S?.error)return S}if(t.eventProfiles){let S=j1({allUniqueParticipantIds:l,ratingsParameters:o,tournamentRecord:m,...t,eventIds:f,drawIds:g});if(S?.error)return S}let{scheduledRounds:I=void 0,schedulerResult:h={}}=a?Y1({...t,tournamentRecord:m}):{};return cf(),ot({...C,tournamentRecord:m,scheduledRounds:I,schedulerResult:h,eventIds:f,venueIds:d,drawIds:g})}function W1(t){let{tournamentRecord:e,drawProfiles:r,allUniqueParticipantIds:n,eventIds:o,drawIds:i}=t,s=0;for(let a of r){let c=dm({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=ra({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 j1(t){let{eventProfiles:e,allUniqueParticipantIds:r,eventIds:n,drawIds:o}=t,i=0;for(let s of e){let a=sA({...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 Y1(t){let{schedulingProfile:e,tournamentRecord:r,autoSchedule:n,periodLength:o,scheduleCompletedMatchUps:i}=t,s=rw({schedulingProfile:e,tournamentRecord:r});if(s.error)return s;let a=s.scheduledRounds;if(n){let{tournamentId:c}=r,u={[c]:r};return{schedulerResult:cm({scheduleCompletedMatchUps:i,tournamentRecords:u,periodLength:o}),scheduledRounds:a}}return{scheduledRounds:a}}var CM={};Xt(CM,{anonymizeTournamentRecord:()=>MM,modifyTournamentRecord:()=>RM});function MM({keepExtensions:t=[],anonymizeParticipantNames:e=!0,tournamentRecord:r,tournamentName:n,personIds:o=[],tournamentId:i}){if(!r)return{error:Y};let s=Array.isArray(t)?TU.concat(...t):TU,a=w=>Array.isArray(t)?w?.extensions?.filter(V=>s.includes(V.name)):w?.extensions,c={};r.extensions=a(r);let u=i||Dt();c[r.tournamentId]=u,r.tournamentId=u,r.createdAt=new Date().toISOString(),r.tournamentName=n||`Anonymized: ${Hn(new Date)}`,r.isMock=!0,delete r.parentOrganisation;for(let w of r.participants||[]){w.extensions=a(w),w.onlineResources=[];let V=Dt();c[w.participantId]=V,w.participantId=V}for(let w of r.participants||[])Array.isArray(w.individualParticipantIds)&&(w.individualParticipantIds=w.individualParticipantIds.map(V=>c[V]));let p=0;for(let w of r.venues||[]){w.venueAbbreviation=`V${p}`,w.extensions=a(w),w.venueName=`Venue #${p}`,w.onlineResources=[],w.addresses=[];let V=Dt();c[w.venueId]=V,w.isMock=!0,p+=1;let k=0;for(let W of w.courts||[])W.courtName=`V${p}C${k}`,W.extensions=a(W),W.onlineResources=[],W.isMock=!0,k+=1}let m=1;for(let w of r.events||[]){w.extensions=a(w),w.onlineResources=[],w.isMock=!0;let V=Dt();c[w.eventId]=V,w.eventId=V;let k=w.category?.categoryName||w.category?.ageCategoryCode||w.category?.ratingType||w.gender;if(w.eventName=`Event ${m} ${k}`,Array.isArray(w.entries))for(let H of w.entries)H.participantId=c[H.participantId];for(let H of w.drawDefinitions||[]){H.extensions=a(H);let K=Dt();if(c[H.drawId]=K,H.drawId=K,H.isMock=!0,Array.isArray(H.entries))for(let B of H.entries)B.participantId=c[B.participantId];let q=B=>{B.extensions=a(B);let $=Dt();c[B.structureId]=$,B.structureId=$;for(let z of B.positionAssignments||[])z.participantId&&(z.participantId=c[z.participantId]);for(let z of B.seedAssignments||[])z.participantId&&(z.participantId=c[z.participantId]);for(let z of B.matchUps||[]){z.isMock=!0;for(let j of z.sides||[])j.lineUp&&(j.lineUp=j.lineUp.map(({participantId:tt,collectionAssignments:Q})=>({participantId:c[tt],collectionAssignments:Q})))}};for(let B of H.structures||[])if(q(B),Array.isArray(B.structures))for(let $ of B.structures)q($);for(let B of H.links||[])B.source.structureId=c[B.source.structureId],B.target.structureId=c[B.target.structureId]}let{extension:W}=dt({name:un,element:w});Array.isArray(W?.value?.flights)&&W?.value.flights?.forEach(H=>{if(H.drawId=c[H.drawId],Array.isArray(H.drawEntries))for(let K of H.drawEntries)K.participantId=c[K.participantId]}),m+=1}let d=r.startDate||Hn(new Date),l=(r.participants||[]).filter(({participantType:w})=>w===Tt),f=l.reduce((w,V)=>{let k=V.person?.sex;return[$t,ne].includes(k)?w[k]+=1:w[os]+=1,w},{[$t]:0,[ne]:0,[os]:0}),g=Object.assign({},...Object.keys(f).map(w=>({[w]:Jy({category:{ageCategoryCode:"O18"},count:f[w],addressProps:{citiesCount:10},personExtensions:[],consideredDate:d,sex:w})?.persons||[]}))),I={[$t]:0,[ne]:0,[os]:0},h=l.length,S=l.reduce((w,V)=>{let k=V.person?.addresses?.[0]||{},{city:W,state:H,postalCode:K}=k;return w.cities.includes(W)||w.cities.push(W),w.states.includes(H)||w.states.push(H),w.postalCodes.includes(K)||w.postalCodes.push(K),w},{cities:[],postalCodes:[],states:[]}),T=S.postalCodes.length,y=S.cities.length,P=S.states.length,{cities:U}=$y({count:y||h,participantsCount:h}),{states:E}=Ky({count:P||h,participantsCount:h}),{postalCodes:A}=zy({count:T||h,participantsCount:h}),N={cities:U,states:E,postalCodes:A};l.forEach((w,V)=>{let k=w?.person,W=k?.sex||os,H=Et(k?.birthDate)?.split("-")[0],K=I[W],q=g[W][K];if(I[W]+=1,H){let[,B,$]=q?.birthDate?.split("-")||[],z=[H,B,$].join("-");q.birthDate=z}if(k?.addresses){let B=Qy({...N,participantIndex:V,nationalityCode:q.nationalityCode});q.addresses=[B]}q.personId=o?.[V]||Dt(),e?(q.standardFamilyName=q.lastName,q.standardGivenName=q.firstName,w.participantName=`${q.standardGivenName} ${q.standardFamilyName}`):(q.standardFamilyName=k?.standardFamilyName,q.standardGivenName=k?.standardGivenName),delete q.firstName,delete q.lastName,q.extensions=a(k),w.person=q,c[k?.personId]=q.personId}),(r.participants||[]).filter(({participantType:w})=>w===ft).forEach(w=>{let{individualParticipantIds:V}=w;w.participantName=q1({individualParticipantIds:V,individualParticipants:l})});let M=(r.participants||[]).filter(({participantType:w})=>w===Lt),R=M.length,b=mm({count:R}).names;M.forEach((w,V)=>{w.participantName=b[V]});let v=(r.participants||[]).filter(({participantType:w})=>w===zr),O=v.length,x=mm({count:O,nameRoot:"Group"}).names;v.forEach((w,V)=>{w.participantName=x[V]});let{extension:F}=dt({element:r,name:Sa});Array.isArray(F?.value)&&F?.value.forEach(w=>{w.tournamentId=c[w.tournamentId],w.structureId=c[w.structureId],w.eventId=c[w.eventId],w.drawId=c[w.drawId]});let{extension:L}=dt({element:r,name:ha});return Array.isArray(L?.value)&&L?.value.forEach(w=>{w.personId=c[w.personId]}),{...C}}function q1({individualParticipantIds:t,individualParticipants:e}){let r=e.filter(({participantId:n})=>t.includes(n)).map(({person:n})=>n?.standardFamilyName).filter(Boolean).sort().join("/");return t.length===1&&(r+="/Unknown"),r}function RM(t){let{ratingsParameters:e=we,participantsProfile:r={},matchUpStatusProfile:n,completeAllMatchUps:o,autoEntryPositions:i,hydrateCollections:s,randomWinningSide:a,schedulingProfile:c,tournamentRecord:u,autoSchedule:p,eventProfiles:m,periodLength:d,venueProfiles:l,drawProfiles:f,isMock:g,uuids:I}=t;if(!u)return{error:Y};let h=[],S=[],T=[];m?.forEach(D=>{let M=u.events?.find((R,b)=>D.eventIndex!==void 0&&b===D.eventIndex||D.eventName&&R.eventName===D.eventName||D.eventId&&R.eventId===D.eventId);M?.gender&&(D.gender=M.gender)});let y=u.participants?.length||void 0;y&&r?.idPrefix&&(r.idPrefix=`${r.idPrefix}-${y}`);let P=tA({startDate:u.startDate,participantsProfile:r,tournamentRecord:u,eventProfiles:m,drawProfiles:f,uuids:I});if(!P.success)return P;if(m){let D=u.events?.length||0;for(let M of m){let{ratingsParameters:R}=M,b=u.events?.find((v,O)=>M.eventIndex!==void 0&&O===M.eventIndex||M.eventName&&v.eventName===M.eventName||M.eventId&&v.eventId===M.eventId);if(b){let{gender:v,category:O,eventType:x}=b,{drawProfiles:F,publish:L}=M,w=ue(jn)(x)&&Tt||ue(qr)(x)&&ft||x;if(F){let{stageParticipantsCount:V,uniqueParticipantsCount:k,uniqueParticipantStages:W}=eA({drawProfiles:F,category:O,gender:v}),{uniqueDrawParticipants:H=[],uniqueParticipantIds:K=[]}=W?oA({event:{eventType:x,category:O,gender:v},uniqueParticipantsCount:k,participantsProfile:r,ratingsParameters:R,tournamentRecord:u,eventProfile:M,uuids:I}):{};h.push(...K);let{stageParticipants:q}=rA({targetParticipants:u.participants||[],allUniqueParticipantIds:h,stageParticipantsCount:V,eventParticipantType:w}),B=iA({uniqueDrawParticipants:H,autoEntryPositions:i,stageParticipants:q,tournamentRecord:u,drawProfiles:F,category:O,gender:v,event:b});if(B.error||(B=nA({matchUpStatusProfile:n,completeAllMatchUps:o,randomWinningSide:a,tournamentRecord:u,drawProfiles:F,isMock:g,event:b}),B.error))return B;T.push(...B.drawIds)}L&&oa({tournamentRecord:u,event:b})}else{let v=sA({startDate:u.startDate,allUniqueParticipantIds:h,matchUpStatusProfile:n,participantsProfile:r,completeAllMatchUps:o,autoEntryPositions:i,randomWinningSide:a,ratingsParameters:R,tournamentRecord:u,eventProfile:M,eventIndex:D,uuids:I});if(v.error)return v;let{eventId:O,drawIds:x,uniqueParticipantIds:F}=v;x&&T.push(...x),S.push(O),F?.length&&h.push(...F),D+=1}}}if(f){let D=(u.events||[]).map(M=>M.drawDefinitions?.map(()=>1)||[]).flat().reduce((M,R)=>M+R,0);for(let M of f){let R=dm({startDate:u.startDate,allUniqueParticipantIds:h,matchUpStatusProfile:n,participantsProfile:r,completeAllMatchUps:o,autoEntryPositions:i,hydrateCollections:s,randomWinningSide:a,ratingsParameters:e,tournamentRecord:u,drawProfile:M,drawIndex:D,uuids:I});if(R.error)return R;let{drawId:b,eventId:v,event:O,uniqueParticipantIds:x}=R;if(R=ra({tournamentRecord:u,event:O,internalUse:!0}),R.error)return R;b&&T.push(b),S.push(v),x?.length&&h.push(...x),D+=1}}let U=l?.length?Pl({tournamentRecord:u,venueProfiles:l}):[],E,A={};if(c?.length){let D={[u.tournamentId]:u},M=Mc({tournamentRecords:D,schedulingProfile:c});if(M.error)return M;if(p){let{tournamentId:R}=u,b={[R]:u};A=cm({tournamentRecords:b,periodLength:d})}}return{totalParticipantsCount:u.participants.length,scheduledRounds:E,schedulerResult:A,...C,eventIds:S,venueIds:U,drawIds:T}}var QM={};Xt(QM,{addDynamicRatings:()=>wg,addIndividualParticipantIds:()=>em,addParticipant:()=>bn,addParticipants:()=>Sn,addPenalty:()=>$M,addPersonRequests:()=>OM,addPersons:()=>KM,createGroupParticipant:()=>GM,createTeamsFromParticipantAttributes:()=>pI,deleteParticipants:()=>$i,filterParticipants:()=>yu,findParticipant:()=>kM,getCompetitionParticipants:()=>kT,getPairedParticipant:()=>In,getParticipantEventDetails:()=>GT,getParticipantMembership:()=>VT,getParticipantScaleItem:()=>Nc,getParticipantSchedules:()=>BT,getParticipantSignInStatus:()=>HT,getParticipantTimeItem:()=>Qh,getParticipants:()=>Gt,getScaleValues:()=>la,mergeParticipants:()=>qM,modifyIndividualParticipantIds:()=>_M,modifyParticipant:()=>rm,modifyParticipantName:()=>VM,modifyParticipantOtherName:()=>wM,modifyParticipantsSignInStatus:()=>xM,modifyPenalty:()=>jM,modifyPersonRequests:()=>bM,mutate:()=>zM,participantScaleItem:()=>yo,query:()=>iN,regenerateParticipantNames:()=>FM,removeIndividualParticipantIds:()=>cg,removeParticipantIdsFromAllTeams:()=>Rp,removePenalty:()=>WM,removePersonRequests:()=>vM,removeRatings:()=>HM,scaledTeamAssignment:()=>BM,setParticipantScaleItem:()=>Dc,setParticipantScaleItems:()=>mD,validateLineUp:()=>Td});var zM={};Xt(zM,{addDynamicRatings:()=>wg,addIndividualParticipantIds:()=>em,addParticipant:()=>bn,addParticipants:()=>Sn,addPenalty:()=>$M,addPersonRequests:()=>OM,addPersons:()=>KM,createGroupParticipant:()=>GM,createTeamsFromParticipantAttributes:()=>pI,deleteParticipants:()=>$i,findParticipant:()=>kM,mergeParticipants:()=>qM,modifyIndividualParticipantIds:()=>_M,modifyParticipant:()=>rm,modifyParticipantName:()=>VM,modifyParticipantOtherName:()=>wM,modifyParticipantsSignInStatus:()=>xM,modifyPenalty:()=>jM,modifyPersonRequests:()=>bM,regenerateParticipantNames:()=>FM,removeIndividualParticipantIds:()=>cg,removeParticipantIdsFromAllTeams:()=>Rp,removePenalty:()=>WM,removePersonRequests:()=>vM,removeRatings:()=>HM,scaledTeamAssignment:()=>BM,setParticipantScaleItem:()=>Dc,setParticipantScaleItems:()=>mD});function uA(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 pA({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===_c&&(i=Et(i),s=Kt(s),a=Kt(a),i&&s&&a)?{date:i,startTime:s,endTime:a,requestType:o.requestType}:o}).filter(Boolean);for(let o of n)o.requestId=uA(),t[e].push(o);return{mergeCount:n.length}}function Dl(t){let{tournamentRecords:e,personRequests:r}=t,n=rt(t,[{[Re]:!0}]);if(n.error)return n;if(!r)return{...C};let o=Object.values(e);for(let i of o){let s=i.participants??[],a=[];for(let c of Object.keys(r))if(Go({tournamentParticipants:s,personId:c})){let u=r[c];u.length&&a.push({personId:c,requests:u})}Object.keys(a).length&&At({element:i,extension:{value:a,name:ha}})}return{...C}}function bM(t){let{tournamentRecords:e,requests:r,personId:n}=t,o=rt(t,[{[Re]:!0},{requests:!0,[He]:Be,[Fr]:G}]);if(o.error)return o;let i=r.map(({requestId:u})=>u).filter(Boolean),{personRequests:s}=bi({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&&pA({personRequests:s,personId:n,requests:c}),Dl({tournamentRecords:e,personRequests:s})}function vM(t){let{tournamentRecords:e,requestType:r,requestId:n,personId:o,date:i}=t,s=rt(t,[{[Re]:!0}]);if(s.error)return s;let{personRequests:a}=bi({tournamentRecords:e}),c=p=>{a&&(a[p]=a[p].filter(m=>(!r||m.requestType!==r)&&(!n||m.requestId!==n)&&(!i||m.date!==i)),a?.[p]?.length||delete a[p])},u=!r&&!n&&!o&&!i;if(!u){if(o&&a?.[o])c(o);else if(a)for(let p of Object.keys(a))c(p)}return u||!a||!Object.keys(a).length?gr({name:ha,tournamentRecords:e,discover:!0}):Dl({tournamentRecords:e,personRequests:a})}function OM(t){let{tournamentRecords:e,personId:r,requests:n}=t,o=rt(t,[{[Re]:!0,[ob]:!0},{requests:!0,[He]:Be,[Fr]:G}]);if(o.error)return o;let{personRequests:i}=bi({tournamentRecords:e}),{mergeCount:s}=pA({personRequests:i,personId:r,requests:n});return s&&i?Dl({tournamentRecords:e,personRequests:i}):{error:G}}function _M({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:r}){let n="modifyIndividualParticipantIds";if(!r)return _({result:{error:Y},stack:n});if(!e||!t)return _({result:{error:st},stack:n});let o=r.participants||[],i=o.find(l=>l.participantId===e);if(!i)return _({result:{error:te},stack:n});if(![Lt,zr].includes(i.participantType))return _({result:{error:An},context:{participantType:i.participantType},stack:n});let s=t.filter(l=>o.find(g=>g.participantId===l)?.participantType!==Tt);if(s.length)return _({result:{error:wr,invalidParticipantIds:s},stack:n});let a=i.individualParticipantIds||[],c=t.filter(l=>!a.includes(l)),u=a.filter(l=>!t.includes(l)),p=em({individualParticipantIds:c,groupingParticipantId:e,tournamentRecord:r});if(p.error)return _({result:p,stack:n});let m=cg({individualParticipantIds:u,groupingParticipantId:e,tournamentRecord:r});if(m.error)return _({result:m,stack:n});let{topics:d}=Lr();if(d.includes(nr)){let l=o.find(({participantId:f})=>f===e);mt({topic:nr,payload:{tournamentId:r.tournamentId,participants:[l]}})}return{...p,...m}}function xM({tournamentRecord:t,participantIds:e,signInState:r}){if(!t)return{error:Y};if(!Array.isArray(e))return{error:st};if(![pu,LU].includes(r))return{error:G,signInState:r};let o=t.participants||[];if(!o.length)return{error:$a};let i=o.map(St),s=e.filter(p=>!i.includes(p));if(s.length)return{error:G,context:{invalidParticipantIds:s}};let a=[],c=new Date().toISOString();for(let p of o){let{participantId:m}=p;if(e.includes(m)){let l=Rg({duplicateValues:!1,tournamentRecord:t,participantId:m,timeItem:{itemType:sc,itemValue:r,createdAt:c}});if(l.error)return l;a.push(p)}}let{topics:u}=Lr();return a.length&&u.includes(nr)&&mt({topic:nr,payload:{tournamentId:t.tournamentId,participants:a}}),{...C}}function wM({tournamentRecord:t,participantId:e,participantOtherName:r}){if(!t)return{error:Y};if(!e)return{error:oe};let{participant:n}=To({tournamentRecord:t,participantId:e});if(!n)return{error:te};n.participantOtherName=r;let{topics:o}=Lr();return o.includes(nr)&&mt({topic:nr,payload:{tournamentId:t.tournamentId,participants:[n]}}),{...C}}function LM({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=AS(e?.standardGivenName??""),l=AS(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 sw({participantMap:t,participant:e,formats:r}){let{participantType:n,individualParticipantIds:o,person:i}=e,s=n&&r[n];if(n!==yr&&s){let{personFormat:a,doublesJoiner:c}=s;n===Tt&&(e.participantName=LM({person:i,personFormat:a})),n===ft&&(e.participantName=o?.map(u=>{let p=t[u]?.person;return LM({person:p,personFormat:a})}).filter(Boolean).join(c??"/"))}}function FM({tournamentRecord:t,formats:e}){if(!t)return{error:Y};if(!ht(e))return{error:st};let r=t.participants??[],n=RI(r,"participantId");for(let o of r)sw({participant:o,participantMap:n,formats:e});return{...C}}function kM(t){let{tournamentRecord:e,policyDefinitions:r,contextProfile:n,participantId:o,personId:i}=t,s=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(typeof o!="string"&&typeof i!="string")return{error:st,stack:"publicFindParticipant"};let a,c;for(let u of Object.values(s)){c=u.tournamentId;let p=u.participants||[];if(a=Go({tournamentParticipants:p,internalUse:!0,policyDefinitions:r,contextProfile:n,participantId:o,personId:i}),a)break}return{participant:a,tournamentId:c,...C}}function GM({individualParticipantIds:t=[],participantRoleResponsibilities:e,participantRole:r=aP,tournamentRecord:n,participantId:o,groupName:i}){if(!n)return{error:Y};if(!i)return{error:st,info:"Missing groupName"};if(!Array.isArray(t))return{info:"Invalid individualParticipantIds",error:G};let a=(Gt({participantFilters:{participantTypes:[Tt]},tournamentRecord:n}).participants??[]).map(m=>m.participantId);for(let m of t)if(!a.includes(m))return{error:An,participantId:m};let c=ot({participantId:o||Dt(),participantRoleResponsibilities:e,participantName:i,individualParticipantIds:t,participantType:zr,participantRole:r}),u=bn({participant:c,tournamentRecord:n});if(u.error)return u;let{topics:p}=Lr();return p.includes(Zo)&&mt({topic:Zo,payload:{tournamentId:n.tournamentId,participants:[c]}}),{...C,participant:J(c)}}function VM({tournamentRecord:t,participantName:e,participantId:r}){if(!t)return{error:Y};if(!r)return{error:oe};if(!e)return{error:st,info:"Missing participantName"};let{participant:n}=To({tournamentRecord:t,participantId:r});if(!n)return{error:te};n.participantName=e;let{topics:o}=Lr();return o.includes(nr)&&mt({topic:nr,payload:{tournamentId:t.tournamentId,participants:[n]}}),{...C}}function BM({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:Y};if(!Array.isArray(i)&&!It(u)&&!p||!It(n)||o&&!Array.isArray(o)||a&&(typeof a!="object"||!Object.keys(a).length))return{error:G};if(!a&&!o.length||!o&&!(e&&a))return{error:st,info:"Missing scaling details"};if(p&&!i){if(m?.eventType!==Cr)return{error:Bn};i=m?.entries?.filter(({entryStatus:h})=>h===kr).map(St)}if(!i?.length&&!u)return{info:"Missing teamParticipantIds or teamsCount",error:st};let d=e??o.map(({participantId:h})=>h);r&&(i?.reverse(),n+=1),n>(i?.length||0)-1&&(n=0);let l=i?.slice(n).concat(...i.slice(0,n))??[],f=[];for(let h of s.participants??[]){let{participantId:S,participantType:T}=h;if(l.includes(S)){if(T!==yr)return{error:An,participant:h};f.push(h)}}if(u&&f.length<u){let h=u-(f?.length||0),S=c??"Team",T=et(0,h).map(E=>({participantName:`${S} ${E+1}`,participantType:yr,participantRole:xe})),{participants:y=[]}=Sn({participants:T,returnParticipants:!0,tournamentRecord:s}),P=y.map(St),U=s.participants?.filter(({participantId:E})=>P.includes(E))??[];f.push(...U)}if(!f.length)return{error:ef};if(t)for(let h of f)h.individualParticipantIds=[];else{let h=f.map(S=>S).flat();e?.length?d=d.filter(S=>!h.includes(S)):o=o?.filter(({participantId:S})=>!h.includes(S))}if(!e?.length&&!o?.length)return{error:Qu,info:"Nothing to be done"};if(!o.length){for(let h of s.participants??[]){let{participantId:S,participantType:T}=h;if(!d.includes(S))continue;if(T!==Tt)return{error:An,participant:h};let y=yo({scaleAttributes:a,participant:h})?.scaleItem,P=a?.accessor?y?.scaleValue?.[a?.accessor]:y?.scaleValue,U={participantId:S,scaleValue:P};o.push(U)}if(!o.length)return{error:te}}o.sort((h,S)=>a?.sortOrder?(S?.scaleValue||0)-(h?.scaleValue||0):(h?.scaleValue||1/0)-(S?.scaleValue||1/0));for(let h of o)if(!h.participantId)return{error:G,scaledParticipant:h};let g=0;for(;g<o.length;){for(let h of f){if(g+1>o.length)break;let S=o[g];h.individualParticipantIds.push(S.participantId),g++}f.reverse()}let I=f.map(St);for(let h of s.events??[]){if(h.eventType!==Cr)continue;let S=(h.entries??[]).filter(T=>I.includes(T.participantId));for(let T of S){let y=T.participantId,U=f.find(A=>A.participantId===y)?.individualParticipantIds;h.entries=(h.entries??[]).filter(A=>!U.includes(A.participantId)),(h.drawDefinitions??[]).forEach(A=>{A.entries=(A.entries??[]).filter(N=>!U.includes(N.participantId))});let{flightProfile:E}=Ht({event:h});(E?.flights||[]).forEach(A=>{A.drawEntries=(A.drawEntries||[]).filter(N=>!U.includes(N.participantId))})}}return{...C,scaledParticipants:o}}function HM(t){let e=rt(t,[{[ie]:!0,[Pf]:!0},{ratingType:!1,[tr]:s=>we[s]}]);if(e.error)return e;let r=`${t.ratingType}.${Gm}`,n=t.asDynamic?r:t.ratingType,o=[Ii,gi,t.eventType,n].join("."),i=t.tournamentRecord.participants??[];for(let s of i)s.timeItems&&(s.timeItems=s.timeItems.filter(a=>a.itemType!==o));return{...C}}function WM(t){let{tournamentRecords:e}=t;if(typeof e!="object"||!Object.keys(e).length)return{error:wt};for(let r of Object.values(e)){let n=$1({...t,tournamentRecord:r});if(n.error&&n.error!==kc)return n}return{...C}}function $1({tournamentRecord:t,penaltyId:e}){if(!t)return{error:Y};if(!e)return{error:Xl};let r=t?.participants??[],n=[],o=!1,i;return r.forEach(s=>{let a=!1;s.penalties=(s.penalties??[]).filter(c=>(c.penaltyId===e&&(a=!0,o||(i=c,o=!0)),a&&n.push(s),c.penaltyId!==e))}),i&&mt({topic:nr,payload:{tournamentId:t.tournamentId,participants:n}}),i?{...C,penalty:i}:{error:kc}}var K1=({penaltyId:t=Dt()}={})=>({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}),mA=K1;function jM(t){let{tournamentRecords:e}=t;if(typeof e!="object"||!Object.keys(e).length)return{error:wt};for(let r of Object.values(e)){let n=z1({...t,tournamentRecord:r});if(n.error&&n.error!==kc||n.success)return n}return{error:kc}}function z1({tournamentRecord:t,modifications:e,penaltyId:r}){if(!t)return{error:Y};if(!e)return{error:G,modifications:e};if(!r)return{error:Xl};let n=t?.participants??[],o=Object.keys(mA()).filter(c=>c!=="penaltyId"),i=Object.keys(e).filter(c=>o.includes(c));if(!i.length)return{error:Ju};let s,a=[];return n.forEach(c=>{let u=!1;c.penalties=(c.penalties??[]).map(p=>(p.penaltyId===r&&(u=!0,i.forEach(m=>Object.assign(p,{[m]:e[m]})),s||(s=p)),p)),u&&a.push(c)}),s&&mt({topic:nr,payload:{tournamentId:t.tournamentId,participants:a}}),s?{...C,penalty:s}:{error:kc}}function YM(t,e,r){return!t&&e?e:t&&!e||typeof t!="object"||typeof e!="object"?t:ut(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=ut(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]=YM(t[i],e[i],r):o[i]=e[i];return o},{})}function qM({participants:t=[],tournamentRecord:e,arraysToMerge:r}){if(!e)return{error:Y};e.participants||(e.participants=[]);let n=t.filter(Br(ro)).map(u=>({[u.participantId]:u})),o=Object.assign({},...n),i=[];e.participants=e.participants.map(u=>{if(o[u.participantId]){let p=YM(u,o[u.participantId],r);return i.push(p),p}return u});let s=e.participants.map(Br(ro))||[],a=t.filter(({participantId:u})=>!s.includes(u)),{topics:c}=Lr();return a.length&&(e.participants=e.participants.concat(...a),c.includes(Zo)&&mt({topic:Zo,payload:{participants:a}})),i.length&&c.includes(nr)&&mt({topic:nr,payload:{tournamentId:e.tournamentId,participants:i}}),{modifiedParticipantsCount:i.length,newParticipantsCount:a.length,...C}}function $M(t){let{tournamentRecord:e,participantIds:r}=t,n=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},o;for(let i of Object.values(n)){let a=(Gt({tournamentRecord:i}).participants??[])?.map(St).filter(c=>r.includes(c));a.length&&(o=Q1({...t,penaltyId:t.penaltyId??o,tournamentRecord:i,participantIds:a}).penaltyId)}return o?{...C,penaltyId:o}:{error:te}}function Q1({refereeParticipantId:t,tournamentRecord:e,participantIds:r,penaltyCode:n,penaltyType:o,extensions:i,penaltyId:s,matchUpId:a,issuedAt:c,notes:u}){if(!e)return{error:Y};if(!r)return{error:oe};if(!o)return{error:gE};let m=(e?.participants??[]).filter(f=>r.includes(f.participantId));if(!m.length)return{error:te};let d=new Date().toISOString(),l=Object.assign(mA({penaltyId:s}),{refereeParticipantId:t,penaltyCode:n,penaltyType:o,matchUpId:a,createdAt:d,issuedAt:c,notes:u});return Array.isArray(i)&&i.forEach(f=>At({element:l,extension:f})),m.forEach(f=>{f.penalties||(f.penalties=[]),f.penalties.push(l)}),mt({topic:nr,payload:{tournamentId:e.tournamentId,participants:m}}),{...C,penaltyId:l.penaltyId}}function KM({participantRole:t=xe,tournamentRecord:e,persons:r}){if(!e)return{error:Y};if(!Array.isArray(r))return{error:G};if(!Object.keys(gd).includes(t))return{error:iE};let n=(e.participants||[]).map(({person:f})=>f?.personId).filter(Boolean),o=[],i=r.filter(f=>f&&(!f.personId||!n.includes(f.personId))).map(f=>(f.personId||(f.personId=Dt()),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=>ot({extensions:f.participantExtensions,timeItems:f.participantTimeItems,participantType:Tt,participantRole:t,person:s(f,["participantExtensions","participantTimeItems","pairedPersons"])})),c=0,u=0,p=Sn({participants:a,tournamentRecord:e});if(p.error)return p;u=p.addedCount||0;let m=[],d=Gt({participantFilters:{participantTypes:[Tt]},tournamentRecord:e})?.participants??[];if(t===xe&&r.filter(({pairedPersons:f})=>f).forEach(({personId:f,pairedPersons:g})=>{Array.isArray(g)&&g.forEach(I=>{let h=[f,I.personId].map(S=>Go({tournamentParticipants:d,personId:S})).filter(Boolean);if(h.length===2){let S=h.map(St);m.push(ot({extensions:I.participantExtensions,timeItems:I.timeItems,participantRole:xe,individualParticipantIds:S,participantType:ft}))}})}),m.length){if(p=Sn({participants:m,tournamentRecord:e}),p.error)return p;c=p.addedCount||0}let l=u+c;return{...C,addedCount:l,newPersonIds:o}}var iR={};Xt(iR,{bulkUpdatePublishedEventIds:()=>XT,getAllEventData:()=>JT,getCourtInfo:()=>ud,getDrawData:()=>Zd,getEventData:()=>tl,getEventPublishStatus:()=>Xr,getPublishState:()=>gs,getTournamentPublishStatus:()=>Su,getVenueData:()=>dc,mutate:()=>oR,publishEvent:()=>oa,publishEventSeeding:()=>XM,publishOrderOfPlay:()=>rR,publishParticipants:()=>eR,query:()=>lN,setEventDisplay:()=>ml,unPublishEvent:()=>nR,unPublishEventSeeding:()=>JM,unPublishOrderOfPlay:()=>tR,unPublishParticipants:()=>ZM});var oR={};Xt(oR,{publishEvent:()=>oa,publishEventSeeding:()=>XM,publishOrderOfPlay:()=>rR,publishParticipants:()=>eR,setEventDisplay:()=>ml,unPublishEvent:()=>nR,unPublishEventSeeding:()=>JM,unPublishOrderOfPlay:()=>tR,unPublishParticipants:()=>ZM});function XM({removePriorValues:t=!0,stageSeedingScaleNames:e,seedingScaleNames:r,tournamentRecord:n,status:o=Nr,drawIds:i=[],event:s}){if(!n)return{error:Y};if(!s)return{error:vt};let a=Xr({event:s,status:o}),c=(a?.seeding?.seedingScaleNames||r)&&{...a?.seeding?.seedingScaleNames,...r},u=(a?.seeding?.stageSeedingScaleNames||e)&&{...a?.seeding?.stageSeedingScaleNames,...e},p=ot({stageSeedingScaleNames:u,seedingScaleNames:c,published:!0,drawIds:i});return na({statusObject:{seeding:p},removePriorValues:t,status:o,event:s}),mt({topic:OU,payload:{tournamentId:n.tournamentId,eventId:s.eventId,drawIds:i}}),{...C}}function JM({removePriorValues:t=!0,seedingScaleNames:e,tournamentRecord:r,status:n=Nr,drawIds:o,stages:i,event:s}){if(!r)return{error:Y};if(!s)return{error:vt};let a=Xr({event:s});if(a){let c=a.seeding;if(Array.isArray(i)&&c.stageSeedingScaleNames)for(let u of i)c.stageSeedingScaleNames[u]&&delete c.stageSeedingScaleNames[u];Array.isArray(e)&&c?.seedingScaleNames&&(c.seedingScaleNames=c.seedingScaleNames.filter(u=>!e.includes(u))),Array.isArray(o)&&c?.drawIds&&(c.drawIds=c.drawIds.filter(u=>!o.includes(u))),(!Object.values(c.stageSeedingScaleNames??{}).length&&!c.seedingScaleNames?.length&&!c.drawIds?.length||!i&&!e&&!o?.length)&&(delete c.stageSeedingScaleNames,delete c.seedingScaleNames,delete c.drawIds,c.published=!1),na({statusObject:{seeding:c},removePriorValues:t,status:n,event:s})}return mt({topic:jf,payload:{tournamentId:r.tournamentId,eventId:s.eventId}}),{...C}}function ZM(t){let e=Dr(t);if(!Object.keys(e).length)return{error:wt};for(let r of Object.values(e)){let n=X1({tournamentRecord:r,...t});if(n.error)return n}return{...C}}function X1({removePriorValues:t=!0,tournamentRecord:e,status:r=Nr}){if(!e)return{error:Y};let n=`${_o}.${xo}`,{timeItem:o}=rn({element:e,itemType:n}),i=o?.itemValue||{[r]:{}};return i[r]&&delete i[r].participants,Qn({timeItem:{itemValue:i,itemType:n},element:e,removePriorValues:t}),mt({payload:{tournamentId:e.tournamentId},topic:Ib}),{...C}}function tR(t){let e=Dr(t);if(!Object.keys(e).length)return{error:wt};for(let r of Object.values(e)){let n=J1({tournamentRecord:r,...t});if(n.error)return n}return{...C}}function J1({removePriorValues:t=!0,tournamentRecord:e,status:r=Nr}){if(!e)return{error:Y};let n=`${_o}.${xo}`,{timeItem:o}=rn({element:e,itemType:n}),i=o?.itemValue||{[r]:{}};return i[r]&&delete i[r].orderOfPlay,Qn({timeItem:{itemValue:i,itemType:n},element:e,removePriorValues:t}),mt({topic:Yf,payload:{tournamentId:e.tournamentId}}),{...C}}function eR(t){let e=Dr(t);if(!Object.keys(e).length)return{error:wt};for(let r of Object.values(e)){let n=Z1({tournamentRecord:r,...t});if(n.error)return n}return{...C}}function Z1({removePriorValues:t,tournamentRecord:e,status:r=Nr}){if(!e)return{error:Y};let n=`${_o}.${xo}`,{timeItem:o}=rn({element:e,itemType:n}),i=o?.itemValue||{[r]:{}};return i[r].participants={published:!0},Qn({timeItem:{itemValue:i,itemType:n},element:e,removePriorValues:t}),mt({payload:{tournamentId:e.tournamentId},topic:xU}),{...C}}function rR(t){let e=Dr(t);if(!Object.keys(e).length)return{error:wt};for(let r of Object.values(e)){let n=t0({tournamentRecord:r,...t});if(n.error)return n}return{...C}}function t0({scheduledDates:t=[],removePriorValues:e,tournamentRecord:r,status:n=Nr,eventIds:o=[]}){if(!r)return{error:Y};let i=`${_o}.${xo}`,{timeItem:s}=rn({element:r,itemType:i}),a=s?.itemValue||{[n]:{}};return a[n].orderOfPlay={published:!0,scheduledDates:t,eventIds:o},Qn({timeItem:{itemValue:a,itemType:i},element:r,removePriorValues:e}),mt({topic:_U,payload:{tournamentId:r.tournamentId,scheduledDates:t,eventIds:o}}),{...C}}function nR({removePriorValues:t=!0,tournamentRecord:e,status:r=Nr,event:n}){if(!e)return{error:Y};if(!n)return{error:vt};let o=`${_o}.${xo}`,{timeItem:i}=du({itemType:o,event:n}),s=i?.itemValue||{[r]:{}};return delete s[r].structureIds,delete s[r].drawDetails,delete s[r].drawIds,zi({event:n,timeItem:{itemValue:s,itemType:o},removePriorValues:t}),na({statusObject:{structureIds:void 0,drawIds:void 0,seeding:void 0},removePriorValues:t,status:r,event:n}),mt({topic:Wf,payload:{tournamentId:e.tournamentId,eventId:n.eventId}}),{eventId:n.eventId,...C}}var sR={};Xt(sR,{getEntryStatusReports:()=>cw,getParticipantStats:()=>aw,getStructureReports:()=>pw,getVenuesReport:()=>mw});function aw({withCompetitiveProfiles:t,opponentParticipantId:e,withIndividualStats:r,teamParticipantId:n,tournamentRecord:o,withScaleValues:i,tallyPolicy:s,matchUps:a}){if(!o)return{error:Y};if(a&&!Array.isArray(a))return{error:dr};if(a=a??Te({tournamentRecord:o,participantsProfile:i?{withScaleValues:i}:void 0}).matchUps,!a?.length)return{error:Xn};let u=[];e&&u.push(e),n&&u.push(n);let p=u.length?{participantIds:u}:{participantTypes:[yr]},m=Gt({participantFilters:p,tournamentRecord:o}).participants??[];if(!m.every(({participantType:A})=>A===yr))return{error:wr};u.length||u.push(...m.map(St));let d=new Map,l=new Map,f=new Map,g=new Map,I=(A,N="")=>l.get(A)||l.set(A,{participantName:N,participantId:A,competitorIds:[],competitiveness:{},matchUpStatuses:{},tiebreaks:[0,0],matchUps:[0,0],points:[0,0],games:[0,0],sets:[0,0]})&&l.get(A);for(let A of m){let{participantId:N,individualParticipantIds:D}=A;g.set(N,D??[]),I(N,A.participantName)}if(n&&!g.get(n))return _({result:{error:te},context:{teamParticipantId:n}});if(e&&!g.get(e))return _({result:{error:te},context:{opponentParticipantId:e}});let h=[],S=A=>{let N=[[],[]];for(let M of A){let R=M.participant;if(R?.participantName){d.set(R.participantId,{participantName:R.participantName,ratings:R.ratings});let b=l.get(R.participantId);b&&(b.participantName=R.participantName)}}let D=({side:M,individualParticipantIds:R})=>M.participantId&&(!R?.length||R.includes(M.participantId))&&[M.participantId]||M.participant?.individualParticipantIds?.length&&(!R?.length||Yt(R,M.participant?.individualParticipantIds).length===M.participant?.individualParticipantIds?.length)&&M.participant.individualParticipantIds;if(g.size){let M=(R,b)=>{for(let v of A){if(!v.participant)continue;let O=D({individualParticipantIds:b,side:v});if(O?.length){let x=v.sideNumber;if(!x)continue;let F=[R];r&&F.push(...O),N[x-1]=F;let L=l.get(R);for(let w of O.filter(Boolean))L&&!L.competitorIds.includes(w)&&L.competitorIds.push(w)}}};if(n)(!e||A.every(b=>b.participant&&(D({individualParticipantIds:g.get(n),side:b})||D({individualParticipantIds:g.get(e),side:b}))))&&M(n,g.get(n));else for(let[R,b]of g)M(R,b)}else if(r)for(let M of A){if(!M.participant)continue;let R=D({individualParticipantIds:[],side:M}),b=M.sideNumber;b&&(N[b-1]=R)}return N};for(let A of a){if(!ht(A))return{error:dr};let{matchUpStatus:N,matchUpFormat:D,matchUpType:M,winningSide:R,score:b,sides:v}=A;if(!v||!b||M===xr||N===Nt)continue;let O=S(v);if(!O.filter(Boolean).length)continue;let x=t&&R&&gu({matchUp:A})?.competitiveness;h.push(A);let F=Dg({matchUpStatus:N,matchUpFormat:D,tallyPolicy:s,winningSide:R,score:b}),L=qS({matchUpStatus:N,matchUpFormat:D,tallyPolicy:s,winningSide:R,score:b}),{pointsTally:w,tiebreaksTally:V}=$S({matchUpFormat:D,score:b});O.forEach((k,W)=>{for(let H of k){let K=d.get(H)?.participantName,q=I(H,K);if(q){let B=(Q,X)=>X.forEach((lt,it)=>q[Q][it]+=lt),$=W?[...V].reverse():V,z=W?[...w].reverse():w,j=W?[...L].reverse():L,tt=W?[...F].reverse():F;if(B("tiebreaks",$),B("points",z),B("games",j),B("sets",tt),R){let Q=R-1===W?0:1;q.matchUps[Q]+=1}if(x){let Q=x.toLowerCase();q.competitiveness[Q]||(q.competitiveness[Q]=[0,0]),q.competitiveness[Q][W]+=1}if(N){let Q=N.toLowerCase();q.matchUpStatuses[Q]||(q.matchUpStatuses[Q]=0),q.matchUpStatuses[Q]+=1}}}})}let T=["tiebreaks","matchUps","points","games","sets"],y=["competitive","routine","decisive"],P=new Map,U=(A,N)=>(A??0)+(N??0);for(let[A,N]of l.entries()){for(let D of T){let M=N[D].reduce(U);if(M){let R=N[D][0]/M,b=`${D}Ratio`,v=parseFloat(R.toFixed(2));N[b]=v,f.set(A,!0),P.has(b)||P.set(b,[]),P.get(b)?.push(v)}}for(let D of y){let M=N.competitiveness?.[D]?.reduce(U);if(M){let R=N.competitiveness[D][0]/M,b=`${D}Ratio`,v=parseFloat(R.toFixed(2));N[b]=v}}}if(!n){let A=(N,D)=>D-N;for(let N of l.values())for(let D of T){let M=`${D}Ratio`;if(typeof N[M]=="number"){let R=P.get(M)?.sort(A).indexOf(N[M]);if(typeof R=="number"&&R>=0){let b=`${D}Rank`;N[b]=R+1}}}}let E={relevantMatchUps:h,...C};return n?(E.teamStats=l.get(n),e&&(E.opponentStats=l.get(e))):E.participatingTeamsCount=f.size,E.allParticipantStats=[...l.values()],E}function lm({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===Pg),s=i?.scaleValue,{wtnRating:a,confidence:c}=s||{};return{timeStamp:i?.scaleDate,personOtherId:n,confidence:c,wtnRating:a,personId:r,tennisId:o}}function cw({tournamentRecord:t}){if(!t)return{error:Y};let e=t.tournamentId,{participantMap:r}=Gt({withScaleValues:!0,withEvents:!0,withSeeding:!0,tournamentRecord:t,withDraws:!0}),o=(Te({matchUpFilters:{matchUpTypes:[aa,vi]},tournamentRecord:t}).matchUps??[]).flatMap(({sides:f,matchUpType:g})=>f?.flatMap(I=>g===vi?I?.participant?.individualParticipantIds:I?.participant?.participantId||I.participantId).filter(Boolean)).filter(Boolean),i=[],s={},a={},c={},u=0,p=({id:f,entry:g,eventId:I,eventType:h})=>{let{qualifyingSeeding:S,mainSeeding:T,entryStatus:y,entryStage:P,drawId:U}=g;s[f]||(s[f]=[]);let{participant:E,events:A}=r?.[f]??{},N=lm({participant:E,eventType:h}),D=A?.[I]?.ranking;y===Eg&&i.push(f),s[f].push({participantType:E?.participantType,participantId:f,tournamentId:e,eventType:h,eventId:I,drawId:U,entryStatus:y,entryStage:P,...N,ranking:D,mainSeeding:T,qualifyingSeeding:S})};for(let f of t.events??[]){let g={},I=N=>{g[N]||(g[N]={count:0}),g[N].count+=1},{drawDefinitions:h=[],eventType:S,eventId:T}=f,y=h.flatMap(N=>{let{drawId:D,entries:M}=N;u+=1;let R=({stage:F,stageSequence:L})=>F===nt&&L===1||F===ct,v=(N.structures??[]).filter(R).flatMap(({positionAssignments:F})=>F).filter(Boolean).map(({participantId:F})=>F),O=({participantId:F})=>v.includes(F),x=F=>{let{participantId:L,entryStatus:w,entryStage:V}=F;I(w);let k=r?.[L]?.draws?.[D]?.seedAssignments?.[nt];return{qualifyingSeeding:r?.[L]?.draws?.[D]?.seedAssignments?.[ct],participantId:L,mainSeeding:k,entryStatus:w,entryStage:V,drawId:D}};return M?.filter(O).map(x)}),P=N=>{let D=N.participantId,M=r?.[D].participant.individualParticipantIds?.filter(R=>o.includes(R));return D&&{[D]:{individualParticipantIds:M}}};S===ko?(()=>{let N=Object.assign({},...y.map(P).filter(Boolean)),D=M=>{N[M.participantId].individualParticipantIds.forEach(R=>{p({id:R,eventType:S,eventId:T,entry:M})})};y.forEach(D)})():y.forEach(N=>{p({id:N?.participantId,eventType:S,eventId:T,entry:N})});let E=Object.values(g).reduce((N,D)=>N+D.count,0);Object.keys(g).forEach(N=>{g[N].pct=g[N].count/E*100}),c[T]={tournamentId:e,eventId:T,entries:y,entryStatuses:g};let A=Object.assign({},...Qr.flatMap(N=>[{[N+"_count"]:g[N]?.count},{[N+"_pct"]:g[N]?.pct}]));a[T]={tournamentId:e,eventId:T,...A}}let m=Object.values(r??{}).filter(({participant:{participantType:f,participantRole:g}})=>f===Tt&&g===xe),d=m.filter(({participant:f})=>!o.includes(f.participantId)).map(({participant:f})=>f.participantId),l={nonParticipatingEntriesCount:d.length,individualParticipantsCount:m.length,eventsCount:Object.values(c).length,nonParticipatingParticipantIds:d,drawDefinitionsCount:u,tournamentId:e};return{entryStatusReports:Object.values(a).flat(),participantEntryReports:Object.values(s).flat(),eventReports:Object.values(c).flat(),withDrawnParticipantIds:i,tournamentEntryReport:l}}function uw({eventType:t,matchUps:e,eventId:r,drawId:n}){let o={},i=g=>{let I=g?.matchUpFormat;I&&(o[I]||(o[I]=0),o[I]+=1)},s=e.filter(g=>r?g.eventId===r:g.drawId===n).reduce((g,I)=>(i(I),(I.sides??[]).flatMap(h=>(h?.participant?.individualParticipants||[h?.participant]).filter(Boolean)).forEach(h=>g[h.participantId]=h),g),{}),a=Object.values(s),c=a.map(g=>lm({participant:g,eventType:t})).filter(({wtnRating:g})=>g),u=(a.length-c.length)/a.length*100,p=c.reduce((g,I)=>{let{wtnRating:h,confidence:S}=I;return g.totalWTN+=h,g.totalConfidence+=S,g},{totalWTN:0,totalConfidence:0}),m=c?.length?p.totalWTN/c.length:0,d=c?.length?p.totalConfidence/c.length:0,f=Object.values(o).reduce((g,I)=>g+(I||0),0);return{matchUpFormatCounts:o,matchUpsCount:f,avgConfidence:d,pctNoRating:u,avgWTN:m}}function pw(t){let{tournamentRecord:e,extensionProfiles:r,firstFlightOnly:n}=t;if(!e)return{error:ca};let o=[],i={},s={},a=[],c=Object.assign({},...(r??[]).map(({name:g,label:I,accessor:h})=>{let S=dt({element:e,name:g})?.extension?.value,T=h?ls({element:S,accessor:h})?.value:S;return{[I||g]:T}})),u=e?.tournamentId,m=Te({participantsProfile:{withScaleValues:!0},tournamentRecord:e}).matchUps??[],d=g=>rn({itemType:xf,itemSubTypes:[ho],element:{timeItems:g}})?.timeItem?.itemValue?.scaleBasis,l=({positionManipulations:g})=>{g?.forEach(I=>{let{structureId:h,name:S}=I,T=I.drawPositions||[I.drawPosition];i[h]||(i[h]=[]),i[h].push(`${S}: ${T.join("/")}`)})},f=e?.events?.flatMap(({timeItems:g,drawDefinitions:I=[],extensions:h,eventType:S,eventName:T,eventId:y,category:P})=>{let E=h?.find(O=>O.name===un)?.value?.flights?.map(O=>({[O.drawId]:O.flightNumber})),A=E&&Object.assign({},...E),N=h?.find(O=>O.name===Ia),D=g?.find(O=>O.itemType===Ia),M=N?.value?.length||D?.itemValue||0,R=Object.values(A??{}),b=A&&Math.min(...R),v=d(g);return s[y]={seedingBasis:v?JSON.stringify(v):void 0,totalPositionManipulations:0,maxPositionManipulations:0,generatedDrawsCount:0,drawDeletionsCount:M,tournamentId:u,eventId:y},I.filter(O=>!n||!E||A[O.drawId]===b).flatMap(O=>{let{matchUpFormat:x,tieFormat:F,timeItems:L,extensions:w,structures:V,drawName:k,drawType:W,drawId:H}=O,{matchUpFormatCounts:K,matchUpsCount:q,avgConfidence:B,pctNoRating:$,avgWTN:z}=uw({eventType:S,matchUps:m,drawId:H}),j=d(L)||v,tt=e0({extensions:w}),Q=tt?.length||0;return l({positionManipulations:tt}),s[y].totalPositionManipulations+=Q,s[y].generatedDrawsCount+=1,Q>s[y].maxPositionManipulations&&(s[y].maxPositionManipulations=Q),V?.filter(X=>X.stageSequence===1&&[ct,nt,qe,de].includes(X.stage)).map(X=>{let lt=[nt,de].includes(X.stage)?m.find(Ar=>Ar.structureId===X.structureId&&Ar.finishingRound===1&&Ar.winningSide):void 0;X.stage===nt&&o.push({eventName:T,drawName:k,structureId:X.structureId});let Rt=lt?.sides?.find(Ar=>Ar.sideNumber===lt.winningSide)?.participant,Ft=Rt?.participantType===yr&&Rt.participantId,Ue=Rt?.participantType===ft?Rt.individualParticipants:[],fe=lm({participant:Ue?.[0]||Rt,eventType:S}),{personId:Me,personOtherId:vr,tennisId:Zr,confidence:lr,wtnRating:Xe}=fe||{},ee=lm({participant:Ue?.[1],eventType:S}),{personId:Pt,personOtherId:ae,tennisId:re,confidence:pr,wtnRating:Jt}=ee||{},{ageCategoryCode:Wt,categoryName:mr,subType:zt}=P??{},pe=X.matchUpFormat||x,Or=(K[pe]||0)/q*100,{tieFormatName:Je,tieFormatDesc:De}=Jd(F),{tieFormatName:Ee,tieFormatDesc:ge}=Jd(X.tieFormat),_r=De===ge,fr=!_r&&Ee,uo=X.tieFormat&&!_r&&ge,be=tt?.filter(Ar=>Ar.structureId===X.structureId)?.length||0;return{...c,tournamentId:u,eventId:y,structureId:X.structureId,drawId:H,eventType:S,category:zt,categoryName:mr,ageCategoryCode:Wt,flightNumber:A[H],drawType:W,stage:X.stage,seedingBasis:j?JSON.stringify(j):void 0,winningPersonId:Me,winningPersonOtherId:vr,winningPersonTennisId:Zr,winningPersonWTNrating:Xe,winningPersonWTNconfidence:lr,winningPerson2Id:Pt,winningPerson2OtherId:ae,winningPerson2TennisId:re,winningPerson2WTNrating:Jt,winningPerson2WTNconfidence:pr,winningTeamId:Ft,positionManipulations:be,pctNoRating:$,matchUpFormat:pe,pctInitialMatchUpFormat:Or,matchUpsCount:q,drawTieFormatName:Je,drawTieFormatDesc:De,tieFormatName:fr,tieFormatDesc:uo,avgConfidence:B,avgWTN:z}})})});return o.forEach(({eventName:g,drawName:I,structureId:h})=>{i[h]?.length&&a.push({eventName:g,drawName:I,actions:i[h]})}),{eventStructureReports:Object.values(s),structureReports:f,flightReports:a}}function e0({extensions:t}){return t?.find(({name:e})=>e===nc)?.value?.slice(1)}function mw({ignoreDisabled:t=!0,tournamentRecords:e,tournamentId:r,venueIds:n=[],dates:o=[]}){if(!Array.isArray(o))return{error:G,dates:o};if(!Array.isArray(n))return{error:G,venueIds:n};if(!(e&&Object.keys(e).filter(l=>!r||l===r)||[]).length)return{error:wt};if(!o.every(Rr))return{error:je};let a=Ao({tournamentRecords:e,ignoreDisabled:t,dates:o});if(a.error)return a;let c=a?.venues?.filter(({venueId:l})=>!n?.length||n.includes(l)),u=a.courts?.reduce((l,f)=>(f.dateAvailability?.forEach(g=>{let I=g.date;l.includes(I)||l.push(I)}),l),[]).filter(l=>!o.length||o.includes(l)),p={venueIds:c?.map(({venueId:l})=>l)},{matchUps:m}=Un({afterRecoveryTimes:!0,tournamentRecords:e,matchUpFilters:p});return{venuesReport:c?.map(l=>r0(u,l,m))}}function r0(t,e,r){let{venueId:n,courts:o,venueName:i}=e,s={};return t.forEach(a=>{let c=0,u=0,p=0;for(let l of o){let f=l.dateAvailability.find(h=>h.date===a),I=(f&&Ns({courtDate:f}).timeSlots)?.reduce((h,S)=>{let{startTime:T,endTime:y}=S,P=qt(y)-qt(T);return h+P},0);I&&(p+=1),c+=I}let m=r.filter(({schedule:l})=>l.venueId===n&&Wn(a,l.scheduledDate));m.forEach(({schedule:l})=>{let f=Kt(l.scheduledTime),g=Yr(f,l.averageMinutes),I=qt(g)-qt(f);u+=I});let d=c?(u/c*100).toFixed(2):"100";s[a]={scheduledMatchUpsCount:m.length,availableCourts:p,availableMinutes:c,scheduledMinutes:u,percentUtilization:d}}),{venueId:n,venueName:i,venueReport:s}}var SR={};Xt(SR,{addMatchUpCourtOrder:()=>ky,addMatchUpEndTime:()=>Vy,addMatchUpOfficial:()=>cM,addMatchUpResumeTime:()=>Hy,addMatchUpScheduleItems:()=>im,addMatchUpScheduledDate:()=>nm,addMatchUpScheduledTime:()=>zo,addMatchUpStartTime:()=>Gy,addMatchUpStopTime:()=>By,addSchedulingProfileRound:()=>dI,allocateTeamMatchUpCourts:()=>om,assignMatchUpCourt:()=>Xi,assignMatchUpVenue:()=>ia,bulkRescheduleMatchUps:()=>lR,bulkScheduleMatchUps:()=>xc,bulkScheduleTournamentMatchUps:()=>Vu,bulkUpdateCourtAssignments:()=>uR,calculateScheduleTimes:()=>gI,clearMatchUpSchedule:()=>gR,clearScheduledMatchUps:()=>am,courtGridRows:()=>nl,findMatchUpFormatTiming:()=>Kp,findVenue:()=>Wo,generateBookings:()=>sm,generateVirtualCourts:()=>tm,getMatchUpsToSchedule:()=>el,getPersonRequests:()=>bi,getProfileRounds:()=>rl,getScheduledRoundsDetails:()=>Lu,getSchedulingProfile:()=>Ko,getSchedulingProfileIssues:()=>ty,matchUpScheduleChange:()=>fR,modifyMatchUpFormatTiming:()=>$g,mutate:()=>hR,proAutoSchedule:()=>cR,proConflicts:()=>mR,publicFindCourt:()=>lS,query:()=>hN,removeEventMatchUpFormatTiming:()=>pl,removeMatchUpCourtAssignment:()=>aR,reorderUpcomingMatchUps:()=>dR,scheduleMatchUps:()=>pR,scheduleProfileRounds:()=>cm,setMatchUpDailyLimits:()=>IR,setMatchUpHomeParticipantId:()=>oI,setSchedulingProfile:()=>Mc,toggleParticipantCheckInState:()=>ll,validateSchedulingProfile:()=>zp});var hR={};Xt(hR,{addMatchUpCourtOrder:()=>ky,addMatchUpEndTime:()=>Vy,addMatchUpOfficial:()=>cM,addMatchUpResumeTime:()=>Hy,addMatchUpScheduleItems:()=>im,addMatchUpScheduledDate:()=>nm,addMatchUpScheduledTime:()=>zo,addMatchUpStartTime:()=>Gy,addMatchUpStopTime:()=>By,addSchedulingProfileRound:()=>dI,allocateTeamMatchUpCourts:()=>om,assignMatchUpCourt:()=>Xi,assignMatchUpVenue:()=>ia,bulkRescheduleMatchUps:()=>lR,bulkScheduleMatchUps:()=>xc,bulkScheduleTournamentMatchUps:()=>Vu,bulkUpdateCourtAssignments:()=>uR,calculateScheduleTimes:()=>gI,clearMatchUpSchedule:()=>gR,clearScheduledMatchUps:()=>am,findMatchUpFormatTiming:()=>Kp,generateBookings:()=>sm,generateVirtualCourts:()=>tm,matchUpScheduleChange:()=>fR,modifyMatchUpFormatTiming:()=>$g,proAutoSchedule:()=>cR,proConflicts:()=>mR,removeEventMatchUpFormatTiming:()=>pl,removeMatchUpCourtAssignment:()=>aR,reorderUpcomingMatchUps:()=>dR,scheduleMatchUps:()=>pR,scheduleProfileRounds:()=>cm,setMatchUpDailyLimits:()=>IR,setMatchUpHomeParticipantId:()=>oI,setSchedulingProfile:()=>Mc,toggleParticipantCheckInState:()=>ll,validateSchedulingProfile:()=>zp});function gI({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:wt};s=s??ku({recoveryMinutes:e,averageMatchUpMinutes:r});let{courts:m,venues:d}=Ao({dates:[a],ignoreDisabled:!0,tournamentRecords:i}),l=m?.filter(M=>!u||u.includes(M.venueId));c||(c=l?.reduce((M,R)=>{let v=R.dateAvailability?.find(O=>!O.date||Wn(a,O.date))?.startTime??R.startTime;return v&&(!M||qt(v)<qt(M))?v:M},void 0)),p||(p=l?.reduce((M,R)=>{let v=R.dateAvailability?.find(O=>!O.date||Wn(a,O.date))?.endTime??R.endTime;return v&&(!M||qt(v)>qt(M))?v:M},void 0));let f=Object.values(i),g=Object.assign({},...f.map(M=>(M.events??[]).map(R=>{let{scheduleTiming:b}=ya({tournamentRecord:M,event:R});return{[R.eventId]:{event:R,scheduleTiming:b}}})).flat()),h=Fu({sortDateMatchUps:!1,tournamentRecords:i,matchUpFilters:{scheduledDate:a,venueIds:u}}),S=h?.dateMatchUps??[],T=h?.completedMatchUps??[],y=[];y.push(...S),y.push(...T);let P={averageTimes:[{minutes:{default:r}}],recoveryTimes:[{minutes:{default:e}}]},U=y?.map(({eventId:M,schedule:R,matchUpFormat:b})=>{let{event:v,scheduleTiming:O}=g[M],x=v?.eventType,F={...O,defaultTiming:P,matchUpFormat:b},{averageMinutes:L,recoveryMinutes:w}=Pp({eventType:x,timingDetails:F}),{courtId:V,venueId:k}=R,W=Kt(R.scheduledTime),H=Yr(W,L);return{recoveryMinutes:w,averageMinutes:L,periodLength:s,startTime:W,endTime:H,courtId:V,venueId:k}}),E={calculateStartTimeFromCourts:t,remainingScheduleTimes:n,averageMatchUpMinutes:r,date:a,clearScheduleDates:o,periodLength:s,startTime:c,endTime:p,bookings:U,courts:l},{scheduleTimes:A}=dl(E),N=u?.length===1&&u[0]||d?.length===1&&d[0].venueId||void 0,D=y.map(Ae);return{venueId:N,scheduleTimes:A,dateScheduledMatchUpIds:D}}function aR(t){let e=rt(t,[{[Re]:!0}]);if(e.error)return e;let{removePriorValues:r,tournamentRecords:n,tournamentId:o,courtDayDate:i,matchUpId:s,courtId:a,drawId:c}=t,u=n[o];if(!u)return{error:Y};let{drawDefinition:p,event:m}=wo({tournamentRecord:u,drawId:c});if(!p)return{error:Z};let d=Bt({drawDefinition:p,event:m,matchUpId:s});if(d.error)return d;if(d?.matchUp?.matchUpType===xr){let{itemValue:l}=Ho({timeItems:d.matchUp.timeItems??[],itemType:so}),f=a&&l.filter(I=>I.courtId!==a);return Jr({duplicateValues:!1,removePriorValues:r,tournamentRecord:u,drawDefinition:p,matchUpId:s,timeItem:{itemType:so,itemValue:f}})}else return Xi({tournamentRecord:u,drawDefinition:p,courtDayDate:i,courtId:"",matchUpId:s})}function cR({scheduleCompletedMatchUps:t,tournamentRecords:e,scheduledDate:r,matchUps:n}){if(!Vr(n))return{error:G};if(n.some(({hasContext:g})=>!g))return{info:"matchUps must have { inContext: true, nextMatchUps: true }",error:Gc};let i=Fu({courtCompletedMatchUps:!0,withCourtGridRows:!0,minCourtGridRows:10,tournamentRecords:e,matchUpFilters:{localPerspective:!0,scheduledDate:r}});if(i.error)return i;let{rows:s}=i,a=[],c=g=>[(g.sides||[]).map(I=>[I.participantId,I.participant?.individualParticipantIds]),(g.potentialParticipants||[]).flat().map(I=>[I.participantId,I.individualParticipantIds])].flat(1/0).filter(Boolean),u=s?.reduce((g,I)=>{let h=[],S=[];Object.values(I).forEach(y=>{if(ht(y)&&(y.matchUpId&&(h.push(y.matchUpId),a.push(y)),y.sides)){let P=c(y);S.push(...P)}});let T=Object.values(I).filter(y=>ht(y)&&!y.matchUpId);return g.concat({matchUpIds:h,availableCourts:T,rowId:I.rowId,participantIds:S})},[]);n.filter(({matchUpStatus:g})=>g&&g!==Nt&&(t||!ce.includes(g))).sort(Mi);let p=sn({matchUps:n.concat(a),includeParticipantDependencies:!0,tournamentRecords:e}).matchUpDependencies,m=[],d=[];for(;n.length&&u.length;){let g=u.shift(),I=[];for(;n.length&&g.availableCourts.length;){let h=n.concat(I).map(D=>D.matchUpId),S=n.shift(),T=S?.matchUpId,y=T&&p[T].matchUpIds.concat(p[T].dependentMatchUpIds),P=T&&h.some(D=>p[T].matchUpIds.includes(D)),U=T&&d.some(D=>p[T].dependentMatchUpIds.includes(D)),E=g.matchUpIds.some(D=>y.includes(D)),A=c(S),N=g.participantIds.some(D=>A.includes(D));if(S&&!E&&!P&&!N&&!U){let D=g.availableCourts.shift();Object.assign(S.schedule,D.schedule),Object.assign(D,S),m.push(S),g.participantIds.push(...A),g.matchUpIds.push(T)}else S&&I.push(S)}n.push(...I),d.push(...g.matchUpIds)}let l=m.map(({matchUpId:g,tournamentId:I,schedule:h,drawId:S})=>({tournamentId:I,matchUpId:g,drawId:S,schedule:{...h,scheduledDate:r}}));return i=xc({tournamentRecords:e,matchUpDetails:l}),{...i,scheduled:m,notScheduled:n}}function uR(t){let{courtDayDate:e}=t,r=rt(t,[{courtAssignments:!0,[He]:Be,[Fr]:st},{[Re]:!0}]);if(r.error)return r;let n=t.courtAssignments.reduce((s,a)=>{let{tournamentId:c}=a;return s[c]||(s[c]=[]),s[c].push(a),s},{}),o;return Object.keys(n).every(s=>{let a=t[Re][s];if(!a)return o={error:Y},!1;let c=n[s].reduce((p,m)=>{let{drawId:d}=m;return p[d]||(p[d]=[]),p[d].push(m),p},{});Object.keys(c).every(p=>{let{drawDefinition:m}=ze({tournamentRecord:a,drawId:p});return m?(c[p].every(d=>{let{matchUpId:l,courtId:f}=d,g=Xi({tournamentRecord:a,drawDefinition:m,courtDayDate:e,matchUpId:l,courtId:f});if(g.success)return g?.success;o={error:DE}}),!0):(o={error:Z},!1)})}),o||C}function pR(t){let{tournamentRecords:e,allDateMatchUpIds:r=[],averageMatchUpMinutes:n=90,recoveryMinutes:o=0,recoveryMinutesMap:i,matchUpPotentialParticipantIds:s={},individualParticipantProfiles:a={},matchUpNotBeforeTimes:c={},matchUpDailyLimits:u={},checkPotentialRequestConflicts:p=!0,remainingScheduleTimes:m,clearScheduleDates:d,periodLength:l=30,scheduleDate:f,matchUpIds:g,venueIds:I,startTime:h,endTime:S,dryRun:T}=t,y=rt(t,[{[Re]:!0,[ec]:!0},{[tr]:Rr,[Fr]:je,[eb]:!0},{[tr]:B=>!B||!isNaN(B),[ib]:!1,[Fr]:G,[sb]:!1,[ab]:!1}]);if(y.error)return y;let P=t.competitionMatchUps??Un({nextMatchUps:!0,tournamentRecords:e}).matchUps??[],U=t.matchUpDependencies??sn({includeParticipantDependencies:!0,matchUps:P,tournamentRecords:e}).matchUpDependencies;P.forEach(B=>{B.schedule?.scheduledDate&&Wn(f,Et(B.schedule.scheduledDate))&&ea({matchUpPotentialParticipantIds:s,matchUpNotBeforeTimes:c,matchUp:B})});let E=g.map(B=>P.find($=>$.matchUpId===B)).filter(Boolean),{venueId:A,scheduleTimes:N,dateScheduledMatchUpIds:D}=gI({tournamentRecords:e,remainingScheduleTimes:m,startTime:Kt(h),endTime:Kt(S),scheduleDate:Et(f),averageMatchUpMinutes:n,clearScheduleDates:d,periodLength:l,venueIds:I}),M={},R=[],b={},v={},O={};P.filter(({matchUpId:B})=>D?.includes(B)).forEach(B=>{uI({matchUpPotentialParticipantIds:s,individualParticipantProfiles:a,matchUp:B,value:1});let $=B.schedule?.scheduledTime;if($){b[B.matchUpId]=$;let z=i?.[B.matchUpId];Oc({recoveryMinutes:z||o,matchUpPotentialParticipantIds:s,individualParticipantProfiles:a,matchUpNotBeforeTimes:c,averageMatchUpMinutes:n,matchUpDependencies:U,scheduleTime:$,matchUp:B})}});let F=E.filter(B=>{let $=D?.includes(B.matchUpId),z=[Nt,Mt,le,br,rr,Ct].includes(B?.matchUpStatus);return!$&&!B.winningSide&&!z}),{matchUpMap:L,overLimitMatchUpIds:w,participantIdsAtLimit:V}=F.reduce((B,$)=>{let{drawId:z,tournamentId:j,matchUpType:tt}=$,{participantIdsAtLimit:Q,relevantParticipantIds:X}=yl({individualParticipantProfiles:a,matchUpPotentialParticipantIds:s,matchUpDailyLimits:u,matchUp:$});return Q?.length?(B.overLimitMatchUpIds.push($.matchUpId),B.participantIdsAtLimit.push(...Q),B):(X.forEach(lt=>{Fa({individualParticipantProfiles:a,participantId:lt});let it=a[lt].counters;it[tt]?it[tt]+=1:it[tt]=1,it[ao]?it[ao]+=1:it[ao]=1}),B.matchUpMap[j]||(B.matchUpMap[j]={}),B.matchUpMap[j][z]?B.matchUpMap[j][z].push($):B.matchUpMap[j][z]=[$],ea({matchUpPotentialParticipantIds:s,matchUpNotBeforeTimes:c,matchUp:$}),B)},{matchUpMap:{},overLimitMatchUpIds:[],participantIdsAtLimit:[]});F=F.filter(({matchUpId:B})=>!w.includes(B));let k=0,W=N?.length??0,{personRequests:H}=bi({tournamentRecords:e,requestType:_c});for(;N?.length&&F.length&&k<=W;){k++;let{scheduleTime:B}=N.shift(),$=F.find(z=>{let{matchUpId:j}=z,{dependenciesScheduled:tt,remainingDependencies:Q}=hl({matchUpScheduleTimes:b,matchUpDependencies:U,allDateMatchUpIds:r,matchUp:z});if(!tt)return O[j]||(O[j]=[]),O[j].push({scheduleTime:B,remainingDependencies:Q}),!1;let{enoughTime:X}=Tl({individualParticipantProfiles:a,matchUpNotBeforeTimes:c,matchUpDependencies:U,scheduleTime:B,matchUp:z});if(!X)return v[j]||(v[j]=[]),v[j].push({scheduleTime:B}),!1;let{conflicts:lt}=Sl({potentials:p,averageMatchUpMinutes:n,requestConflicts:M,personRequests:H,scheduleTime:B,scheduleDate:f,matchUp:z});if(lt?.length)return!1;let it=i?.[z.matchUpId];return Oc({recoveryMinutes:it||o,matchUpPotentialParticipantIds:s,individualParticipantProfiles:a,matchUpNotBeforeTimes:c,averageMatchUpMinutes:n,matchUpDependencies:U,scheduleTime:B,matchUp:z}),b[z.matchUpId]=B,!0});F=F.filter(({matchUpId:z})=>z!==$?.matchUpId),$||R.push(B)}F.forEach(B=>{uI({individualParticipantProfiles:a,matchUpPotentialParticipantIds:s,value:-1,matchUp:B})});let K=[];Object.keys(L).forEach(B=>{let $=e[B];$&&Object.keys(L[B]).forEach(z=>{let{drawDefinition:j}=wo({tournamentRecord:$,drawId:z});j&&L[B][z].forEach(({matchUpId:Q})=>{let X=b[Q];if(X){let lt=X.split(":").map(Jn).join(":"),it=`${Et(f)}T${lt}`;T?K.push(Q):(zo({drawDefinition:j,matchUpId:Q,scheduledTime:it}).success&&K.push(Q),A&&ia({tournamentRecords:e,tournamentRecord:$,drawDefinition:j,matchUpId:Q,venueId:A}))}})})});let q=$m(F);return{...C,requestConflicts:Object.values(M),remainingScheduleTimes:N?.map(({scheduleTime:B})=>B),individualParticipantProfiles:a,matchUpNotBeforeTimes:c,participantIdsAtLimit:V,skippedScheduleTimes:R,overLimitMatchUpIds:w,scheduledMatchUpIds:K,noTimeMatchUpIds:q,recoveryTimeDeferred:v,dependencyDeferred:O}}function mR({tournamentRecords:t,matchUps:e}){if(!Vr(e))return{error:Xn};if(e.some(({matchUpId:f,hasContext:g})=>f&&!g))return{info:"matchUps must have { inContext: true, nextMatchUps: true }",error:Gc};let r=Math.max(...e.map(({schedule:f})=>f?.courtOrder||1).map(f=>pt(f))),n=et(1,r+1).map(f=>e.filter(g=>pt(g.schedule?.courtOrder)===f)),o={},i={},s={};n.flat().filter(Boolean).sort(Mi).forEach(({schedule:f})=>delete f[ng]);let c=ut(e.map(({drawId:f})=>f)),u=sn({includeParticipantDependencies:!0,tournamentRecords:t,drawIds:c}).matchUpDependencies,p=n.map((f,g)=>f.reduce((I,h)=>{if(!h.matchUpId)return I;let{matchUpId:S,winnerMatchUpId:T,loserMatchUpId:y,schedule:P,sides:U,potentialParticipants:E}=h,A=P?.courtId;o[S]=g,i[A]=[],I.matchUpIds.push(S),s[S]=h;let N=u[S].matchUpIds;N.length&&I.sourceMatchUpIds.push(...N);let D=U?.map(R=>[R.participant?.individualParticipantIds,R.participantId]).flat().filter(Boolean)??[],M=E?.flat().map(({individualParticipantIds:R,participantId:b})=>[R,b]).flat().filter(Boolean)||[];return I.participantIds.push(...M,...D),T&&I.targetMatchUpIds.push(T),y&&I.targetMatchUpIds.push(y),I},{sourceMatchUpIds:[],targetMatchUpIds:[],participantIds:[],matchUpIds:[]})),m=(f,g)=>u[f].sources.reduce((I,h,S)=>h.includes(g)&&S+1||I,0),d=p.map(()=>[]),l=(f,g,I,h)=>{if(!s[f].schedule[ng]){s[f].schedule[ng]=g,s[f].schedule[qU]=h,d[o[f]].push({matchUpId:f,issueType:I,issueIds:h,issue:g});let S=s[f].schedule.courtId;i[S]||(i[S]=[]),i[S].push({matchUpId:f,issue:g,issueType:I,issueIds:h})}};return p.forEach((f,g)=>{let I=g?p[g-1]:void 0,h=p.slice(g+1),S={},T=Sr(f.participantIds),y=Object.keys(T).filter(E=>T[E]>1),P=f.matchUpIds.filter(E=>u[E].participantIds.some(A=>y.includes(A)));P.forEach(E=>{S[E]||(S[E]={}),S[E][uc]||(S[E][uc]=P.filter(A=>A!==E))});let U=I&&f.participantIds.filter(E=>I.participantIds.includes(E));U&&U.forEach(E=>{let A=f.matchUpIds.concat(I.matchUpIds).filter(N=>u[N].participantIds.includes(E));A.forEach(N=>{S[N]||(S[N]={}),S[N][pc]||(S[N][pc]=A.filter(D=>D!==N))})}),f.matchUpIds.forEach(E=>{let A=u[E].matchUpIds;for(let D of h){let M=D.matchUpIds.filter(R=>A.includes(R));M?.length&&(M.forEach(R=>l(R,uS,Aa,[E])),l(E,uS,Aa,M))}if(S[E]?.[uc]&&l(E,uc,cS,S[E][uc]),f.sourceMatchUpIds.includes(E)){let D=f.matchUpIds.filter(M=>u[M].matchUpIds.includes(E));l(E,uc,Aa,D),f.matchUpIds.filter(M=>u[M].matchUpIds.includes(E)).forEach(M=>l(M,uc,Aa,[E]))}let N=I?.matchUpIds?.filter(D=>m(E,D)>1);if(N?.length&&(l(E,pS,Aa,N),N.forEach(D=>l(D,pS,Aa,[E]))),S[E]?.[pc]&&l(E,pc,cS,S[E][pc]),I?.targetMatchUpIds?.includes(E)){let D=s[E].schedule.courtId,M=A.filter(b=>I.matchUpIds.includes(b));M.some(b=>s[b].schedule.courtId===D)||(M.forEach(b=>l(b,pc,Aa,[E])),l(E,pc,Aa,M))}})}),{courtIssues:i,rowIssues:d}}function dR(t){let e="reorderUpcomingMatchUps",{tournamentRecords:r}=t;if(typeof r!="object"||!Object.keys(r).length)return _({result:{error:wt},stack:e});let{matchUpsContextIds:n,firstToLast:o}=t;if(!n)return _({result:{error:st},stack:e});let i=n?.length;if(!i)return{...C};let s=0;return n.forEach((c,u)=>{let{tournamentId:p,drawId:m,matchUpId:d}=c,l=u+(o?-1:1);l<0&&(l=i-1),l===i&&(l=0);let f=n[l].schedule.scheduledTime,g=a({tournamentId:p,scheduledTime:f,matchUpId:d,drawId:m});if(g.success)s++;else return g}),s===i?C:_({result:{error:PE},stack:e});function a({tournamentId:c,scheduledTime:u,matchUpId:p,drawId:m}){let d=r[c],{drawDefinition:l}=wo({tournamentRecord:d,drawId:m});return l?zo({drawDefinition:l,scheduledTime:u,matchUpId:p}):{error:Mr}}}function lR(t){let{scheduleChange:e,matchUpIds:r,dryRun:n}=t;if(!r||!Array.isArray(r))return{error:rs};if(typeof e!="object")return{error:G};let o=Dr(t),i=[],s=[];for(let c of Object.values(o)){let u=n0({tournamentRecord:c,scheduleChange:e,matchUpIds:r,dryRun:n});if(u.error)return u;Array.isArray(u.notRescheduled)&&s.push(...u.notRescheduled);let p=$m(u.notRescheduled),m=[];u.rescheduled?.forEach(d=>{let{matchUpId:l}=d;p.includes(l)&&m.push(l),i.push(d)}),m.length&&(s=u?.notRescheduled?.filter(({matchUpId:d})=>!m.includes(d))||[])}let a=!!(i.length&&!s.length);return{...C,rescheduled:i,notRescheduled:s,allRescheduled:a}}function n0({tournamentRecord:t,scheduleChange:e,matchUpIds:r,dryRun:n}){if(!t)return{error:Y};if(!r||!Array.isArray(r))return{error:rs};if(typeof e!="object")return{error:G};let o=[],i=[],{minutesChange:s,daysChange:a}=e;if(!s&&!a)return{...C};if(s&&isNaN(s))return{error:G};if(a&&isNaN(a))return{error:G};let{matchUps:c}=Te({matchUpFilters:{matchUpIds:r},tournamentRecord:t}),u=({matchUpStatus:y})=>!ce.includes(y),p=c?.filter(y=>_a({schedule:y.schedule})).filter(y=>u({matchUpStatus:y.matchUpStatus}));if(!p?.length)return{...C};let{tournamentInfo:m}=Us({tournamentRecord:t}),{startDate:d,endDate:l}=m,f=p?.reduce((y,P)=>{let{matchUpId:U,drawId:E}=P;return y[E]?y[E].push(U):y[E]=[U],y},{}),g=1440;for(let y of Object.keys(f)){let P=wo({tournamentRecord:t,drawId:y});if(P.error)return P;let U=P.drawDefinition,E=f[y].filter(A=>r.includes(A));for(let A of E)if(A&&U){let D=p.find(x=>x.matchUpId===A)?.schedule,{scheduledTime:M,scheduledDate:R}=D,b,v,O;if(!b&&a&&R){let x=Et(R);O=sp(x,a),b=new Date(O)<new Date(d)||new Date(O)>new Date(l)}if(s&&M){let x=Et(M),L=qt(Kt(M))+s;if(b=L<0||L>g,!b){let w=Yr(M,s),V=x&&O||R===x&&x;v=V?`${V}T${w}`:w}}if(b)i.push(A);else{if(!n){if(v){let x=zo({scheduledTime:v,drawDefinition:U,matchUpId:A});if(x.error)return x}if(O){let x=nm({scheduledDate:O,drawDefinition:U,matchUpId:A});if(x.error)return x}}(v||O)&&o.push(A)}}}let I=Te({matchUpFilters:{matchUpIds:r},tournamentRecord:t}).matchUps??[],h=I.filter(({matchUpId:y})=>o.includes(y)),S=I.filter(({matchUpId:y})=>i.includes(y)),T=h.length&&!S.length;return{...C,rescheduled:h,notRescheduled:S,allRescheduled:T}}function fR(t){let e="matchUpScheduleChange",{tournamentRecords:r}=t;if(typeof r!="object"||!Object.keys(r).length)return{error:wt};let{sourceMatchUpContextIds:n,targetMatchUpContextIds:o,sourceCourtId:i,targetCourtId:s,courtDayDate:a}=t||{},{drawId:c,matchUpId:u,tournamentId:p}=n||{},{drawId:m,matchUpId:d,tournamentId:l}=o||{};if(!u&&!d)return _({result:{error:st},stack:e});let{matchUps:f}=Un({matchUpFilters:{matchUpIds:[u,d].filter(Boolean),drawIds:[c,m].filter(Boolean)},tournamentRecords:t.tournamentRecords}),g=f?.find(({matchUpId:y})=>y===u),I=f?.find(({matchUpId:y})=>y===d),h=0;if(s&&u&&!d){let y=S({tournamentId:p,matchUpId:u,courtId:s,matchUp:g,drawId:c,tournamentRecords:r,sourceCourtId:i,courtDayDate:a});if(y?.success&&h++,y.error)return _({result:y,stack:e})}else if(i&&s&&u&&d){let y=S({tournamentId:p,matchUpId:u,courtId:s,matchUp:g,drawId:c,tournamentRecords:r,sourceCourtId:i,courtDayDate:a});if(y.success&&h++,y.error)return _({result:y,stack:e,info:"source"});let P=S({tournamentId:l,sourceCourtId:s,matchUpId:d,matchUp:I,courtId:i,drawId:m,tournamentRecords:r,courtDayDate:a});if(P.success&&h++,P.error)return _({result:P,stack:e,info:"target"})}else return{error:st};return h?C:_({result:{error:_s},stack:e});function S(y){let{tournamentRecords:P,tournamentId:U,matchUp:E,drawId:A}=y,N=P[U],{drawDefinition:D}=wo({tournamentRecord:N,drawId:A});return E.matchUpType===jt?T({...y,tournamentRecord:N,drawDefinition:D}):Xi({...y,tournamentRecord:N,drawDefinition:D})}function T({removePriorValues:y,tournamentRecords:P,tournamentRecord:U,drawDefinition:E,sourceCourtId:A,courtDayDate:N,matchUpId:D,matchUp:M,courtId:R}){let b=[R].concat(M.schedule.allocatedCourts.map(({courtId:v})=>v).filter(v=>v!==A));return om({removePriorValues:y,tournamentRecords:P,tournamentRecord:U,drawDefinition:E,courtDayDate:N,matchUpId:D,courtIds:b})}}function gR({scheduleAttributes:t=[so,Bo,Hi,Wi,ji,Oo,Di,Pi,Yi],tournamentRecord:e,drawDefinition:r,matchUpId:n}){let o="clearMatchUpSchedule",i=r?or({matchUpFilters:{matchUpIds:[n]},inContext:!1,drawDefinition:r}).matchUps?.[0]:Te({matchUpFilters:{matchUpIds:[n]},tournamentRecord:e,inContext:!1}).matchUps?.[0];if(!i)return{error:Le};let s=(i.timeItems??[]).filter(a=>a?.itemType&&!t.includes(a?.itemType));return i.timeItems=s,gt({tournamentId:e.tournamentId,context:o,drawDefinition:r,matchUp:i}),{...C}}function IR(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:wt};if(typeof n!="object")return{error:lo};let i=Object.keys(o).filter(s=>!r||r===s);if(r&&!i.includes(r))return{error:G};for(let s of i){let a=o[s],c=At({extension:{name:ou,value:{dailyLimits:n}},element:a});if(c.error)return c}return{...C}}var RR={};Xt(RR,{addCollectionDefinition:()=>SI,addCollectionGroup:()=>UR,aggregateTieFormats:()=>NR,compareTieFormats:()=>$o,getTieFormat:()=>QT,modifyCollectionDefinition:()=>II,modifyTieFormat:()=>DR,mutate:()=>MR,orderCollectionDefinitions:()=>ER,query:()=>uN,removeCollectionDefinition:()=>hI,removeCollectionGroup:()=>yR,tieFormatGenderValidityCheck:()=>Mm,validateCollectionDefinition:()=>qc});var MR={};Xt(MR,{addCollectionDefinition:()=>SI,addCollectionGroup:()=>UR,aggregateTieFormats:()=>NR,modifyCollectionDefinition:()=>II,modifyTieFormat:()=>DR,orderCollectionDefinitions:()=>ER,removeCollectionDefinition:()=>hI,removeCollectionGroup:()=>yR});function ui({drawDefinition:t,structureId:e,matchUpId:r,structure:n,matchUp:o,eventId:i,event:s}){let a="getTieFormat",c;if(e=n?.structureId??e,r=o?.matchUpId??r,(r||e)&&!t)return{error:Z};if(i&&s)c=ni(s);else if(r){if(t&&(!o||!n)){let u=Bt({drawDefinition:t,matchUpId:r});if(u.error)return u;if(u.matchUp?.matchUpType!==xr)return _({result:{error:dr},stack:a});n||(n=u.structure),o||(o=u.matchUp)}c=Tp({item:o,drawDefinition:t,structure:n,event:s})||Tp({item:n,drawDefinition:t,structure:n,event:s})||ni(t)||ni(s)}else if(t&&e){if(!n){let u=at({drawDefinition:t,structureId:e});if(u.error)return u;n=u?.structure}c=Tp({item:n,drawDefinition:t,structure:n,event:s})||ni(t)||ni(s)}else c=ni(t)||ni(s);return c?{...C,structure:n,tieFormat:c,matchUp:o}:_({result:{error:bs},stack:a})}function Nl({matchUp:t,updateInProgressMatchUps:e}){return!t.winningSide&&![ce].includes(t.matchUpStatus)&&(e||t.matchUpStatus!==Ln&&!Ie(t))}function TR({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 lw({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((U,E)=>(U[E.collectionId]=(U[E.collectionId]||0)+E.matchUpCount,U),{}),I=({tieFormat:U})=>{let E=U?.collectionDefinitions.reduce((A,N)=>(A[N.collectionId]=(A[N.collectionId]||0)+N.matchUpCount,A),{});return TR({from:E,to:g}).equivalent},h=ui({drawDefinition:r})?.tieFormat,S=ui({event:a})?.tieFormat;if(a&&i){for(let U of a.drawDefinitions??[])T({drawDefinition:U});a.tieFormat=ir(o),f+=1}else if(s){if(!s.tieMatchUps)return _({result:{error:dr},stack:u});let U=Sr(s.tieMatchUps?.map(({collectionId:M})=>M)),E=TR({to:g,from:U}),{changes:A,changesArePossible:N,cannotChangeReaon:D}=dw({matchUp:s,check:E});if(E.equivalent)if(Nl({matchUp:s,updateInProgressMatchUps:t}))s.tieFormat=ir(o),f+=1;else return _({result:{error:$l},info:"matchUp is IN_PROGRESS or COMPLETE",stack:u});else if(N)P({tieFormat:o,matchUp:s,changes:A,uuids:c});else return _({context:{collectionMap:g,matchUpMap:U},result:{error:Lo},info:D||"specified changes not possible",stack:u});d+=1,gt({eventId:a?.eventId,context:u,drawDefinition:r,tournamentId:p,matchUp:s})}else if(n){let E=y({inheritedTieFormat:h??S,structure:n})?.modifiedMatchUpsCount;E&&(d+=E,m+=1,f+=1);let A=!n.tieFormat||$o({ancestor:n.tieFormat,descendant:o}).different;A&&(n.tieFormat=ir(o),m+=1,f+=1),(E||A)&&r&&Ot({structureIds:[n.structureId],eventId:a?.eventId,drawDefinition:r})}else if(r)T({drawDefinition:r}),r.tieFormat=ir(o),f+=1;else return{error:Z};return{modifiedStructuresCount:m,modifiedMatchUpsCount:d,addedMatchUpsCount:l,modifiedCount:f,...C,tieFormat:o};function T({drawDefinition:U}){let E=U.structures||[],A=[];for(let N of E){if(N.tieFormat)continue;let M=y({inheritedTieFormat:S,structure:N})?.modifiedMatchUpsCount;if(M){m+=1,d+=M;let R=N.structureId;A.push(R)}}return Ot({structureIds:A,eventId:a?.eventId,drawDefinition:U}),A.length}function y({inheritedTieFormat:U,structure:E}){let A=0,N=Ut({matchUpFilters:{matchUpTypes:[jt]},structure:E})?.matchUps||[];for(let D of N){let M=Nl({matchUp:D,updateInProgressMatchUps:t}),R=!1,b=Sr(D.tieMatchUps?.map(({collectionId:O})=>O)),v=TR({from:b,to:g});if(v.equivalent)D.tieFormat&&I(D)&&M&&(D.tieFormat=ir(o),R=!0);else{let{changes:O,changesArePossible:x}=dw({matchUp:D,check:v});if(x&&!D.tieFormat)P({changes:O,matchUp:D,tieFormat:o,uuids:c});else if(U)(!D.tieFormat||$o({ancestor:U,descendant:D.tieFormat}).different)&&(D.tieFormat=U,R=!0);else return _({result:{error:bs},stack:u})}R&&(A+=1,gt({tournamentId:e?.tournamentId,drawDefinition:r,context:u,eventId:i,matchUp:D}))}return{modifiedMatchUpsCount:A}}function P({uuids:U,matchUp:E,tieFormat:A,changes:N}){E.tieFormat=ir(A);let D=[],M=[];return N.forEach(R=>{if(R.countChange>0){let b=Math.max(0,...E.tieMatchUps.filter(x=>x.collectionId===R.collectionId).map(Br("collectionPosition"))),v=A.collectionDefinitions.find(x=>x.collectionId===R.collectionId),O=Du({matchUpsLimit:R.countChange,collectionPositionOffset:b,collectionDefinition:v,matchUp:E,uuids:U});M.push(...J(O,!1,!0)),l+=M.length,E.tieMatchUps.push(...O)}else{let b=R.toBePlayedTieMatchUpIds.slice(0,Math.abs(R.countChange));console.log("remove",b.length),D.push(...b),E.tieMatchUps=E.tieMatchUps.filter(({matchUpId:v})=>!b.includes(v))}}),M.length&&Co({matchUps:M,drawDefinition:r,tournamentId:p,eventId:i}),D.length&&Yn({matchUpIds:D,action:"updateTieFormat",drawDefinition:r,tournamentId:p,eventId:i}),{matchUpIdsRemoved:D,matchUpsAdded:M}}}function dw({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===Qt).map(Br("matchUpId")),c=a.length+s>=0||s>0;return!c&&s<0&&(r="Insufficient TO_BE_PLAYED matchUps"),n.push({toBePlayedTieMatchUpIds:a,collectionId:i,countChange:s}),c}),changes:n,cannotChangeReaon:r}}function Bu({appliedPolicies:t,drawDefinition:e,auditData:r}){if(!t?.audit?.[qm])return;let{extension:n}=dt({name:qm,element:e}),o={value:Array.isArray(n?.value)?n?.value.concat(r):[r],name:qm};At({element:e,extension:o})}function II({updateInProgressMatchUps:t=!1,tournamentRecord:e,collectionOrder:r,collectionName:n,tieFormatName:o,drawDefinition:i,matchUpFormat:s,matchUpCount:a,collectionId:c,matchUpType:u,structureId:p,matchUpId:m,category:d,eventId:l,gender:f,event:g,collectionValueProfiles:I,collectionValue:h,matchUpValue:S,scoreValue:T,setValue:y}){let P="modifyCollectionDefinition";if(s&&!Pr({matchUpFormat:s}))return _({result:{error:G},context:{matchUpFormat:s},stack:P});if(n&&typeof n!="string")return _({result:{error:G},context:{collectionName:n},stack:P});if(f&&!Object.values(Nm).includes(f))return _({result:{error:G},context:{gender:f},stack:P});if(d&&typeof d!="object")return _({result:{error:G},context:{category:d},stack:P});let U={collectionValueProfiles:I,collectionValue:h,matchUpValue:S,scoreValue:T,setValue:y};if(!Object.values(U).filter(Boolean).length&&!r&&!n&&!s&&!a&&!u)return _({result:{error:st},stack:P});if(Object.values(U).filter(Boolean).length>1)return _({info:"Only one value assignment allowed per collectionDefinition",result:{error:G},stack:P});let E=ui({drawDefinition:i,structureId:p,matchUpId:m,eventId:l,event:g});if(E.error)return _({result:E,stack:P});let{matchUp:A,structure:N,tieFormat:D}=E,M=ir(D),R=D?.collectionDefinitions.find(K=>K.collectionId===c),b=M?.collectionDefinitions.find(K=>K.collectionId===c);if(!R)return _({info:"source collectionDefinition",result:{error:ve},context:{collectionId:c},stack:P});let v=h??S??T??y;if(I?.length){let K=CI({matchUpCount:a??R?.matchUpCount??0,collectionValueProfiles:I});if(K.errors)return _({result:{error:G},info:K.errors,stack:P})}else if(v&&!It(v))return _({result:{error:G},info:"value is not an integer",context:{value:v},stack:P});let O=(K,q)=>Yt(Object.keys(K),Object.keys(q)).length===Object.keys(K).length&&Yt(Object.values(K),Object.values(q)).length===Object.values(K).length,x=I&&(!R.collectionValueProfiles||!O(R.collectionValueProfiles,I)),F=It(h)&&R.collectionValue!==h||It(S)&&R.matchUpValue!==S||It(T)&&R.scoreValue!==T||It(y)&&R.setValue!==y||x,L=[];if(F&&(b.collectionValueProfiles=void 0,b.collectionValue=void 0,b.matchUpValue=void 0,b.scoreValue=void 0,b.setValue=void 0,Object.assign(b,U),L.push({collectionId:c,...ot(U)})),(It(T)||It(y))&&b.collectionGroupNumber){let K=b.collectionGroupNumber;M.collectionDefinitions=M.collectionDefinitions.map(q=>{let{collectionGroupNumber:B,...$}=q;return B===K?$:q}),M.collectionGroups=M.collectionGroups.filter(({groupNumber:q})=>q!==K),L.push({collectionId:c,change:"collectionGroupNumber removed"})}let{aggregateValue:w,valueGoal:V}=Ps(M),k=ot({aggregateValue:w,valueGoal:V});if((k.aggregateValue!==D?.winCriteria.aggregateValue||k.valueGoal!==D?.winCriteria.valueGoal)&&(M.winCriteria=k,L.push({collectionId:c,winCriteria:k})),It(r)&&R.collectionOrder!==r&&(b.collectionOrder=r,L.push({collectionId:c,collectionOrder:r})),n&&R.collectionName!==n&&(b.collectionName=n,L.push({collectionId:c,collectionName:n})),s&&R.matchUpFormat!==s&&(b.matchUpFormat=s,L.push({collectionId:c,matchUpFormat:s})),It(a)&&R.matchUpCount!==a&&(b.matchUpCount=a,L.push({collectionId:c,matchUpCount:a})),u&&R.matchUpType!==u)return _({result:{error:Zu},context:{matchUpType:u},stack:P});d&&R.category!==d&&(b.category=d,L.push({collectionId:c,category:d})),f&&R.gender!==f&&(b.gender=f,L.push({collectionId:c,gender:f}));let W=ot(M);if(E=ar({tieFormat:W}),E.error)return _({result:E,stack:P});if(!L.length)return _({result:{...C,modifications:L}});if(D?.tieFormatName!==o?(W.tieFormatName=o,L.push({tieFormatName:o})):L.length&&(delete W.tieFormatName,L.push("tieFormatName removed: modifications without new tieFormatName")),E=lw({tieFormat:W,updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:i,structure:N,eventId:l,matchUp:A,event:g}),!E.error){let{appliedPolicies:K}=yt({tournamentRecord:e}),q=ot({collectionDefinition:b,drawId:i?.drawId,action:P,structureId:p,matchUpId:m,eventId:l});Bu({appliedPolicies:K,drawDefinition:i,auditData:q})}return _({result:{...E,modifications:L},stack:P})}function fw({updateInProgressMatchUps:t,drawDefinition:e,structureId:r,structure:n,matchUpId:o,matchUp:i}){let s=[];return o&&i?s=[i]:r&&n?s=Ut({matchUpFilters:{matchUpTypes:[jt]},structure:n})?.matchUps??[]:e&&(s=or({matchUpFilters:{matchUpTypes:[jt]},drawDefinition:e})?.matchUps??[]),{targetMatchUps:s.filter(c=>!c.winningSide&&c.matchUpStatus!==le&&(t||c.matchUpStatus!==Ln&&!Ie(c)))}}function gw({updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:r,targetMatchUps:n,tieFormat:o,event:i}){for(let s of n){let a=!!s.tieFormat;a&&(s.tieFormat=ir(o));let c;if(t){let u=yt({tournamentRecord:e,drawDefinition:r,event:i}).appliedPolicies,p=co({matchUpId:s.matchUpId,exitWhenNoValues:!0,tournamentRecord:e,appliedPolicies:u,drawDefinition:r,event:i});if(p.error)return p;c=p.score}a&&!c&>({tournamentId:e?.tournamentId,context:"updateTargetTeamMatchUps",eventId:i?.eventId,matchUp:s,drawDefinition:r})}return{...C}}function dA({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}=Ps(c);c.winCriteria=ot({aggregateValue:l,valueGoal:f}),(e&&e!==f||l&&!n)&&(o?c.tieFormatName=o:delete c.tieFormatName);let{targetMatchUps:g}=fw({updateInProgressMatchUps:t,drawDefinition:i,structureId:s,structure:a,matchUpId:u,matchUp:p});gw({updateInProgressMatchUps:t,tournamentRecord:r,targetMatchUps:g,drawDefinition:i,tieFormat:c,event:d});let I=ot(c),h=ar({tieFormat:I});if(h.error)return h;if(m&&d)d.tieFormat=I;else if(u&&p)p.tieFormat=c;else if(a)a.tieFormat=I;else if(i)i.tieFormat=I;else if(!p||!i)return{error:Z};return Ot({drawDefinition:i,eventId:d?.eventId}),{...C}}function yR({updateInProgressMatchUps:t=!0,collectionGroupNumber:e,tournamentRecord:r,drawDefinition:n,tieFormatName:o,structureId:i,matchUpId:s,matchUp:a,eventId:c,event:u}){if(!e)return{error:st};if(isNaN(e))return{error:G};let p="removeCollectionGroup",m=a?void 0:ui({drawDefinition:n,structureId:i,matchUpId:s,eventId:c,event:u});if(m?.error)return _({result:m,stack:p});let d=m?.structure;a=a??m?.matchUp;let l=m?.tieFormat,f=l?.winCriteria.valueGoal,g=l?.winCriteria.aggregateValue,I=ir(l);if(m=ar({tieFormat:I}),m.error)return _({result:m,stack:p});let h=[];if(I.collectionDefinitions=I.collectionDefinitions.map(S=>{let{collectionGroupNumber:T,...y}=S;return T!==e?S:(h.push(S.collectionId),y)}),I.collectionGroups=I.collectionGroups.filter(({groupNumber:S})=>S!==e),m=dA({updateInProgressMatchUps:t,originalValueGoal:f,wasAggregateValue:g,tournamentRecord:r,drawDefinition:n,tieFormatName:o,structureId:i,structure:d,tieFormat:I,matchUpId:s,matchUp:a,eventId:c,event:u}),!m.error){let{appliedPolicies:S}=yt({tournamentRecord:r}),T=ot({drawId:n?.drawId,collectionGroupNumber:e,action:p,structureId:i,matchUpId:s,eventId:c});Bu({appliedPolicies:S,drawDefinition:n,auditData:T})}return _({result:{...m,modifiedCollectionIds:h},stack:p})}function Ml({tieFormat:t,orderMap:e}){let r=ir(t);return r.collectionDefinitions.forEach(n=>{let o=e[n.collectionId];o&&(n.collectionOrder=o)}),r.collectionDefinitions?.sort((n,o)=>Ba(n.collectionOrder)-Ba(o.collectionOrder)),r}function ER({tournamentRecord:t,drawDefinition:e,structureId:r,matchUpId:n,orderMap:o,eventId:i,matchUp:s,event:a}){if(typeof o!="object"||!Object.values(o).every(c=>It(c)))return _({result:{error:G},context:{orderMap:o}});if(i&&a?.tieFormat)Iw({tournamentRecord:t,event:a,orderMap:o});else if(n){let c=e&&Bt({drawDefinition:e,matchUpId:n});if(c?.error)return c;if(s=c.matchUp,!s)return{error:hr};s?.tieFormat&&(s.tieFormat=Ml({tieFormat:s.tieFormat,orderMap:o}),gt({tournamentId:t?.tournamentId,eventId:a?.eventId,drawDefinition:e,matchUp:s}))}else if(r){let c=at({drawDefinition:e,structureId:r});if(c.error)return c;let u=c.structure;if(u?.tieFormat)u.tieFormat=Ml({tieFormat:u.tieFormat,orderMap:o}),hw({eventId:a?.eventId,tournamentRecord:t,drawDefinition:e,structure:u,orderMap:o}),Ot({drawDefinition:e,structureIds:[u.structureId]});else if(e.tieFormat)AR({structureIds:[r],tournamentRecord:t,drawDefinition:e,orderMap:o,event:a});else if(a?.tieFormat)Iw({structureIds:[r],tournamentRecord:t,orderMap:o,event:a});else return{error:ve}}else if(e?.tieFormat)AR({tournamentRecord:t,drawDefinition:e,orderMap:o,event:a});else return{error:ve};return{...C}}function Iw({tournamentRecord:t,structureIds:e,orderMap:r,event:n}){let o=Ml({tieFormat:n.tieFormat,orderMap:r});e?.length||(n.tieFormat=o);for(let i of n.drawDefinitions??[])AR({tournamentRecord:t,drawDefinition:i,structureIds:e,orderMap:r,event:n})}function AR({tournamentRecord:t,drawDefinition:e,structureIds:r,orderMap:n,event:o}){let i=e.tieFormat??o?.tieFormat,s=Ml({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=Ml({tieFormat:c.tieFormat??e.tieFormat??o?.tieFormat,orderMap:n})),hw({eventId:o?.eventId,tournamentRecord:t,drawDefinition:e,structure:c,orderMap:n}),a.push(c.structureId));Ot({drawDefinition:e,structureIds:a})}function hw({tournamentRecord:t,drawDefinition:e,structure:r,orderMap:n,eventId:o}){let i=Ut({matchUpFilters:{matchUpTypes:[jt]},structure:r})?.matchUps;for(let s of i)s.tieFormat&&(s.tieFormat=Ml({tieFormat:s.tieFormat,orderMap:n}),gt({tournamentId:t?.tournamentId,drawDefinition:e,eventId:o,matchUp:s}))}function hI({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:ui({drawDefinition:n,structureId:s,matchUpId:a,eventId:c,event:p});if(d?.error)return _({result:d,stack:m});let l=d?.structure;u=u??d?.matchUp;let f=d?.tieFormat,g=ir(f);if(d=ar({tieFormat:g}),d.error)return _({result:d,stack:m});let I=g?.collectionDefinitions?.find(M=>M.collectionId===i);if(!I)return _({result:{error:ve,collectionId:i}});g.collectionDefinitions=g.collectionDefinitions.filter(M=>M.collectionId!==i),I.collectionGroupNumber&&(g.collectionDefinitions=g.collectionDefinitions.map(M=>{let{collectionGroupNumber:R,...b}=M;return b}),g.collectionGroups=g.collectionGroups.filter(({groupNumber:M})=>M!==I.collectionGroupNumber));let{aggregateValue:h,valueGoal:S}=Ps(g);g.winCriteria=ot({aggregateValue:h,valueGoal:S});let T=f?.winCriteria.valueGoal,y=f?.winCriteria.aggregateValue;(T&&T!==S||h&&!y)&&(o?g.tieFormatName=o:delete g.tieFormatName);let P=[];a&&u?P=[u]:s&&l?P=Ut({matchUpFilters:{matchUpTypes:[jt]},structure:l})?.matchUps??[]:n?P=or({matchUpFilters:{matchUpTypes:[jt]},drawDefinition:n})?.matchUps??[]:p&&(P=$n({matchUpFilters:{matchUpTypes:[jt]},drawDefinition:n})?.matchUps??[]);let U=(P||[]).filter(M=>{let b=M.tieMatchUps?.filter(O=>O.collectionId===i)?.some(Ie),v=e&&M.tieFormat?$o({descendant:M.tieFormat,ancestor:g})?.different:!1;return t&&!b||!M.winningSide&&M.matchUpStatus!==le&&(t||M.matchUpStatus!==Ln&&!Ie(M)&&!v)});if(!U.length)return{error:_s};let{appliedPolicies:E}=yt({tournamentRecord:r});if(a&&u&&t){let M=u.tieMatchUps?.filter(R=>R.collectionId===i);for(let R of M??[]){let b=La({matchUpId:R.matchUpId,tieMatchUpId:u?.matchUpId,winningSide:void 0,removeScore:!0,tournamentRecord:r,appliedPolicies:E,drawDefinition:n,event:p});if(b.error||(b=Bt({drawDefinition:n,matchUpId:a}),b.error))return b;u=b?.matchUp}}let A=[];for(let M of U){for(let R of M?.sides??[])R.lineUp=(R.lineUp??[]).map(b=>({participantId:b.participantId,collectionAssignments:(b?.collectionAssignments??[]).filter(v=>v.collectionId!==i)}));if(M.tieMatchUps=(M.tieMatchUps??[]).filter(R=>{let b=R.collectionId===i;return b&&A.push(R.matchUpId),!b}),M.tieFormat&&(M.tieFormat=ir(g)),t){let R=co({matchUpId:M.matchUpId,exitWhenNoValues:!0,tournamentRecord:r,appliedPolicies:E,drawDefinition:n,event:p});if(R.error)return R}gt({tournamentId:r?.tournamentId,eventId:p?.eventId,drawDefinition:n,context:m,matchUp:M})}A.length&&Yn({tournamentId:r?.tournamentId,matchUpIds:A,eventId:p?.eventId,drawDefinition:n});let N=ot(g);if(d=ar({tieFormat:N}),d.error)return _({result:d,stack:m});if(c&&p)p.tieFormat=N;else if(a&&u)u.tieFormat=N;else if(l)l.tieFormat=N;else if(n)n.tieFormat=N;else if(!u||!n)return{error:Z};Ot({drawDefinition:n,eventId:p?.eventId});let D=ot({drawId:n?.drawId,action:m,collectionId:i,structureId:s,matchUpId:a,eventId:c});return Bu({appliedPolicies:E,drawDefinition:n,auditData:D}),{tieFormat:N,deletedMatchUpIds:A,targetMatchUps:U,...C}}function UR({updateInProgressMatchUps:t=!0,tournamentRecord:e,groupDefinition:r,drawDefinition:n,collectionIds:o,tieFormatName:i,structureId:s,matchUpId:a,matchUp:c,eventId:u,event:p}){let m="addCollectionGroup";if(!Array.isArray(o))return _({result:{error:st},stack:m});let d=c?void 0:ui({drawDefinition:n,structureId:s,matchUpId:a,eventId:u,event:p});if(d?.error)return _({result:d,stack:m});let l=d?.structure;c=c||d?.matchUp;let f=d?.tieFormat,g=f?.winCriteria.valueGoal,I=ir(f);if(d=ar({tieFormat:I}),d.error)return _({result:d,stack:m});for(let T of I.collectionDefinitions){let{collectionId:y,collectionGroupNumber:P}=T;if(P&&o.includes(y))return _({info:"collectionIds cannot be part of other collectionGroups",result:{error:G},stack:m})}let S=(I.collectionGroups||[]).reduce((T,y)=>y.groupNumber>T?y.groupNumber:T,0)+1;return r.groupNumber=S,I.collectionDefinitions=I.collectionDefinitions.map(T=>o.includes(T.collectionId)?{...T,collectionGroupNumber:S}:T),I.collectionGroups=[...I.collecitonGroups||[],r],dA({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 SI({updateInProgressMatchUps:t=!0,collectionDefinition:e,referenceCategory:r,tournamentRecord:n,policyDefinitions:o,enforceCategory:i,referenceGender:s,drawDefinition:a,tieFormatName:c,enforceGender:u,structureId:p,matchUpId:m,matchUp:d,eventId:l,uuids:f,event:g}){let I="addCollectionDefinition",h=yt({tournamentRecord:n,drawDefinition:a,event:g}).appliedPolicies??{},S=o?.[er]??h?.[er];i=i??S?.participants?.enforceCategory;let T=(u??S?.participants?.enforceGender)!==!1,y=!!((r??g?.category)&&i!==!1),P=!!((s??g?.gender)&&T),U=qc({referenceCategory:r??g?.category,collectionDefinition:e,referenceGender:s,checkCategory:y,checkGender:P,event:g});if(U.error)return _({result:U,stack:I});let E=d?.tieFormat?void 0:ui({drawDefinition:a,structureId:p,matchUpId:m,eventId:l,event:g});if(E?.error)return _({result:{error:E.error},stack:I});let A=E?.structure;d=d??E?.matchUp;let N=d?.tieFormat??E?.tieFormat,D=ir(N);if(E=ar({tieFormat:D}),E?.error)return _({result:{error:E.error},stack:I});if(!e.collectionId)e.collectionId=Dt();else if(D.collectionDefinitions.map(({collectionId:k})=>k).includes(e.collectionId))return _({context:{collectionId:e.collectionId},result:{error:RE}});D.collectionDefinitions.push(e),D.collectionDefinitions.sort((V,k)=>(V.collectionOrder||0)-(k.collectionOrder||0)).forEach((V,k)=>V.collectionOrder=k+1);let{aggregateValue:M,valueGoal:R}=Ps(D);D.winCriteria=ot({aggregateValue:M,valueGoal:R});let b=N?.winCriteria.valueGoal,v=N?.winCriteria.aggregateValue;(b&&b!==R||M&&!v)&&(c?D.tieFormatName=c:delete D.tieFormatName);let O=[],x=[],F=[],L=ot(D);if(E=ar({tieFormat:L}),E?.error)return _({result:{error:E.error},stack:I});if(l&&g){g.tieFormat=L;for(let V of g.drawDefinitions??[])if(!V.tieFormat)for(let k of V.structures??[]){if(k.tieFormat)continue;let W=PR({updateInProgressMatchUps:t,collectionDefinition:e,structure:k,uuids:f});x.push(...W.newMatchUps),F.push(...W.targetMatchUps),O.push(k.structureId)}lA({modifiedMatchUps:F,eventId:g?.eventId,modifiedStructureIds:O,tournamentRecord:n,drawDefinition:a,addedMatchUps:x,stack:I})}else if(p&&A){A.tieFormat=L;let V=PR({updateInProgressMatchUps:t,collectionDefinition:e,structure:A,uuids:f});x.push(...V.newMatchUps),F=V.targetMatchUps,lA({modifiedMatchUps:F,eventId:g?.eventId,modifiedStructureIds:O,tournamentRecord:n,drawDefinition:a,addedMatchUps:x,stack:I})}else if(m&&d){if(!Nl({matchUp:d,updateInProgressMatchUps:t}))return _({result:{error:$l},stack:I});d.tieFormat=L;let V=Du({collectionDefinition:e,matchUp:d,uuids:f});Array.isArray(d.tieMatchUps)||(d.tieMatchUps=[]),d.tieMatchUps.push(...V),x.push(...V),lA({modifiedMatchUps:[d],eventId:g?.eventId,modifiedStructureIds:O,tournamentRecord:n,drawDefinition:a,addedMatchUps:x,stack:I})}else if(a){a.tieFormat=L;for(let V of a.structures??[]){let k=PR({updateInProgressMatchUps:t,collectionDefinition:e,structure:V,uuids:f});O.push(V.structureId),x.push(...k.newMatchUps),F.push(...k.targetMatchUps)}lA({modifiedMatchUps:F,eventId:g?.eventId,tournamentRecord:n,drawDefinition:a,addedMatchUps:x,stack:I})}else return{error:Z};let w=ot({drawId:a?.drawId,collectionDefinition:e,action:I,structureId:p,matchUpId:m,eventId:l});return Bu({appliedPolicies:h,drawDefinition:a,auditData:w}),{tieFormat:L,targetMatchUps:F,addedMatchUps:x,...C}}function PR({updateInProgressMatchUps:t,collectionDefinition:e,structure:r,uuids:n}){let o=[],s=(Ut({matchUpFilters:{matchUpTypes:[jt]},structure:r})?.matchUps).filter(a=>Nl({matchUp:a,updateInProgressMatchUps:t})&&!a.tieFormat);for(let a of s){let c=Du({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 lA({modifiedStructureIds:t,tournamentRecord:e,modifiedMatchUps:r,drawDefinition:n,addedMatchUps:o,eventId:i,stack:s}){Co({tournamentId:e?.tournamentId,matchUps:o,drawDefinition:n,eventId:i}),r?.forEach(a=>{gt({tournamentId:e?.tournamentId,drawDefinition:n,context:s,matchUp:a,eventId:i})}),Ot({structureIds:t,drawDefinition:n,eventId:i})}function DR({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(!ar({tieFormat:r}).valid)return _({result:{error:Lo},info:"falied validation",stack:m});let d=ui({drawDefinition:i,structureId:s,matchUpId:a,eventId:c,event:p});if(d.error)return _({result:d,stack:m});let{matchUp:l,tieFormat:f}=d,g=ir(f),I=$o({descendant:r,ancestor:g,considerations:o});if(I.invalid)return _({context:{invalid:I.invalid},result:{error:Lo},stack:m});if(!I?.different)return _({result:{...C},info:"Nothing to do",stack:m});let h=g.collectionDefinitions.map(({collectionId:D})=>D),S=r.collectionDefinitions.map(({collectionId:D})=>D),T=h.filter(D=>!S.includes(D)),y=r.collectionDefinitions.filter(({collectionId:D})=>!h.includes(D)),P=y.map(Br("collectionId")),U=[],E,A=r.tieFormatName;for(let D of r.collectionDefinitions){if(P.includes(D.collectionId))continue;let M=II({updateInProgressMatchUps:t,...D,tournamentRecord:n,tieFormatName:A,drawDefinition:i,structureId:s,matchUpId:a,eventId:c,event:p});if(M.modifications&&U.push(...M.modifications),M.error)return _({result:M,stack:m});M.tieFormat&&(E=M.tieFormat)}for(let D of y){let M=SI({updateInProgressMatchUps:t,collectionDefinition:D,tournamentRecord:n,drawDefinition:i,tieFormatName:A,structureId:s,matchUpId:a,matchUp:l,eventId:c,uuids:u,event:p});if(M.error)return _({result:M,stack:m});M.tieFormat&&(E=M.tieFormat)}for(let D of T){let M=hI({updateInProgressMatchUps:t,tieFormatComparison:e,tournamentRecord:n,drawDefinition:i,tieFormatName:A,collectionId:D,structureId:s,matchUpId:a,eventId:c,matchUp:l,event:p});if(M.error)return _({result:M,stack:m});M.tieFormat&&(E=M.tieFormat)}return f?.tieFormatName!==A?(E.tieFormatName=A,U.push({tieFormatName:A})):(U.length||P.length||T.length)&&(delete E.tieFormatName,U.push("tieFormatName removed: modifications without new tieFormatName")),E.collectionDefinitions=E.collectionDefinitions.sort((D,M)=>Ba(D.collectionOrder)-Ba(M.collectionOrder)).map((D,M)=>({...D,collectionOrder:M+1})),{processedTieFormat:ir(E),modifications:U,...C}}function NR({tournamentRecord:t}){if(!t)return{error:Y};let e=0;for(let r of t.events??[]){let n=r.tieFormats??[],o=p=>{if(!p.tieFormat)return;let m;for(let d of n)$o({descendant:p.tieFormat,ancestor:d}).different||(m=d.tieFormatId);if(m)p.tieFormatId=m,delete p.tieFormat;else{let d=J(p.tieFormat,void 0,!0);d.tieFormatId||(d.tieFormatId=Dt()),p.tieFormatId=d.tieFormatId,delete p.tieFormat,n.push(d),e+=1}},i=r.eventType;o({tieFormat:r.tieFormat,eventType:i});for(let p of r.drawDefinitions??[]){o({tieFormat:p.tieFormat,eventType:i});for(let m of p.structures??[])o({tieFormat:m.tieFormat,eventType:i})}let s=(p,m)=>{let d=c.matchUps?.find(l=>l.matchUpId===p);d&&(d.tieFormatId=m,delete d.tieFormat,gt({tournamentId:t?.tournamentId,eventId:r.eventId,matchUp:d}))},a=p=>{let m=J(p.tieFormat,void 0,!0);m.tieFormatId||(m.tieFormatId=Dt()),n.push(m),e+=1,s(p.matchUpId,m.tieFormatId)},c=$n({matchUpFilters:{matchUpTypes:[xr]},event:r}),u=c.matchUps??[];for(let p of u){let m;for(let d of n)p.tieFormat&&$o({descendant:p.tieFormat,ancestor:d}).different||(m=d.tieFormatId);m?s(p.matchUpId,m):a(p)}n.length&&(r.tieFormats=n)}return{...C,addedCount:e}}var VR={};Xt(VR,{addDrawDefinitionExtension:()=>fp,addEventExtension:()=>Mo,addEventTimeItem:()=>zi,addExtension:()=>At,addNotes:()=>Fp,addOnlineResource:()=>_R,addParticipantExtension:()=>gU,addParticipantTimeItem:()=>Rg,addTimeItem:()=>Qn,addTournamentExtension:()=>Cf,addTournamentTimeItem:()=>Pc,analyzeDraws:()=>Cu,analyzeTournament:()=>KT,copyTournamentRecord:()=>CR,createTournamentRecord:()=>um,generate:()=>bR,getAggregateTeamResults:()=>$T,getAllowedDrawTypes:()=>Kd,getAllowedMatchUpFormats:()=>WT,getAppliedPolicies:()=>yt,getCompetitionDateRange:()=>Qd,getCompetitionPenalties:()=>jT,getPolicyDefinitions:()=>vo,getTournamentInfo:()=>Us,getTournamentPenalties:()=>zd,getTournamentPersons:()=>qT,getTournamentPoints:()=>Xd,getTournamentStructures:()=>vS,getTournamentTimeItem:()=>Jm,mutate:()=>GR,query:()=>aN,removeDrawDefinitionExtension:()=>IU,removeEventExtension:()=>gp,removeExtension:()=>gr,removeNotes:()=>Ng,removeOnlineResource:()=>OR,removeParticipantExtension:()=>hU,removeTournamentExtension:()=>bf,setTournamentCategories:()=>LR,setTournamentDates:()=>TI,setTournamentEndDate:()=>kR,setTournamentName:()=>xR,setTournamentNotes:()=>wR,setTournamentStartDate:()=>FR,setTournamentStatus:()=>vR});var bR={};Xt(bR,{copyTournamentRecord:()=>CR,createTournamentRecord:()=>um});function CR(t){let e=rt(t,[{tournamentRecord:!0,startDate:!0,endDate:!1,tournamentName:!0}]);if(e.error)return e;let{startDate:r,endDate:n}=t.tournamentRecord,o=24*60*60*1e3,s=(r&&n?new Date(Et(n)).getTime()-new Date(Et(r)).getTime():0)/o,a=t.endDate||JI(t.startDate,s),c=l=>l?.filter(({itemType:f})=>t.itemTypeList?.includes(f)),u=l=>l?.filter(({name:f})=>t.extensionList?.includes(f)),p=l=>{let{timeItems:f,extensions:g,...I}=l;return J({...I,timeItems:c(f),extensions:u(g)},!1,!0)},m=l=>{let{drawDefinitions:f,timeItems:g,extensions:I,startDate:h,endDate:S,...T}=l;return J({extensions:u(I),timeItems:c(g),startDate:t.startDate,endDate:a,...T},!1,!0)},d={participants:t.copyParticipants?t.tournamentRecord.participants?.map(p)??[]:[],parentOrganisation:J({...t.tournamentRecord.parentOrganisation},!1,!0),venues:J(t.tournamentRecord.venues??[],!1,!0),extensions:u(t.tournamentRecord.extensions),timeItems:c(t.tournamentRecord.timeItems),events:t.tournamentRecord.events?.map(m)??[],weekdays:[...t.tournamentRecord.weekdays??[]],tournamentName:t.tournamentName,startDate:t.startDate,tournamentId:Dt(),endDate:a};return{...C,tournamentRecord:d}}var GR={};Xt(GR,{addDrawDefinitionExtension:()=>fp,addEventExtension:()=>Mo,addEventTimeItem:()=>zi,addExtension:()=>At,addNotes:()=>Fp,addOnlineResource:()=>_R,addParticipantExtension:()=>gU,addParticipantTimeItem:()=>Rg,addTimeItem:()=>Qn,addTournamentExtension:()=>Cf,addTournamentTimeItem:()=>Pc,removeDrawDefinitionExtension:()=>IU,removeEventExtension:()=>gp,removeExtension:()=>gr,removeNotes:()=>Ng,removeOnlineResource:()=>OR,removeParticipantExtension:()=>hU,removeTournamentExtension:()=>bf,setTournamentCategories:()=>LR,setTournamentDates:()=>TI,setTournamentEndDate:()=>kR,setTournamentName:()=>xR,setTournamentNotes:()=>wR,setTournamentStartDate:()=>FR,setTournamentStatus:()=>vR});var o0="ABANDONED",i0="ACTIVE",s0="CANCELLED",a0="COMPLETED",c0="IN_PROGRESS",fA={ABANDONED:o0,ACTIVE:i0,CANCELLED:s0,COMPLETED:a0,IN_PROGRESS:c0};function vR({tournamentRecord:t,status:e}){return t?e&&!Object.keys(fA).includes(e)?{error:G,info:"Unknown status"}:(t.tournamentStatus=e,{...C}):{error:Y}}function OR(t){let e=rt(t,[{tournamentRecord:!0,onlineResource:!0}]);if(e.error)return e;let{tournamentRecord:r,onlineResource:n,organisationId:o,participantId:i,personId:s,courtId:a,venueId:c}=t;if(o){if(r.parentOrganisation?.parentOrganisationId!==o)return _({result:{error:ve}});Rl({element:r.parentOrganisation,onlineResource:n})}else if(i||s){let u=(r.participants??[]).find(p=>s&&p.person?.personId===s||p.participantId===i);if(!u)return s?_({result:{error:ve}}):_({result:{error:te}});if(s){if(u.person?.personId!==s)return _({result:{error:xi}});Rl({element:u.person,onlineResource:n})}else Rl({element:u,onlineResource:n})}else if(a){let u=(r.venues??[]).filter(p=>!c||p.venueId===c).flatMap(p=>(p.courts??[]).filter(m=>m.courtId===a))?.[0];if(!u)return _({result:{error:Os}});Rl({element:u,onlineResource:n})}else if(c){let u=(r.venues??[]).find(p=>p.venueId===c);if(!u)return _({result:{error:Li}});Rl({element:u,onlineResource:n})}else Rl({element:r,onlineResource:n}),mt({payload:{parentOrganisation:r.parentOrganisation,onlineResources:r.onlineResources,tournamentId:r.tournamentId},topic:Bi});return{...C}}function Rl({element:t,onlineResource:e}){let r=(t.onlineResources??[]).filter(n=>!(n?.[Ja]===e[Ja]&&n?.[Za]===e[Za]&&n?.[tc]===e[tc]));t.onlineResources=r}function _R(t){let e=rt(t,[{tournamentRecord:!0,onlineResource:!0}]);if(e.error)return e;let{tournamentRecord:r,onlineResource:n,organisationId:o,participantId:i,personId:s,courtId:a,venueId:c}=t;if(o){if(r.parentOrganisation?.parentOrganisationId!==o)return _({result:{error:ve}});Cl({element:r.parentOrganisation,onlineResource:n})}else if(i||s){let u=(r.participants??[]).find(p=>s&&p.person?.personId===s||p.participantId===i);if(!u)return s?_({result:{error:ve}}):_({result:{error:te}});if(s){if(u.person?.personId!==s)return _({result:{error:xi}});Cl({element:u.person,onlineResource:n})}else Cl({element:u,onlineResource:n})}else if(a){let u=(r.venues??[]).filter(p=>!c||p.venueId===c).flatMap(p=>(p.courts??[]).filter(m=>m.courtId===a))?.[0];if(!u)return _({result:{error:Os}});Cl({element:u,onlineResource:n})}else if(c){let u=(r.venues??[]).find(p=>p.venueId===c);if(!u)return _({result:{error:Li}});Cl({element:u,onlineResource:n})}else Cl({element:r,onlineResource:n}),mt({payload:{parentOrganisation:r.parentOrganisation,onlineResources:r.onlineResources,tournamentId:r.tournamentId},topic:Bi});return{...C}}function Cl({element:t,onlineResource:e}){let r=(t.onlineResources??[]).filter(n=>n?.[Ja]!==e[Ja]&&n?.[Za]!==e[Za]&&n?.[tc]!==e[tc]);return r.push(e),t.onlineResources=r,{...C}}function xR({tournamentRecord:t,promotionalName:e,tournamentName:r,formalName:n}){if(!t)return{error:Y};let o=t.tournamentId,i={tournamentId:o};return r&&r!==t.tournamentName&&(t.tournamentName=r,i.tournamentName=r),e&&e!==t.promotionalName&&(t.promotionalName=e,i.promotionalName=e),n&&n!==t.formalName&&(t.formalName=n,i.formalName=n),t.promotionalName===t.tournamentName&&(delete t.promotionalName,i.promotionalName=""),t.formalName===t.tournamentName&&(delete t.formalName,i.formalName=""),Object.keys(i).length>1&&mt({topic:Bi,payload:{parentOrganisation:t.parentOrganisation,tournamentId:o,...i}}),{...C}}function wR({tournamentRecord:t,notes:e}){if(!t)return{error:Y};let r=e?Fp({element:t,notes:e}):Ng({element:t});return r.error?r:(mt({topic:Bi,payload:{parentOrganisation:t.parentOrganisation,tournamentId:t.tournamentId,notes:e??""}}),{...C})}function LR({tournamentRecord:t,categories:e}){return t?(e=(e||[]).filter(r=>r.categoryName&&r.type),t.tournamentCategories=e,mt({topic:Bi,payload:{parentOrganisation:t.parentOrganisation,tournamentId:t.tournamentId,categories:e}}),{...C}):{error:Y}}function Sw({tournamentRecord:t}){if(!t)return{error:Y};let{startDate:e,endDate:r}=t,n=ws(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=qt(p.startTime),l=qt(p.endTime);return m.startTime&&qt(m.startTime)<d&&(p.startTime=m.startTime),m.endTime&&qt(m.endTime)>l&&(p.endTime=m.endTime),p},{startTime:"08:00",endTime:"18:00"}),c=n.map(p=>i.dateAvailability?.find(d=>d.date===p)??{date:p,startTime:s,endTime:a}),u=i.dateAvailability?.find(p=>!p.date);u&&c.unshift(u),i.dateAvailability=c}return{...C}}function TI(t){let{tournamentRecord:e,startDate:r,endDate:n,weekdays:o}=t,i=t.activeDates?.filter(Boolean),s=rt(t,[{tournamentRecord:!0},{[tr]:l=>Po.test(l),[Fr]:je,startDate:!1,endDate:!1},{[tr]:l=>l.filter(Boolean).every(f=>Po.test(f)),[Fr]:je,activeDates:!1},{[tr]:Dy,weekdays:!1}]);if(s.error)return s;if(n&&r&&new Date(n)<new Date(r))return{error:G};if(n&&r&&new Date(r)>new Date(n))return{error:G};if(i?.length){let l=r||e.startDate,f=n||e.endDate,g=!l||i.every(h=>new Date(h)>=new Date(l)),I=!f||i.every(h=>new Date(h)<=new Date(f));if(!g||!I)return{error:je}}let a;(r&&e.startDate&&new Date(r)>new Date(e.startDate)||n&&e.endDate&&new Date(n)<new Date(e.endDate))&&(a=!0);let c=ws(e.startDate,e.endDate);r&&(e.startDate=r),n&&(e.endDate=n);let u=ws(e.startDate,e.endDate),p=c.filter(l=>!u.includes(l)),m=u.filter(l=>!c.includes(l));for(let l of e.events??[])r&&l.startDate&&new Date(l.startDate)<new Date(r)&&(l.startDate=r),n&&l.startDate&&new Date(l.startDate)>new Date(n)&&(l.startDate=r??n),n&&l.endDate&&new Date(l.endDate)>new Date(n)&&(l.endDate=n),r&&l.endDate&&new Date(l.endDate)<new Date(r)&&(l.endDate=n??r);r&&e.endDate&&new Date(r)>new Date(e.endDate)&&(e.endDate=r),n&&e.startDate&&new Date(n)<new Date(e.startDate)&&(e.startDate=n),i&&(e.activeDates=i),o&&(e.weekdays=o);let d=a&&u0({tournamentRecord:e})?.unscheduledMatchUpIds;return Sw({tournamentRecord:e}),mt({payload:ot({parentOrganisation:e.parentOrganisation,tournamentId:e.tournamentId,activeDates:i,startDate:r,weekdays:o,endDate:n}),topic:Bi}),{...C,unscheduledMatchUpIds:d,datesAdded:m,datesRemoved:p}}function FR({tournamentRecord:t,startDate:e}){return e?TI({tournamentRecord:t,startDate:e}):{error:je}}function kR({tournamentRecord:t,endDate:e}){return e?TI({tournamentRecord:t,endDate:e}):{error:je}}function u0({tournamentRecord:t}){let e=Te({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&&!am({scheduledDates:o,tournamentRecord:t}).clearedScheduleCount?{error:bA}:{unscheduledMatchUpIds:i}}var QR={};Xt(QR,{addCourt:()=>Ul,addCourts:()=>lI,addVenue:()=>mc,deleteCourt:()=>$R,deleteVenue:()=>IA,deleteVenues:()=>HR,disableCourts:()=>WR,disableVenues:()=>jR,enableCourts:()=>YR,enableVenues:()=>qR,generate:()=>BR,generateCourts:()=>Zg,getCompetitionVenues:()=>$p,getCourts:()=>gy,getVenuesAndCourts:()=>Ao,modifyCourt:()=>AI,modifyCourtAvailability:()=>yI,modifyVenue:()=>KR,mutate:()=>zR,publicFindVenue:()=>dS,query:()=>UN});var BR={};Xt(BR,{generateCourts:()=>Zg});var zR={};Xt(zR,{addCourt:()=>Ul,addCourts:()=>lI,addVenue:()=>mc,deleteCourt:()=>$R,deleteVenue:()=>IA,deleteVenues:()=>HR,disableCourts:()=>WR,disableVenues:()=>jR,enableCourts:()=>YR,enableVenues:()=>qR,modifyCourt:()=>AI,modifyCourtAvailability:()=>yI,modifyVenue:()=>KR});function bl(t){if(!t?.tournamentRecord&&!Array.isArray(t?.venueMatchUps))return{error:Y};if(!t?.courtId)return{error:_i};let{scheduleVisibilityFilters:e,tournamentRecord:r,matchUpFilters:n,venueMatchUps:o,courtId:i}=t,{schedulingProfile:s}=Ko({tournamentRecord:r});if(Array.isArray(o))return{matchUps:u({matchUps:o,courtId:i})};let{matchUps:a}=Te({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 sl({matchUps:d,schedulingProfile:s})}}function Tw({scheduleVisibilityFilters:t,tournamentRecord:e,matchUpFilters:r,venueId:n}){if(!e)return{error:Y};if(!n)return{error:Xo};let{schedulingProfile:o}=Ko({tournamentRecord:e}),{matchUps:i}=Te({scheduleVisibilityFilters:t,tournamentRecord:e,matchUpFilters:r});return{matchUps:a({matchUps:i,venueId:n})};function a({matchUps:c,venueId:u}){let p=c.filter(m=>{let d=m.schedule?.allocatedCourts?.map(({venueId:l})=>l);return m.schedule?.venueId===u||d?.includes(u)});return sl({matchUps:p,schedulingProfile:o})}}function yI({tournamentRecord:t,dateAvailability:e,disableNotice:r,venueMatchUps:n,courtId:o,force:i}){if(!t)return{error:Y};if(!o)return{error:_i};let s=cA({dateAvailability:e});if(s.error)return s;let{updatedDateAvailability:a,totalMergeCount:c}=p0(e);e=a;let u=ps({tournamentRecord:t,courtId:o});if(u.error)return u;let{court:p,venue:m}=u,{matchUps:d}=bl({tournamentRecord:t,venueMatchUps:n,courtId:o});if(d?.length){let l=yt({tournamentRecord:t})?.appliedPolicies,f=i??l?.[No]?.allowDeletionWithScoresPresent?.courts,g=[];g.length&&(f||console.log("throw error: scheduled court matchUps",g.length))}return p&&(p.dateAvailability=e,!r&&m&&mt({payload:{venue:m,tournamentId:t.tournamentId},topic:yi,key:m.venueId})),{...C,totalMergeCount:c}}function p0(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(ow);let{mergedAvailability:i,mergeCount:s}=m0(r[o]);n.push(...i.map(a=>({date:o,...a}))),e+=s}),{updatedDateAvailability:n,totalMergeCount:e}}function m0(t){let e,r,n,o=t.length,i=0,s=[];for(;t.length&&o;){let c=t.shift(),{startTime:u,endTime:p,bookings:m}=c;if(o-=1,!e)e=u,n=m,r=p;else if(ma(ke(r),ke(u),!1)>0){let l={startTime:e,endTime:r};n?.length&&(l.bookings=n),s.push(l),e=u,n=m,r=p}else m&&(n?n.push(m):n=m),r=p,i+=1}let a={startTime:e,endTime:r};return n?.length&&(a.bookings=n),s.push(a),{mergedAvailability:s,mergeCount:i}}function vl({matchUpsCount:t=0}){let r=`Schedule would be deleted from ${t} ${t===1?"matchUp":"matchUps"}; use { force: true }`;return{error:_E,info:r}}function gA({tournamentRecord:t,drawDefinition:e,matchUpId:r,drawId:n}){let o="removeCourtAssignment";if(!r)return{error:sr};if(!e&&!n)return{error:an};let i;if(!e){if(!t)return{error:Y};({drawDefinition:e}=ze({tournamentRecord:t,drawId:n}))}if(e)({matchUp:i}=Bt({drawDefinition:e,matchUpId:r}));else{if(!t)return{error:Y};let s=Te({tournamentRecord:t,inContext:!1}).matchUps??[];({matchUp:i}=zS({matchUps:s,matchUpId:r}))}return i?(i.timeItems&&i.timeItems.find(a=>[Bo,so].includes(a.itemType))&&(i.timeItems=i.timeItems.filter(({itemType:a})=>![Bo,so].includes(a)),gt({tournamentId:t?.tournamentId,context:o,drawDefinition:e,matchUp:i})),{...C}):{error:Le}}function IA(t){if(typeof t?.venueId!="string")return{error:Xo};let{tournamentRecord:e,venueId:r,force:n}=t,o=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!Object.keys(o).length)return{error:Y};let s=Un({tournamentRecords:o,contextFilters:{venueIds:[r]}}).matchUps??[],a=yt({tournamentRecord:e})?.appliedPolicies,c=n??a?.[No]?.allowDeletionWithScoresPresent?.venues;if(!s.length||c)for(let u of Object.values(o)){for(let m of s){let d=gA({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&&mt({payload:{venueId:r,tournamentId:u.tournamentId},topic:Lf,key:r})}else return vl({matchUpsCount:s.length});return Rc({tournamentRecords:o}),{...C}}function HR({tournamentRecord:t,venueIds:e,force:r}){if(!t)return{error:Y};if(!Array.isArray(e))return{error:G};for(let n of t.venues||[]){let{venueId:o}=n;if(e.includes(o)){let{venueId:i}=n,s=IA({tournamentRecord:t,venueId:i,force:r});if(s.error)return s}}return{...C}}function WR(t){let{courtIds:e,dates:r}=t,n=Dr(t),o=[{[Re]:!0,[dp]:!0}],i=rt(t,o);if(i.error)return i;for(let s of Object.values(n))d0({tournamentRecord:s,courtIds:e,dates:r});return{...C}}function d0({tournamentRecord:t,courtIds:e,dates:r}){let n=Array.isArray(r)&&r.length?{dates:r}:!0,o=i=>At({extension:{value:n,name:no},creationTime:!1,element:i});for(let i of t.venues||[])for(let s of i.courts||[])if(e?.includes(s.courtId)){let a=o(s);if(a.error)return a}return{...C}}function jR(t){let{tournamentRecords:e,tournamentId:r,venueIds:n}=t,o=[{[Re]:!0,[lp]:!0}],i=rt(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];l0({tournamentRecord:c,venueIds:n})}return{...C}}function l0({tournamentRecord:t,venueIds:e}){for(let r of t.venues||[])if(e?.includes(r.venueId)){let n=At({creationTime:!1,element:r,extension:{name:no,value:!0}});if(n.error)return n}return{...C}}function YR(t){let e=Dr(t),r=[{[Re]:!0}];!t.enableAll&&r.push({[dp]:!0});let n=rt(t,r);if(n.error)return n;let{enableAll:o,courtIds:i,dates:s}=t;for(let a of Object.values(e))f0({tournamentRecord:a,courtIds:i,enableAll:o,dates:s});return{...C}}function f0({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}=dt({element:i,name:no});if(s){let a=s.value;Array.isArray(a.dates)&&(a.dates=a.dates.filter(c=>!n.includes(c))),At({extension:{name:no,value:a},creationTime:!1,element:i})}}else gr({element:i,name:no});return{...C}}function qR(t){let e=Dr(t),r=[{[Re]:!0}];!t.enableAll&&r.push({[lp]:!0});let n=rt(t,r);if(n.error)return n;let{venueIds:o,enableAll:i}=t;for(let s of Object.values(e))for(let a of s.venues||[])(i||o?.includes(a.venueId))&&gr({element:a,name:no});return{...C}}function $R(t){let{courtId:e,disableNotice:r,force:n}=t,o=Dr(t),i=rt(t,[{[Re]:!0,[Mh]:!0}]);if(i.error)return i;let s,a;for(let c of Object.values(o)){if(a=g0({tournamentRecord:c,disableNotice:r,courtId:e,force:n}),a.error&&a.error!==Os)return a;a.success&&(s=!0)}return s?{...C}:a}function g0({tournamentRecord:t,disableNotice:e,courtId:r,force:n}){let o=ps({tournamentRecord:t,courtId:r});if(o.error)return o;let i=o.venue,{matchUps:s}=bl({tournamentRecord:t,courtId:r}),a=yt({tournamentRecord:t})?.appliedPolicies,c=n??a?.[No]?.allowDeletionWithScoresPresent?.courts;if(!s?.length||c){for(let u of s??[]){let p=gA({matchUpId:u.matchUpId,drawId:u.drawId,tournamentRecord:t});if(p.error)return p}i&&(i.courts=(i.courts??[]).filter(u=>u.courtId!==r),e||mt({payload:{venue:i,tournamentId:t.tournamentId},topic:yi,key:i.venueId}))}else return vl({matchUpsCount:s.length});return{...C}}function AI(t){let{disableNotice:e,modifications:r,courtId:n,force:o,venueMatchUps:i}=t,s=Dr(t);if(!Object.keys(s).length)return{error:wt};let a,c;for(let u of Object.values(s)){let p=I0({tournamentRecord:u,disableNotice:e,venueMatchUps:i,modifications:r,courtId:n,force:o});if(p?.error)return p;a=!0}return a?{...C}:c}function I0({tournamentRecord:t,disableNotice:e,venueMatchUps:r,modifications:n,courtId:o,force:i}){if(!t)return{error:Y};if(!o)return{error:_i};if(!n||typeof n!="object")return{error:lo};let s=ps({tournamentRecord:t,courtId:o});if(s.error)return s;let{venue:a,court:c}=s,u=Object.keys(nw()).filter(l=>l!=="courtId");if(!Object.keys(n).filter(l=>u.includes(l)).length)return{error:Ju};let m=u.filter(l=>!["dateAvailability"].includes(l)),d=Object.keys(n).filter(l=>m.includes(l));if(c&&d.forEach(l=>Object.assign(c,{[l]:n[l]})),n.dateAvailability){let l=yI({dateAvailability:n.dateAvailability,tournamentRecord:t,venueMatchUps:r,disableNotice:e,courtId:o,force:i});if(l.error)return l}return e||mt({payload:{venue:a,tournamentId:t.tournamentId},topic:yi,key:a?.venueId}),{...C,court:J(c)}}var h0=()=>({venueId:void 0,venueName:"",venueAbbreviation:"",onlineResources:[],venueType:void 0,addresses:[],contacts:[],courts:[],roles:[]}),yw=h0;function KR(t){let{modifications:e,venueId:r,force:n}=t,o=Dr(t);if(!Object.keys(o).length)return{error:wt};if(typeof r!="string")return{error:Xo};let i,s;for(let a of Object.values(o)){let c=S0({tournamentRecord:a,modifications:e,venueId:r,force:n});if(c.success&&(s=!0),c.error&&(i=c.error),c.error&&c.error!==Li)return c}return Rc({tournamentRecords:o}),s?{...C}:{error:i}}function S0({tournamentRecord:t,modifications:e,venueId:r,force:n}){if(!t)return{error:Y};if(!e||typeof e!="object")return{error:lo};if(!r)return{error:Xo};let o=yt({tournamentRecord:t})?.appliedPolicies,i=n??o?.[No]?.allowDeletionWithScoresPresent?.venues,{matchUps:s}=Tw({tournamentRecord:t,venueId:r}),a=Wo({tournamentRecord:t,venueId:r});if(a.error)return a;let c=a.venue,u=Object.keys(yw()).filter(h=>h!=="venueId");if(!Object.keys(e).filter(h=>u.includes(h)).length)return{error:Ju};let m=u.filter(h=>!["courts","onlineResources"].includes(h)),d=Object.keys(e).filter(h=>m.includes(h));c&&d.forEach(h=>Object.assign(c,{[h]:e[h]}));let l=c?.courts?.map(h=>h.courtId)??[],f=e.courts?.map(h=>h.courtId)||[],g=f.length?l.filter(h=>!f.includes(h)):e?.courts&&l,I=[];if(g?.length){let S=c?.courts?.filter(T=>g.includes(T.courtId))?.map(T=>{let y=bl({courtId:T.courtId,tournamentRecord:t,venueMatchUps:s});for(let P of y.matchUps??[])I.push({matchUpId:P.matchUpId,drawId:P.drawId});return y.matchUps?.length??0}).reduce((T,y)=>T+y);if(c&&(!S||i))c.courts=c.courts?.filter(T=>f.includes(T.courtId)),Vu({schedule:{courtId:"",scheduledDate:""},matchUpDetails:I,removePriorValues:!0,tournamentRecord:t});else return vl({matchUpsCount:S})}if(e.courts)for(let h of e.courts){let{courtId:S}=h||{},T=AI({modifications:h,disableNotice:!0,tournamentRecord:t,venueMatchUps:s,courtId:S,force:n});if(T.error===Os&&(T=Ul({disableNotice:!0,tournamentRecord:t,venueId:r,court:h})),T.error)return T}return Rc({tournamentRecord:t}),c&&mt({payload:{venue:c,tournamentId:t.tournamentId},topic:yi,key:c?.venueId}),{...C,venue:J(c)}}var XR={};Xt(XR,{JSON2CSV:()=>Nw,UUID:()=>Dt,UUIDS:()=>th,allNumeric:()=>DI,attributeFilter:()=>Vi,chunkArray:()=>ye,chunkByNth:()=>xl,chunkSizeProfile:()=>DA,constantToString:()=>Qe,countValues:()=>pC,createMap:()=>RI,dateTime:()=>ZI,definedAttributes:()=>ot,dehydrateMatchUps:()=>Dw,extractAttributes:()=>QU,flattenJSON:()=>SA,generateDateRange:()=>ws,generateHashCode:()=>hC,generateRange:()=>et,generateTimeCode:()=>uA,groupValues:()=>UA,hasAttributeValues:()=>IC,instanceCount:()=>Sr,intersection:()=>Yt,isConvertableInteger:()=>It,isNumeric:()=>Zt,isOdd:()=>UI,isPowerOf2:()=>vn,makeDeepCopy:()=>J,matchUpScheduleSort:()=>Pw,matchUpSort:()=>Mi,nearestPowerOf2:()=>Sm,nextPowerOf2:()=>es,noNulls:()=>uC,noNumeric:()=>NI,numericSort:()=>me,occurrences:()=>mC,overlap:()=>Fe,randomMember:()=>yn,randomPop:()=>tn,shuffleArray:()=>Ir,structureSort:()=>Si,subSort:()=>dC,undefinedToNull:()=>MI,unique:()=>ut,visualizeScheduledMatchUps:()=>Aw});function Aw({scheduledMatchUps:t,showGlobalLog:e}){rv();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=>{Rn({color:"blue",method:"draw",structure:n[o],keyColors:{structure:"magenta"}},!0);let i=t.filter(a=>a.structureId===o),s=Ke({matchUps:i})?.roundMatchUps||[];Object.keys(s).forEach(a=>{Rn({roundNumber:a,keyColors:{roundNumber:"brightcyan"}},!0),s[a].forEach(({matchUpId:c,schedule:u})=>{let p=Kt(u.scheduledTime);Rn({matchUpId:c,time:p,date:u.scheduledDate,venue:u.venueId,keyColors:{time:"brightcyan",date:"brightcyan",matchUpId:"yellow",venue:"magenta"}},!0)})})}),e&&ev()}var{extractTime:Ew,timeStringMinutes:Uw}=ZI;function Pw(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=Uw(Ew(r.scheduledTime)),i=Uw(Ew(n.scheduledTime));return o-i}}return new Date(r.scheduledDate).getTime()-new Date(n.scheduledDate).getTime()}return 0}function Dw({tournamentRecord:t}){if(!t)return{error:Y};if(typeof t!="object"||!t.tournamentId)return{error:G};let{matchUps:e}=Te({tournamentRecord:t,inContext:!1});if(e?.length){let r=T0({tournamentRecord:t});A0(e,r)}return{...C}}function T0({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 y0=["collectionId","collectionPosition","drawPositions","extensions","finishingPositionRange","finishingRound","isMock","matchUpId","matchUpStatus","matchUpStatusCodes","orderOfFinish","processCodes","roundNumber","tieFormat","tieMatchUps","roundPosition","score","sides","winnerMatchUpId","loserMatchUpId","matchUpDuration","winningSide"];function A0(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))y0.includes(c)||delete r[c];r.sides&&r.drawPositions&&!r.tieMatchUps&&delete r.sides,a&&(r.matchUpFormat=a)}}function Nw(t,e){if(e&&typeof e!="object")return{error:G};let{columnTransform:r={}}=e||{},{includeTransformAccessors:n,includeHeaderRow:o=!0,returnTransformedJSON:i,removeEmptyColumns:s,onlyHeaderRow:a,columnAccessors:c=[],functionMap:u={},columnMap:p={},valuesMap:m={},context:d={},delimiter:l='"',columnJoiner:f=",",rowJoiner:g=`\r
|
|
26
|
+
`),u=r?.map(({key:l,value:f})=>`${l}="${f}"`).join(" "),p=u?` ${u}`:"";if(e==="childArray")return c;let m=c?.length?`${i}${c}${i}`:"",d=a?.length?`${i}${a}${i}`:"";return`<${e}${p}>${m}${d}</${e}>`}function lx(t){let e=rt(t,[{[ie]:!0}]);if(e.error)return e;let{tournamentRecord:r}=t,{startDate:n,tournamentId:o,tournamentName:i}=r,{participantMap:s,matchUps:a,mappedMatchUps:c}=Gt({withMatchUps:!0,withEvents:!0,tournamentRecord:r}),u=r.participants.filter(y=>y.participantType===Lt),p=a?.filter(y=>y.matchUpType===Lt)??[],m=p?.reduce((y,P)=>{let U=P?.tieMatchUps??[];return U&&[...y,...U]},[])??[],d=a?.filter(y=>y.matchUpType===xt)??[],l=a?.filter(y=>y.matchUpType===_t)??[],f=m.length===d.length+l.length,g=p.length===1&&f,h={mappedMatchUps:c,participantMap:s,tournamentName:i,tournamentId:o,tournament:f?"N":"Y",startDate:n},S=[],T=[];if(g){let y=p[0],{json:P,xml:U}=mx({teamParticipants:u,teamMatchUp:y,...h,doubles:l,singles:d});T.push(P),S.push(U)}else for(let y of p){let P=y?.sides?.map(({participant:N})=>N?.participantId).filter(Boolean);if(P?.length!==2)continue;let U=P.map(N=>N&&s?.[N]?.participant),{xml:E,json:A}=mx({doubles:y.tieMatchUps?.filter(N=>N.matchUpType===_t),singles:y.tieMatchUps?.filter(N=>N.matchUpType===xt),teamParticipants:U,teamMatchUp:y,...h});T.push(A),S.push(E)}return{json:T,xml:S,...C}}function mx({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=Hn(a,"/","MDY"),l=p?.participantName||m?.[1]?.participantName,f=p?.participantId||m?.[1]?.participantId,g=m?.[0]?.participantName,I=m?.[0]?.participantId,h={},S=t.map(y=>({team:{...S1({teamParticipant:y,teamMatchUp:i,uniValues:h,participantMap:r,mappedMatchUps:e,homeid:f})}})),T=ot({venue:{tournamentname:s?n:void 0,neutralgame:p?"N":"Y",gameid:o,officials:{},tournament:s,rules:{},homename:l,visname:g,homeid:f,visid:I,date:d},childArray:S,singles_matches:u?.map(y=>dx({matchUp:y,homeid:f,uniValues:h})),doubles_matches:c?.map(y=>dx({matchUp:y,homeid:f,uniValues:h}))});return{json:T,xml:QN({json:T,tagName:"tngame"})}}function I1({homeid:t,uniValues:e,participant:r}){if(!r)return{};let n=r.individualParticipants?.length===2,o=n?ut(r.individualParticipants?.map(g=>g.teams?.[0]?.participantId)):[],i=n?ut(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 ot({vh:m,uni:d,uni_1:l,uni_2:f,team:a,name:c,name_1:u,name_2:p})}function h1({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 S1({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:P})=>P.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 P of p??[]){let U=n?.[P],E=U.sides.find(({participant:N})=>N.participantId===s)?.sideNumber,A=U.score?.sets?.[0]?.[`side${E}Score`]??0;I+=A;for(let N of U.tieMatchUps??[]){let{matchUpType:D,winningSide:M}=N,R=M&&(M===E?"w":"l")||"";R&&(l[D][R]+=1);let b=R==="w"?"1":"0",v=R==="l"?"1":"0";if(D===xt){let O=g.length+1;g.push({singles_pair:{pair:O,won:b,lost:v,tied:"0"}})}else if(D===_t){let O=f.length+1;f.push({doubles_pair:{pair:O,won:b,lost:v,tied:"0"}})}}}let h=[{singles:{childArray:g,won:l.SINGLES.w,lost:l.SINGLES.l}},{doubles:{childArray:f,won:l.DOUBLES.w,lost:l.DOUBLES.l}}],S=[],T=1;for(let P of t.individualParticipantIds){let U=r?.[P];if(U){let{participant:E,counters:A}=U,N={won:A?.DOUBLES?.wins||0,lost:A?.DOUBLES?.losses||0},D={won:A?.SINGLES?.wins||0,lost:A?.SINGLES?.losses||0},{participantName:M,participantId:R}=E;i[s][R]=T,S.push({player:{name:M,uni:T,singles:D,doubles:N}})}T+=1}return{vh:c,id:s,name:a,score:d||I,totals:h,childArray:S}}function dx({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=h1({sets:t.score?.sets,sideNumber:p});return{[i===xt?"singles_score":"doubles_score"]:{...I1({homeid:e,uniValues:r,participant:m}),...d}}});return{[i===xt?"singles_match":"doubles_match"]:{match:n,order:o,childArray:a}}}var T1="ASC",XN="ASC",y1="DESC",Ry="DESC",fx={ASC:T1,ASCENDING:XN,DESC:y1,DESCENDING:Ry};function Cy(t){let{tieFormat:e}=t,{useDefaultEventRanking:r,tournamentRecord:n,drawDefinition:o,scaleAccessor:i,singlesOnly:s,attach:a,event:c}=t;if(c?.eventType!==Cr)return{error:Bn};if(!n)return{error:Y};if(!e&&!o)return{error:Mr};if(e=e??We({drawDefinition:o,event:c})?.tieFormat,ar({tieFormat:e}).error)return{error:Lo};if(typeof i!="object"&&!r)return{error:G,context:{scaleAccessor:i}};let u={},m=(o?.entries??c?.entries??[]).filter(R=>R?.entryStatus===kr).map(St),{participants:d=[]}=Gt({withIndividualParticipants:!0,withScaleValues:!0,tournamentRecord:n}),l=d.filter(({participantId:R})=>m.includes(R)),f=R=>R===fi?"rankings":"ratings",g=c?.category?.categoryName??c?.category?.ageCategoryCode,{scaleName:I=g,scaleType:h=fi,sortOrder:S,accessor:T}=i||{},y=f(h),P=(R,b)=>{let v=R[y]?.[b];if(!v&&r&&(v=R[y]?.[aa]),Array.isArray(v)){let O=v.find(x=>x.scaleName===I)?.scaleValue;if(Zt(O))return O;if(T&&typeof O=="object")return O[T]}return 0},U=(R,b,v)=>{let O=S===Ry?b:R,x=S===Ry?R:b;return P(O,v)-P(x,v)},E=(R,b)=>U(R,b,aa),A=(R,b)=>U(R,b,vi),N=[],D=e?.collectionDefinitions??[];for(let R of l){let b=R.individualParticipants?.sort(E)??[],v=s?b:R.individualParticipants?.sort(A)??[],O={};for(let F of D){let L=[],{collectionId:w,matchUpCount:V,matchUpType:k,gender:W}=F,H=ue(aa)(k);et(0,V).forEach(K=>{let q=H?b:v??[],B=K+1,$=[];et(0,H?1:2).forEach(z=>{let j=q?.find(tt=>{let Q=W&&([$t,ne].includes(W)&&W||W===Tr&&[$t,ne][z]);return(!Q||Q===tt.person?.sex)&&!L.includes(tt.participantId)})?.participantId;j&&($.push(j),L.push(j),O[j]||(O[j]=[]),O[j].push({collectionPosition:B,collectionId:w}))}),H||N.push($)})}let x=Object.keys(O).map(F=>({collectionAssignments:O[F],participantId:F}));u[R.participantId]=x}let M=[];for(let R of N){let{participant:b}=In({tournamentParticipants:d,participantIds:R});if(!b){let v={individualParticipantIds:R,participantRole:xe,participantType:ft};M.push(v)}}if(a){for(;M.length;)bn({participant:M.pop(),tournamentRecord:n});At({element:o,extension:{name:Ro,value:u}})}return{...C,lineUps:u,participantsToAdd:M}}function Zg(t){if(!t)return{error:st};let e=rt(t,[{dates:!1,[tr]:s=>Array.isArray(s)&&s.every(Rr)},{uuids:!1,[tr]:s=>Array.isArray(s)&&s.every(Vt)},{startTime:!1,endTime:!1,[tr]:QI},{idPrefix:!1,namePrefix:!1,[tr]:Vt},{count:!0,[tr]:Zt}]);if(e.error)return e;let{startDate:r,endDate:n}=t.tournamentRecord??{},o=t.dates||r&&n&&ws(r,n)||[],i=et(1,t.count+1).map(s=>ot({courtId:t.uuids?.pop()??(t.idPrefix&&`${t.idPrefix}-${s}`)??Dt(),courtName:t.courtNames?.pop()??(t.namePrefix&&`${t.namePrefix} ${s}`),dateAvailability:o.map(a=>({startTime:t.startTime??"08:00",endTime:t.endTime??"20:00",date:a}))}));return{...C,courts:i}}var JN={};Xt(JN,{default:()=>A1,garman:()=>hx});function wa({court:t,date:e}){let r=e&&t.dateAvailability.find(o=>Wn(o.date,e)),n=t.dateAvailability.find(o=>!o.date);return r||n}function Ns(t){let e=rt(t,[{courtDate:!0,_ofType:Kr}]);if(e.error)return e;let{includeBookingTypes:r=[],courtDate:n}=t,o=[],i=ke(n.startTime);(n.bookings||[]).filter(a=>!a.bookingType||!r.includes(a.bookingType)).sort((a,c)=>gf(a.startTime).localeCompare(gf(c.startTime))).forEach(a=>{let c={startTime:Kt(i.toISOString()),endTime:a.startTime};ke(a.startTime)>i&&o.push(c),ke(a.endTime)>i&&(i=ke(a.endTime))});let s={startTime:Kt(i.toISOString()),endTime:n.endTime};return ke(n.endTime)>i&&o.push(s),{timeSlots:o}}function gx({averageMatchUpMinutes:t,includeBookingTypes:e,periodStartTime:r,periodEndTime:n}){let o=s=>{let{timeSlots:a}=Ns({includeBookingTypes:e,courtDate:s});return!!a?.filter(i)?.length};function i(s){let a=ke(s.startTime),c=ke(s.endTime);return a>r||c<n?!1:ma(r,c)>=t}return{enoughTime:o}}function by(t){let e=rt(t,[{periodStart:!0,date:!0},{courts:!0,_ofType:Be}]);if(e.error)return e;let{averageMatchUpMinutes:r,includeBookingTypes:n,periodStart:o,date:i}=t,s=t.courts,a=ke(o),c=hf(a,r),{enoughTime:u}=gx({averageMatchUpMinutes:r,includeBookingTypes:n,periodStartTime:a,periodEndTime:c});return{availableToScheduleCount:(s?.filter(m=>{if(!Array.isArray(m.dateAvailability))return!1;let d=wa({date:i,court:m});return!!(d&&u(d))})||[]).length,...C}}function tm(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:G,courts:i};if(!Array.isArray(s))return{error:Am};if(!Rr(o))return{error:je};r&&(Array.isArray(r)?r.includes(o)&&(s=[]):s=[]);let{courtBookings:a,unassignedBookings:c}=s.reduce((l,f)=>{let{courtId:g}=f;return g?l.courtBookings[g]?l.courtBookings[g].push(f):l.courtBookings[g]=[f]:l.unassignedBookings.push(f),l},{courtBookings:{},unassignedBookings:[]}),u=i.map((l,f)=>{let{courtId:g,courtName:I}=l,h=a[g]||[],S=wa({date:o,court:l})||{},{bookings:T=[],startTime:y,endTime:P,date:U}=S,A=[e[f]&&{startTime:y,endTime:e[f]},...J(T,!1,!0),...h].filter(Boolean);return{courtId:g,courtName:I,dateAvailability:{bookings:A,startTime:y,endTime:P,date:U}}});c.sort((l,f)=>qt(l.startTime)-qt(f.startTime));let p=()=>u.map(l=>{let f=l.dateAvailability,{timeSlots:g=[]}=Ns({courtDate:f});return{courtName:l.courtName,courtId:l.courtId,timeSlots:g}}).flat(),m=[];for(let l of c){let{startTime:f,endTime:g,averageMinutes:I,recoveryMinutes:h,matchUpId:S}=l,T=qt(f),y=qt(g),U=p().reduce((E,{courtId:A,courtName:N,timeSlots:D})=>{let M;return D.find(({startTime:b,endTime:v})=>{M=qt(b)-T;let O=T>=qt(b);return y<=qt(v)&&E.startDifference!==0&&((M===0||M+n>=0)&&(E.startDifference===void 0||M<E.startDifference)||O)})?{courtName:N,courtId:A,startDifference:M}:E},{});if(U.courtId){let E={averageMinutes:I,recoveryMinutes:h,matchUpId:S,startTime:f,endTime:g};m.push(E),u.find(({courtId:N})=>N===U.courtId)?.dateAvailability.bookings.push(E)}else console.log({unassignedBooking:l})}return{virtualCourts:u.map(({courtId:l,courtName:f,dateAvailability:g})=>({dateAvailability:[g],courtName:f,courtId:l})),assignedBookings:m}}function ku({averageMatchUpMinutes:t,periodLength:e=30,recoveryMinutes:r}){let n=(t||90)+(r||0);return e>n?n:e||30}function vy(t){let{startTime:e="8:00",endTime:r="20:30",count:n=10,date:o}=t??{};return et(0,n).map(()=>({dateAvailability:[{date:o,startTime:e,endTime:r}]}))}function bc({scheduleDate:t,startTime:e,endTime:r,courts:n}){let o=e&&"startTime"||r&&"endTime"||void 0;return n.reduce((i,s)=>{let a=wa({date:t,court:s}),c=o&&(a?.[o]||s[o]);return c&&(!i||e&&qt(c)<qt(i)||r&&qt(c)>qt(i))?c:i},void 0)}function Ix({averageMinutes:t,startTime:e,endTime:r,courts:n,date:o}){e=e||bc({courts:n,scheduleDate:o,startTime:!0}),r=r||bc({courts:n,scheduleDate:o,endTime:!0});let i;if(e&&r){let s=ke(e),a=ke(r);for(let c of n||[]){if(!Array.isArray(c.dateAvailability))continue;let u=wa({court:c,date:o}),{timeSlots:p}=Ns({courtDate:u});p?.forEach(m=>{let d=ke(m.startTime),l=ke(m.endTime);if(d>a||d<s||l<s)return!1;if(ma(d,l)>=t){let I=Kt(d.toISOString());(!i||I<i)&&(i=I)}})}}return{firstTimeSlotStartTime:i}}function dl(t){let e=rt(t,[{courts:!0,_ofType:Be}]);if(e.error)return e;let{date:r=If(),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||ku({averageMatchUpMinutes:u}),r=Et(r),n=Kt(n),o=Kt(o);let l=0,f=0,g=0,I=0,h=0;!s&&m&&(s=vy({startTime:n,endTime:o,count:m,date:r}));let{virtualCourts:S}=tm({remainingScheduleTimes:c,clearScheduleDates:p,scheduleDate:r,periodLength:i,bookings:d,courts:s}),{firstTimeSlotStartTime:T}=Ix({averageMinutes:u,courts:S,startTime:n,endTime:o,date:r});a&&T&&(n=T||n);let y=qt(n),U=qt(o)-y,E=Math.floor(U/i),N=et(0,E+1).map(M=>{let R=y+M*i,b=BC(R),v=by({courts:S??[],averageMatchUpMinutes:u,periodStart:b,date:r});if(v.error)return{error:v.error};let{availableToScheduleCount:O=0}=v,x=O>f?O-f:0;h+=M?O:0;let F=M?h/M:O,w=i*F/u,V=M?w*(M-1)+F:F,k=O?f&&V-l||x:0;l=V,f=O,g+=k;let W=pt(g)-I;return I+=W,{periodStart:b,add:W,availableToScheduleCount:O,newCourts:x,totalMatchUps:I}});return{scheduleTimes:N.reduce((M,R)=>{let v=et(0,R.add).map(()=>({scheduleTime:R.periodStart}));return M.concat(...v)},[]).flat(),timingProfile:N,totalMatchUps:I}}var hx={getCourtsAvailableAtPeriodStart:by,generateTimeSlots:Ns,getScheduleTimes:dl,courtGenerator:vy},A1=hx;var Oy={};Xt(Oy,{isValid:()=>Pr,isValidMatchUpFormat:()=>Pr,parse:()=>Ye,stringify:()=>ip});var yM={};Xt(yM,{allCompetitionMatchUps:()=>Un,allDrawMatchUps:()=>or,allEventMatchUps:()=>$n,allTournamentMatchUps:()=>Te,analyzeMatchUp:()=>Xp,applyLineUps:()=>SM,assignMatchUpSideParticipant:()=>tM,assignTieMatchUpParticipantId:()=>gl,bulkMatchUpStatusUpdate:()=>fM,calculateWinCriteria:()=>Ps,checkInParticipant:()=>eI,checkMatchUpIsComplete:()=>ds,checkOutParticipant:()=>tI,competitionScheduleMatchUps:()=>Fu,disableTieAutoCalc:()=>dM,drawMatchUps:()=>fy,enableTieAutoCalc:()=>uM,eventMatchUps:()=>al,filterMatchUps:()=>Ni,findMatchUp:()=>jg,getAllDrawMatchUps:()=>se,getAllStructureMatchUps:()=>Ut,getCheckedInParticipantIds:()=>us,getCompetitionMatchUps:()=>Qp,getEventMatchUpFormatTiming:()=>iy,getHomeParticipantId:()=>uy,getMatchUpCompetitiveProfile:()=>gu,getMatchUpContextIds:()=>py,getMatchUpDailyLimits:()=>ul,getMatchUpDailyLimitsUpdate:()=>sy,getMatchUpDependencies:()=>sn,getMatchUpFormat:()=>my,getMatchUpFormatTiming:()=>Iu,getMatchUpFormatTimingUpdate:()=>ny,getMatchUpScheduleDetails:()=>pd,getMatchUpType:()=>md,getMatchUpsStats:()=>dy,getModifiedMatchUpFormatTiming:()=>il,getParticipantResults:()=>Mu,getPredictiveAccuracy:()=>cy,getRoundMatchUps:()=>Ke,getRounds:()=>ly,isValidMatchUpFormat:()=>Pr,matchUpActions:()=>Od,mutate:()=>TM,participantScheduledMatchUps:()=>ay,query:()=>EN,removeDelegatedOutcome:()=>pM,removeMatchUpSideParticipant:()=>nI,removeTieMatchUpParticipantId:()=>rM,replaceTieMatchUpParticipantId:()=>rI,resetAdHocMatchUps:()=>IM,resetMatchUpLineUps:()=>iI,resetScorecard:()=>aI,resetTieFormat:()=>sI,setDelegatedOutcome:()=>gM,setMatchUpFormat:()=>lM,setMatchUpStatus:()=>Gu,setOrderOfFinish:()=>hM,substituteParticipant:()=>mM,tallyParticipantResults:()=>Ca,toggleParticipantCheckInState:()=>ll,tournamentMatchUps:()=>cl,updateTieMatchUpScore:()=>co,validMatchUp:()=>Zf,validMatchUps:()=>Vr});var TM={};Xt(TM,{applyLineUps:()=>SM,assignMatchUpSideParticipant:()=>tM,assignTieMatchUpParticipantId:()=>gl,bulkMatchUpStatusUpdate:()=>fM,checkInParticipant:()=>eI,checkOutParticipant:()=>tI,disableTieAutoCalc:()=>dM,enableTieAutoCalc:()=>uM,findMatchUp:()=>jg,removeDelegatedOutcome:()=>pM,removeMatchUpSideParticipant:()=>nI,removeTieMatchUpParticipantId:()=>rM,replaceTieMatchUpParticipantId:()=>rI,resetAdHocMatchUps:()=>IM,resetMatchUpLineUps:()=>iI,resetScorecard:()=>aI,resetTieFormat:()=>sI,setDelegatedOutcome:()=>gM,setMatchUpFormat:()=>lM,setMatchUpStatus:()=>Gu,setOrderOfFinish:()=>hM,substituteParticipant:()=>mM,toggleParticipantCheckInState:()=>ll,updateTieMatchUpScore:()=>co});function tM({tournamentRecord:t,drawDefinition:e,participantId:r,sideNumber:n,matchUpId:o,event:i}){if(r&&typeof r!="string")return{error:mn};if(!e)return{error:Z};if(!o)return{error:sr};let s=n===void 0;if(s&&(n=1),![1,2].includes(n))return _({result:{error:G,context:{sideNumber:n}}});let{matchUp:a,structure:c}=Bt({drawDefinition:e,matchUpId:o,event:i});if(!a)return{error:Le};if(!(!c?.structures&&!(e.drawType&&e.drawType!==$r)&&!c?.matchUps?.find(({roundPosition:p})=>!!p)))return{error:ym};if(!r&&(a?.score?.scoreStringSide1||ce.includes(a?.matchUpstatus)||a?.matchUpStatus&&[he,Ce].includes(a.matchUpStatus)))return{error:Ku,info:"matchUp has completed status or score"};if(a){if(a.sides=[1,2].map(p=>{let m=a.sides?.find(d=>d.sideNumber===p)??{sideNumber:p};return n===p?{...m,participantId:r}:m}),s)for(let p of a.sides)p.sideNumber&&(p.sideNumber=3-p.sideNumber);gt({tournamentId:t?.tournamentId,context:"assignSideParticipant",drawDefinition:e,matchUp:a})}return{...C,sidesSwapped:s}}function Jr({removePriorValues:t,tournamentRecord:e,duplicateValues:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:s,event:a}){let{matchUp:c}=Bt({drawDefinition:n,event:a,matchUpId:i});if(!c)return{error:Le};let u=Qn({removePriorValues:t,element:c,duplicateValues:r,timeItem:s});return o||gt({tournamentId:e?.tournamentId,eventId:a?.eventId,context:"addTimeItem",drawDefinition:n,matchUp:c}),u}function tI(t){let e=[{[ie]:!0},{[Ve]:!0},{[ro]:!0},{[ln]:!0}],r=rt(t,e);if(r.error)return r;let n=Ds(t,[{[is]:_n,attr:{[tu]:!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&&Km.includes(u)||u&&ce.includes(u)||Ie({score:p}))return{error:LA};let m=us({matchUp:c});if(m?.error)return m;let{checkedInParticipantIds:d,allRelevantParticipantIds:l}=m??{};if(!l?.includes(s))return{error:mn};if(!d?.includes(s))return{error:pE};let f=iS({matchUp:c});if(f?.error)return f;let{sideParticipantIds:g,nestedIndividualParticipantIds:I}=f??{},h=g?.indexOf(s);return h!==void 0&&[0,1].includes(h)&&(I?.[h]??[]).forEach(T=>{Jr({drawDefinition:i,matchUpId:a,timeItem:{itemType:ad,itemValue:T}})}),Jr({tournamentRecord:o,drawDefinition:i,matchUpId:a,timeItem:{itemValue:s,itemType:ad}}),{...C,checkedOut:!0}}function eI(t){let e=[{[ie]:!0},{[Ve]:!0},{[ro]:!0},{[ln]:!0}],r=rt(t,e);if(r[fn])return r;let n=Ds(t,[{[is]:_n,attr:{[tu]:!0}}]);if(n[fn])return n;let{tournamentRecord:o,drawDefinition:i,participantId:s,matchUpId:a}=t,c=us({matchUp:n?.matchUp?.matchUp});if(c?.error)return c;let{checkedInParticipantIds:u,allRelevantParticipantIds:p}=c??{};if(!p?.includes(s))return{[fn]:mn};let m={...C,checkedIn:!0};return u?.includes(s)||Jr({tournamentRecord:o,drawDefinition:i,matchUpId:a,timeItem:{itemValue:s,itemType:sd}}),m}function ll(t){let e=rt(t,[{[ro]:!0,[Ve]:!0,[ln]:!0}]);if(e.error)return e;let r=t.tournamentId??t.activeTournamentId,n=t.tournamentRecord??(r&&t.tournamentRecords?.[r]);if(!n)return{error:Y};let i=Ds(t,[{[is]:_n,attr:{[tu]:!0},[fn]:Le}]).matchUp?.matchUp;if(!i)return{error:Le};let{checkedInParticipantIds:s=[]}=us({matchUp:i}),{participantId:a,matchUpId:c,drawDefinition:u}=t;return a&&s.includes(a)?tI({tournamentRecord:n,drawDefinition:u,participantId:a,matchUpId:c,matchUp:i}):eI({tournamentRecord:n,drawDefinition:u,participantId:a,matchUpId:c,matchUp:i})}function fl({tournamentRecord:t,drawDefinition:e,tieMatchUpId:r,event:n}){if(!t)return{error:Y};if(!e)return{error:an};if(!n)return{error:jr};let o=Ne({drawDefinition:e}),{matchUp:i}=Bt({matchUpId:r,drawDefinition:e,matchUpsMap:o});if(!i)return{error:Le};let{matchUp:s,structure:a}=Bt({tournamentParticipants:t.participants,matchUpId:r,inContext:!0,drawDefinition:e,matchUpsMap:o,event:n});if(!s)return{error:Le};let{collectionPosition:c,drawPositions:u,collectionId:p,matchUpTieId:m,matchUpType:d}=s;if(d&&!Lc([xt,_t],d))return{error:dr};let{positionAssignments:l}=bt({structure:a}),f=l?.filter(U=>u?.includes(U.drawPosition)),{matchUp:g}=Bt({matchUpId:m,drawDefinition:e,matchUpsMap:o}),I=g?.sides?.map(St)??[],h=f?.map(St)??[],S=[...I,...h],{participants:T}=Gt({tournamentRecord:t,participantFilters:{participantTypes:[Lt],participantIds:S}}),{matchUp:y}=Bt({matchUpId:m,inContext:!0,drawDefinition:e,matchUpsMap:o}),P=We({matchUp:g,drawDefinition:e,structure:a,event:n})?.tieFormat;return{inContextDualMatchUp:y,inContextTieMatchUp:s,relevantAssignments:f,collectionPosition:c,teamParticipants:T,collectionId:p,matchUpType:d,dualMatchUp:g,tieMatchUp:i,tieFormat:P,structure:a,...C}}function rI(t){let e=fl(t);if(e.error)return e;let r="replaceTieMatchUpParticipantid",{existingParticipantId:n,tournamentRecord:o,newParticipantId:i,drawDefinition:s,substitution:a,event:c}=t;if(!n||!i)return _({result:{error:oe},stack:r});if(n===i)return{...C};let{inContextDualMatchUp:u,inContextTieMatchUp:p,collectionPosition:m,collectionId:d,dualMatchUp:l,tieMatchUp:f,tieFormat:g}=e,I=p?.matchUpType,h=p?.sides?.find(V=>V.participant?.participantId===n||V.participant?.individualParticipantIds?.includes(n));if(!h)return{error:te};let S=Gt({tournamentRecord:o,participantFilters:{participantIds:[n,i]}})?.participants??[];if(S.length!==2)return _({result:{error:oe},stack:r});if(S[0].participantType!==S[1].participantType)return _({result:{error:An},stack:r});let{appliedPolicies:T}=yt({tournamentRecord:o,drawDefinition:s,event:c}),y=t.policyDefinitions?.[er]??T?.[er]??hs[er],P=S.find(({participantId:V})=>V===i);if((t.enforceGender??y?.participants?.enforceGender)!==!1&&[$t,ne].includes(p?.gender)&&p?.gender!==P?.person?.sex)return{error:xi,info:"Gender mismatch"};let E=y?.processCodes?.substitution;ba({tournamentId:o.tournamentId,eventId:c.eventId,inContextDualMatchUp:u,drawDefinition:s,dualMatchUp:l});let A=l?.sides?.find(({sideNumber:V})=>V===h.sideNumber);if(!A)return _({result:{sideNumber:h.sideNumber,existingParticipantId:n,error:ve},stack:r});if(p?.sides?.flatMap(V=>V.participant?.individualParticipantIds||V.participant?.participantId||[])?.includes(i))return _({result:{error:zu},stack:r});let D=u?.sides?.find(({sideNumber:V})=>V===h.sideNumber)?.participantId,M=A.lineUp,R=M?.find(({participantId:V})=>i===V),b=M?.reduce((V,k)=>k.substitutionOrder>V?k.substitutionOrder:V,0),v=M?.map(V=>{let k=J(V,!1,!0);if(![n,i].includes(k.participantId))return k;if(!a&&[n,i].includes(k.participantId)&&(k.collectionAssignments=k.collectionAssignments?.filter(W=>!(W.collectionPosition===m&&W.collectionId===d))),a&&n===k.participantId&&(k.collectionAssignments=k.collectionAssignments.map(W=>W.collectionPosition===m&&W.collectionId===d&&W.substitutionOrder===void 0?{...W,substitutionOrder:b}:W)),k.participantId===i){k.collectionAssignments||(k.collectionAssignments=[]);let W={collectionId:d,collectionPosition:m};a&&(W.previousParticipantId=n,W.substitutionOrder=(b??0)+1),k.collectionAssignments.push(W)}return k})??[];if(!R){let V={collectionId:d,collectionPosition:m};a&&(V.substitutionOrder=(b??0)+1,V.previousParticipantId=n);let k={collectionAssignments:[V],participantId:i};v.push(k)}let O=I===_t,{assignedParticipantIds:x}=Np({lineUp:M,collectionPosition:m,collectionId:d}),{assignedParticipantIds:F}=Np({lineUp:v,collectionPosition:m,collectionId:d});if(A.lineUp=v,D&&g){let V=Ki({participantId:D,lineUp:v,drawDefinition:s,tieFormat:g});if(V.error)return _({result:V,stack:r})}else console.log("team participantId not found");let L,w;if(O){let{tournamentRecord:V}=t,k=In({participantIds:F,tournamentRecord:V});if(!k.participant){let K=bn({returnParticipant:!0,pairOverride:!0,tournamentRecord:V,participant:{participantRole:xe,individualParticipantIds:F,participantType:ft}});if(K.error)return _({result:K,stack:r});L=K.participant?.participantId}k=In({participantIds:x,tournamentRecord:V});let W=k.participant?.participantId;W&&$i({participantIds:[W],tournamentRecord:V}).success&&(w=W)}if(a||h.substitutions?.length===1){if(a)E&&f&&(f.processCodes=ut([...f?.processCodes??[],...E]));else for(let V of E||[]){let k=f?.processCodes?.lastIndexOf(V);k!==void 0&&f?.processCodes?.splice(k,1)}f&>({tournamentId:o?.tournamentId,matchUp:f,context:r,drawDefinition:s})}return l&>({tournamentId:o?.tournamentId,matchUp:l,context:r,drawDefinition:s}),{...C,modifiedLineUp:v,participantRemoved:w,participantAdded:L}}function _y({collectionPosition:t,teamParticipantId:e,dualMatchUpSide:r,drawDefinition:n,participantIds:o,collectionId:i}){if(!i||!t||!Array.isArray(o))return{modifiedLineUp:r?.lineUp||[],error:G};let s=r?.lineUp||ms({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 Sx({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:r}){let n=(r.events||[]).filter(i=>i?.eventType===_e&&i?.entries?.some(s=>s.participantId===e)),o=i=>!t.includes(i.participantId);for(let i of n){i.entries=(i.entries||[]).filter(o);let{flightProfile:s}=Ht({event:i});s?.flights?.forEach(a=>{a.drawEntries=(a.drawEntries||[]).filter(o)}),i?.drawDefinitions?.forEach(a=>{a.entries=(a.entries||[]).filter(o)})}return{...C}}function em({individualParticipantIds:t,groupingParticipantId:e,removeFromOtherTeams:r,tournamentRecord:n}){let o="addIndividualParticipantIds";if(!n)return _({result:{error:Y},stack:o});if(!e||!t)return _({result:{error:st},stack:o});let i=n.participants??[],s=i.find(m=>m.participantId===e);if(!s)return _({result:{error:te},stack:o});if(s?.participantType&&![Lt,zr].includes(s.participantType))return _({context:{participantType:s.participantType},result:{error:An},stack:o});let a=t.filter(m=>i.find(l=>l.participantId===m)?.participantType!==Tt);if(a.length)return _({result:{error:wr,invalidParticipantIds:a},stack:o});s.individualParticipantIds||(s.individualParticipantIds=[]);let c=s.individualParticipantIds,u=t.filter(m=>!c.includes(m));u.length&&(r&&Rp({individualParticipantIds:u,tournamentRecord:n}),s.individualParticipantIds=s.individualParticipantIds.concat(...u));let{topics:p}=Lr();if(p.includes(nr)){let m=i.find(({participantId:d})=>d===e);mt({topic:nr,payload:{participants:[m]}})}return Sx({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:n}),{groupingParticipant:J(s,!1,!0),added:u.length,...C}}function rm(t){let{updateParticipantName:e=!0,groupingParticipantId:r,removeFromOtherTeams:n,tournamentRecord:o,pairOverride:i,participant:s}=t;if(!o)return{error:Y};if(!s)return{error:wi};if(!s.participantId)return bn({tournamentRecord:o,participant:s});let{participant:a}=To({participantId:s.participantId,tournamentRecord:o});if(!a)return bn({tournamentRecord:o,participant:s});let{participantRoleResponsibilties:c,individualParticipantIds:u,participantOtherName:p,participantName:m,participantRole:d,participantType:l,onlineResources:f,contacts:g,person:I}=s;if(l&&a.participantType!==l)return{error:oE};let h={};if(g&&(h.contacts=g),f&&(h.onlineResources=f),p&&Vt(p)&&(h.participantOtherName=p),m&&Vt(m)&&(h.participantName=m),Array.isArray(u)){let{participants:S}=Gt({participantFilters:{participantTypes:[Tt]},tournamentRecord:o}),T=S?.map(St);if(T){let y=u.filter(P=>Vt(P)&&T.includes(P));([zr,jt].includes(l||a.participantType)||l===ft&&(y.length===2||i))&&(h.individualParticipantIds=y),a.participantType===mu.PAIR&&e&&(h.participantName=E1({individualParticipants:S,newValues:h}))}}return Object.keys(gd).includes(d)&&(h.participantRole=d),Object.keys(mu).includes(l)&&(h.participantType=l),Array.isArray(c)&&(h.participantRoleResponsibilties=c),a.participantType===mu.INDIVIDUAL&&I&&U1({updateParticipantName:e,existingParticipant:a,newValues:h,person:I}),Object.assign(a,ot(h)),r&&em({individualParticipantIds:[a.participantId],groupingParticipantId:r,removeFromOtherTeams:n,tournamentRecord:o}),mt({topic:nr,payload:{tournamentId:o.tournamentId,participants:[a]}}),{participant:J(a),...C}}function E1({individualParticipants:t,newValues:e}){let r=e.individualParticipantIds,n=t.filter(({participantId:o})=>r.includes(o)).map(({person:o})=>o?.standardFamilyName).filter(Boolean).sort().join("/");return r.length===1&&(n+="/Unknown"),n}function U1({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(Nm).includes(m)&&(o.sex=m);let d;if(Vt(c)&&(o.personId=c),a&&Vt(a)&&(P1(a)||a==="")&&(o.nationalityCode=a),i&&typeof Vt(i)&&i.length>1&&(o.standardFamilyName=i,d=!0),s&&typeof Vt(s)&&s.length>1&&(o.standardGivenName=s,d=!0),d&&t){let l=`${o.standardGivenName} ${o.standardFamilyName}`;r.participantName=l}u&&Rr(u)&&(o.birthdate=u),p&&Vt(p)&&(o.tennisId=p),Object.assign(e.person,o)}function P1(t){return ti.flatMap(({iso:e,ioc:r})=>[e,r]).filter(Boolean).includes(t)}function gl(t){let e=fl(t);if(e.error)return e;let r="assignTieMatchUpParticipantId",n=t.teamParticipantId,{tournamentRecord:o,drawDefinition:i,participantId:s,event:a}=t;if(!s)return _({result:{error:oe},stack:r});if(t.sideNumber&&![1,2].includes(t.sideNumber))return _({result:{error:jl},stack:r});let{inContextDualMatchUp:c,inContextTieMatchUp:u,relevantAssignments:p,collectionPosition:m,teamParticipants:d,collectionId:l,matchUpType:f,dualMatchUp:g,tieFormat:I}=e;if(u?.sides?.flatMap(B=>B.participant?.individualParticipantIds||B.participant?.participantId||[])?.includes(s))return _({result:{...C},stack:r});n=n??(t.sideNumber?c?.sides?.find(B=>B.sideNumber===t.sideNumber)?.participantId:void 0);let S=Gt({participantFilters:{participantIds:[s]},tournamentRecord:o})?.participants?.[0];if(!S)return _({result:{error:te},stack:r});let{appliedPolicies:T}=yt({tournamentRecord:o,drawDefinition:i,event:a}),y=t.policyDefinitions?.[er]??T?.[er]??hs[er];if((t.enforceGender??y?.participants?.enforceGender)!==!1&&[$t,ne].includes(u?.gender)&&u?.gender!==S.person?.sex)return{error:xi,info:"Gender mismatch"};let{individualParticipantIds:U,participantType:E}=S;if(ue(xt)(f)&&E!==Tt)return{error:An};let A=E===Tt?[s]:U,N=n&&d?.find(({participantId:B})=>B===n)||d?.find(({individualParticipantIds:B})=>Fe(A,B));if(!N)return{error:ef};if(n||(n=N.participantId),!n)return{error:te};let M=p?.find(B=>B.participantId===N?.participantId)?.drawPosition,R=g?.sides?.find(B=>B.participantId===n)?.sideNumber,b=u?.sides?.find(B=>M&&B.drawPosition===M)?.sideNumber,v=R??b??t.sideNumber;if(!I)return{error:bs};if(!I.collectionDefinitions?.find(B=>B.collectionId===l))return{error:zA};ba({tournamentId:o.tournamentId,eventId:a.eventId,inContextDualMatchUp:c,drawDefinition:i,dualMatchUp:g});let x=g?.sides?.find(B=>B.sideNumber===v),F=u?.sides?.find(B=>B.sideNumber===v),V=(x?.lineUp??ms({participantId:n,drawDefinition:i})?.lineUp)?.filter(B=>B.collectionAssignments?.find($=>$.collectionPosition===m&&$.collectionId===l&&!$.previousParticipantId))?.map(B=>B?.participantId),k=V?.length>1&&V||(E===ft?S.individualParticipantIds:[s]),W=_y({collectionPosition:m,teamParticipantId:n,dualMatchUpSide:x,drawDefinition:i,participantIds:k,collectionId:l});if(W.error)return _({result:W,stack:r});let{modifiedLineUp:H}=W,K;if(f===_t){if(E!==ft){let B=eM({collectionPosition:m,teamParticipantId:n,drawDefinition:i,modifiedLineUp:H,participantId:s,collectionId:l,tieFormat:I});if(B?.error)return _({result:B,stack:r});if(B=q({side:F}),B.error)return B;K=B.deletedParticipantId,x&&(x.lineUp=H),g&>({tournamentId:o?.tournamentId,matchUp:g,context:r,drawDefinition:i})}else if(E===ft)for(let B of k)eM({collectionPosition:m,teamParticipantId:n,drawDefinition:i,modifiedLineUp:H,participantId:B,collectionId:l,tieFormat:I})}else{let B=eM({collectionPosition:m,teamParticipantId:n,drawDefinition:i,modifiedLineUp:H,participantId:s,collectionId:l,tieFormat:I});if(B?.error)return B}if(x&&(x.lineUp=H),g&>({tournamentId:o?.tournamentId,matchUp:g,context:r,drawDefinition:i}),K){let{error:B}=$i({participantIds:[K],tournamentRecord:o});B&&console.log("cleanup")}return{...C,modifiedLineUp:H};function q({side:B}){let $;if(B.participant){let z=B.participant.individualParticipantIds||[];if(z.filter(Boolean).length===1){let{participant:tt}=In({participantIds:z,tournamentRecord:o});z.push(s);let{participant:Q}=In({participantIds:z,tournamentRecord:o});if(!Q&&tt){tt.individualParticipantIds=z;let X=rm({pairOverride:!0,tournamentRecord:o,participant:tt});if(X.error)return X}else $=tt?.participantId}}else{let j=bn({participant:{individualParticipantIds:[s],participantRole:xe,participantType:ft},pairOverride:!0,tournamentRecord:o});if(j.error)return j}return{...C,deletedParticipantId:$}}}function eM({collectionPosition:t,teamParticipantId:e,drawDefinition:r,modifiedLineUp:n,participantId:o,collectionId:i,tieFormat:s}){let a=ms({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 Ki({participantId:e,lineUp:n,drawDefinition:r,tieFormat:s})}function rM(t){let{tournamentRecord:e,drawDefinition:r,participantId:n,event:o}=t,i="removeTieMatchUpParticiapantId";if(!n)return _({result:{error:oe},stack:i});let s=fl(t);if(s.error)return s;let{appliedPolicies:a}=yt({tournamentRecord:e,drawDefinition:r,event:o}),u=(t.policyDefinitions?.[er]??a?.[er]??hs[er])?.processCodes?.substitution,{inContextDualMatchUp:p,inContextTieMatchUp:m,relevantAssignments:d,collectionPosition:l,teamParticipants:f,collectionId:g,matchUpType:I,dualMatchUp:h,tieMatchUp:S,tieFormat:T}=s;if(!h)return _({result:{error:hr},stack:i});let y=m?.sides?.find(R=>R.participant?.participantId===n||R.participant?.individualParticipantIds?.includes(n));if(!y)return _({result:{error:te},stack:i});let P=t.policyDefinitions?.[en]??a?.[en];if(!y.substitutions?.length&&(Ie({score:m?.score})||m?.winningSide)&&P?.requireParticipantsForScoring!==!1)return _({result:{error:vE},stack:i});let U=p?.sides?.find(({sideNumber:R})=>R===y.sideNumber)?.participantId;if(!U)return _({result:{error:te},stack:i});let E=Gt({participantFilters:{participantIds:[n]},tournamentRecord:e})?.participants?.[0];if(!E)return _({result:{error:te},stack:i});if(I===xt&&E.participantType===ft)return _({result:{error:xi},stack:i});let A=E.participantType===Tt?[n]:E.individualParticipantIds;ba({tournamentId:e.tournamentId,eventId:o.eventId,inContextDualMatchUp:p,drawDefinition:r,dualMatchUp:h});let N=h.sides?.find(({sideNumber:R})=>R===y.sideNumber);if(!N&&(h.sides?.filter(({lineUp:R})=>!R).length||0)<2){let R=f?.map(({participantId:b})=>({drawPosition:d?.find(v=>v.participantId===b)?.drawPosition,teamParticipantId:b}));N=h.sides?.find(b=>R?.find(({drawPosition:v})=>v===b.drawPosition)?.teamParticipantId===U)}if(!N)return _({result:{error:te,context:{participantId:n}}});let{modifiedLineUp:D,previousParticipantIds:M}=_y({collectionPosition:l,teamParticipantId:U,dualMatchUpSide:N,participantIds:A,drawDefinition:r,collectionId:g});if(N.lineUp=D,U&&T&&Ki({participantId:U,lineUp:D,drawDefinition:r,tieFormat:T}),I===_t&&E.participantType===Tt){let R=m?.sides?.find(O=>O.sideNumber===N?.sideNumber),{participantId:b}=R??{},v=b&&Gt({participantFilters:{participantIds:[b]},tournamentRecord:e,withDraws:!0})?.participants?.[0];if(v){let O=v?.individualParticipantIds?.filter(x=>x!==n)??[];if(M&&O.push(...M),O.length>2)return _({result:{error:wr},stack:i});if(v.draws?.length){if(O.length===1){let{participant:x}=In({participantIds:O,tournamentRecord:e});if(!x){let L=bn({participant:{participantRole:xe,individualParticipantIds:O,participantType:ft},pairOverride:!0,tournamentRecord:e});if(L.error)return _({result:L,stack:i})}}}else if(O.length){v.individualParticipantIds=O;let x=rm({participant:v,pairOverride:!0,tournamentRecord:e});if(x.error)return _({result:x,stack:i})}else{let x=$i({participantIds:[b],tournamentRecord:e});x.error&&console.log("cleanup",{result:x})}}else return _({result:{error:te},stack:i})}if(y.substitutions?.length===1&&!m?.sides?.find(b=>b.sideNumber!==y.sideNumber)?.substitutions?.length&&S?.processCodes?.length){for(let b of u||[]){let v=S.processCodes.lastIndexOf(b);S.processCodes.splice(v,1)}gt({tournamentId:e?.tournamentId,matchUp:S,context:i,drawDefinition:r})}return gt({tournamentId:e?.tournamentId,matchUp:h,context:i,drawDefinition:r}),{...C,modifiedLineUp:D}}function nI(t){let e=rt(t,[{[ie]:!0,[Ve]:!0,[ln]:!0}]);if(e.error)return e;let{drawDefinition:r,sideNumber:n,matchUpId:o,event:i}=t;if(n&&![1,2].includes(n))return{error:G,sideNumber:n};let{matchUp:s,structure:a}=Bt({drawDefinition:r,matchUpId:o,event:i});return s?cr({structure:a})?(s.sides?.forEach(c=>{(!n||c.sideNumber===n)&&delete c.participantId}),gt({tournamentId:t.tournamentRecord?.tournamentId,context:"assignSideParticipant",drawDefinition:r,matchUp:s}),{...C}):{error:ym}:{error:Le}}function Tx({matchUpStatuses:t=[Nt,Ct,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=Fe(s||[],t),u=Fe(a||[],t);return{sourceMatchUp:o,winnerHadMatchUpStatus:c,winnerMatchUpStatuses:s,loserHadMatchUpStatus:u,loserMatchUpStatuses:a}}function yx({inContextDrawMatchUps:t,sourceMatchUpStatus:e,targetDrawPosition:r,tournamentRecord:n,sourceMatchUpId:o,drawDefinition:i,structureId:s,dualMatchUp:a,roundNumber:c,matchUpsMap:u,event:p}){let{structure:m}=at({drawDefinition:i,structureId:s});if(m?.structureType===Ge)return{...C};u=u??Ne({drawDefinition:i});let l=(u?.mappedMatchUps||{})[s].matchUps,{initialRoundNumber:f}=fs({drawPosition:r,matchUps:l}),g=l?.filter(h=>h.roundNumber>=c&&h.roundNumber!==f&&h.drawPositions?.includes(r)),{positionAssignments:I}=bt({drawDefinition:i,structureId:s});for(let h of g??[])D1({inContextDrawMatchUps:t,sourceMatchUpStatus:e,positionAssignments:I,targetDrawPosition:r,tournamentRecord:n,sourceMatchUpId:o,drawDefinition:i,dualMatchUp:a,matchUpsMap:u,matchUp:h,event:p});return{...C}}function D1({inContextDrawMatchUps:t,positionAssignments:e,sourceMatchUpStatus:r,targetDrawPosition:n,tournamentRecord:o,sourceMatchUpId:i,drawDefinition:s,dualMatchUp:a,matchUpsMap:c,matchUp:u,event:p}){let m="removeSubsequentDrawPosition";if(a){let g=t.find(({matchUpId:h})=>u.matchUpId===h).sides?.find(h=>h.drawPosition===n)?.sideNumber,I=u.sides?.find(h=>h.sideNumber===g);I&&delete I.lineUp}u.drawPositions=(u.drawPositions||[]).map(f=>f===n?void 0:f).filter(Boolean);let l=e.filter(({drawPosition:f})=>u.drawPositions?.includes(f)).filter(f=>f.bye).length;return u.matchUpStatus=l&&Nt||[Mt,Ct].includes(u.matchUpStatus)&&u.matchUpStatus||Qt,[Ct,Mt].includes(u.matchUpStatus)&&(u.winningSide=void 0),u.matchUpStatusCodes&&NS({inContextDrawMatchUps:t,sourceMatchUpStatus:r,sourceMatchUpId:i,matchUpsMap:c,matchUp:u}),gt({tournamentId:o?.tournamentId,eventId:p?.eventId,context:`${m}-${n}`,drawDefinition:s,matchUp:u}),{...C}}function vc(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=cr({structure:p}),{drawPositions:f,winningSide:g}=c.matchUp||{};if(!l&&!f)return{error:ja};let{targetLinks:{loserTargetLink:I,winnerTargetLink:h,byeTargetLink:S},targetMatchUps:{loserMatchUp:T,winnerMatchUp:y,byeMatchUp:P}}=c,U=Gn({...t,matchUpStatus:i||Qt,removeWinningSide:!0});if(U.error)return U;let E;if(d){let{matchUpTieId:L,matchUpsMap:w}=t;if(E=co({appliedPolicies:t.appliedPolicies,matchUpId:L,tournamentRecord:n,drawDefinition:o,matchUpsMap:w,event:m}),!e&&!E.removeWinningSide)return{...C}}if(l)return{...C};let{matchUps:A}=Ut({afterRecoveryTimes:!1,inContext:!0,drawDefinition:o,matchUpsMap:s,structure:p}),{positionAssignments:N}=Se({structure:p}),D=g-1,M=1-D,R=f[D],b=f[M],{winnerParticipantId:v,loserParticipantId:O}=N?.reduce((L,w)=>(w.drawPosition===b&&(L.loserParticipantId=w.participantId),w.drawPosition===R&&(L.winnerParticipantId=w.participantId),L),{winnerParticipantId:void 0,loserParticipantId:void 0})||{},x=A.filter(L=>L.drawPositions?.includes(b));if(y&&nM({sourceMatchUpStatus:i,sourceMatchUpId:u,inContextDrawMatchUps:r,winningDrawPosition:R,winnerParticipantId:v,tournamentRecord:n,winnerTargetLink:h,drawDefinition:o,winnerMatchUp:y,dualMatchUp:a,matchUpsMap:s}),T){let{winnerHadMatchUpStatus:L}=Tx({drawPositionMatchUps:x,loserDrawPosition:b,sourceMatchUps:A}),V=I.linkCondition===On;if(L&&V){let W=Math.min(...T.drawPositions);xy({targetLink:I,inContextDrawMatchUps:r,drawDefinition:o,drawPosition:W,matchUpsMap:s,event:m})}let k=N1({sourceMatchUpStatus:i,sourceMatchUpId:u,loserParticipantId:O,tournamentRecord:n,loserTargetLink:I,drawDefinition:o,loserMatchUp:T,dualMatchUp:a,matchUpsMap:s,event:m});if(k.error)return k}if(P){let L=Math.min(...P.drawPositions);xy({sourceMatchUpId:u,targetLink:S,inContextDrawMatchUps:r,drawDefinition:o,drawPosition:L,matchUpsMap:s,event:m})}return{...C,...E&&{tieMatchUpResult:E}}}function nM({inContextDrawMatchUps:t,winningDrawPosition:e,sourceMatchUpStatus:r,winnerParticipantId:n,tournamentRecord:o,winnerTargetLink:i,sourceMatchUpId:s,drawDefinition:a,winnerMatchUp:c,matchUpsMap:u,dualMatchUp:p,event:m}){let{structureId:d,roundNumber:l}=c,f="removeDirectedWinner";if(i){let g=i.target.structureId,{structure:I}=at({drawDefinition:a,structureId:g});if(!I)return{error:kt};let{positionAssignments:h}=Se({structure:I});I.seedAssignments=(I.seedAssignments??[]).filter(N=>N.participantId!==n);let T=h?.find(N=>N.participantId===n)?.drawPosition,{matchUps:y}=Ut({drawDefinition:a,structure:I,event:m}),P=y.map(N=>N.drawPositions).flat(1/0).filter(Boolean),U=Sr(P);if((T?U[T]:void 0)===1)h?.forEach(N=>{N.participantId===n&&delete N.participantId});else{let N=y.filter(({drawPositions:D})=>D.includes(T));console.log("not removing from position assignments since instances > 1",{drawPositionMatchUps:N,winnerTargetLink:i})}let A=u?.drawMatchUps?.find(({matchUpId:N})=>N===c.matchUpId);A&>({tournamentId:o?.tournamentId,eventId:m?.eventId,matchUp:A,context:f,drawDefinition:a})}return l&&yx({targetDrawPosition:e,inContextDrawMatchUps:t,sourceMatchUpStatus:r,tournamentRecord:o,sourceMatchUpId:s,drawDefinition:a,dualMatchUp:p,matchUpsMap:u,roundNumber:l,structureId:d}),{...C}}function N1({sourceMatchUpStatus:t,loserParticipantId:e,tournamentRecord:r,loserTargetLink:n,sourceMatchUpId:o,drawDefinition:i,loserMatchUp:s,matchUpsMap:a,dualMatchUp:c,event:u}){let p="removeDirectedLoser",m=n.target.structureId,{structure:d}=at({drawDefinition:i,structureId:m});if(!d)return{error:kt};let{positionAssignments:l}=Se({structure:d}),f=l?.find(g=>g.participantId===e)?.drawPosition;if(l?.forEach(g=>{g.participantId===e&&delete g.participantId}),d.seedAssignments=(d.seedAssignments??[]).filter(g=>g.participantId!==e),c){let g=s?.sides.reduce((S,T,y)=>T.drawPosition===f?y:S,void 0),I=a?.drawMatchUps?.find(({matchUpId:S})=>S===s.matchUpId),h=I?.sides?.[g];h&&(delete h.lineUp,gt({tournamentId:r?.tournamentId,eventId:u?.eventId,matchUp:I,context:p,drawDefinition:i}))}return{...C}}function xy({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,matchUpsMap:o,targetLink:i,event:s}){let a=i.target.structureId,c="removeDirectedBye";Rn({color:"brightyellow",method:c,drawPosition:n});let u=lc({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:r,drawPosition:n,matchUpsMap:o,structureId:a,event:s});return _({result:u,stack:c})}function Ax(t){let{matchUpFormat:e,score:r}=t,n=r?.sets?.length,o=e&&Ye(e),{setFormat:i,finalSetFormat:s,bestOf:a}=o??{};return(a&&n===a&&s||i)?.timed||!1}function Ex({tournamentRecord:t,drawDefinition:e,structure:r,matchUp:n}){let o="attemptToSetMatchUpStatusBYE";if(n?.winningSide)return _({result:{error:pa},context:{matchUpStatus:Nt},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=Nt,n.matchUpStatusCodes=[],gt({tournamentId:t?.tournamentId,context:o,drawDefinition:e,matchUp:n}),{...C}):_({result:{error:KA},info:"matchUp does not include BYE",stack:o})}function Il(t){let{tournamentRecord:e,appliedPolicies:r,drawDefinition:n,matchUpsMap:o,targetData:i,structure:s,event:a}=t,c="doubleExitAdvancement";if(s.structureType===Ge)return _({result:{...C},stack:c});let{matchUp:u,targetMatchUps:p,targetLinks:m}=i,{loserMatchUp:d,winnerMatchUp:l,loserTargetDrawPosition:f}=p,g=[Ct,Mt].includes(d?.matchUpStatus)&&!d.sides?.map(I=>I.participantId??I.participant).filter(Boolean).length;if(d&&d.matchUpStatus!==Nt){let{loserTargetLink:I}=m;if(r?.progression?.doubleExitPropagateBye){let h=Px({loserTargetDrawPosition:f,tournamentRecord:e,loserTargetLink:I,drawDefinition:n,loserMatchUp:d,matchUpsMap:o,event:a});if(h.error)return _({result:h,stack:c})}else if(!g){let{feedRound:h,drawPositions:S,matchUpId:T}=d,y=h?2:2-S.indexOf(f),P=Ux({...t,targetMatchUp:d,walkoverWinningSide:y,tournamentRecord:e,sourceMatchUp:u,matchUpId:T});if(P.error)return _({result:P,stack:c})}}if(l){let I=Ux({...t,matchUpId:l.matchUpId,targetMatchUp:l,tournamentRecord:e,sourceMatchUp:u});if(I.error)return _({result:I,stack:c})}return _({result:{...C},stack:c})}function Ux(t){let{inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:n,sourceMatchUp:o,targetMatchUp:i,matchUpsMap:s}=t,a=n.structures.find(({structureId:q})=>q===i.structureId),c=t.matchUpStatus===Ce?Ce:he,u=t.matchUpStatus===Ce?Mt:Ct,p="conditionallyAdvanceDrawPosition",m=s.drawMatchUps.find(q=>q.matchUpId===i.matchUpId);if(!m)return{error:hr};let d=o?.drawPositions||[],l=m.drawPositions?.filter(Boolean),f=o?.structureId===i.structureId;if(f&&Fe(d,l)&&(l=l.filter(q=>!d.includes(q))),f&&l.length>1)return _({result:{error:Wa},stack:p});let{pairedPreviousMatchUpIsDoubleExit:g,pairedPreviousMatchUp:I}=PS(t),h=ur({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),{targetMatchUps:S,targetLinks:T}=h,{loserTargetDrawPosition:y,winnerMatchUp:P,loserMatchUp:U}=S;if(U){let{loserTargetLink:q}=T,B=Px({loserTargetDrawPosition:y,loserMatchUp:U,tournamentRecord:r,loserTargetLink:q,drawDefinition:n,matchUpsMap:s});if(B.error)return _({result:B,stack:p})}let E=m.drawPositions?.filter(Boolean)||[],A=E.length===1,N=t.walkoverWinningSide||A&&hd({drawPosition:E[0],matchUpId:i.matchUpId,inContextDrawMatchUps:e})||void 0,D=[Ct,Mt].includes(m.matchUpStatus)&&!E.length,M=m.finishingRound===1,R=D&&!M?c:u,b=e.find(q=>q.matchUpId===I.matchUpId),v=[],O;o&&(o?.structureId===b?.structureId?o.roundPosition<I?.roundPosition?O=1:O=2:i.feedRound?o.structureId===i.structureId?O=2:O=1:N&&(O=3-N));let x=t.matchUpStatus,F=I?.matchUpStatus;O===1?v=[{matchUpStatus:wy(x),previousMatchUpStatus:x,sideNumber:1},{matchUpStatus:wy(F),previousMatchUpStatus:F,sideNumber:2}]:O===2&&(v=[{matchUpStatus:wy(F),previousMatchUpStatus:F,sideNumber:1},{matchUpStatus:wy(x),previousMatchUpStatus:x,sideNumber:2}]),v.length&&(v=v.map(q=>ot(q)));let L=Gn({...t,winningSide:N,matchUp:m,matchUpStatusCodes:v,context:p,matchUpStatus:R});if(L.error)return _({result:L,stack:p});if(D)return Il({...t,matchUpStatus:R,targetData:h});if(!P)return _({result:{...C},stack:p});let w=l.length===2?l[N-1]:l[0],{positionAssignments:V}=bt({structure:a}),k=V?.find(q=>q.drawPosition===w),W=s.drawMatchUps.find(q=>q.matchUpId===P.matchUpId),H=W?.drawPositions?.filter(Boolean),K=H.length===1;if(w){if(k?.bye){let q=ur({matchUpId:W.matchUpId,inContextDrawMatchUps:e,drawDefinition:n});if(K){let B=H.filter(Boolean)[0],$=hd({drawPosition:B,matchUpId:W.matchUpId,inContextDrawMatchUps:e}),z=Gn({appliedPolicies:t.appliedPolicies,matchUpId:W.matchUpId,matchUp:W,matchUpStatus:u,matchUpStatusCodes:[],removeScore:!0,context:p,drawDefinition:n,winningSide:$});return z.error?_({result:z,stack:p}):hS({drawPositionToAdvance:B,matchUpId:W.matchUpId,inContextDrawMatchUps:e,drawDefinition:n,matchUpsMap:s})}else if([Ct,Mt].includes(P.matchUpStatus)){let B=Il({...t,matchUpId:W.matchUpId,matchUpStatus:R,targetData:q});if(B.error)return _({result:B,stack:p})}return _({result:{...C},stack:p})}return hc({matchUpId:P.matchUpId,drawPosition:w,inContextDrawMatchUps:e,drawDefinition:n})}else if(g){if(!W)return{error:hr};if(K){let $=H[0],z=hd({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawPosition:$});console.log("existing drawPosition is winningSide",{walkoverWinningSide:z})}let q=[Ct,Mt].includes(W.matchUpStatus)?u:c,B=Gn({matchUpId:W.matchUpId,appliedPolicies:t.appliedPolicies,matchUp:W,matchUpStatusCodes:[],removeScore:!0,context:p,drawDefinition:n,matchUpStatus:q});if(B.error)return _({result:B,stack:p});if(q===c){let $=Il({...t,matchUpId:i.matchUpId,matchUpStatus:q,targetData:h});if($.error)return $}}return _({result:{...C},stack:p})}function Px(t){let{loserTargetDrawPosition:e,tournamentRecord:r,loserTargetLink:n,drawDefinition:o,matchUpsMap:i,event:s}=t,a=n?.target?.structureId,{structure:c}=at({drawDefinition:o,structureId:a});return c?Hr({drawPosition:e,tournamentRecord:r,drawDefinition:o,structureId:a,matchUpsMap:i,event:s}):{error:pi}}function wy(t){return t===he?Ct:t===Ce?Mt:t}function Dx(t){let{tournamentRecord:e,drawDefinition:r,matchUpStatus:n,structure:o,matchUp:i}=t,s=!!(i.tieMatchUps&&!i.rondPosition&&t.inContextDrawMatchUps.find(h=>h.matchUpId===i.matchUpId).containerStructureId),a="attemptToSetMatchUpStatus",c=n===Nt,u=i.winningSide,p=[he,Ce].includes(n),m=Ua({matchUpStatus:n}),d=og({matchUpStatus:n}),l=!m&&!d,f=t.matchUpTieId||u&&m&&!p,g=u&&p,I=()=>Gn({...t,removeScore:[oo,Ct].includes(n),matchUpStatus:n||Qt});return l&&{error:xI}||f&&oM(t)||g&&M1(t)||u&&vc(t)||d&&I()||c&&Ex({tournamentRecord:e,drawDefinition:r,structure:o,matchUp:i})||!m&&{error:xI}||p&&R1(t)||s&&oM(t)||_({result:{error:pa},stack:a})}function M1(t){let e=vc(t);return e.error?e:Il(t)}function R1(t){let e=oM({...t,removeScore:!0});return e.error?e:Il(t)}function oM(t){let e="scoreModification";if(t.isCollectionMatchUp&&t.dualMatchUp?.winningSide&&!t.projectedWinningSide){let i=vc(t);if(i.error)return _({result:i,stack:e})}let n=!!t.matchUp.collectionId,o=Gn({...t,context:e});if(n){let{matchUpTieId:i,drawDefinition:s,matchUpsMap:a}=t,c=co({tournamentRecord:t.tournamentRecord,appliedPolicies:t.appliedPolicies,matchUpId:i,event:t.event,drawDefinition:s,matchUpsMap:a});if(c.error)return _({result:c,stack:e});Object.assign(o,{tieMatchUpResult:c})}return _({result:o,stack:e})}function Nx({drawDefinition:t,structure:e,matchUp:r}){let{drawPositions:n}=r,{positionAssignments:o}=bt({drawDefinition:t,structure:e}),s=o?.filter(({drawPosition:m})=>n?.includes(m))?.map(m=>{let{extension:d}=dt({element:m,name:Jo});return d?.value?.groupOrder}),{containerStructures:a}=as({drawDefinition:t}),c=a[e.structureId];return{structureIds:Ws({drawDefinition:t,structureId:c})?.links?.source?.filter(m=>Fe(s,m.source?.finishingPositions||[])).map(m=>m.source.structureId)}}function Ly({drawDefinition:t,structure:e,matchUp:r}){let n=[];if(e.finishingPosition===li&&si({drawDefinition:t,structure:e})){let{structureIds:i}=Nx({drawDefinition:t,structure:e,matchUp:r});i?.length&&n.push(...i)}return{connectedStructureIds:n}}function Mx(t){let e,{inContextDrawMatchUps:r,inContextMatchUp:n,drawDefinition:o,winningSide:i}=t,s=t.targetData.targetLinks?.winnerTargetLink;if(s.target.feedProfile===dn){let a=n.sides.find(({sideNumber:u})=>u!==i).participantId,c=r.find(u=>u.structureId===s.target.structureId&&u.roundNumber===s.target.roundNumber&&u.sides.some(({participantId:p})=>p===a));if(c?.matchUpStatus===Qt){let u=ur({matchUpId:c.matchUpId,inContextDrawMatchUps:r,drawDefinition:o});if(!Ci({inContextDrawMatchUps:r,drawDefinition:o,targetData:u})){let{structure:m}=at({structureId:c.structureId,drawDefinition:o}),d=bt({structure:m}).positionAssignments;for(let l of d||[])if(l.participantId===a){let f=n.sides.find(({sideNumber:g})=>g===i).participantId;if(l.participantId=f,m?.positionAssignments)m.positionAssignments=d;else if(m?.structures){let g=Object.assign({},...(d||[]).map(I=>({[I.drawPosition]:I.participantId})));for(let I of m.structures)I.positionAssignments?.forEach(h=>h.participantId=g[h.drawPosition])}bo({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:o,structure:m}),e=!0}}}}return{...C,qualifierReplaced:e}}function Rx(t){let e,{inContextDrawMatchUps:r,inContextMatchUp:n,drawDefinition:o,winningSide:i}=t,s=t.targetData.targetLinks?.winnerTargetLink;if(s.target.feedProfile===dn){let a=n.sides.find(({sideNumber:p})=>p===i)?.participantId,c=r.filter(p=>p.structureId===s.target.structureId&&p.roundNumber===s.target.roundNumber&&p.sides.some(({participantId:m,qualifier:d})=>d&&!m)),u=yn(c);if(u?.matchUpStatus===Qt){let p=ur({matchUpId:u.matchUpId,inContextDrawMatchUps:r,drawDefinition:o});if(!Ci({inContextDrawMatchUps:r,drawDefinition:o,targetData:p})){let d=u.sides.find(g=>g.qualifier&&!g.participantId)?.drawPosition,{structure:l}=at({structureId:u.structureId,drawDefinition:o});if(!l)return{error:kt};let f=bt({structure:l}).positionAssignments;for(let g of f||[])if(g.drawPosition===d&&!g.participantId){if(g.participantId=a,l.positionAssignments)l.positionAssignments=f;else if(l.structures){let I=Object.assign({},...(f||[]).map(h=>({[h.drawPosition]:h.participantId})));for(let h of l.structures)h.positionAssignments?.forEach(S=>S.participantId=I[S.drawPosition])}bo({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:o,structure:l}),e=!0}}}}return{...C,qualifierPlaced:e}}function Cx(t){let e="attemptToSetWinningSide",r,{appliedPolicies:n,disableAutoCalc:o,drawDefinition:i,dualMatchUp:s,winningSide:a,structure:c,matchUp:u}=t;if(s?._disableAutoCalc&&o!==!1)return Rd(t);if(u.winningSide&&u.winningSide!==a){let{connectedStructureIds:l}=Ly({drawDefinition:i,structure:c,matchUp:u});l.length&&(console.log({connectedStructureIds:l}),r=!0);let f=vc(t);if(f.error)return f}let p=JS(t);if(p.error)return _({result:p,stack:e});let m,d;return t.qualifierChanging&&n?.[eu]?.autoReplaceQualifiers&&(m=Mx(t).qualifierReplaced),t.qualifierAdvancing&&n?.[eu]?.autoPlaceQualifiers&&(d=Rx(t).qualifierPlaced),_({result:ot({...C,...p,connectedStructures:r,qualifierReplaced:m,qualifierPlaced:d}),stack:e})}var Fy={drawPositionToRemove:"green",iteration:"brightred",winner:"green",loser:"brightred"};function iM(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";Rn({color:"brightyellow",method:u,matchUpId:a,iteration:c,keyColors:Fy});let{targetMatchUps:{loserMatchUp:p,winnerMatchUp:m,loserTargetDrawPosition:d},targetLinks:{loserTargetLink:l}}=i;if(m&&m.matchUpStatus!==Nt){let{stage:I,roundNumber:h,roundPosition:S,structureName:T}=m;Rn({winner:"winner",roundPosition:S,structureName:T,roundNumber:h,keyColors:Fy,stage:I}),bx({...t,targetMatchUp:m,sourceMatchUp:s,iteration:c})}let f=p?.matchUpStatus===Nt&&(p?.feedRound||p?.roundNumber===1),g=i?.targetLinks?.loserTargetLink?.linkCondition===On;if(f&&g){let I=e.filter(({roundNumber:P,structureId:U})=>U===s.structureId&&P===1),h=I.map(({roundPosition:P})=>P),S=ye(h.sort(),2).find(P=>P.includes(s.roundPosition));if((I.filter(({roundPosition:P})=>S.includes(P))?.map(({matchUpStatus:P})=>P)).every(P=>[Ce,he].includes(P)))return _({result:{...C},stack:u})}if(p&&(p.matchUpStatus!==Nt||f)){let I=e.find(({matchUpId:E})=>E===p.matchUpId),{structure:h}=at({drawDefinition:n,structureId:I.structureId}),{stage:S,roundNumber:T,roundPosition:y,feedRound:P,structureName:U}=p;if(Rn({loser:"loser",roundPosition:y,structureName:U,roundNumber:T,keyColors:Fy,feedRound:P,stage:S}),r?.progression?.doubleExitPropagateBye||f)xy({drawPosition:d,targetLink:l,inContextDrawMatchUps:e,drawDefinition:n,matchUpsMap:o});else{let E=bx({...t,targetMatchUp:p,structure:h,iteration:c});if(E.error)return _({result:E,stack:u})}}return _({result:{...C},stack:u})}function bx(t){let{inContextDrawMatchUps:e,appliedPolicies:r,drawDefinition:n,sourceMatchUp:o,targetMatchUp:i,matchUpsMap:s,structure:a,iteration:c}=t,u="conditionallyRemoveDrawPosition";Rn({method:u,structureName:a?.structureName,iteration:c});let p=ur({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:n}),{targetMatchUps:{winnerMatchUp:m}}=p,d=s?.drawMatchUps.find(y=>y.matchUpId===i.matchUpId),l=[],f,g,I;if(i.feedRound)I=m?.drawPositions?.filter(Boolean)?.find(P=>i.drawPositions.includes(P));else if(!o)I=Yt(i?.drawPositions||[],m?.drawPositions||[])?.[0];else if(g=DS({structureId:a.structureId,matchUp:o,matchUpsMap:s})?.pairedPreviousMatchUp,f=[he,Ce].includes(g?.matchUpStatus),l=g?.drawPositions?.filter(Boolean)||[],[...ce,Nt].includes(g?.matchUpStatus)||g?.winningSide){let P=o.drawPositions||[],U=i.drawPositions?.filter(Boolean);Fe(P,U)&&(U=U?.filter(A=>!P.includes(A))),I=P.concat(l).find(A=>U?.includes(A))}if(m&&I){let{stage:y,roundNumber:P,roundPosition:U,structureName:E}=m;Rn({method:"removeDirectedWinner",drawPositionToRemove:I,color:"brightgreen",roundPosition:U,structureName:E,roundNumber:P,keyColors:Fy,stage:y}),nM({winningDrawPosition:I,winnerMatchUp:m,inContextDrawMatchUps:e,drawDefinition:n,matchUpsMap:s})}let h=iM({targetData:p,matchUp:i,inContextDrawMatchUps:e,appliedPolicies:r,drawDefinition:n,matchUpsMap:s,structure:a,iteration:c});if(h.error)return _({result:h,stack:u});let S=C1({pairedPreviousDoubleExit:f,noContextTargetMatchUp:d}),T=!f;return h=Gn({...t,matchUpId:i.matchUpId,matchUp:d,removeWinningSide:!0,matchUpStatusCodes:[],context:u,matchUpStatus:S,removeScore:T,score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0}}),h.error?_({result:h,stack:u}):{...C}}function C1({pairedPreviousDoubleExit:t,noContextTargetMatchUp:e}){return e.matchUpStatus===Nt?Nt:t?[Ce,Mt].includes(e?.matchUpStatus)?Mt:Ct:Qt}function vx(t){let e,{inContextDrawMatchUps:r,inContextMatchUp:n,drawDefinition:o}=t,i=t.targetData.targetLinks?.winnerTargetLink;if(i.target.feedProfile===dn){let s=n.sides?.find(({sideNumber:c})=>c===n.winningSide)?.participantId,a=r.find(c=>c.structureId===i.target.structureId&&c.roundNumber===i.target.roundNumber&&c.sides?.some(({participantId:u})=>u===s));if(a&&a.matchUpStatus===Qt){let c=ur({matchUpId:a.matchUpId,inContextDrawMatchUps:r,drawDefinition:o});if(!Ci({inContextDrawMatchUps:r,drawDefinition:o,targetData:c})){let{structure:p}=at({structureId:a.structureId,drawDefinition:o}),m=bt({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])}bo({tournamentId:t.tournamentRecord?.tournamentId,event:t.event,drawDefinition:o,structure:p}),e=!0}}}}return{qualifierRemoved:e}}function _x(t){let{matchUp:e,matchUpStatus:r,score:n,winningSide:o}=t,i="noDownStreamDependencies";if([he,Ce].includes(e?.matchUpStatus)&&![he,Ce].includes(r)){let I=iM(t);if(I.error)return _({result:I,stack:i})}let a=r===he,c=Ie({score:n})&&!a&&(t.isCollectionMatchUp&&!t.projectedWinningSide||!o),u=t?.inContextMatchUp?.collectionId&&Ax(t.inContextMatchUp),p=t.removeScore||!u&&![pn,br].includes(r||pn),m=t.isCollectionMatchUp&&t.dualMatchUp.winningSide&&!t.projectedWinningSide||e.winningSide&&!o&&!Ie({score:n}),d=r&&r!==Qt,l=I=>{let h,{structure:S,drawDefinition:T,dualMatchUp:y,disableAutoCalc:P}=t;if(y?._disableAutoCalc&&P!==!1)return Rd({...t,removeWinningSide:m});let{connectedStructureIds:U}=Ly({drawDefinition:T,structure:S,matchUp:e});U.length&&(console.log({connectedStructureIds:U}),h=!0),Object.assign(t,{removeScore:I});let E=vc(t);if(E.error)return E;if(t.removingQualifier&&t.appliedPolicies?.[eu]?.autoRemoveQualifiers){let A=vx(t);return{...C,connectedStructures:h,...A}}return{...C,connectedStructures:h}};if(m&&o&&t.isCollectionMatchUp)return Ox(t);let f=[oo,br].includes(r)&&t.dualWinningSideChange,g=(o||f)&&Cx(t)||c&&l(p)||d&&Dx(t)||m&&l(p)||e&&Ox({...t,removeScore:!0})||{...C};return _({result:g,stack:i})}function Ox(t){let e="ndd:scoreModification";if(t.isCollectionMatchUp&&t.dualMatchUp?.winningSide&&!t.projectedWinningSide&&!t.autoCalcDisabled){let o=vc(t);if(o.error)return o}let n=Gn({...t,context:e});if(t.isCollectionMatchUp){let{matchUpTieId:o,drawDefinition:i,event:s,matchUpsMap:a}=t,{removeWinningSide:c}=co({tournamentRecord:t.tournamentRecord,appliedPolicies:t.appliedPolicies,matchUpId:o,drawDefinition:i,matchUpsMap:a,event:s});c&&console.log("REMOVE WINNING SIDE")}return _({result:n,stack:e})}function oI(t){let e=rt(t,[{[ie]:!0,[Ve]:!0,[ln]:!0},{homeParticipantId:!0,[fn]:oe}]);if(e.error)return e;let r=Ds(t,[{[is]:_n,attr:{[tu]:!0}}]);if(r.error)return r;let n=r?.matchUp?.matchUp?.sides?.map(m=>m?.participantId);if(t.homeParticipantId&&!n?.includes(t.homeParticipantId))return{error:mn};let{disableNotice:o=!0,homeParticipantId:i,removePriorValues:s,tournamentRecord:a,drawDefinition:c,matchUpId:u}=t;return Jr({duplicateValues:!1,removePriorValues:s,tournamentRecord:a,drawDefinition:c,disableNotice:o,matchUpId:u,timeItem:{itemType:cd,itemValue:i}})}function sM({timeStamp:t,schedule:e,matchUp:r}){let{itemValue:n,timeStamp:o}=Ho({timeItems:r?.timeItems||[],itemType:Ap});return!e||o&&t&&new Date(o).getTime()>new Date(t).getTime()?{timeModifiers:n}:e}function zo(t){let e="addMatchUpScheduledTime",r=t.matchUp,{removePriorValues:n,tournamentRecord:o,drawDefinition:i,disableNotice:s,scheduledTime:a,matchUpId:c}=t;if(!c)return _({result:{error:sr},stack:e});if(!Wc(a))return _({result:{error:Eo},stack:e});if(!r){let I=Bt({drawDefinition:i,matchUpId:c});if(I.error)return _({result:I,stack:e});r=I.matchUp}let u=Et(a),p=Hs({matchUp:r}).scheduledDate,m=u&&!p;if((sM({matchUp:r}).timeModifiers||[])?.length){let I=aM({disableNotice:!0,removePriorValues:n,tournamentRecord:o,timeModifiers:[],drawDefinition:i,matchUpId:c,matchUp:r});if(I?.error)return _({result:I,stack:e})}let f=Xa(a,!0,m);return Jr({duplicateValues:!1,removePriorValues:n,tournamentRecord:o,drawDefinition:i,disableNotice:s,matchUpId:c,timeItem:{itemType:ji,itemValue:f}})}function aM({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,timeModifiers:o,matchUpId:i,matchUp:s}){let a="addMatchUpTimeModifiers";if(!i)return _({result:{error:sr},stack:a});if(o!==void 0&&!Array.isArray(o))return _({info:ii("timeModifiers"),result:{error:G},stack:a});if(!s){let l=Bt({drawDefinition:r,matchUpId:i});if(l.error)return _({result:l,stack:a});s=l.matchUp}let c=sM({matchUp:s}).timeModifiers||[],u=o.filter(l=>!c.includes(l));if(o.length&&!u.length)return{...C};if(u.some(l=>sS.includes(l))){c=c.filter(f=>!sS.includes(f));let l=zo({disableNotice:!0,removePriorValues:t,scheduledTime:"",tournamentRecord:e,drawDefinition:r,matchUpId:i});if(l.error)return _({result:l,stack:a})}let m=o?.length?[...u,...c]:void 0;return Jr({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:i,timeItem:{itemType:Ap,itemValue:m}})}function nm({scheduledDate:t,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i}){if(!i)return{error:sr};let s=t&&Po.test(t);if(t&&!s)return{error:je};let c={itemValue:Et(t),itemType:Wi};return Jr({duplicateValues:!1,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:c})}function om({removePriorValues:t,tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,courtDayDate:i,matchUpId:s,courtIds:a}){if(!r&&!e)return{error:Y};if(!s)return{error:sr};let c=Bt({drawDefinition:n,matchUpId:s});if(c.error)return c;if(c?.matchUp?.matchUpType!==xr)return{error:dr};if(!(a===void 0||Array.isArray(a)&&a.length&&a.every(d=>typeof d=="string")))return{error:G,context:{courtIds:a}};let p;if(a){let d=e||r&&{[r.tournamentId]:r},l=Ao({tournamentRecords:d});if(l.error)return l;let f=l.courts?.filter(g=>a.includes(g.courtId));if(f?.length!==a.length)return{error:G,context:{courtIds:a}};p=f?.map(g=>({venueId:g.venueId,courtId:g.courtId}))}return Jr({duplicateValues:!1,removePriorValues:t,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:s,timeItem:{itemType:so,itemDate:i,itemValue:p}})}function ia({removePriorValues:t,tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,venueId:s}){if(!r)return{error:Y};if(!i)return{error:sr};if(s){let c=Wo({tournamentRecords:e,tournamentRecord:r,venueId:s});if(c.error)return c}return Jr({duplicateValues:!1,removePriorValues:t,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:{itemType:Hi,itemValue:s}})}function Xi({removePriorValues:t,tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,courtDayDate:i,matchUpId:s,courtId:a}){if(!r&&!e)return{error:Y};if(!s)return{error:sr};if(a){let u=ps({tournamentRecords:e,tournamentRecord:r,courtId:a});if(u.error)return u;let p=u.venue?.venueId;ia({tournamentRecords:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:s,venueId:p})}return Jr({duplicateValues:!1,removePriorValues:t,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:s,timeItem:{itemType:Bo,itemDate:i,itemValue:a}})}function Ms(t,e){let r=$I.test(t)?t:Kt(t),n=Et(t)||Et(e)||Hn(new Date);return new Date(`${n}T${r}`).getTime()}function im(t){let e="addMatchUpScheduleItems",r=rt(t,[{drawDefinition:!0,matchUpId:!0},{schedule:!0,[He]:Kr}],e);if(r.error)return r;let{matchUpDependencies:n,inContextMatchUps:o}=t,{errorOnAnachronism:i=!1,checkChronology:s=!0,removePriorValues:a,tournamentRecords:c,tournamentRecord:u,drawDefinition:p,disableNotice:m,drawMatchUps:d,matchUpId:l,schedule:f,event:g}=t,I,h;if(d)I=d.find(O=>O.matchUpId===l);else{let O=Bt({drawDefinition:p,event:g,matchUpId:l});if(O.error)return O;I=O.matchUp}let{endTime:S,courtId:T,courtIds:y,courtOrder:P,resumeTime:U,homeParticipantId:E,scheduledDate:A,scheduledTime:N,startTime:D,stopTime:M,timeModifiers:R,venueId:b}=f;s&&(!n||!o)&&({matchUpDependencies:n,matchUps:o}=sn({drawDefinition:p}));let v=n?.[l]?.matchUpIds;if(f.scheduledDate&&s&&v){let O=o?.filter(x=>(x.schedule?.scheduledDate||Et(x.schedule?.scheduledTime))&&v.includes(x.matchUpId)).map(({schedule:x})=>{let F=bm(x);return new Date(F).getTime()});if(O?.length){let x=bm(f),F=new Date(x).getTime();if(Math.max(...O)>=F){if(i)return _({result:{error:bI},stack:e});h=bI}}}if(A!==void 0){let O=nm({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,scheduledDate:A,matchUpId:l});if(O?.error)return _({result:O,stack:e,context:{scheduledDate:A}})}if(N!==void 0){let O=zo({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,scheduledTime:N,matchUpId:l,matchUp:I});if(O?.error)return _({result:O,stack:e,context:{scheduledTime:N}})}if(D!==void 0){let O=Gy({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,matchUpId:l,startTime:D,event:g});if(O?.error)return _({result:O,stack:e,context:{startTime:D}})}if(M!==void 0){let O=By({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,matchUpId:l,stopTime:M,event:g});if(O?.error)return _({result:O,stack:e,context:{stopTime:M}})}if(U!==void 0){let O=Hy({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,resumeTime:U,matchUpId:l,event:g});if(O?.error)return _({result:O,stack:e,context:{resumeTime:U}})}if(S!==void 0){let O=Vy({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,matchUpId:l,endTime:S,event:g});if(O?.error)return _({result:O,stack:e,context:{endTime:S}})}if(y!==void 0){let O=om({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,matchUpId:l,courtIds:y});if(O?.error)return _({result:O,stack:e,context:{courtIds:y}})}if(T!==void 0&&A!==void 0){let O=Xi({courtDayDate:A,disableNotice:!0,removePriorValues:a,tournamentRecords:c,tournamentRecord:u,drawDefinition:p,matchUpId:l,courtId:T});if(O?.error)return _({result:O,stack:e,context:{courtId:T}})}if(b!==void 0){let O=ia({disableNotice:!0,removePriorValues:a,tournamentRecords:c,tournamentRecord:u,drawDefinition:p,matchUpId:l,venueId:b});if(O?.error)return _({result:O,stack:e,context:{venueId:b}})}if(P!==void 0&&It(P)){let O=ky({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,courtOrder:P,matchUpId:l});if(O?.error)return _({result:O,stack:e,context:{courtOrder:P}})}if(R!==void 0){let O=aM({disableNotice:!0,removePriorValues:a,tournamentRecord:u,drawDefinition:p,timeModifiers:R,matchUpId:l,matchUp:I});if(O?.error)return _({result:O,stack:e,context:{timeModifiers:R}})}return Vt(E)&&oI({disableNotice:!0,homeParticipantId:E,removePriorValues:a,tournamentRecord:u,drawDefinition:p,matchUpId:l}),m||gt({tournamentId:u?.tournamentId,eventId:g?.eventId,context:e,drawDefinition:p,matchUp:I}),h?{...C,warnings:[h]}:{...C}}function ky({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,courtOrder:o,matchUpId:i}){if(!i)return{error:sr};if(o&&!It(o))return{error:G,info:"courtOrder must be numeric"};let s=o&&pt(o);return Jr({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:i,timeItem:{itemType:yp,itemValue:s}})}function cM({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,participantId:o,officialType:i,matchUpId:s}){if(!s)return{error:sr};if(!o)return{error:oe};if(e){let c=Gt({tournamentRecord:e,participantFilters:{participantTypes:[Tt],participantRoles:[ag]}}).participants??[];if(!Go({tournamentParticipants:c,participantId:o}))return{error:te}}let a={itemType:"SCHEDULE.ASSIGNMENT.OFFICIAL",itemValue:o};return i&&(a.itemSubTypes=[i]),Jr({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:s,timeItem:a})}function Gy({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,startTime:i,event:s}){if(!o)return{error:sr};if(!Wc(i))return{error:Eo};let{matchUp:a}=Bt({drawDefinition:r,event:s,matchUpId:o}),{scheduledDate:c}=Hs({matchUp:a}),p=(a?.timeItems??[]).filter(m=>[Yi,Pi,Di].includes(m?.itemType)).map(m=>Ms(m.itemValue,c)).reduce((m,d)=>!m||d<m?d:m,void 0);if(!p||Ms(i,c)<p){a?.timeItems&&(a.timeItems=a.timeItems.filter(l=>l.itemType!==Oo));let m=Xa(i,!0,!0);return Jr({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,timeItem:{itemType:Oo,itemValue:m}})}else return{error:AE}}function Vy({validateTimeSeries:t=!0,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,endTime:s,event:a}){if(!i)return{error:sr};if(!Wc(s))return{error:Eo};let{matchUp:c}=Bt({drawDefinition:n,event:a,matchUpId:i}),{scheduledDate:u}=Hs({matchUp:c}),m=(c?.timeItems??[]).filter(d=>[Oo,Pi,Yi].includes(d?.itemType)).map(d=>Ms(d.itemValue,u)).reduce((d,l)=>!d||l>d?l:d,void 0);if(!t||!m||Ms(s,u)>m){c?.timeItems&&(c.timeItems=c.timeItems.filter(f=>f.itemType!==Di));let d=Xa(s,!0,!0);return Jr({duplicateValues:!1,removePriorValues:e,tournamentRecord:r,drawDefinition:n,disableNotice:o,matchUpId:i,timeItem:{itemType:Di,itemValue:d}})}else return{error:TE}}function By({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,stopTime:i,event:s}){if(!o)return{error:sr};if(!Wc(i))return{error:Eo};let{matchUp:a}=Bt({drawDefinition:r,event:s,matchUpId:o}),{scheduledDate:c}=Hs({matchUp:a}),u=a?.timeItems??[];if(u.reduce((g,I)=>I.itemType===Di||g,void 0))return{error:HI};let m=u.filter(g=>[Oo,Pi,Yi].includes(g?.itemType)).sort((g,I)=>Ms(g.itemValue,c)-Ms(I.itemValue,c)),d=m[m.length-1],l=d&&d.itemType===Yi,f=m.filter(g=>!l||g.createdAt!==d.createdAt).map(g=>Ms(g.itemValue,c)).reduce((g,I)=>!g||I>g?I:g,void 0);if(Ms(i,c)>f){if(a?.timeItems&&l){let h=d.createdAt;a.timeItems=a.timeItems.filter(S=>S.createdAt!==h)}let I={itemValue:Xa(i,!0,!0),itemType:Yi};return Jr({duplicateValues:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:o,timeItem:I})}else return{error:yE}}function Hy({removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,resumeTime:o,matchUpId:i,event:s}){if(!i)return{error:sr};if(!Wc(o))return{error:Eo};let{matchUp:a}=Bt({drawDefinition:r,event:s,matchUpId:i}),{scheduledDate:c}=Hs({matchUp:a}),u=a?.timeItems??[];if(u.reduce((g,I)=>I.itemType===Di||g,void 0))return{error:HI};let m=u.filter(g=>[Oo,Pi,Yi].includes(g?.itemType)).sort((g,I)=>Ms(g.itemValue,c)-Ms(I.itemValue,c)),d=m[m.length-1],l=d&&d.itemType===Pi,f=m.filter(g=>!l||g.createdAt!==d.createdAt).map(g=>Ms(g.itemValue,c)).reduce((g,I)=>!g||I>g?I:g,void 0);if(Ms(o,c)>f){if(a?.timeItems&&l){let h=d.createdAt;a.timeItems=a.timeItems.filter(S=>S.createdAt!==h)}let I={itemValue:Xa(o,!0,!0),itemType:Pi};return Jr({duplicateValues:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:r,disableNotice:n,matchUpId:i,timeItem:I})}else return{error:UC}}function xx({drawDefinition:t,matchUpStatus:e,matchUpsMap:r,winningSide:n,dualMatchUp:o,tieFormat:i,structure:s,matchUp:a,event:c,score:u}){let p=J(o,void 0,!0);for(let d of p?.tieMatchUps||[])d.matchUpId===a.matchUpId&&(d.winningSide=n,d.score=u,!Ie({score:u})&&!e?Object.assign(d,{...Ru}):e&&(d.matchUpStatus=e));i=i??We({matchUp:a,structure:s,drawDefinition:t,event:c})?.tieFormat;let{winningSide:m}=Uc({matchUp:p,drawDefinition:t,matchUpsMap:r,structure:s,tieFormat:i,event:c});return{projectedWinningSide:m}}function wx(t){let{tournamentRecord:e,inContextMatchUp:r,structure:n,drawDefinition:o}=t,i=r.roundNumber,s=r.sides.find(U=>U.sideNumber===r.winningSide),a=r.sides.find(U=>U.sideNumber!==r.winningSide),{drawPosition:c,participantId:u}=s,{drawPosition:p,participantId:m}=a,d="swapWinnerLoser",{matchUps:l}=Ut(t),f=l.filter(({drawPositions:U,roundNumber:E})=>U?.includes(c)&&E>i);Ur({changeWinner:!0})&&console.log({existingWinnerSubsequentMatchUps:f}),f.forEach(U=>{U.drawPositions=U.drawPositions?.map(E=>E===c?p:E)||[],gt({tournamentId:e?.tournamentId,eventId:t.event?.eventId,context:d,drawDefinition:o,matchUp:U})});let{stage:g,stageSequence:I}=n,h=o.structures.filter(({stage:U,stageSequence:E})=>U===g&&E>I).map(({structureId:U})=>U),{targetLinks:{loserTargetLink:S,winnerTargetLink:T}}=t.targetData,y=[S?.target.structureId,T?.target?.structureId].filter(Boolean);return o.structures.filter(({stage:U,structureId:E})=>U!==g&&y.includes(E)).forEach(({stage:U,stageSequence:E,structureId:A})=>{h.includes(A)||h.push(A),o.structures.filter(({stage:N,stageSequence:D})=>N===U&&D>E).forEach(({structureId:N})=>{h.includes(N)||h.push(N)})}),o.structures.filter(({structureId:U})=>h.includes(U)).forEach(U=>{let{positionAssignments:E}=bt({structure:U}),A=E?.find(({participantId:D})=>D===u),N=E?.find(({participantId:D})=>D===m);A&&(A.participantId=m),N&&(N.participantId=u)}),Gn({...t,context:d})}function La(t){let e="setMatchUpStatus";t.matchUpStatus&&[Ct,he].includes(t.matchUpStatus)&&(t.score=void 0);let{allowChangePropagation:r,disableScoreValidation:n,tournamentRecords:o,tournamentRecord:i,disableAutoCalc:s,enableAutoCalc:a,drawDefinition:c,matchUpStatus:u,winningSide:p,matchUpId:m,event:d,score:l}=t;if(!c)return{error:Z};if(u&&[oo,pn,br,Qt].includes(u)&&p)return{error:G,winningSide:p,matchUpStatus:u};if(![void 0,...Lh].includes(u))return _({result:{error:pa},info:"matchUpStatus does not exist",stack:"setMatchUpStatus"});let f=Ne({drawDefinition:c}),{matchUps:g}=se({nextMatchUps:!0,tournamentRecord:i,inContext:!0,drawDefinition:c,matchUpsMap:f,event:d}),I=f.drawMatchUps.find(k=>k.matchUpId===m),h=g?.find(k=>k.matchUpId===m);if(!I||!g)return{error:Le};if((I.winningSide||p)&&u===Nt)return{context:"Cannot have Bye with winningSide",error:Bl,matchUpStatus:u};let S=h?.structureId,{structure:T}=at({drawDefinition:c,structureId:S}),y=ue(jt)(I.matchUpType),P=h?.drawPositions?.filter(Boolean),U=h?.matchUpTieId,E=ur({matchUpId:U||m,inContextDrawMatchUps:g,drawDefinition:c});Object.assign(t,{inContextDrawMatchUps:g,inContextMatchUp:h,matchUpTieId:U,matchUpsMap:f,targetData:E,structure:T,matchUp:I});let A=Ci(t),N;if(y){if(s)At({extension:{name:ga,value:!0},element:I});else if(a){let k=I.winningSide,{winningSide:W,scoreStringSide1:H,scoreStringSide2:K,set:q}=Uc({drawDefinition:c,matchUpsMap:f,structure:T,matchUp:I,event:d}),B={scoreStringSide1:H,scoreStringSide2:K,sets:q?[q]:[]};if(N=W!==k,A&&N)return _({stack:"winningSideWithDownstreamDependencies",result:{error:Um},context:{winningSide:p,matchUp:I}});gr({name:ga,element:I}),Object.assign(t,{winningSide:W,dualWinningSideChange:N,projectedWinningSide:W,score:B})}ba({tournamentId:i?.tournamentId,inContextDualMatchUp:h,eventId:d?.eventId,dualMatchUp:I,drawDefinition:c})}if(y&&u&&[ic].includes(u))return{info:"Not supported for matchUpType: TEAM",error:G};if(l&&!y&&!n){let k=I.matchUpFormat??T?.matchUpFormat??c?.matchUpFormat??d?.matchUpFormat,W=Vg({existingMatchUpStatus:I.matchUpStatus,matchUpFormat:k,matchUpStatus:u,winningSide:p,score:l});if(W.error)return W}let D=yt({policyTypes:[eu,en],tournamentRecord:i,drawDefinition:c,event:d})?.appliedPolicies??{};ht(t.policyDefinitions)&&Object.assign(D,t.policyDefinitions);let M=v1({assignedDrawPositions:P,inContextMatchUp:h,appliedPolicies:D,drawDefinition:c,matchUpStatus:u,structure:T,matchUp:I});if(M?.error)return M;let R=h?.stage===ct&&h.finishingRound===1,b=R&&p,v=R&&I.winningSide&&!p&&(!t.matchUpStatus||t.matchUpStatus&&og({matchUpStatus:t.matchUpStatus}))&&(!t.outcome||!Ie({outcome:t.outcome})),O=b&&p!==I.winningSide&&I.winningSide;if(Object.assign(t,{qualifierAdvancing:b,qualifierChanging:O,removingQualifier:v,appliedPolicies:D}),U){let{matchUp:k}=Bt({matchUpId:U,inContext:!0,drawDefinition:c,matchUpsMap:f,event:d});if(k){let W=We({matchUp:k,drawDefinition:c,structure:T,event:d})?.tieFormat,{projectedWinningSide:H}=xx({drawDefinition:c,matchUpStatus:u,dualMatchUp:k,matchUpsMap:f,winningSide:p,tieFormat:W,structure:T,matchUp:I,event:d,score:l}),K=k.winningSide;N=H!==K;let q=k._disableAutoCalc;Object.assign(t,{isCollectionMatchUp:!0,dualWinningSideChange:N,projectedWinningSide:H,autoCalcDisabled:q,matchUpTieId:U,dualMatchUp:k,tieFormat:W})}}let x=Ua({matchUpStatus:u});if(!U){if(A&&!p&&(u&&og({matchUpStatus:u})||u&&[he,Ce].includes(u)))return{error:Bl,activeDownstream:A,winningSide:p};if(p&&p===I.winningSide&&u&&!x)return{context:"winningSide must include directing matchUpStatus",error:Bl,directingMatchUpStatus:x,matchUpStatus:u}}let{schedule:F}=t;if(F){let k=im({disableNotice:!0,tournamentRecords:o,tournamentRecord:i,drawDefinition:c,matchUpId:m,schedule:F});if(k.error)return k}let L=!y&&!N&&p&&I.winningSide&&I.winningSide!==p;if(r&&L&&I.roundPosition)return wx(t);let w=p&&!U||t.projectedWinningSide;Rn({activeDownstream:A,matchUpWinner:w,method:e,winningSide:p});let V=!A&&_x(t)||w&&b1(t)||(x||t.autoCalcDisabled)&&Lx(t)||{error:CE};return _({result:V,stack:e})}function b1(t){let{matchUp:e,winningSide:r,matchUpTieId:n,dualWinningSideChange:o}=t;return r===e.winningSide||n&&!o?Lx(t):_({stack:"winningSideWithDownstreamDependencies",result:{error:Um},context:{winningSide:r,matchUp:e}})}function Lx(t){let{tournamentRecord:e,matchUp:r,event:n}=t,o=t.isCollectionMatchUp&&r.winningSide&&!t.winningSide&&!Ie({score:t.score}),i=t.isCollectionMatchUp?t.matchUpStatus||o&&Qt||t.winningSide&&le||pn:t.matchUpStatus||le,s=t.removeScore||[oo,Ct].includes(i)&&![pn,br].includes(i),a=Gn({...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=co({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 v1({assignedDrawPositions:t,inContextMatchUp:e,appliedPolicies:r,drawDefinition:n,matchUpStatus:o,structure:i,matchUp:s}){if(r?.[en]?.requireParticipantsForScoring===!1)return{...C};let a=e?.sides?.map(p=>p.participantId).filter(Boolean).length,c=s?.sides?[]:bt({structureId:i?.structureId,drawDefinition:n}).positionAssignments,u=a&&a===2||s.collectionId&&cr({structure:i})&&a&&a>=1||t?.length===2&&c?.filter(p=>t.includes(p.drawPosition)).every(p=>p.participantId);return o&&wh.includes(o)&&!u?_({info:"matchUpStatus requires assigned participants",context:{matchUpStatus:o,requiredParticipants:u},result:{error:pa}}):{...C}}function uM({tournamentRecord:t,drawDefinition:e,matchUpId:r,event:n}){if(!e)return{error:Z};let{matchUp:o}=Bt({drawDefinition:e,matchUpId:r,event:n});return o?.matchUpType!==xr?{error:dr}:La({enableAutoCalc:!0,tournamentRecord:t,drawDefinition:e,matchUpId:r,event:n})}function pM({drawDefinition:t,event:e,matchUpId:r}){if(!t)return{error:Z};if(!r)return{error:sr};let{matchUp:n}=Bt({drawDefinition:t,event:e,matchUpId:r});return n?gr({name:Bm,element:n}):{error:Le}}function Fx({substituteParticipantId:t,existingParticipantId:e,tournamentRecord:r,drawDefinition:n,sideNumber:o,matchUpId:i,event:s}){let a="substituteParticipant";if(!n)return{error:Z};if(!i)return{error:sr};if(!e||!t)return _({result:{error:oe},stack:a});let{matchUp:c}=Bt({drawDefinition:n,matchUpId:i,event:s});if(!c)return{error:Le};if(!c.collectionId)return _({result:{error:dr},stack:a});let u=Ne({drawDefinition:n}),{matchUps:p}=se({tournamentParticipants:r?.participants,inContext:!0,drawDefinition:n,matchUpsMap:u}),m=p?.find(g=>g.matchUpId===i),l=p?.find(g=>g.matchUpId===m?.matchUpTieId)?.sides?.find(g=>g.participant.individualParticipants.some(({participantId:I})=>I===e));return!l||o&&l.sideNumber!==o?{error:mn}:l.participant?.individualParticipants?.map(St).filter(g=>g!==e)?.includes(t)?rI({newParticipantId:t,tieMatchUpId:i,existingParticipantId:e,substitution:!0,tournamentRecord:r,drawDefinition:n,event:s}):_({result:{error:mn},stack:a})}function mM(t){return Fx(t)}function dM({drawDefinition:t,matchUpId:e,event:r}){if(!t)return{error:Z};let{matchUp:n}=Bt({drawDefinition:t,matchUpId:e,event:r});return At({extension:{name:ga,value:!0},element:n})}function lM(t){let e="setMatchUpFormat",r=rt(t,[{tournamentRecord:!0},{[tr]:P=>Pr({matchUpFormat:P}),[Fr]:qa,matchUpFormat:!0}]);if(r.error)return _({result:r,stack:e});let{tournamentRecord:n,drawDefinition:o,scheduledDates:i,stageSequences:s,matchUpFormat:a,structureId:c,eventType:u,matchUpId:p,eventId:m,stages:d,drawId:l,event:f,force:g}=t;if(i&&!Array.isArray(i))return _({result:{error:G,scheduledDates:i},stack:e});if(u&&!Lc([jn,qr],u))return _({result:{error:Bn},stack:e});let I=0,h=t.structureIds||c&&[c].filter(Boolean)||[],S=t.eventIds||m&&[m].filter(Boolean)||[],T=t.drawIds||l&&[l].filter(Boolean)||[];if((c||h?.length)&&!o)return _({result:{error:Z},stack:e});if(l&&p&&o){let P=$d({tournamentRecord:n,drawDefinition:o,matchUpFormat:a,structureIds:h,structureId:c,matchUpId:p});if(P.error)return P;I+=1}let y=P=>{let U=[];for(let E of P.structures||[]){if(Array.isArray(d)&&!d.includes(E.stage)||Array.isArray(s)&&!s.includes(E.stageSequence)||h?.length&&!h.includes(E.structureId))continue;h?.length&&E.matchUpFormat!==a&&(E.matchUpFormat=a,U.push(E.structureId),I+=1);let A=((g||i)&&Ut({matchUpFilters:{matchUpStatuses:[Qt]},structure:E}).matchUps)??[],N=(i&&Ut({matchUpFilters:{matchUpStatuses:[Qt]},contextFilters:{scheduledDates:i},afterRecoveryTimes:!1,inContext:!0,structure:E}).matchUps)??[];if(A?.length){let D=N?N.map(Ae):A.map(Ae);for(let M of A)D.includes(M.matchUpId)&&(M.matchUpFormat=i?.length?a:void 0,gt({tournamentId:n?.tournamentId,eventId:f?.eventId,context:e,drawDefinition:P,matchUp:M}))}}return!U.length&&P.matchUpFormat!==a&&(P.matchUpFormat=a,I+=1),U};for(let P of n?.events||[])if(!(S?.length&&!S.includes(P.eventId)||u&&u!==P.eventType||u===_e))if(Array.isArray(s)||Array.isArray(d)||h?.length||T?.length)for(let U of P.drawDefinitions||[]){if(Array.isArray(T)&&!T.includes(U.drawId))continue;let E=y(U);Ot({structureIds:E,drawDefinition:U})}else P.matchUpFormat!==a&&(P.matchUpFormat=a,I+=1);return I?{...C,modificationsCount:I}:{...C,info:_s}}function iI({inheritance:t=!0,tournamentRecord:e,drawDefinition:r,matchUpId:n,event:o}){if(!r)return{error:Z};let i=Bt({drawDefinition:r,matchUpId:n})?.matchUp;if(!i?.tieMatchUps)return{error:dr};let s=Bt({inContext:!0,drawDefinition:r,matchUpId:n,event:o})?.matchUp,a=0;return(i?.sides||[]).forEach(c=>{c.lineUp&&delete c.lineUp}),(s?.sides||[]).forEach(c=>{if(a+=1,t===!1){let u=s?.tieFormat,p=c.participantId;u&&p&&Ki({drawDefinition:r,participantId:p,lineUp:[],tieFormat:u})}gt({tournamentId:e?.tournamentId,context:"resetMatchUpLineUps",eventId:o?.eventId,drawDefinition:r,matchUp:i})}),{...C,modificationsCount:a}}function Wy(t){let{matchUpFormat:e,matchUpStatus:r,winningSide:n,score:o}=t;if(!o)return{sets:[]};let i=o.sets||[],s=jo({winnerFirst:!1,matchUpFormat:e,matchUpStatus:r,sets:i}),a=jo({winnerFirst:!1,reversed:!0,matchUpFormat:e,matchUpStatus:r,sets:i}),c=jo({matchUpFormat:e,matchUpStatus:r,winningSide:n,sets:i}),u=s===c?a:s;return n&&(s=n===1?c:u,a=n===2?c:u),{score:{sets:i,scoreStringSide1:s,scoreStringSide2:a}}}function Gu(t){let e=rt(t,[{[ln]:!0,[Ve]:!0}]);if(e.error)return e;let r=Dr(t);if(!t.drawDefinition){let h=t.tournamentRecord??(t.tournamentId&&r[t.tournamentId]);t.tournamentRecord||(t.tournamentRecord=h);let S=ze({eventId:t.eventId,drawId:t.drawId,tournamentRecord:h});if(S.error)return S;S.drawDefinition&&(t.drawDefinition=S.drawDefinition),t.event=S.event}let{disableScoreValidation:n,policyDefinitions:o,tournamentRecord:i,disableAutoCalc:s,enableAutoCalc:a,drawDefinition:c,matchUpId:u,schedule:p,event:m,notes:d}=t,l=t.matchUpFormat||t.outcome?.matchUpFormat,{policy:f}=ei({policyType:en,tournamentRecord:i,event:m}),g=t.allowChangePropagation!==void 0&&t.allowChangePropagation||f?.allowChangePropagation!==void 0&&f.allowChangePropagation||void 0,{outcome:I}=t;if(I?.winningSide&&![1,2].includes(I.winningSide))return{error:Em};if(l){let h=$d({tournamentRecord:i,drawDefinition:c,matchUpFormat:l,matchUpId:u,event:m});if(h.error)return h}if(I?.score?.sets&&!I.score.scoreStringSide1){let{score:h}=Wy(I);I.score=h,I.score.sets=I.score.sets.filter(S=>S.side1Score||S.side2Score||S.side1TiebreakScore||S.side2TiebreakScore)}return La({matchUpStatusCodes:I?.matchUpStatusCodes,matchUpStatus:I?.matchUpStatus,winningSide:I?.winningSide,allowChangePropagation:g,disableScoreValidation:n,score:I?.score,tournamentRecords:r,policyDefinitions:o,tournamentRecord:i,disableAutoCalc:s,enableAutoCalc:a,drawDefinition:c,matchUpFormat:l,matchUpId:u,schedule:p,event:m,notes:d})}function fM(t){if(!t?.outcomes)return{error:st};if(!Array.isArray(t.outcomes))return{error:st,info:{outcomes:t.outcomes}};let e=t.tournamentRecords||t.tournamentRecord&&{[t.tournamentRecord.tournamentId]:t.tournamentRecord}||{},r=t.outcomes??[],n=r.reduce((o,i)=>o.includes(i.tournamentId)?o:o.concat(i.tournamentId),[]);for(let o of n){let i=e[o];if(!i)return{error:Y};let s=r.filter(a=>a.tournamentId===o);if(s.length){let a=O1({outcomes:s,tournamentRecord:i});if(a.error)return a}}return{...C}}function O1(t){let{tournamentRecords:e,tournamentRecord:r,outcomes:n,policyDefinitions:o}=t,i={};n.forEach(s=>{let{eventId:a}=s;i[a]||(i[a]=[]),i[a].push(s)});for(let s of Object.keys(i)){let{event:a}=ze({tournamentRecord:r,eventId:s});for(let c of i[s]){let{drawId:u}=c,p=a?.drawDefinitions?.find(m=>m.drawId===u);if(p&&u){let{matchUpFormat:m,matchUpId:d}=c,l=Gu({schedule:c?.schedule,tournamentRecords:e,policyDefinitions:o,tournamentRecord:r,drawDefinition:p,matchUpFormat:m,matchUpId:d,outcome:c,drawId:u,event:a});if(l.error)return l}}}return{...C}}function kx({drawDefinition:t,matchUpId:e,outcome:r,matchUp:n}){if(!n&&!t)return{error:Z};if(!r)return{error:st,info:"missing outcome"};if(!n&&!e)return{error:hr};if(!n){let i=Bt({drawDefinition:t,matchUpId:e});if(i.error)return i;n=i.matchUp}return typeof r!="object"||!r.score?.scoreStringSide1||!r.score?.scoreStringSide2?{error:G}:At({element:n,extension:{name:Bm,value:r}})}function gM(t){return kx(t)}function sI(t){let e="resetTieFormat",{drawDefinition:r,event:n,uuids:o}=t,i=rt(t,[{[ie]:!0,[ln]:!0}],e);if(i.error)return i;let s=Ds(t,[{[is]:_n}]);if(s[fn])return s;let a=t.tournamentRecord?.tournamentId,{matchUp:c,structure:u}=s?.matchUp??{};if(!c?.tieMatchUps)return _({result:{error:dr},info:"Must be a TEAM matchUp",stack:e});if(!c.tieFormat)return{...C};let p=We({structure:u,drawDefinition:r,event:n})?.tieFormat;if(!p)return _({result:{error:ve},info:"No inherited tieFormat",stack:e});let m=[],d=[],l=[],f=[];for(let g of p.collectionDefinitions){let{matchUpCount:I,collectionId:h}=g;d.push(h);let S=(c.tieMatchUps||[]).filter(T=>T.collectionId===h);if(S.length>I)S.sort((T,y)=>(T.matchUpStatus===Qt?1:0)-(y.matchUpStatus===Qt?1:0)),l.push(...S.slice(0,I)),m.push(...S.slice(3).map(Ae));else if(l.push(...S),S.length<I){let T=I-S.length,y=Du({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),Co({eventId:n?.eventId,matchUps:f,drawDefinition:r,tournamentId:a})),m.length&&Yn({matchUpIds:m,eventId:n?.eventId,drawDefinition:r,tournamentId:a}),c&&(c.tieMatchUps=l,c.tieFormatId=void 0,c.tieFormat=void 0,gt({structureId:u?.structureId,eventId:n?.eventId,context:e,drawDefinition:r,tournamentId:a,matchUp:c})),{...C,newMatchUps:f,deletedMatchUpIds:m}}function aI(t){let{tournamentRecord:e,drawDefinition:r,matchUpId:n,event:o}=t,i="resetScorecard";if(!r)return _({result:{error:Z},stack:i});if(!n)return _({result:{error:sr},stack:i});if(!Vt(n))return _({result:{error:G,matchUpId:n},stack:i});let s=Ne({drawDefinition:r}),{matchUps:a}=se({nextMatchUps:!0,inContext:!0,drawDefinition:r,matchUpsMap:s}),c=s.drawMatchUps.find(I=>I.matchUpId===n),u=a?.find(I=>I.matchUpId===n);if(!c||!a)return{error:Le};if(c.matchUpType!==Cr)return{error:dr};let p=ur({inContextDrawMatchUps:a,drawDefinition:r,matchUpId:n}),m=u?.structureId,{structure:d}=at({drawDefinition:r,structureId:m});if(Object.assign(t,{inContextDrawMatchUps:a,inContextMatchUp:u,matchUpsMap:s,targetData:p,structure:d,matchUp:c}),Ci(t))return{error:Um};if(c.tieMatchUps?.length)for(let I of c.tieMatchUps){let h=La({matchUpId:I.matchUpId,matchUpTieId:n,winningSide:void 0,removeScore:!0,tournamentRecord:e,drawDefinition:r,event:o});if(h.error)return _({result:h,stack:i})}let f=yt({tournamentRecord:e,drawDefinition:r,event:o})?.appliedPolicies,g=co({event:t.event,removeScore:!0,tournamentRecord:e,appliedPolicies:f,drawDefinition:r,matchUpsMap:s,matchUpId:n});if(g.error)return _({result:g,stack:i});if(t.tiebreakReset&&!g.tieFormatRemoved){let I=We({drawDefinition:r,structure:d,event:o})?.tieFormat;if(c.tieFormat&&I){let{matchUpCountDifference:h,descendantDifferences:S,ancestorDifferences:T,valueDifference:y}=$o({descendant:c.tieFormat,ancestor:I});if(S.collectionIds.length===1&&!T.collectionIds.length&&!T.groupsCount&&h===1&&y===1){let P=sI({tournamentRecord:e,drawDefinition:r,matchUpId:n,event:o});if(P.error)return P}}}return{...C}}function IM(t){let e=rt(t,[{[Ve]:!0,[Do]:!0},{[Gs]:{[ec]:!1,roundNumbers:!1},[bh]:"At least one must be provided",[He]:Be}]);if(e.error)return e;let r=tT(t);if(r.error)return r;let{matchUpIds:n}=r,o=ue(Cr)(t.event.eventType),{tournamentRecord:i,drawDefinition:s,event:a}=t;for(let c of n){if(o){let p=aI({tiebreakReset:!0,tournamentRecord:i,drawDefinition:s,matchUpId:c,event:a});if(p.error||t.removeAssignments&&iI({inheritance:!1,drawDefinition:s,matchUpId:c}).error)return p}let u=La({winningSide:void 0,removeScore:!0,tournamentRecord:i,drawDefinition:s,matchUpId:c,event:a});if(u.error)return u;if(t.removeAssignments){let p=nI({...t,matchUpId:c});if(p.error)return p}}return{...C}}function Gx({tournamentRecord:t,drawDefinition:e,finishingOrder:r}){if(!e)return{error:Z};let n="setOrderOfFinish";if(!Array.isArray(r))return _({info:ii("finishingOrder"),result:{error:G},stack:n});let{completedMatchUps:o,matchUpsMap:i}=js({inContext:!0,drawDefinition:e}),s=o?.map(Ae)??[],a=r.map(Ae),{matchUpTypes:c,roundNumbers:u,structureIds:p,matchUpTieIds:m}=(o??[]).filter(({matchUpId:T})=>a.includes(T)).reduce((T,y)=>{let{matchUpTieId:P,matchUpType:U,roundNumber:E,structureId:A}=y;return T.matchUpTypes.includes(U)||T.matchUpTypes.push(U),T.roundNumbers.includes(E)||T.roundNumbers.push(E),T.structureIds.includes(A)||T.structureIds.push(A),T.matchUpTieIds.includes(P)||T.matchUpTieIds.push(P),T},{matchUpTypes:[],roundNumbers:[],structureIds:[],matchUpTieIds:[]});if(c.length>1||m.length>1||u.length>1||p.length>1)return _({info:"matchUpType, structureId and roundNumber must be equivalent",result:{error:G},stack:n});let d,l,f={},g=[],I=[];if(!r.every(({orderOfFinish:T,matchUpId:y})=>(g.push(y),T&&I.push(T),f[y]=T,d=s.includes(y),l=T===void 0||It(T)&&Math.floor(T)>0,d&&l)))return _({result:{error:d?G:pa},info:!d&&"matchUps must be completed"||!l&&"orderOfFinish must be integer > 0 or undefined"||void 0,stack:n});let S=o?.filter(T=>T.structureId===p[0]&&T.roundNumber===u[0]&&T.matchUpType===c[0]&&T.matchUpTieId===m[0]&&!g.includes(T.matchUpId));for(let T of S??[]){let{orderOfFinish:y}=T||{};if(y){if(!It(y))return _({context:{orderOfFinish:y,matchUp:T},result:{error:G},stack:n});I.push(y)}}if(PI(I).length!==I.length||Math.max(...I)>I.length)return _({info:"Values not unique or greater than expected number of values",result:{error:G},stack:n});if(p.length){let T=hu({matchUpFilters:{matchUpIds:a},structureId:p[0],drawDefinition:e,matchUpsMap:i});if(T.error)return _({result:T,stack:n});T.completedMatchUps?.forEach(y=>{y.orderOfFinish=f[y.matchUpId],gt({tournamentId:t.tournamentId,context:"setOrderOfFinish",drawDefinition:e,matchUp:y})})}return{...C}}function hM(t){return Gx(t)}function SM(t){let{tournamentRecord:e,drawDefinition:r,matchUpId:n,lineUps:o,event:i}=t,s="applyLineUps",a=rt(t,[{[ie]:!0,[Ve]:!0,[ln]:!0},{lineUps:!0,[He]:Be}],s);if(a.error)return a;let c=e.participants||[],u=Bt({tournamentParticipants:c,inContext:!0,drawDefinition:r,matchUpId:n});if(u.error)return u;if(!u.matchUp)return{error:Le};let{matchUp:p,structure:m}=u,{drawPositions:d,matchUpType:l}=p;if(l!==jt)return{error:dr};if(!d?.length)return{error:ja};let f=We({matchUp:p,drawDefinition:r,structure:m,event:i})?.tieFormat,g={};for(let h of o){if(!Array.isArray(h))return{error:G,lineUp:h};let S={},T=[];for(let A of h){if(typeof A!="object")return{error:G,lineUpAssignment:A};let{participantId:N,collectionAssignments:D=[]}=A;if(!Array.isArray(D))return{error:G,collectionAssignments:D};let M=c.find(b=>b.participantId===N);if(!M)return{error:te};if(M.participantType!==Tt)return{error:An};let R=p.sides?.find(b=>b.participant?.individualParticipantIds?.includes(N))?.sideNumber;R&&T.push(R);for(let b of D){if(typeof b!="object")return{error:G,collectionAssignment:b};let{collectionId:v,collectionPosition:O}=b,x=f?.collectionDefinitions?.find(w=>w.collectionId===v);if(!x)return{error:G,collectionId:v};let F=`${v}-${O}`;S[F]||(S[F]=[]);let L=S[F].length;if(ue(xt)(x.matchUpType)&&L||x.matchUpType===_t&&L>1)return{info:"Excessive collectionPosition assignments",error:G};S[F].push(N)}}let y=Object.values(S);for(let A of y)if(A.length===2){let{participant:N}=In({tournamentParticipants:c,participantIds:A});if(!N){let M=bn({participant:{participantType:ft,participantRole:xe,individualParticipantIds:A},pairOverride:!0,tournamentRecord:e});if(M.error)return M}}let P=Sr(T),U=(P[1]||0)>(P[2]||0)&&1||(P[2]||0)>(P[1]||0)&&2||void 0,E=Object.keys(g).map(A=>parseInt(A));U&&!E.includes(U)&&(g[U]=h)}if(!Object.keys(g).length)return{error:rf};if(u=Bt({drawDefinition:r,matchUpId:n}),u.error)return u;if(!u.matchUp)return{error:Le};let{matchUp:I}=u;I.sides||(I.sides=[]);for(let h of[1,2]){let S=I.sides.find(y=>y.sideNumber===h),T=g[h];if(T)S?S.lineUp=T:I.sides.push({lineUp:T,sideNumber:h});else continue}return gt({tournamentId:e?.tournamentId,context:s,drawDefinition:r,matchUp:I}),{...C}}var fI={};Xt(fI,{anonymizeTournamentRecord:()=>MM,generate:()=>NM,generateEventWithDraw:()=>dm,generateOutcome:()=>mI,generateOutcomeFromScoreString:()=>cI,generateParticipants:()=>sa,generateTournamentRecord:()=>DM,modifyTournamentRecord:()=>RM,mutate:()=>CM});var NM={};Xt(NM,{generateEventWithDraw:()=>dm,generateOutcome:()=>mI,generateOutcomeFromScoreString:()=>cI,generateParticipants:()=>sa,generateTournamentRecord:()=>DM});function cI(t){let{matchUpFormat:e,matchUpStatus:r,winningSide:n,scoreString:o}=t;if(!o)return{outcome:{...Ru,winningSide:n,matchUpStatus:r}};if(n&&![1,2,void 0].includes(n))return{error:G,winningSide:n};let i=o&&jd({scoreString:o}),s={},a=jo({sets:i,matchUpFormat:e}),c=jo({sets:i,reversed:!0,matchUpFormat:e});return n===2?(s.scoreStringSide1=c,s.scoreStringSide2=a):(s.scoreStringSide1=a,s.scoreStringSide2=c),s.sets=jd({scoreString:s.scoreStringSide1}),ot({outcome:{matchUpStatus:r,winningSide:n,score:s}})}function hl({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 Fa({individualParticipantProfiles:t,participantId:e}){t[e]||(t[e]={typeChangeTimeAfterRecovery:void 0,timeAfterRecovery:void 0,priorMatchUpType:void 0,potentialRecovery:{},potentialCounted:{},potentialBookings:{},bookings:[],counters:{}})}function Vx({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 Oc({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,typeChangeRecoveryMinutes:r,averageMatchUpMinutes:n=0,matchUpNotBeforeTimes:o,matchUpDependencies:i,recoveryMinutes:s=0,scheduleTime:a,matchUp:c}){let u=Kt(c?.schedule?.endTime),p=u?Yr(u,pt(s)):Yr(a,pt(n)+pt(s)),m=r&&(u?Yr(Kt(u),r):Yr(a,pt(n)+pt(r))),d=i?.[c.matchUpId]?.participantIds||[],l=(c.roundPosition&&t[c.matchUpId]||[]).flat();d.forEach(f=>{Fa({individualParticipantProfiles:e,participantId:f});let I=e[f].priorMatchUpType!==c.matchUpType&&m||p;l.includes(f)?Vx({individualParticipantProfiles:e,drawId:c.drawId,recoveryValue:I,participantId:f,scheduleTime:a}):(e[f].timeAfterRecovery=I,e[f].bookings.push({scheduleTime:a,timeAfterRecovery:I}))}),ea({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:o,timeAfterRecovery:p,matchUp:c})}function jy({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||qt(f)<qt(d.scheduleTime)?g:d},{});m.scheduleTime&&qt(u)>qt(m.scheduleTime)&&(i=m)}return{scheduledDependent:i}}function Bx(t){let{sides:e,matchUpType:r}=t||{};return(e||[]).map(n=>r===_t&&(n?.participant?.individualParticipants||[])||n?.participant&&[n.participant]||[]).flat()}var _c="DO_NOT_SCHEDULE",Hx={DO_NOT_SCHEDULE:_c};function Sl({averageMatchUpMinutes:t=90,requestConflicts:e={},potentials:r=!0,personRequests:n,scheduleTime:o,scheduleDate:i,matchUp:s}){let a=Bx(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===_c&&Wn(i,l.date)),u=[],p=s?.matchUpId,m=ke(Kt(o),Et(i)),d=Kt(hf(m,t).toISOString());for(let l of c){let{requestId:f,startTime:g,endTime:I}=l;(o>g&&o<I||d>g&&d<I)&&(u.push({matchUpId:p,request:l,scheduleTime:o}),e[f]?(e[f].scheduleTimes.includes(o)||e[f].scheduleTimes.push(o),e[f].matchUpIds.includes(p)||e[f].matchUpIds.push(p)):e[f]={request:l,scheduleTimes:[o],matchUpIds:[p]})}return{conflicts:u}}function uI({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,matchUp:r,value:n}){let{matchUpType:o}=r,{individualParticipantIds:i}=uu(r),a=(t[r.matchUpId]||[]).filter(u=>!Fe(u,i)).flat();[...i,...a].forEach(u=>{if(Fa({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[ao]?p[ao]+=n:n>0&&(p[ao]=n),a.includes(u)&&(e[u].potentialCounted[r.drawId]=!0)}})}function Wx({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,dateScheduledMatchUpIds:r,greatestAverageMinutes:n,dateScheduledMatchUps:o,matchUpNotBeforeTimes:i,matchUpScheduleTimes:s,matchUpDependencies:a,clearScheduleDates:c,scheduleDate:u,minutesMap:p,matchUps:m}){let d=[];r||(o=m?.filter(g=>{let I=g.schedule||{},h=g.matchUpStatus===Nt;return h&&d.push({tournamentId:g.tournamentId,matchUpId:g.matchUpId}),!h&&_a({schedule:I})&&(!u||g.schedule.scheduledDate===u)}),r=o.map(Ae));let l=Array.isArray(c)?c.includes(u):c,f=l?[]:m.filter(({matchUpId:g})=>r.includes(g));for(let g of f){uI({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,value:1,matchUp:g});let I=g.schedule?.scheduledTime;if(I){s[g.matchUpId]=I;let h=p?.[g.matchUpId]?.recoveryMinutes;Oc({individualParticipantProfiles:e,matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:i,matchUpDependencies:a,averageMatchUpMinutes:n,recoveryMinutes:h,scheduleTime:I,matchUp:g})}}return{dateScheduledMatchUpIds:r,byeScheduledMatchUpDetails:d,dateScheduledMatchUps:o,clearDate:l}}function sm({defaultRecoveryMinutes:t=0,averageMatchUpMinutes:e=90,dateScheduledMatchUps:r,tournamentRecords:n,venueIds:o=[],periodLength:i,scheduleDate:s,matchUps:a}){if(typeof n!="object")return{error:wt};if(!Vr(a)&&!Array.isArray(r))return{error:Xn};i=i??ku({recoveryMinutes:t,averageMatchUpMinutes:e});let c=Object.assign({},...Object.values(n).map(d=>(d.events??[]).map(l=>{let{scheduleTiming:f}=ya({tournamentRecord:d,event:l});return{[l.eventId]:{event:l,scheduleTiming:f}}})).flat()),u={averageTimes:[{minutes:{default:e}}],recoveryTimes:[{minutes:{default:t}}]};r||(r=a?.filter(d=>{let l=d.schedule;return _a({schedule:l})&&(!s||d.schedule.scheduledDate===s)}));let p=r?.filter(d=>(!o.length||o.includes(d.schedule.venueId))&&d.matchUpStatus!==Nt);return{bookings:p?.map(({eventId:d,schedule:l,matchUpFormat:f})=>{let{event:g,scheduleTiming:I}=c[d],h=g?.eventType,S={...I,defaultTiming:u,matchUpFormat:f},{averageMinutes:T,recoveryMinutes:y}=Pp({timingDetails:S,eventType:h}),{courtId:P,venueId:U}=l,E=Kt(l.scheduledTime),A=Yr(E,T);return{recoveryMinutes:y,averageMinutes:T,periodLength:i,startTime:E,courtId:P,endTime:A,venueId:U}}).filter(Boolean),relevantMatchUps:p,dateScheduledMatchUps:r}}function jx({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:wt};a=a??ku({recoveryMinutes:r,averageMatchUpMinutes:n});let{courts:l,venues:f}=Ao({dates:[c],ignoreDisabled:!0,tournamentRecords:i}),g=l?.filter(U=>!p||p.includes(U.venueId))??[];u=u??bc({courts:g,scheduleDate:c,startTime:!0}),d=d??bc({courts:g,scheduleDate:c,endTime:!0});let{bookings:I,dateScheduledMatchUps:h}=sm({defaultRecoveryMinutes:r,averageMatchUpMinutes:n,tournamentRecords:i,scheduleDate:c,periodLength:a,venueIds:p,matchUps:m}),S={calculateStartTimeFromCourts:t,remainingScheduleTimes:e,averageMatchUpMinutes:n,clearScheduleDates:o,date:c,periodLength:a,startTime:u,bookings:I,endTime:d,courts:g},{scheduleTimes:T}=dl(S),y=p?.length===1&&p[0]||f?.length===1&&f[0].venueId||void 0;return{dateScheduledMatchUpIds:h?.map(Br("matchUpId")),dateScheduledMatchUps:h,scheduleTimes:T,venueId:y}}function Yx({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 Yy({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,scheduleCompletedMatchUps:r,containedStructureIds:n,matchUpNotBeforeTimes:o,matchUpScheduleTimes:i,matchUpDependencies:s,clearScheduleDates:a,tournamentRecords:c,periodLength:u,scheduleDate:p,useGarman:m,matchUps:d,courts:l,venues:f}){let g={},I=[],h=[],S=[];for(let T of f){let{rounds:y=[],venueId:P}=T,{scheduledRoundsDetails:U,greatestAverageMinutes:E,orderedMatchUpIds:A,minutesMap:N}=Lu({scheduleCompletedMatchUps:r,containedStructureIds:n,tournamentRecords:c,periodLength:u,matchUps:d,rounds:y});S.push(...A??[]);let{groupedRounds:D}=Yx({scheduledRoundsDetails:U,greatestAverageMinutes:E,garmanSinglePass:!0}),M,R=[];m&&({scheduleTimes:R,dateScheduledMatchUpIds:M}=jx({averageMatchUpMinutes:D[0]?.averageMinutes,scheduleDate:Et(p),venueIds:[T.venueId],clearScheduleDates:a,tournamentRecords:c,periodLength:u,matchUps:d}));let b=Wx({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,dateScheduledMatchUpIds:M,greatestAverageMinutes:E,matchUpNotBeforeTimes:o,matchUpScheduleTimes:i,matchUpDependencies:s,clearScheduleDates:a,scheduleDate:p,minutesMap:N,matchUps:d});({dateScheduledMatchUpIds:M}=b);let v=b,{byeScheduledMatchUpDetails:O,clearDate:x}=b;O?.length&&h.push(...O);let{matchUpsToSchedule:F,matchUpMap:L}=el({matchUpPotentialParticipantIds:t,scheduleCompletedMatchUps:r,dateScheduledMatchUpIds:M,matchUpNotBeforeTimes:o,matchUpScheduleTimes:i,orderedMatchUpIds:A,clearDate:x,matchUps:d}),w=l.filter(V=>V.venueId===P);g[P]={previousRemainingScheduleTimes:[],courtsCount:w.length,greatestAverageMinutes:E,scheduledRoundsDetails:U,dateScheduledMatchUps:v,matchUpsToSchedule:F,scheduleTimes:R,groupedRounds:D,venueCourts:w,minutesMap:N,matchUpMap:L},a||I.push(...M)}return{allDateScheduledByeMatchUpDetails:h,allDateScheduledMatchUpIds:I,venueScheduledRoundDetails:g,allDateMatchUpIds:S}}function qx(t,e){let r=qt(t.scheduleTime),n=qt(t.timeAfterRecovery),o=qt(e.scheduleTime),i=qt(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 ot({hasOverlap:s||a||u||c||p,startAisContained:a,endAisContained:u,startBisContained:c,endBisContained:p},!0)}function Tl({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=>{Fa({individualParticipantProfiles:t,participantId:f});let g=t[f];if(!g.timeAfterRecovery)return!0;let I=Kt(o?.schedule?.endTime),h=I?Yr(I,pt(c)):Yr(n,pt(a)+pt(c));return!!![...Object.keys(g.potentialBookings).filter(P=>P!==o.drawId).map(P=>g.potentialBookings[P]).flat(),...g.bookings].find(P=>qx({scheduleTime:n,timeAfterRecovery:h},P).hasOverlap)}),p=e[o.matchUpId],d=(p?ma(ke(p),ke(n),!1):0)>=0;return{enoughTime:u&&d}}function qy({autoSchedulingAudit:t,tournamentRecords:e}){mt({topic:Ti,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:Uy,itemValue:o};for(let s of Object.values(e)){let a=s.tournamentId;rp(Ti)?mt({payload:{type:Uy,tournamentId:a,detail:o},topic:Ti}):Pc({tournamentRecord:s,timeItem:i})}}function yl({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,matchUpDailyLimits:r={},matchUp:n}){let{enteredIndividualParticipantIds:o}=uu(n),{matchUpId:i,matchUpType:s}=n,a=(n.roundPosition&&t[i]||[]).flat(),c=ut(o.concat(...a));return c.forEach(p=>{Fa({individualParticipantProfiles:e,participantId:p})}),{participantIdsAtLimit:c.filter(p=>{let m=e[p];if(m)return[s,ao].find(d=>{let l=m.counters?.[d]||0,f=r[d]||0;return l&&f&&l>=f})}),relevantParticipantIds:c}}function Vu({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:Y};if(!c&&(!u||!Array.isArray(u)))return{error:rs};if(!c&&(!p||typeof p!="object"))return{error:UE};let m,d=[],l=0;if(n&&!o){let I=sn({tournamentRecords:s,tournamentRecord:a});o=I.matchUpDependencies,m=I.matchUps}m||(m=Te({tournamentRecord:a})?.matchUps??[]);let f=m.reduce((I,h)=>{let{matchUpId:S,drawId:T,matchUpStatus:y}=h;return(e||y!==Nt)&&(t||!ce.includes(y))&&(I[T]?I[T].push(S):I[T]=[S]),I},{}),g=c?.map(I=>I.matchUpId);for(let I of Object.keys(f)){let{drawDefinition:h}=wo({tournamentRecord:a,drawId:I});if(!h)continue;let S=f[I].filter(y=>u?.includes(y)??g?.includes(y)),T=or({inContext:!1,drawDefinition:h}).matchUps;for(let y of S){let P=c?.find(E=>E.matchUpId===y)?.schedule||p,U=im({schedule:P,matchUpDependencies:o,errorOnAnachronism:r,removePriorValues:i,inContextMatchUps:m,tournamentRecords:s,tournamentRecord:a,checkChronology:n,drawDefinition:h,drawMatchUps:T,matchUpId:y});if(U?.warnings?.length&&d.push(...U.warnings),U?.success&&(l+=1),U.error)return U}}return d.length?{...C,scheduled:l,warnings:d}:{...C,scheduled:l}}function xc(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 Vu(t);let p=rt(t,[{[Re]:!0},{[Gs]:{matchUpContextIds:!1,matchUpDetails:!1},[Fr]:G,[He]:Be}]);if(p.error)return p;if((!c||o)&&!u)return{error:st,info:"schedule is required"};let m=[],d=0,{matchUpDependencies:l}=sn({tournamentRecords:s});for(let f of Object.values(s)){let{tournamentId:g}=f,I=o?.filter(S=>S.tournamentId===g).map(Ae),h=c?.filter(S=>S?.tournamentId===g);if(I?.length||h?.length){let S=Vu({matchUpDetails:h,scheduleCompletedMatchUps:e,scheduleByeMatchUps:r,matchUpDependencies:l,errorOnAnachronism:n,removePriorValues:i,tournamentRecords:s,tournamentRecord:f,checkChronology:a,matchUpIds:I,schedule:u});if(S.warnings?.length&&m.push(...S.warnings),S.scheduled&&(d+=S.scheduled),S.error)return S}}return m.length?{...C,scheduled:d,warnings:m}:{...C,scheduled:d}}function $x({schedulingProfileModifications:t,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:r,schedulingProfileIssues:n,dateSchedulingProfiles:o,containedStructureIds:i,matchUpDependencies:s,matchUpDailyLimits:a,clearScheduleDates:c,tournamentRecords:u,schedulingProfile:p,personRequests:m,periodLength:d,matchUps:l,courts:f,dryRun:g}){let I={},h={},S={},T={},y={},P={},U={},E={},A={},N={};for(let R of o){let b=Et(R?.scheduleDate),v=R?.venues||[],O={},x={},F=(B,$)=>{B.forEach(z=>{let j=x[z].counters;j[$]?j[$]+=1:j[$]=1,j[ao]?j[ao]+=1:j[ao]=1})};S[b]={},T[b]={},I[b]={},h[b]={},U[b]=[],E[b]=[],A[b]=[],N[b]=[];let L={};l.forEach(B=>{B.schedule?.scheduledDate&&Wn(b,Et(B.schedule.scheduledDate))&&ea({matchUpPotentialParticipantIds:O,matchUpNotBeforeTimes:L,matchUp:B})});let{allDateScheduledByeMatchUpDetails:w,venueScheduledRoundDetails:V,allDateMatchUpIds:k}=Yy({matchUpPotentialParticipantIds:O,individualParticipantProfiles:x,scheduleCompletedMatchUps:r,containedStructureIds:i,matchUpNotBeforeTimes:L,matchUpScheduleTimes:P,matchUpDependencies:s,clearScheduleDates:c,tournamentRecords:u,useGarman:!0,periodLength:d,scheduleDate:b,matchUps:l,courts:f,venues:v}),W=10,H=0,K,q=10;for(;!K;){for(let{venueId:B}of v){let $=0,z=V[B];for(;z.courtsCount&&z.scheduleTimes?.length&&z.matchUpsToSchedule?.length&&$<=z.courtsCount;){let{scheduleTime:j,attempts:tt=0}=z.scheduleTimes.shift(),Q=z.matchUpsToSchedule.find(X=>{let{matchUpId:lt,matchUpType:it}=X,{participantIdsAtLimit:Rt,relevantParticipantIds:Ft}=yl({matchUpPotentialParticipantIds:O,individualParticipantProfiles:x,matchUpDailyLimits:a,matchUp:X});if(Rt.length)return E[b].includes(lt)||E[b].push(lt),!1;let{scheduledDependent:Ue}=jy({matchUpScheduleTimes:P,matchUpDependencies:s,scheduleTime:j,matchUpId:lt,details:z});if(Ue)return!1;let{dependenciesScheduled:fe,remainingDependencies:Me}=hl({matchUpScheduleTimes:P,matchUpDependencies:s,allDateMatchUpIds:k,matchUp:X});if(!fe)return T[b][lt]||(T[b][lt]=[]),T[b][lt].push({scheduleTime:j,remainingDependencies:Me}),!1;let{enoughTime:vr}=Tl({individualParticipantProfiles:x,matchUpNotBeforeTimes:L,matchUpDependencies:s,scheduleTime:j,details:z,matchUp:X});if(!vr)return S[b][lt]||(S[b][lt]=[]),S[b][lt].push({scheduleTime:j}),!1;let Zr=z.greatestAverageMinutes,{conflicts:lr}=Sl({potentials:e,averageMatchUpMinutes:Zr,requestConflicts:N,personRequests:m,scheduleTime:j,scheduleDate:b,matchUp:X});if(lr?.length)return y[b]||(y[b]=[]),y[b].push(...lr),!1;F(Ft,it);let Xe=z.minutesMap?.[lt]?.recoveryMinutes;return Oc({matchUpPotentialParticipantIds:O,individualParticipantProfiles:x,matchUpNotBeforeTimes:L,averageMatchUpMinutes:Zr,matchUpDependencies:s,recoveryMinutes:Xe,scheduleTime:j,matchUp:X}),P[lt]=j,!0});z.matchUpsToSchedule=z.matchUpsToSchedule.filter(({matchUpId:X})=>X!==Q?.matchUpId),Q?$+=1:(h[b][B]||(h[b][B]=[]),h[b][B].push({scheduleTime:j,attempts:tt+1}))}z.matchUpsToSchedule?.length&&(h[b][B]=h[b][B]?.filter(j=>{let tt=j.attempts<W;return tt&&z.scheduleTimes.push(j),!tt})),(!z.scheduleTimes?.length||!z.matchUpsToSchedule?.length)&&(z.complete=!0)}H+=1,K=v.every(({venueId:B})=>V[B].complete)||H===q}for(let{venueId:B}of v){let $=V[B].matchUpMap;Object.keys($).forEach(z=>{let j=u[z];j&&Object.keys($[z]).forEach(tt=>{let{drawDefinition:Q}=wo({tournamentRecord:j,drawId:tt});Q&&$[z][tt].forEach(({matchUpId:lt})=>{let it=P[lt];if(it){let Rt=it.split(":").map(Jn).join(":"),Ft=`${Et(b)}T${Rt}`;g?U[b].push(lt):(zo({drawDefinition:Q,scheduledTime:Ft,matchUpId:lt}).success&&U[b].push(lt),B&&ia({tournamentRecord:j,drawDefinition:Q,matchUpId:lt,venueId:B}))}})})}),A[b]=V[B].matchUpsToSchedule.map(Ae),I[b][B]=V[B].scheduleTimes.sort((z,j)=>qt(z.scheduleTime)-qt(j.scheduleTime))}!g&&w?.length&&xc({matchUpDetails:w,scheduleByeMatchUps:!0,removePriorValues:!0,tournamentRecords:u,schedule:{scheduledDate:"",scheduledTime:"",courtOrder:"",courtId:"",venueId:""}});for(let B of R.venues)for(let $ of B.rounds){let j=($.matchUps?.map(({matchUpId:Q})=>Q)||[]).filter(Q=>U[b].includes(Q));$.canScheduledMatchUpIds=j;let tt=Math.round(j.length/$.matchUpsCount*1e4)/100;(tt===1/0||isNaN(tt))&&(tt=0),$.possibleToSchedulePct=tt,$.matchUpsCount===j.length&&($.possibleToSchedule=!0)}}let D=o.map(({scheduleDate:R})=>R),M={timeStamp:Date.now(),overLimitMatchUpIds:E,scheduledMatchUpIds:U,schedulingProfile:p,noTimeMatchUpIds:A,requestConflicts:N,scheduledDates:D};return qy({tournamentRecords:u,autoSchedulingAudit:M}),{...C,schedulingProfileModifications:t,schedulingProfileIssues:n,scheduleTimesRemaining:I,dateSchedulingProfiles:o,skippedScheduleTimes:h,recoveryTimeDeferredMatchUpIds:S,dependencyDeferredMatchUpIds:T,matchUpScheduleTimes:P,overLimitMatchUpIds:E,scheduledMatchUpIds:U,noTimeMatchUpIds:A,requestConflicts:N,scheduledDates:D}}function AM({averageMinutes:t,startTime:e,endTime:r,court:n,date:o}){if(!Array.isArray(n.dateAvailability))return{error:st,stack:"getEarliestCourtTime"};let i=bc({scheduleDate:o,courts:[n],startTime:!0}),s=bc({scheduleDate:o,courts:[n],endTime:!0});e=e||i,r=r||s;let a=wa({court:n,date:o}),{timeSlots:c}=Ns({courtDate:a}),u=ke(e),p=ke(r);return{earliestCourtTime:c?.reduce((d,l)=>{let f=ke(l.startTime),g=ke(l.endTime);if(f>p||g<u)return d;let I=u>f?u:f;if(ma(I,g)>=t){let T=Kt(I.toISOString());(!d||T<d)&&(d=T)}return d},void 0),courtStartTime:i,courtEndTime:s}}function Kx({schedulingProfileModifications:t,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:r,schedulingProfileIssues:n,dateSchedulingProfiles:o,containedStructureIds:i,matchUpDependencies:s,matchUpDailyLimits:a,clearScheduleDates:c,tournamentRecords:u,periodLength:p=30,schedulingProfile:m,personRequests:d,matchUps:l=[],courts:f,dryRun:g}){let I={},h={},S={},T={},y={},P={},U={},E={},A={};for(let M of o??[]){let R=Et(M?.scheduleDate),b=M?.venues||[],v={},O={},x=(Q,X)=>{Q.forEach(lt=>{let it=O[lt].counters;it[X]?it[X]+=1:it[X]=1,it[ao]?it[ao]+=1:it[ao]=1})};I[R]={},h[R]={},P[R]=[],U[R]=[],E[R]=[],A[R]=[];let F={};l?.forEach(Q=>{Q.schedule?.scheduledDate&&Wn(R,Et(Q.schedule.scheduledDate))&&ea({matchUpPotentialParticipantIds:v,matchUpNotBeforeTimes:F,matchUp:Q})});let{allDateScheduledByeMatchUpDetails:L,allDateScheduledMatchUpIds:w,venueScheduledRoundDetails:V,allDateMatchUpIds:k}=Yy({matchUpPotentialParticipantIds:v,individualParticipantProfiles:O,scheduleCompletedMatchUps:r,containedStructureIds:i,matchUpNotBeforeTimes:F,matchUpScheduleTimes:y,matchUpDependencies:s,clearScheduleDates:c,tournamentRecords:u,periodLength:p,scheduleDate:R,matchUps:l,courts:f,venues:b}),W=l?.filter(({matchUpId:Q})=>w.includes(Q)),{bookings:H}=sm({dateScheduledMatchUps:W,tournamentRecords:u,scheduleDate:R,periodLength:p}),{virtualCourts:K}=tm({scheduleDate:R,periodLength:p,bookings:H,courts:f}),q=K?.reduce((Q,X)=>{let{earliestCourtTime:lt,courtEndTime:it}=AM({date:R,averageMinutes:0,court:X});return(!Q.startTime||ke(lt)<ke(Q.startTime))&&(Q.startTime=lt),(!Q.endTime||ke(it)>ke(Q.endTime))&&(Q.endTime=it),Q},{}),B=q.startTime,$=({courtId:Q,booking:X})=>K?.find(lt=>lt.courtId===Q)?.dateAvailability[0].bookings.push(X),z=10,j=0,tt;for(;!tt;){for(let{venueId:Q}of b){let X=V[Q],lt=X.matchUpsToSchedule.length,it=[],Rt=[],Ft,Ue=0;for(;!Ft;){for(let fe of X.matchUpsToSchedule){if(Rt.length===X.courtsCount||it.length===X.courtsCount){Ft=!0;break}let{matchUpId:Me,matchUpType:vr}=fe,{participantIdsAtLimit:Zr,relevantParticipantIds:lr}=yl({matchUpPotentialParticipantIds:v,individualParticipantProfiles:O,matchUpDailyLimits:a,matchUp:fe});if(Zr.length){U[R].includes(Me)||U[R].push(Me);continue}let{dependenciesScheduled:Xe,remainingDependencies:ee}=hl({matchUpScheduleTimes:y,matchUpDependencies:s,allDateMatchUpIds:k,matchUp:fe});if(!Xe){h[R][Me]||(h[R][Me]=[]),h[R][Me].push({remainingDependencies:ee});continue}let Pt=[],ae=K?.reduce((re,pr)=>{if(Rt.includes(pr.courtId))return re;let{earliestCourtTime:Jt}=AM({averageMinutes:X.greatestAverageMinutes,startTime:B,date:R,court:pr});if(re.scheduleTime&&qt(Jt)>=qt(re.scheduleTime))return re;let{scheduledDependent:Wt}=jy({matchUpScheduleTimes:y,matchUpDependencies:s,scheduleTime:Jt,matchUpId:Me,details:X});if(Wt)return re;let{enoughTime:mr}=Tl({individualParticipantProfiles:O,matchUpNotBeforeTimes:F,matchUpDependencies:s,scheduleTime:Jt,details:X,matchUp:fe});if(!mr)return I[R][Me]||(I[R][Me]=[]),I[R][Me].includes(Jt)||I[R][Me].push(Jt),re;let zt=X.minutesMap?.[Me]?.averageMinutes||X.greatestAverageMinutes,{conflicts:pe}=Sl({potentials:e,averageMatchUpMinutes:zt,requestConflicts:A,personRequests:d,scheduleTime:Jt,scheduleDate:R,matchUp:fe});if(pe?.length)return Pt.push(...pe),!1;x(lr,vr);let Pe=X.minutesMap?.[Me]?.recoveryMinutes;return Oc({matchUpPotentialParticipantIds:v,individualParticipantProfiles:O,matchUpNotBeforeTimes:F,averageMatchUpMinutes:zt,matchUpDependencies:s,recoveryMinutes:Pe,scheduleTime:Jt,matchUp:fe}),(!re.scheduleTime||qt(Jt)<qt(re.scheduleTime))&&(re.averageMatchUpMinutes=zt,re.recoveryMinutes=Pe,re.scheduleTime=Jt,re.courtName=pr.courtName,re.courtId=pr.courtId),re},{});if(ae.scheduleTime){let{averageMatchUpMinutes:re,recoveryMinutes:pr,scheduleTime:Jt,courtId:Wt}=ae;y[Me]=Jt,T[Me]=Wt,it.push(Me),Rt.push(Wt);let mr=Jt,zt=Yr(mr,re);$({courtId:Wt,booking:{averageMatchUpMinutes:re,recoveryMinutes:pr,periodLength:p,matchUpId:Me,startTime:mr,courtId:Wt,endTime:zt,venueId:Q}}),X.matchUpsToSchedule=X.matchUpsToSchedule.filter(Pe=>Pe.matchUpId!==Me)}else Pt?.length&&(S[R]||(S[R]=[]),S[R].push(...Pt))}(Rt.length===X.courtsCount||it.length===X.courtsCount||!X.matchUpsToSchedule.length)&&(Ft=!0),X.matchUpsToSchedule.length&&it<X.courtsCount&&(ke(B)<ke(q.endTime)?B=Yr(B,p):(Ft=!0,X.complete=!0)),Ue+=1,!Ft&&Ue>=lt&&(Ft=!0)}X.matchUpsToSchedule?.length||(X.complete=!0)}j+=1,tt=b.every(({venueId:Q})=>V[Q].complete)||j===z}for(let{venueId:Q}of b){let X=V[Q].matchUpMap;Object.keys(X).forEach(lt=>{let it=u[lt];it&&Object.keys(X[lt]).forEach(Rt=>{let{drawDefinition:Ft}=wo({tournamentRecord:it,drawId:Rt});Ft&&X[lt][Rt].forEach(({matchUpId:fe})=>{let Me=y[fe],vr=T[fe];if(Me){let Zr=Me.split(":").map(Jn).join(":"),lr=`${Et(R)}T${Zr}`;g||(zo({drawDefinition:Ft,scheduledTime:lr,matchUpId:fe}),Xi({courtDayDate:R,tournamentRecords:u,tournamentRecord:it,drawDefinition:Ft,matchUpId:fe,courtId:vr})),P[R].push(fe)}})})}),E[R]=V[Q].matchUpsToSchedule.map(Ae)}!g&&L?.length&&xc({matchUpDetails:L,scheduleByeMatchUps:!0,removePriorValues:!0,tournamentRecords:u,schedule:{scheduledDate:"",scheduledTime:"",courtOrder:"",courtId:"",venueId:""}});for(let Q of M.venues)for(let X of Q.rounds){let it=(X.matchUps??[]).map(({matchUpId:Ft})=>Ft)?.filter(Ft=>P[R].includes(Ft));X.canScheduledMatchUpIds=it;let Rt=Math.round((it?.length||0)/X.matchUpsCount*1e4)/100;(Rt===1/0||isNaN(Rt))&&(Rt=void 0),X.possibleToSchedulePct=Rt,X.matchUpsCount===it?.length&&(X.possibleToSchedule=!0)}}let N=(o??[]).map(({scheduleDate:M})=>M),D={timeStamp:Date.now(),overLimitMatchUpIds:U,scheduledMatchUpIds:P,schedulingProfile:m,noTimeMatchUpIds:E,requestConflicts:A,scheduledDates:N};return qy({tournamentRecords:u,autoSchedulingAudit:D}),{...C,schedulingProfileModifications:t,schedulingProfileIssues:n,dateSchedulingProfiles:o,recoveryTimeDeferredMatchUpIds:I,dependencyDeferredMatchUpIds:h,matchUpScheduleTimes:y,overLimitMatchUpIds:U,scheduledMatchUpIds:P,noTimeMatchUpIds:E,requestConflicts:A,scheduledDates:N}}function am(t){let{scheduleAttributes:e=["scheduledDate","scheduledTime","courtOrder"],ignoreMatchUpStatuses:r=ce,scheduledDates:n,venueIds:o}=t,i=Dr(t),s=ht(i)?Object.values(i).map(({tournamentId:c})=>c).filter(Boolean):[];if(!s?.length)return{error:wt};let a=0;for(let c of s){let u=i[c],p=_1({ignoreMatchUpStatuses:r,scheduleAttributes:e,tournamentRecord:u,scheduledDates:n,venueIds:o});if(p.error)return p;a+=p.clearedScheduleCount??0}return{...C,clearedScheduleCount:a}}function _1({scheduleAttributes:t=["scheduledDate","scheduledTime","courtOrder"],ignoreMatchUpStatuses:e=ce,tournamentRecord:r,scheduledDates:n,venueIds:o=[]}){if(typeof r!="object")return{error:Y};if(!Array.isArray(e)||!Array.isArray(o))return{error:G};o.length&&t.push("venueId");let i=Te({matchUpFilters:{scheduledDates:n},tournamentRecord:r}).matchUps??[],s={};i.forEach(({matchUpStatus:u,schedule:p,drawId:m,matchUpId:d})=>{(!u||!e.includes(u))&&_a({schedule:p,scheduleAttributes:t})&&(!o?.length||o.includes(p.venueId))&&(s[m]||(s[m]=[]),s[m].push(d))});let a=r.tournamentId,c=0;for(let u in s){let{event:p,drawDefinition:m}=ze({tournamentRecord:r,drawId:u}),d=or({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&&![so,Bo,Hi,yp,Wi,ji].includes(g?.itemType);return I||(f=!0),I}),f&&(gt({context:"clear schedules",eventId:p?.eventId,drawDefinition:m,tournamentId:a,matchUp:l}),c+=1)}}return{...C,clearedScheduleCount:c}}function cm(t){let{checkPotentialRequestConflicts:e=!0,scheduleCompletedMatchUps:r,clearScheduleDates:n,scheduleDates:o=[],tournamentRecords:i,periodLength:s,useGarman:a,dryRun:c,pro:u}=t,p=rt(t,[{[Re]:!0},{[tr]:N=>!N||Array.isArray(N)&&N.every(Rr),[Dh]:!1,[He]:Be}]);if(p.error)return p;let m=Ko({tournamentRecords:i});if(m.error)return m;if(!m.schedulingProfile.length)return{...C};let{modifications:d,issues:l=[],schedulingProfile:f=[]}=m,g=Object.assign({},...Object.values(i).map(N=>as({tournamentRecord:N}).containedStructures)),I=o.map(N=>{if(Rr(N))return Et(N)}).filter(Boolean),h=f.map(N=>N.scheduleDate).map(N=>Rr(N)&&Et(N)).filter(N=>N&&(!o.length||I.includes(N)));if(!h.length)return{error:tE};if(n&&!c){let N=Array.isArray(n)?n:[];am({tournamentRecords:i,scheduledDates:N})}let S=Ao({ignoreDisabled:!1,tournamentRecords:i}).courts,{matchUps:T}=Un({matchUpFilters:{matchUpTypes:[xt,_t]},afterRecoveryTimes:!0,nextMatchUps:!0,tournamentRecords:i}),{matchUpDependencies:y}=sn({includeParticipantDependencies:!0,tournamentRecords:i,matchUps:T}),{matchUpDailyLimits:P}=ul({tournamentRecords:i}),{personRequests:U}=bi({requestType:_c,tournamentRecords:i}),E=f.filter(N=>{let D=Et(N?.scheduleDate);return h.includes(D)}).sort((N,D)=>new Date(N.scheduleDate).getTime()-new Date(D.scheduleDate).getTime()),A={schedulingProfileModifications:d,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:r,schedulingProfileIssues:l,dateSchedulingProfiles:E,containedStructureIds:g,matchUpDependencies:y,matchUpDailyLimits:P,clearScheduleDates:n,tournamentRecords:i,schedulingProfile:f,personRequests:U,periodLength:s,useGarman:a,matchUps:T,dryRun:c,courts:S};return u?Kx(A):$x(A)}function um(t){let{tournamentRecord:e,tournamentRecords:r,activeTournamentId:n,...o}=t||{};return o.tournamentId||(o.tournamentId=Dt()),o.startDate&&!Qa(o.startDate)&&!Cm.test(o.startDate)?{error:je}:o.endDate&&!Qa(o.endDate)&&!Cm.test(o.endDate)?{error:je}:(o.extensions&&(o.extensions=o.extensions.filter(wn)),{...o})}function pI({addParticipants:t=!0,participantAttribute:e,tournamentRecord:r,personAttribute:n,teamNames:o,accessor:i,uuids:s}){if(!r)return{error:Y};let a={},c=(r.participants??[]).filter(({participantType:f,participantRole:g})=>f===Tt&&g===xe),u=0;for(let f of c){let I=i&&ls({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()??Dt(),individualParticipantIds:[],participantRole:xe,participantType:Lt};let h={value:n??e,name:Oh};At({element:a[I],extension:h}),u+=1}a[I].individualParticipantIds.push(f.participantId)}}let p=Object.keys(a),m=(r.participants??[]).map(f=>{if(f.participantType!==Lt||f.participantRole!==xe)return;let{extension:g}=dt({name:Oh,element:f}),I=g?.value;if(p.includes(I))return f.participantId}).filter(Boolean),d=0,l=[];return Object.keys(a).forEach(f=>{let g=a[f],{participantId:I}=g;m.includes(I)||(r.participants||(r.participants=[]),t&&r.participants.push(g),l.push(g),d++)}),t&&d?(mt({payload:{tournamentId:r.tournamentId,participants:l},topic:Zo}),{...C,participantsAdded:d}):l.length?{...C,newParticipants:l}:{error:yC}}var zx=[{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 Qx=["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 $y({count:t=1,participantsCount:e=32}={}){let r=Ir(Qx),n=r.slice(0,t);return{cities:et(0,e).map(i=>i<Math.min(t,r.length)?n[i]:yn(n))}}function Ky({count:t=1,participantsCount:e=32}={}){let r=Ir(zx),n=r.slice(0,t).map(i=>Object.keys(i)).flat();return{states:et(0,e).map(i=>i<Math.min(t,r.length)?n[i]:yn(n))}}function zy({count:t=1,participantsCount:e=32}={}){let r=et(0,t).map(()=>et(0,5).map(()=>po(0,9)).join(""));return{postalCodes:et(0,e).map(o=>o<t?r[o]:yn(r))}}function pm({idPrefix:t,participantType:e,index:r,uuids:n}){let o=Vt(e)?e[0]:"X";return t?`${t}-${o}-${r}`:n?.pop()||Dt()}function Qy(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 Xx={lastNames:["Abbey","Ahern","Ampleforth","Ananiadis","Andelic","Assange","Atreides","Austen","Bach","Banks","Barrington","Batty","Bauers","Beals","Beer","Bennett","Berry","Bonaparte","Brewer","Brockovich","Bukowski","Cassidy","Catton","Calvino","Carlin","Carson","Chip","Constant","Crane","Crowne","Cummings","Curie","Dallas","Diamond","Deckard","Drazic","Dunbar","Earhart","Eisenstein","Eldritch","Elliot","Ellul","Escher","Eyre","Faulkner","Fulcher","Fukuoka","Godel","Goldstein","Greer","Hedges","Herbert","Holmgren","Humperdinck","Huxley","Illich","Jeffers","Jensen","Jevons","Johnson","Johnstone","Jovovich","Kingsnorth","Langer","Fernwright","Fuller","Le Guin","Lem","Lovelace","Mander","McLuhan","Midgely","Mond","Montoya","Moore","Murry","Nagle","Nearing","Ogden","Ophuls","Parks","Paz","Peet","Perfect","Pendejo","Pevensie","Postman","Ripley","Rodda","Rumfoord","Runciter","Rugen","Sale","Schumacher","Shaftoe","Shelley","Shepard","Smith","Stratton","Stewart","Swift","Tillich","Turing","Tyrell","Twain","Yeats","Veblen","Yates","Vonnegut","Waterhouse","Watson","Wolin","Wirt","Waschuk","Wormwood"],firstFemale:["Ada","Amelia","Amelie","America","Anne","Antonia","Aravis","Astrid","Beatrice","Brienne","Buttercup","Caitlin","Cimorene","Cordelia","Desdemona","Ellen","Elizabeth","Emily","Emmie","Erin","Eva","Evelyn","Heather","Helen","Hermia","Hypatia","Imogen","Jane","Jasmine","Juliana","Juliet","Katniss","Leeloo","Lenina","Lilith","Linda","Lizzie","Louise","Lucy","Marie","Mary","Martha","Matilda","Milla","Miranda","Meg","Melba","Nicole","Ola","Portia","Pris","Rachael","Rachel","Rebecca","River","Rosa","Rosalind","Scout","Sharn","Susanne","Titania","Uhura","Ursula","Valentina","Viola","Virginia","Xena","Zoe"],firstMale:["Alan","Aldous","August","Axel","Barda","Barry","Bill","Bruce","Charles","Chris","Constantine","Darwin","David","Derrick","Edward","Emmanuel","Ernst","Estlin","Fezzik","Filby","Frank","Frito","George","Glen","Helmholtz","Inigo","Italo","Ivan","Jacques","James","Jared","Jerry","Joe","Johann","Julian","John Michael","Jonathan","Korben","Kirkpatrick","Kurt","Lief","Malachi","Mark","Marhsall","Masanobu","Maurits","Michael","Mustapha","Neil","Nikola","Octavio","Palmer","Paul","Pierre","Robinson","Rick","Rincewind","Roy","Shannon","Sheldon","Stafford","Stanislaw","Stanley","Syme","Thorstein","Thomas","Tyrone","Vizzini","Walton","Walker","Warren","Wendell","Westley","William","Winston","Zoran"]};function Xy(t){let{count:e=100,sex:r}=t||{};if(!e||r&&![$t,ne].includes(r))return{personData:[],error:G};let n=Math.ceil(e*1.3),{lastNames:o,firstFemale:i,firstMale:s}=Xx,a=ti.map(({iso:I})=>I).filter(Boolean),c=Math.ceil(n/o.length),u=Math.ceil(n/i.length),p=Math.ceil(n/s.length),m=et(0,c).flatMap(()=>{let I=J(o,!1,!0);return et(0,o.length).map(()=>tn(I))}),d=et(0,u).flatMap(()=>{let I=J(i,!1,!0);return et(0,i.length).map(()=>tn(I))}),l=et(0,p).flatMap(()=>{let I=J(s,!1,!0);return et(0,s.length).map(()=>tn(I))}),f={};for(let I=0;I<n;I++){let h=m.pop(),S=r||yn([$t,ne]),T=S===$t?l.pop():d.pop(),y=yn(a);f[`${T}${h}`]={nationalityCode:y,sex:S,firstName:T,lastName:h}}return{personData:Object.values(f).slice(0,e)}}function Jy(t){let e=t?.count||1,{personExtensions:r,consideredDate:n,isMock:o=!0,gendersCount:i,personData:s,category:a,sex:c}=t||{};if(isNaN(e))return{error:G};let u=i?.[$t]||c===$t&&e||0,p=i?.[ne]||c===ne&&e||0;e=Math.max(e,u+p);let m=e-(u+p),d=u&&Xy({count:u,sex:$t}).personData||[],l=p&&Xy({count:p,sex:ne}).personData||[],f=[...d,...l,...m&&Xy({count:m}).personData||[]],g=f.filter(A=>!c||u&&p||A.sex===c),I=[];if(Array.isArray(s)){let A=s.filter(N=>typeof N.firstName!="string"||typeof N.lastName!="string"||N.sex&&![$t,ne].includes(N.sex)||N.nationalityCode&&(typeof N.nationalityCode!="string"||N.nationalityCode.length>3||!ti.find(({iso:D,ioc:M})=>[D,M].includes(N.nationalityCode)))?!1:(N.nationalityCode&&I.push(N.nationalityCode),!0));if(A.length)g=A;else return{error:G}}let h=s?g:Ir(g);if(h.length<e){let{maleFirstNames:A,maleLastNames:N,femaleFirstNames:D,femaleLastNames:M,nationalityCodes:R}=f.reduce((b,v)=>{let{firstName:O,lastName:x,nationalityCode:F}=v;return v.sex===$t?(b.maleFirstNames.includes(O)||b.maleFirstNames.push(O),b.maleLastNames.includes(x)||b.maleLastNames.push(x)):(b.femaleFirstNames.includes(O)||b.femaleFirstNames.push(O),b.femaleLastNames.includes(x)||b.femaleLastNames.push(x)),b.nationalityCodes.includes(F)||b.nationalityCodes.push(F),b},{maleFirstNames:[],maleLastNames:[],femaleFirstNames:[],femaleLastNames:[],nationalityCodes:[]});et(0,e-h.length).forEach(()=>{let b=c||yn([$t,ne]),v=yn(R),O=b===$t?yn(A):yn(D),x=b===$t?yn(N):yn(M),F={firstName:O,lastName:x,sex:b,nationalityCode:v};h.push(F)})}let{ageMinDate:S,ageMaxDate:T}=Ls({consideredDate:n,category:a}),y=pt(S?.slice(0,4)||0)||pt(T?.slice(0,4)||0)-3,P=pt(T?.slice(0,4)||0)||pt(S?.slice(0,4)||0)+3,U=(S||T)&&[y,P],E=h.slice(0,e).map((A,N)=>{let[D,M]=U||[],R=U&&tn(et(D,M)),b=tn(et(0,365)),v=R&&HC(R,b);return Object.assign(ot({extensions:r||[{name:"regionCode",value:N+1}],birthDate:v,isMock:o}),A)});return{persons:E.length&&E||h[0],nationalityCodes:I}}var Jx=["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 mm({nameRoot:t="TEAM",count:e=1}={}){let n=Ir(Jx).slice(0,e);return n.length<e&&et(0,e-n.length).forEach(o=>n.push(`${t} ${o+1}`)),{names:n}}function sa(t){let{scaledParticipantsCount:e,rankingRange:r}=t,{ratingsParameters:n=we,valuesInstanceLimit:o,ratingsValues:i=[],consideredDate:s,categories:a,category:c,nationalityCodesCount:u,nationalityCodeType:p,nationalityCodes:m,participantsCount:d=32,participantType:l,teamSize:f=8,personIds:g,idPrefix:I,uuids:h,personExtensions:S,addressProps:T,gendersCount:y,matchUpType:P,personData:U,sex:E,inContext:A,withISO2:N,withIOC:D,scaleAllParticipants:M}=t,R=l===ft||P===vi,b=l===Lt||P===Lt;r&&(!Array.isArray(r)||!r.every(ee=>Zt(ee))||r.length!==2)&&(r=void 0),e=M?d:e;let v=1e3,O=e&&e>v?e:v;r=r||[1,O],r[1]+=1;let x=d*(R&&2||b&&(f??8)||1),F=Jy({count:x,personExtensions:S,consideredDate:s,gendersCount:y,personData:U,category:c,sex:E});if(F.error)return F;let{nationalityCodes:L,persons:w}=F,V={},k={},W={},H={},K=ee=>{Object.assign(V,ee.doublesRankings),Object.assign(k,ee.singlesRankings),Object.assign(H,ee.doublesRatings),Object.assign(W,ee.singlesRatings)};if(ht(c)){let ee=Zx({scaledParticipantsCount:e,ratingsParameters:n,participantType:l,ratingsValues:i,rankingRange:r,category:c});K(ee)}Array.isArray(a)&&a.forEach(ee=>{let Pt=Zx({scaledParticipantsCount:e,ratingsParameters:n,participantType:l,ratingsValues:i,rankingRange:r,category:ee});K(Pt)});let q=ti.filter(ee=>p==="IOC"&&ee.ioc||ee.iso);function B(ee){let Pt=Math.ceil(x/ee);return o&&Pt>o?Math.ceil(x/o):ee}let{postalCodesProfile:$,postalCodesCount:z,statesProfile:j,citiesProfile:tt,citiesCount:Q,statesCount:X}=T||{},lt=ee=>Object.keys(ee).map(Pt=>et(0,j[Pt]).map(()=>Pt)).flat(),it=tt&<(tt)||T?.cities||$y({count:Q||x,participantsCount:x}).cities,Rt=j&<(j)||T?.states||Ky({count:X||x,participantsCount:x}).states,Ft=$&<($)||T?.postalCodes||zy({count:z||x,participantsCount:x}).postalCodes,Ue={cities:it,states:Rt,postalCodes:Ft},fe=B(u),Me=fe?Ir(q).slice(0,u):m&&q.filter(ee=>m.includes(ee.iso))||q,vr=Ir(et(0,Math.ceil(x/(fe||1))).map(()=>Me).flat(1/0)),Zr=mm({count:d}).names;return{participants:et(0,d).map(ee=>{let Pt=R&&2||b&&(f??8)||1,ae=et(0,Pt).map(mr=>{let zt=ee*Pt+mr;return Xe(zt)}),re=ae.map(mr=>mr.participantId),pr=ae.map(mr=>mr.person.standardFamilyName).join("/"),Jt=R?ft:Lt,Wt={participantId:pm({participantType:Jt,index:ee,idPrefix:I,uuids:h}),participantName:R?pr:Zr[ee],participantRole:xe,individualParticipantIds:re,participantType:Jt};return A&&(Wt.individualParticipants=ae),R||b?[Wt,...ae]:ae}).flat(),...C};function Xe(ee){let Pt=w[ee],{nationalityCode:ae,participantExtensions:re,participantTimeItems:pr,extensions:Jt,firstName:Wt,birthDate:mr,lastName:zt,personId:pe,sex:Pe}=Pt||{},Or=Wt||"GivenName",Je=zt||"FamilyName",De=`${Or} ${Je}`,Ee=vr[ee],ge=L?.length&&ae||Ee&&(p==="IOC"?Ee.ioc||Ee.iso:Ee.iso||Ee.ioc)||ae;vr?.length&&!ge&&!ae&&console.log("%c Invalid Nationality Code",{participantIndex:ee,country:Ee});let _r=Qy({...Ue,participantIndex:ee,nationalityCode:ge}),fr=ot({participantId:pm({participantType:Tt,index:ee,idPrefix:I,uuids:h}),extensions:re,timeItems:pr,participantRole:xe,participantType:Tt,participantName:De,person:{personId:pe||g?.length&&g[ee]||Dt(),birthDate:Rr(mr)?mr:void 0,addresses:[_r],standardFamilyName:Je,standardGivenName:Or,nationalityCode:ge,extensions:Jt,sex:Pe}});if(D&&ge){let be=ti.find(({iso:Ar})=>Ar===ge);be?.ioc&&(fr.person.iocNationalityCode=be.ioc),be?.label&&(fr.person.countryName=be.label)}if(N&&ge){let be=ti.find(({iso:Ar})=>Ar===ge);be?.iso2&&(fr.person.iso2NationalityCode=be.iso2),be?.label&&(fr.person.countryName=be.label)}let uo=be=>{let Ar=be.categoryName||be.ratingType||be.ageCategoryCode,Zi=k[Ar]?.[ee],Tn=V[Ar]?.[ee];Zy({scaleValue:Zi,eventType:Fs,scaleType:fi,participant:fr,category:be}),Zy({scaleValue:Tn,eventType:ko,scaleType:fi,participant:fr,category:be});let ts=W[Ar]?.[ee],ju=H[Ar]?.[ee];Zy({scaleValue:ts,eventType:Fs,scaleType:gi,participant:fr,category:be}),Zy({scaleValue:ju,eventType:ko,scaleType:gi,participant:fr,category:be})};return Array.isArray(a)?a.forEach(be=>uo(be)):c&&uo(c),fr}}function Zy({scaleValue:t,participant:e,eventType:r,scaleType:n,category:o}){let i=o.categoryName||o.ratingType||o.ageCategoryCode,s=[Ii,n,r,i].join("."),a={itemValue:t,itemType:s};i&&t&&(e.timeItems||(e.timeItems=[]),e.timeItems.push(a))}function Zx(t){let{category:e,scaledParticipantsCount:r,ratingsParameters:n,participantType:o,ratingsValues:i=[]}=t,s=e.rankingRange||t.rankingRange||[1,1e3],a={},c={},u={},p={},{categoryName:m,ageCategoryCode:d,ratingType:l}=e,f=e.categoryName||e.ratingType||e.ageCategoryCode;if((m||d)&&!l){let[g,I]=s||[];if(c[f]=Ir(et(g,I)).slice(0,r||po(20,30)),[ft,Lt].includes(o)){let[h,S]=s||[];a[f]=Ir(et(h,S)).slice(0,r||po(20,30))}}if(l&&n[l]){let{ratingMax:g,ratingMin:I,ratingAttributes:h}=e,S={...n[l],...h||{}},{attributes:T={},decimalsCount:y,accessors:P,range:U,step:E}=S,A=O=>{let x={},F=Object.keys(O||{});for(let L of F){let w=O[L];if(typeof w=="object"&&w.generator){let{range:V}=w,[k,W]=V.slice().sort();x[L]=po(k,W)}else x[L]=w}return x},D=U[0]>U[1]?2:.7,[M,R]=U.slice().sort(),v=et(0,2e3).map(()=>EA(M,R,D,E,y)).filter(x=>(!g||x<=g)&&(!I||x>=I)).slice(0,r||po(20,30)).map(x=>P?Object.assign({},...P.map(F=>({[F]:x})),A(T)):x);u[f]=[...i,...v],[ft,Lt].includes(o)&&(p[f]=[...i,...v])}return{singlesRankings:c,doublesRankings:a,singlesRatings:u,doublesRatings:p}}function Al(t){let{alternatesCount:e=0,tieFormatName:r,drawSize:n}=t,o=0,i=0,s=0,a=0,c={},u={[$t]:0,[ne]:0,[Tr]:0,[os]:0,[Pn]:0};(ht(t.tieFormat)?t.tieFormat:Zn({namedFormat:r}))?.collectionDefinitions?.filter(Boolean).forEach(f=>{let{category:g,collectionId:I,matchUpType:h,matchUpCount:S,gender:T}=f;if([$t,ne].includes(T)){let y=S*(h===_t?2:1);u[T]<y&&(u[T]=y)}else T===Tr&&(u[$t]<S&&(u[$t]=S),u[ne]<S&&(u[ne]=S));if(g){let y=JSON.stringify(g);c[y]=g}if(I||(f.collectionId=Dt()),ue(_t)(h)){let y=S;a+=S,o=Math.max(o,y)}if(ue(xt)(h)){let y=S;s+=S,i=Math.max(i,y)}});let m=Object.keys(c).length?Math.max(s,a*2):Math.max(i,o*2),d=o*(n+e),l=i*(n+e);return{maxDoublesDraw:d,maxSinglesDraw:l,teamSize:m,genders:u}}function tw({participantsProfile:t,eventProfiles:e,drawProfiles:r}){let{participantsCount:n,participantType:o=Tt}=t||{},i=n||0,s={[ne]:0,[Tr]:0,[os]:0,[$t]:0,[Pn]:0},a=0,c=0,u=0,p=0,m=0,d=({alternatesCount:f=0,uniqueParticipants:g,tieFormatName:I,drawSize:h=0,eventType:S,tieFormat:T,category:y,gender:P,stage:U})=>{let E=S===qr,A=S===_e,N=!!(g||U===ct||y||P);if(A){p=Math.max(p,h+f),T=typeof T=="object"?T:Zn({namedFormat:I});let{teamSize:D,maxDoublesDraw:M,maxSinglesDraw:R,genders:b}=Al({alternatesCount:f,tieFormatName:I,tieFormat:T,drawSize:h});u=Math.max(u,D),c=Math.max(c,R),N||(a=Math.max(a,M)),Object.keys(b).forEach(v=>s[v]+=b[v])}else if(E)if(N){let D=(h+f)*2;m+=D,P&&(s[P]+=D)}else h+f&&h+f>a&&(a=h+f);else if(N){let D=h+f;P&&(s[P]+=D),m+=D}else h&&h>c&&(c=h+f)};if(e?.forEach(f=>{let{tieFormatName:g,tieFormat:I,drawProfiles:h,eventType:S,category:T,gender:y}=f;if(h)for(let P of h){let{tieFormatName:U,tieFormat:E}=P;d({...P,tieFormatName:U||g,tieFormat:E||I,eventType:S,category:T,gender:y})}}),Array.isArray(r))for(let f of r)d(f);let l=Math.max(p*u,a*2,c);return a&&(o=ft),(n||i)<l&&(n=l),n&&a&&[ft,_e].includes(o)&&(c&&Math.floor(c/2)>a?n=Math.floor(c/2):(!c||a*2>=c)&&(n=Math.ceil(n/2))),n===void 0&&(n=!e?.length&&!r?.length?32:0),n<i&&(n=i),{uniqueParticipantsCount:m,participantsCount:n,largestTeamDraw:p,largestTeamSize:u,participantType:o,gendersCount:s}}function tA({participantsProfile:t,tournamentRecord:e,eventProfiles:r,drawProfiles:n,startDate:o,uuids:i}){if(t?.participantsCount===0)return{addedCount:0,...C};let{participantsCount:s,participantType:a,largestTeamDraw:c,largestTeamSize:u,gendersCount:p}=tw({participantsProfile:t,eventProfiles:r,drawProfiles:n}),m=t?.teamKey,d=sa({consideredDate:o,...t,participantsCount:s,participantType:a,gendersCount:p,uuids:i}).participants,l=0,f=Sn({tournamentRecord:e,participants:d});if(f.error)return f;if(l+=f.addedCount,m){let S=pI({tournamentRecord:e,...m});if(S.error)return S}let g=d.filter(({participantType:S})=>S===Tt).map(St),I=t?.idPrefix?`${Lt}-${t.idPrefix}`:void 0,h=et(0,c).map(S=>{let T=g.slice(S*u,(S+1)*u),y=pm({index:S,participantType:a,idPrefix:I,uuids:i});return{participantName:`Team ${S+1}`,participantRole:xe,individualParticipantIds:T,participantType:Lt,participantId:y}});return f=Sn({participants:h,tournamentRecord:e}),f.error?f:(l+=f.addedCount,{addedCount:l,...C})}function eA({drawProfiles:t,category:e,gender:r}){let n={},o=t?.reduce((s,a)=>{let{qualifyingPositions:c=0,participantsCount:u=0,uniqueParticipants:p,stage:m=nt,drawSize:d=0}=a||{};Object.keys(s).includes(m)||(s[m]=0);let l=(u||d)-c;return p||r||e||m===ct?(Object.keys(n).includes(m)||(n[m]=0),n[m]+=l):s[m]=Math.max(s[m],l),s},{}),i=Object.keys(n);return i.forEach(s=>o[s]+=n[s]),{stageParticipantsCount:o,uniqueParticipantsCount:n,uniqueParticipantStages:i}}function rA({allUniqueParticipantIds:t,stageParticipantsCount:e,eventParticipantType:r,targetParticipants:n}){let o=e[nt]||0,i=e[ct]||0;return{stageParticipants:{QUALIFYING:n?.filter(({participantType:a})=>a===r).filter(({participantId:a})=>!t.includes(a)).slice(0,i),MAIN:n?.filter(({participantType:a})=>a===r).filter(({participantId:a})=>!t.includes(a)).slice(i,i+o)}}}var k1={[Ct]:2,[he]:1,[Ce]:1,[rr]:1,[Mt]:4};function mI(t){let{defaultWithScorePercent:e=2,winningSide:r}=t,{matchUpStatusProfile:n=k1,matchUpFormat:o=Dn,pointsPerMinute:i=1,sideWeight:s=4}=t;if(!Pr({matchUpFormat:o}))return{error:Hl};if(typeof n!="object")return{error:G};if(e>100&&(e=100),isNaN(e)||isNaN(i)||isNaN(s))return{error:G};let a=Object.keys(n).filter(b=>Object.keys(Vh).includes(b)&&b!==le);if(Object.keys(a).reduce((b,v)=>b+n[v],0)>100)return{error:G,matchUpStatusProfile:n};let u=a.reduce((b,v)=>(b.pointer=b.pointer+n[v],b.valueMap.push([b.pointer,v]),b),{pointer:0,valueMap:[]}),p=po(1,100),m=(u.valueMap.find(b=>p<=b[0])??[100,le])[1],d={sets:[],scoreStringSide1:"",side2ScoreString:""};if([Ct,Mt].includes(m)){r=r||po(1,2);let b={score:d,matchUpStatus:m,winningSide:r};if(!(m===Mt&&po(1,100)>100-e))return{outcome:b}}else if([he,Ce].includes(m))return{outcome:{score:d,matchUpStatus:m}};let l=Ye(o),{bestOf:f=1,exactly:g,setFormat:I,finalSetFormat:h}=l??{},S=[],T=po(0,1),y=r?[r-1]:[...et(0,s).map(()=>T),1-T],U=[rr,Mt,pn,ss].includes(m)&&(tn(et(1,g||f))||1),E,A=et(1,(g??f)+1);for(let b of A){let v=b===(g??f),{set:O,incomplete:x,winningSideNumber:F}=G1({setFormat:v&&h||I,incomplete:U===b,pointsPerMinute:i,matchUpStatus:m,weightedRange:y,setNumber:b});if(S.push(O),x){E=F;break}if(Xp({matchUp:{score:{sets:S},matchUpFormat:o}}).calculatedWinningSide)break}let N=Xp({matchUp:{score:{sets:S},matchUpFormat:o,winningSide:r}}),D=E?r||E:N.calculatedWinningSide,{score:M}=Wy({winningSide:D,score:{sets:S},matchUpStatus:m});return{outcome:{winningSide:D,matchUpStatus:m,score:M}}}function G1({weightedRange:t=[0,1],pointsPerMinute:e,matchUpStatus:r,incomplete:n,setFormat:o,setNumber:i}){let s={setNumber:i},{setTo:a,tiebreakFormat:c,tiebreakAt:u,tiebreakSet:p,timed:m,minutes:d}=o,l=po(0,t.length-1),f=t[l],g;if(m){let I=d*e,h=Math.round(I*.2),S=I+tn([1,-1])*h,T=cC(S,2),y=[T,S-T];f&&y.reverse(),g=t[l]+1;let P=y[0]>y[1]&&1||y[1]>y[0]&&2||0;if(n){let[A,N]=y;return Object.assign(s,{side1Score:A,side2Score:N}),ce.includes(r)?{set:s,incomplete:n,winningSideNumber:g}:{set:s,incomplete:n}}P||(y[po(0,1)]+=1),P=y[0]>y[1]?1:2,P!==g&&y.reverse();let[U,E]=y;return Object.assign(s,{side1Score:U,side2Score:E,winningSide:g}),{set:s}}else{if(n)return s.side1Score=po(0,u),s.side2Score=po(0,u),ce.includes(r)&&(g=t[l]+1),{set:s,incomplete:n,winningSideNumber:g};{let I=et(1,a+1).map(E=>et(0,a+2-E).map(()=>E)).flat(),h=I[po(0,I.length-1)],S=a&&Bg({isSide1:!0,tiebreakAt:u,lowValue:h,setTo:a}),T=!S,y=t.length===1&&t[l]+1;if(!T){y?(S[0]>S[1]?1:2)!==y&&S.reverse():f&&S.reverse();let[E,A]=S;Object.assign(s,{side1Score:E,side2Score:A})}let P=wu({matchUpScoringFormat:{setFormat:o},setObject:s}),U;if(P.hasTiebreakCondition||T){let{NoAD:E,tiebreakTo:A}=c||p||{},N=et(1,A+1).map(R=>et(0,A+2-R).map(()=>R)).flat(),D=N[po(0,N.length-1)],M=qp({isSide1:!0,tiebreakNoAd:E,tiebreakTo:A,lowValue:D});if(M)if(T){let R=M[0]>M[1]?1:2;y?R!==y&&M.reverse():f&&M.reverse(),[s.side1TiebreakScore,s.side2TiebreakScore]=M,U=M[0]>M[1]&&1||M[1]>M[0]&&2||void 0}else P.leadingSide===2?[s.side1TiebreakScore,s.side2TiebreakScore]=M:[s.side2TiebreakScore,s.side1TiebreakScore]=M}s.winningSide=P.winningSide||P.leadingSide||y||U}}return{set:s}}function El(t){let{matchUpStatusProfile:e,completeAllMatchUps:r,randomWinningSide:n,tournamentRecord:o,completionGoal:i,drawDefinition:s,event:a}=t;if(!s)return{error:Z};let c=t.matchUpFormat||s.matchUpFormat||a?.matchUpFormat,u=s.structures.slice().sort(Si),p=0,{matchUps:m,matchUpsMap:d}=se({matchUpFilters:{matchUpTypes:[jt],roundNumbers:[1]},contextFilters:{stages:[nt,ct]},inContext:!0,drawDefinition:s});if(m?.length){let h=a?.category?.ageCategoryCode||a?.category?.categoryName;if(h){let T=Cy({singlesOnly:!0,tournamentRecord:o,drawDefinition:s,scaleAccessor:{scaleName:h,sortOrder:XN,scaleType:fi},event:a});if(T.error)return T;let{lineUps:y,participantsToAdd:P}=T;Sn({tournamentRecord:o,participants:P}),At({element:s,extension:{name:Ro,value:y}})}else{let S=m[0]?.structureId,{positionAssignments:T}=bt({drawDefinition:s,structureId:S});if(T?.length){let{participants:y}=Gt({participantFilters:{participantTypes:[jt]},tournamentRecord:o}),P=U=>{let E=U.tieMatchUps.filter(ue(xt)),A=U.tieMatchUps.filter(ue(_t));E.forEach((N,D)=>{let M=N.matchUpId;N.sides.forEach(R=>{let{drawPosition:b}=R,v=y?.find(O=>{let{participantId:x}=O;return T.find(L=>L.participantId===x)?.drawPosition===b});if(v){let O=v.individualParticipantIds?.[D];O&&gl({teamParticipantId:v.participantId,participantId:O,tournamentRecord:o,drawDefinition:s,tieMatchUpId:M,event:a})}})}),A.forEach((N,D)=>{let M=N.matchUpId;N.sides.forEach(R=>{let{drawPosition:b}=R,v=y?.find(O=>{let{participantId:x}=O;return T.find(L=>L.participantId===x)?.drawPosition===b});v&&v.individualParticipantIds?.slice(D*2,D*2+2)?.forEach(x=>{gl({teamParticipantId:v.participantId,participantId:x,tournamentRecord:o,drawDefinition:s,tieMatchUpId:M,event:a})})})})};m.forEach(P)}}}let l=typeof r=="string"&&r,f=l&&le,g=u.length===2&&u[0].finishingPosition===li&&Yt(u.map(({stage:h})=>h),[nt,de]).length===2,I=u.map(({structureId:h})=>h);for(let h of I){if(p>=i)break;let S=s.structures.find(P=>P.structureId===h),T=Ut({contextFilters:{matchUpTypes:[_t,xt]},afterRecoveryTimes:!1,tournamentRecord:o,inContext:!0,drawDefinition:s,matchUpsMap:d,structure:S,event:a}).matchUps;T.length;let y=T.filter(({winningSide:P})=>!P).sort(Mi).map(Ae);for(let P of y){if(!isNaN(i)&&p>=i)break;let{matchUps:U}=Ut({matchUpFilters:{matchUpTypes:[_t,xt]},afterRecoveryTimes:!1,tournamentRecord:o,inContext:!0,drawDefinition:s,matchUpsMap:d,structure:S,event:a}),E=U.find(N=>N.matchUpId===P),A=[he,Ce].includes(E.matchUpStatus);if(E?.readyToScore&&!A){let D=V1({matchUpStatusProfile:e,tournamentRecord:o,drawDefinition:s,targetMatchUp:E,matchUpFormat:c,matchUpStatus:f,scoreString:l,winningSide:!n&&1,event:a});if(D?.error)return D;p+=1}}g&&S.finishingPosition===li&&t.completeRoundRobinPlayoffs&&Ks({structureId:S.structureId,applyPositioning:!0,drawDefinition:s})}return{...C,completedCount:p}}function EM(t){let{matchUpStatusCodes:e,policyDefinitions:r,tournamentRecord:n,drawDefinition:o,targetMatchUp:i,matchUpStatus:s,matchUpFormat:a,scoreString:c,winningSide:u,event:p}=t;if(!i||i.matchUpStatus===Nt)return;let{matchUpId:m}=i||{},{outcome:d}=cI({matchUpFormat:a,matchUpStatus:s,scoreString:c,winningSide:u});return e&&(d.matchUpStatusCodes=e),Gu({tournamentRecord:n,policyDefinitions:r,drawDefinition:o,matchUpFormat:a,matchUpId:m,outcome:d,event:p})}function V1(t){let{matchUpStatusProfile:e={},tournamentRecord:r,policyDefinitions:n,drawDefinition:o,matchUpStatus:i,matchUpFormat:s,targetMatchUp:a,scoreString:c,winningSide:u,event:p}=t;if(c||i)return EM(t);let{matchUpId:m}=a||{},{outcome:d}=mI({matchUpStatusProfile:e,matchUpFormat:s,winningSide:u});return Gu({policyDefinitions:n,tournamentRecord:r,drawDefinition:o,matchUpFormat:s,matchUpId:m,outcome:d,event:p})}function nA({matchUpStatusProfile:t,completeAllMatchUps:e,randomWinningSide:r,tournamentRecord:n,drawProfiles:o,isMock:i,event:s}){let a=Ht({event:s}).flightProfile,{eventName:c,eventType:u,category:p}=s,{startDate:m}=n,d=[],l=p?.categoryName||p?.ageCategoryCode||p?.ratingType,f=s.drawDefinitions?.map(({drawId:g})=>g);if(Array.isArray(a?.flights))for(let[g,I]of a.flights.entries()){let{drawId:h,stage:S,drawName:T,drawEntries:y}=I;d.push(I.drawId);let P=o[g],{seedsCount:U,generate:E=!0}=P||{};if(E){let A=y.filter(Br(ro)).map(Br(ro)),N=l||c;if(n&&U&&U<=A.length&&et(1,U+1).forEach((x,F)=>{let L={scaleValue:x,scaleName:N,scaleType:ho,eventType:u,scaleDate:m},w=A[F];Dc({tournamentRecord:n,participantId:w,scaleItem:L})}),f?.includes(h))break;let D=xa({...P,matchUpType:u,seedingScaleName:N,tournamentRecord:n,drawEntries:y,drawName:T,drawId:h,isMock:i,event:s,stage:S});if(D.error)return{error:D.error,drawIds:[]};let{drawDefinition:M}=D;if(!M)return{error:Mr};let R=o[g]?.drawExtensions;if(Array.isArray(R)&&R.filter(wn).forEach(O=>At({element:M,extension:O})),D=Cc({suppressNotifications:!0,tournamentRecord:n,drawDefinition:M,event:s}),D.error)return{error:D.error,drawIds:[]};if(P?.withPlayoffs){let O=M.structures?.[0].structureId,x=kp({idPrefix:P.idPrefix,...P.withPlayoffs,tournamentRecord:n,drawDefinition:M,structureId:O,isMock:i,event:s});if(x?.error)return x}let b=P?.completionGoal;if(!(P?.automated===!1)&&(e||b)){let O=P?.matchUpFormat,x=El({completeAllMatchUps:!b&&e,matchUpStatusProfile:t,randomWinningSide:r,tournamentRecord:n,completionGoal:b,drawDefinition:M,matchUpFormat:O,event:s});if(x.error)return{error:x.error,drawIds:[]};let F=x.completedCount;if(P?.drawType===Io){let L=M.structures?.find(k=>k.stage===nt);if(!L)return{error:kt};let w=Ks({structureId:L.structureId,tournamentRecord:n,drawDefinition:M,event:s});if(w.error)return{error:w.error,drawIds:[]};let V=b?b-(F??0):void 0;if(w=El({completeAllMatchUps:!b&&e,completionGoal:b?V:void 0,matchUpStatusProfile:t,randomWinningSide:r,tournamentRecord:n,drawDefinition:M,matchUpFormat:O,event:s}),w.error)return{error:w.error,drawIds:[]}}}}}return{...C,drawIds:d}}function oA(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=ue(jn)(m)&&Tt||ue(qr)(m)&&ft||m,l=r[nt]||0,f=r[ct]||0,g=i.drawProfiles?.length?l+f:i.participantsProfile?.participantsCount??0,I=[$t,ne].includes(p)?p:void 0,h=e?.idPrefix?`E-${s}-${e?.idPrefix}`:void 0,{participants:S}=sa({uuids:i.uuids||c,...e,scaledParticipantsCount:i.scaledParticipantsCount,consideredDate:o?.startDate,rankingRange:i.rankingRange,participantType:d,participantsCount:g,ratingsParameters:n,category:u,idPrefix:h,sex:I}),y=Sn({tournamentRecord:o,participants:S});if(y.error)return y;let P=S?.filter(({participantType:E})=>E===d),U=S?.map(St);return{uniqueDrawParticipants:P,uniqueParticipantIds:U}}function ew({autoEntryPositions:t,tournamentRecord:e,drawParticipants:r,drawProfile:n,event:o}){let{drawType:i=go,qualifyingPositions:s=0,stage:a=nt,drawSize:c=0,drawName:u,drawId:p}=n,m=c-s,d=r.slice(0,m).map(St);if(d.length){let g=Fn({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=Zp({drawName:u||i,qualifyingPositions:s,drawEntries:l,drawId:p,event:o,stage:a});return f.error?f:{...C}}function iA({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=nt,drawSize:l=0}=u,f=l-p,g=m||s||i||d===ct,I=g?t.slice(c,c+f):r[d||nt]||[];g&&(c+=f);let h=ew({autoEntryPositions:e,drawParticipants:I,tournamentRecord:n,drawProfile:u,event:a});if(h.error)return h}return{...C}}function sA(t){let{allUniqueParticipantIds:e,matchUpStatusProfile:r,participantsProfile:n,completeAllMatchUps:o,autoEntryPositions:i,hydrateCollections:s,randomWinningSide:a,ratingsParameters:c,tournamentRecord:u,eventProfile:p,eventIndex:m,publish:d,isMock:l,uuids:f}=t,g=p.gender,I=p.eventName,{eventType:h=jn,policyDefinitions:S,drawProfiles:T=[],eventExtensions:y,surfaceCategory:P,tieFormatName:U,processCodes:E,discipline:A,eventLevel:N,timeItems:D,ballType:M,category:R}=p,b=p.eventId||Dt(),v=p.tieFormat||(h===_e?Zn({namedFormat:U,event:{eventId:b,category:R,gender:g},hydrateCollections:s,isMock:l}):void 0),O=u.participants;for(let j of T)!g&&j.gender&&(g=j?.gender);let{stageParticipantsCount:x,uniqueParticipantsCount:F,uniqueParticipantStages:L}=eA({drawProfiles:T,category:R,gender:g}),w=ue(jn)(h)&&Tt||ue(qr)(h)&&ft||h,{uniqueDrawParticipants:V=[],uniqueParticipantIds:k=[]}=L?oA({event:{eventType:h,category:R,gender:g},uniqueParticipantsCount:F,participantsProfile:n,ratingsParameters:c,tournamentRecord:u,eventProfile:p,eventIndex:m,uuids:f}):{},{eventAttributes:W}=p;typeof W!="object"&&(W={});let H=R?.categoryName||R?.ageCategoryCode||R?.ratingType;I=I||H||"Generated Event";let K={...W,surfaceCategory:P,processCodes:E,discipline:A,eventLevel:N,eventName:I,eventType:h,tieFormat:v,ballType:M,category:R,eventId:b,gender:g};if(y?.length&&Array.isArray(y)){let j=y.filter(wn);j?.length&&Object.assign(K,{extensions:j})}if(Array.isArray(D)&&D.forEach(j=>zi({event:$,timeItem:j})),typeof S=="object")for(let j of Object.keys(S))Qi({policyDefinitions:{[j]:S[j]},event:K});K.category&&(K.category.categoryName=H);let q,B=ra({suppressNotifications:!1,internalUse:!0,tournamentRecord:u,event:K});if(B.error)return B;let $=B?.event,{stageParticipants:z}=rA({allUniqueParticipantIds:e,stageParticipantsCount:x,eventParticipantType:w,targetParticipants:O});if(T?.length){let j=iA({uniqueDrawParticipants:V,autoEntryPositions:i,stageParticipants:z,tournamentRecord:u,drawProfiles:T,category:R,gender:g,event:$});if(j.error)return j;let tt=nA({matchUpStatusProfile:r,completeAllMatchUps:o,randomWinningSide:a,tournamentRecord:u,drawProfiles:T,isMock:l,event:$});if(tt.error)return tt;q=tt.drawIds}else if(p?.participantsProfile?.participantsCount){let j=V.map(St);if(j.length){let tt=Fn({participantIds:j,autoEntryPositions:i,tournamentRecord:u,entryStage:nt,event:$});if(tt.error)return tt}}return d&&oa({tournamentRecord:u,event:$}),{drawIds:q,eventId:b,uniqueParticipantIds:k}}function dI({tournamentRecords:t,scheduleDate:e,venueId:r,round:n}){if(!Rr(e))return{error:je};let o="addSchedulingProfileRound",{extension:i}=dt({name:Sa,tournamentRecords:t,discover:!0}),s=i?.value||[],a=s.find(l=>Wn(e,l.scheduleDate));if(!a){let{startDate:l,endDate:f}=Qd({tournamentRecords:t}),g=new Date(e);if(l&&g<new Date(l)||f&&g>new Date(f))return{error:je};a={scheduleDate:e,venues:[]},s.push(a)}let c=a.venues.find(l=>l.venueId===r);c||(c={venueId:r,rounds:[]},a.venues.push(c));let u=["notBeforeTime"],p=l=>Object.keys(l).filter(f=>!u.includes(f)).sort().map(f=>ht(l[f])?p(l[f]):l[f]).flat().join("|");if(c.rounds.find(l=>p(l)===p(n)))return _({result:{error:VA},stack:o});c.rounds.push(n);let d=Mc({tournamentRecords:t,schedulingProfile:s});return d.error?d:{...C}}function rw({schedulingProfile:t,tournamentRecord:e}){if(typeof t!="object")return{error:G};let r=as({tournamentRecord:e}).containedStructures,n=Te({tournamentRecord:e}).matchUps??[],{tournamentId:o}=e,i=[];for(let s of t){let{scheduleDate:a,venues:c=[]}=s;for(let u of c){let{rounds:p,venueId:m}=u;for(let d of p){let{drawId:l,winnerFinishingPositionRange:f,roundSegment:g}=d,h=n.filter(S=>{let T=f?.indexOf("-")>0&&f.split("-").map(P=>+P),y=S.finishingPositionRange?.winner;return S.drawId===l&&(!d.roundNumber||S.roundNumber===d.roundNumber)&&(!y||!T||Yt(y,T).length===2||ut(y).length===ut(T).length&&Yt(y,T).length===ut(y).length)})[0];if(h){let{eventId:S,roundNumber:T,drawName:y,structureName:P,roundName:U}=h,E=h.structureId;T&&!f&&(E=Object.keys(r).find(D=>r[D].includes(E))??E);let A={tournamentId:o,structureId:E,roundNumber:T,roundSegment:g,eventId:S,drawId:l},N=dI({tournamentRecords:{[o]:e},round:A,scheduleDate:a,venueId:m});if(N.error)return N;i.push({structureName:P,roundName:U,drawName:y,...A})}}}}return{scheduledRounds:i}}function dm(t){let e=rt(t,[{drawProfile:!0,_ofType:Kr}]);if(e.error)return e;let{allUniqueParticipantIds:r=[],participantsProfile:n={},matchUpStatusProfile:o,completeAllMatchUps:i,autoEntryPositions:s,hydrateCollections:a,randomWinningSide:c,ratingsParameters:u,tournamentRecord:p,isMock:m=!0,drawProfile:d,startDate:l,drawIndex:f,uuids:g}=t,I=J(d,!1,!0),{excessParticipantAlternates:h=!0,matchUpFormat:S=Dn,drawType:T=go,tournamentAlternates:y=0,alternatesCount:P=0,qualifyingPositions:U,qualifyingProfiles:E,generate:A=!0,eventExtensions:N,drawExtensions:D,completionGoal:M,tieFormatName:R,buildTeams:b,seedsCount:v,timeItems:O,drawName:x,category:F,idPrefix:L,publish:w,gender:V,stage:k}=I,W=I.drawSize||(I.ignoreDefaults?void 0:32),H=I.eventId||Dt(),K=d.eventType||d.matchUpType||jn,q=K===qr?ft:Tt,B=ht(d.tieFormat)&&d.tieFormat||K===Lt&&Zn({event:{eventId:H,category:F,gender:V},namedFormat:R,hydrateCollections:a,isMock:m})||void 0,$=F?.categoryName||F?.ageCategoryCode||F?.ratingType,z=d.eventName||$||`Generated ${K}`,j=p?.participants||[],tt=(E?.map(Pt=>Pt.structureProfiles||[]).flat().reduce((Pt,ae)=>{let re=!ae.participantsCount||ae.participantsCount>ae.drawSize?ae.drawSize:ae.participantsCount||0;return Pt+re},0)||0)*(q===ft?2:1),Q=(!d.participantsCount||d.participantsCount>W?W:d.participantsCount)||0,X={eventName:z,eventType:K,tieFormat:B,category:F,eventId:H,gender:V};Array.isArray(O)&&O.forEach(Pt=>zi({event:X,timeItem:Pt}));let{eventAttributes:lt}=d;if(typeof lt!="object"&&(lt={}),Object.assign(X,lt),N?.length&&Array.isArray(N)){let Pt=N.filter(wn);Pt?.length&&Object.assign(X,{extensions:Pt})}let it=[];if(n?.participantsCount===0||d.uniqueParticipants||tt||!p||V||F){let Pt=(Q||0)+P+tt,ae=Pt,re={[$t]:0,[ne]:0},pr,Jt;K===Lt&&({teamSize:pr,genders:Jt}=Al({alternatesCount:P,tieFormatName:R,tieFormat:B,drawSize:W}),Object.keys(Jt).forEach(pe=>{[$t,ne].includes(pe)&&Jt[pe]&&(re[pe]=W*Jt[pe])}),ae=pr*((W||0)+tt));let Wt=n?.idPrefix?`D-${f}-${n?.idPrefix}`:void 0,zt=sa({...n,scaledParticipantsCount:d.scaledParticipantsCount||n.scaledParticipantsCount,participantsCount:ae,consideredDate:p?.startDate,sex:V||n?.sex,rankingRange:d.rankingRange,uuids:d.uuids||g,ratingsParameters:u,participantType:q,gendersCount:re,idPrefix:Wt,category:F}).participants;if(X.category&&(X.category.categoryName=$),p){let pe=Sn({participants:zt,tournamentRecord:p});if(pe.error)return pe}if(zt.forEach(({participantId:pe})=>it.push(pe)),j=zt,K===Lt){let pe=Jt[$t]?zt.filter(({participantType:be,person:Ar})=>be===Tt&&Ar?.sex===$t).map(St):[],Pe=Jt[ne]?zt.filter(({participantType:be,person:Ar})=>be===Tt&&Ar?.sex===ne).map(St):[],Or=zt.filter(({participantType:be})=>be===Tt).map(St).filter(be=>!pe.includes(be)&&!Pe.includes(be)),Je=[...I.teamNames??[],...mm({count:Pt}).names],De=pr-(Jt[$t]+Jt[ne]),Ee=0,ge=0,_r=0,fr=et(0,Pt).map(be=>{let Ar=Pe.slice(Ee,Ee+Jt[ne]),Zi=pe.slice(ge,ge+Jt[$t]),Tn=Or.slice(_r,_r+De);Ee+=Jt[ne],ge+=Jt[$t],_r+=De;let ts=b!==!1?[...Ar,...Zi,...Tn]:[];return{participantName:Je[be]||`Team ${be+1}`,participantOtherName:`TM${be+1}`,participantRole:xe,individualParticipantIds:ts,participantType:Lt,participantId:Dt()}}),uo=Sn({participants:fr,tournamentRecord:p});if(!uo.success)return uo;j=fr}}let Rt=Pt=>{let{participantType:ae}=Pt;return ue(jn)(K)&&ae===Tt||ue(qr)(K)&&ae===ft?!0:K===Lt&&ae===Lt},Ft=Pt=>!d.gender||Pt.person?.sex===d.gender?!0:Pt.individualParticipantIds?.some(ae=>{let re=j.find(pr=>pr.participantId===ae);return re&&Ft(re)}),Ue=j.filter(Rt).filter(Ft).filter(({participantId:Pt})=>!r.includes(Pt)),fe=Ue.slice(0,Q).map(Pt=>Pt.participantId);if(m&&fe?.length){let Pt=Fn({autoEntryPositions:s,entryStage:k,tournamentRecord:p,participantIds:fe,event:X});if(Pt.error)return Pt}let Me=tt?Ue.slice(Q,Q+tt).map(Pt=>Pt.participantId):0;if(m&&Me?.length){let Pt=0,ae=1,re=(Jt,Wt)=>Jt.stageSequence-Wt.stageSequence,pr=(Jt,Wt)=>Jt.roundTarget-Wt.roundTarget;for(let Jt of E.sort(pr)){ae=Jt.roundTarget||ae;let Wt=1,mr;for(let zt of Jt.structureProfiles.sort(re)){let Pe=(zt.drawSize||hm(zt.participantsCount))-(mr||0),Or=Me.slice(Pt,Pt+Pe),Je=Fn({entryStage:ct,entryStageSequence:Wt,autoEntryPositions:s,tournamentRecord:p,participantIds:Or,roundTarget:ae,event:X});if(Je.error)return Je;mr=zt.qualifyingPositions,Pt+=Pe,Wt+=1}ae+=1}}let vr=h&&p?.participants?.filter(({participantId:Pt})=>!fe.includes(Pt)).filter(Rt).filter(Ft).slice(0,P||W-Q||y).map(Pt=>Pt.participantId);if(m&&vr?.length){let Pt=Fn({participantIds:vr,autoEntryPositions:!1,entryStatus:nn,tournamentRecord:p,event:X});if(Pt.error)return Pt.error}let Zr=$||z;p&&v&&v<=fe.length&&et(1,v+1).forEach((ae,re)=>{let pr={scaleName:Zr,scaleDate:l,scaleType:rg,scaleValue:ae,eventType:K},Jt=fe[re];Dc({tournamentRecord:p,participantId:Jt,scaleItem:pr})});let lr=xa({...J(d,!1,!0),tournamentRecord:p,seedingScaleName:Zr,matchUpFormat:S,eventId:H,isMock:m,event:X});if(lr.error)return lr;if(!lr.drawDefinition)return{error:Mr};let{drawDefinition:Xe}=lr,ee=Xe.drawId;if(Array.isArray(D)&&D.filter(wn).forEach(Pt=>At({element:Xe,extension:Pt})),A){if(Cc({drawDefinition:Xe,event:X,suppressNotifications:!0}),d.withPlayoffs){let ae=Xe.structures?.[0].structureId,re=kp({...d.withPlayoffs,tournamentRecord:p,drawDefinition:Xe,structureId:ae,idPrefix:L,isMock:m,event:X});if(re?.error)return re}let Pt=d.automated===!1;if(m&&!Pt){let ae=re=>{let pr=El({completeAllMatchUps:re.completeAllMatchUps,completionGoal:re.completionGoal,matchUpStatusProfile:o,randomWinningSide:c,tournamentRecord:p,drawDefinition:Xe,matchUpFormat:S,event:X});if(pr.error)return pr;let Jt=pr.completedCount;if(T===Io){let Wt=Xe.structures?.find(pe=>pe.stage===nt);if(!Wt)return{error:kt};Ks({structureId:Wt.structureId,tournamentRecord:p,drawDefinition:Xe,event:X});let mr=M?M-(Jt??0):void 0,zt=El({completionGoal:M?mr:void 0,matchUpStatusProfile:o,completeAllMatchUps:i,randomWinningSide:c,tournamentRecord:p,drawDefinition:Xe,matchUpFormat:S,event:X});if(zt.error)return zt}};if(M&&ae({completionGoal:M}),d.outcomes){let{matchUps:re}=or({inContext:!0,drawDefinition:Xe,event:X});for(let pr of d.outcomes){let{matchUpStatus:Jt=le,matchUpStatusCodes:Wt,stageSequence:mr=1,matchUpIndex:zt=0,structureOrder:pe,matchUpFormat:Pe,drawPositions:Or,roundPosition:Je,stage:De=nt,roundNumber:Ee,winningSide:ge,scoreString:_r}=pr,fr=re?.reduce((Tn,ts)=>{let{structureId:ju,matchUpId:iC}=ts;return Tn[ju]?Tn[ju].push(iC):Tn[ju]=[iC],Tn},{})??[],uo=Object.assign({},...Object.keys(fr).map((Tn,ts)=>({[Tn]:ts+1}))),Ar=re?.filter(Tn=>(!De||Tn.stage===De)&&(!mr||Tn.stageSequence===mr)&&(!Ee||Tn.roundNumber===Ee)&&(!Je||Tn.roundPosition===Je)&&(!pe||uo[Tn.structureId]===pe)&&(!Or||Yt(Or,Tn.drawPositions).length===2))?.[zt],Zi=EM({matchUpStatusCodes:Wt,tournamentRecord:p,drawDefinition:Xe,targetMatchUp:Ar,matchUpFormat:Pe,matchUpStatus:Jt,scoreString:_r,winningSide:ge});if(Zi?.error)return Zi}}i&&ae({completeAllMatchUps:i})}w&&oa({tournamentRecord:p,event:X})}else{let Pt=Zp({drawEntries:Xe.entries,drawName:x||T,qualifyingPositions:U,drawId:ee,event:X,stage:k});if(Pt.error)return Pt}return{...C,event:ot(X),uniqueParticipantIds:it,targetParticipants:j,drawDefinition:Xe,eventId:H,drawId:ee}}var UM=()=>({altitude:void 0,courtId:void 0,courtName:"",courtDimensions:void 0,latitude:void 0,longitude:void 0,surfaceCategory:void 0,surfaceType:void 0,surfacedDate:void 0,dateAvailability:[],onlineResources:[],pace:void 0,notes:void 0}),nw=UM;function aA(t){return parseInt(t)}function PM({startTime:t="",endTime:e=""}={}){if(!t||!e||!xs.test(t)||!xs.test(e))return!1;let[r,n]=t.split(":").map(aA),[o,i]=e.split(":").map(aA);return o<r?!1:!(r===o&&i<n)}function ow(t,e){let[r,n]=t.startTime.split(":").map(aA),[o,i]=e.startTime.split(":").map(aA);return r<o?-1:r>o?1:n<i?-1:n>i?1:0}function cA({dateAvailability:t}){if(!t)return{error:eE};if(!Array.isArray(t))return{error:ql};let e="Dates must be formated => YYYY-MM-DD",r="Times must be 24 hour => 00:00";for(let n of t){if(typeof n!="object")return{error:ql};let{date:o,startTime:i,endTime:s,bookings:a=[]}=n;if(!i||!s)return{error:ql};if(o&&!Po.test(o))return{error:je,dateAvailability:{date:o},info:e};if(!xs.test(i))return{error:Eo,dateAvailability:{startTime:i},info:r};if(!xs.test(s))return{error:Eo,dateAvailability:{endTime:s},info:r};if(i===s)return{error:Eo,dateAvailability:{startTime:i,endTime:s},info:"startTime and endTime are equivalent"};if(!PM({startTime:i,endTime:s}))return{error:Eo,dateAvailability:{startTime:i,endTime:s},info:"endTime must be after startTime"};if(a){if(!Array.isArray(a))return{error:Am};for(let c of a){if(typeof c!="object")return{error:Am};let{startTime:u,endTime:p}=c;if(!xs.test(u))return{error:Eo,booking:{startTime:u},info:r};if(!xs.test(p))return{error:Eo,booking:{endTime:p},info:r};if(u===p)return{error:Eo,dateAvailability:{startTime:u,endTime:p},info:"startTime and endTime are equivalent"};if(!PM({startTime:u,endTime:p}))return{error:Eo,dateAvailability:{startTime:u,endTime:p},info:"endTime must be after startTime"}}}}return{valid:!0}}function Ul({tournamentRecord:t,disableNotice:e,venueId:r,courtId:n,court:o}){let{venue:i}=Wo({tournamentRecord:t,venueId:r});if(!i)return{error:Li};i.courts||(i.courts=[]);let s={...UM(),venueId:r,courtId:n};if(s.courtId||(s.courtId=Dt()),i.courts.some(c=>c.courtId===s.courtId))return{error:hE};{let c=(o?.dateAvailability||[]).map(m=>({...m,date:Et(m.date),startTime:Kt(m.startTime),endTime:Kt(m.endTime),bookings:m.bookings?.map(({startTime:d,endTime:l,bookingType:f})=>({startTime:Kt(d),endTime:Kt(l),bookingType:f}))})),u=Object.keys(s);for(let m of u)if(o?.[m])if(m==="dateAvailability"){let d=cA({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||mt({payload:{venue:i,tournamentId:t.tournamentId},topic:yi,key:i.venueId}),{...C,court:J(s),venueId:r}}}function lI(t){let{tournamentRecord:e,venueId:r}=t;if(typeof r!="string"||!r)return{error:Xo};let n=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},o=[],i;for(let s of Object.values(n)){let{venue:a}=Wo({tournamentRecord:s,venueId:r});if(a){let c=B1({...t,tournamentRecord:s});for(let u of c?.courts??[])o.push(u?.courtId);if(c.error)return c;i=!0}}return i?{...C,courtIds:o}:{error:Li}}function B1({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:Xo};let l=Wo({tournamentRecord:n,venueId:m});if(l.error)return l;let{venue:f}=l;if(!Zt(s)||!o)return{error:IE};s=s??o.length;let h=et(0,s).map(S=>{let T=i?.[S],y=T?d.map(P=>({date:Hn(P),startTime:a,endTime:u,...T})):e;return T&&a&&u&&y.push({startTime:a,endTime:u}),{courtName:o[S]||r&&f?.venueAbbreviation&&`${f?.venueAbbreviation} ${S+1}`||`${t} ${S+1}`,dateAvailability:y}}).map((S,T)=>{let y=c?.pop()||p&&`${p}-${T+1}`;return Ul({disableNotice:!0,tournamentRecord:n,courtId:y,venueId:m,court:S})}).map(S=>S.court).filter(Boolean);return h.length!==s?_({info:"not all courts could be generated",result:{error:G}}):(f&&mt({payload:{venue:f,tournamentId:n.tournamentId},topic:yi,key:f.venueId}),{...C,courts:J(h)})}function Pl({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()??Dt(),dateAvailability:m,startTime:d="07:00",endTime:l="19:00",courtTimings:f,courtsCount:g,courtNames:I,venueName:h,idPrefix:S,courtIds:T}=c,y={venueName:h||`Venue ${a+1}`,venueAbbreviation:u,venueId:p},P=mc({tournamentRecord:t,venue:y});if(P.error){if(e)continue;return P}s.push(p);let U=ws(o,i),E=!Array.isArray(m)&&[{startTime:d,endTime:l}].concat(U.map(A=>({date:Hn(A),startTime:d,endTime:l})));if(g||I){let A=lI({dateAvailability:m||E,tournamentRecord:t,courtTimings:f,courtsCount:g,courtNames:I,startTime:d,idPrefix:S,courtIds:T,endTime:l,venueId:p,dates:U});if(A.error)return A}}return s}function iw(t){let{tournamentRecord:e,leagueProfiles:r,eventIds:n,venueIds:o,drawIds:i,allUniqueParticipantIds:s,uuids:a}=t,c=0;for(let p of r){let m=[],{tieFormatName:d=vm,teamProfiles:l=[],teamsCount:f=0,category:g,idPrefix:I,gender:h}=p,S=p.leagueName??p.eventName??`League ${c+1}`,T=p.leagueId??p.eventId??a?.pop()??Dt();n.push(T);let y=ht(p.tieFormat)&&p.tieFormat||Zn({event:{eventId:T,category:g,gender:h},namedFormat:d,isMock:t.isMock})||void 0;if(!y)return{error:bs};let P=Math.max(f,l.length),U=et(0,P),{genders:E,teamSize:A}=Al({tieFormat:y,drawSize:P}),N={[ne]:0,[Tr]:0,[os]:0,[$t]:0,[Pn]:0};Object.keys(E).forEach(R=>N[R]+=E[R]);for(let R of U){let b=l?.[R]?.teamName??`Team ${R+1}`,v=l?.[R]?.teamId||a?.pop()||Dt(),O=p.startDate??t.startDate,x=sa({...p?.participantsProfile,participantsCount:A,consideredDate:O,gendersCount:N,category:g,gender:h,uuids:a}).participants,F=x.map(H=>H.participantId),L=Lt,w=v??pm({participantType:L,idPrefix:I,index:R,uuids:a});m.push({participantId:w,entryStatus:kr,entryStage:nt});let V=l?.[R]?.venueIds??[],k={participantId:w,participantRole:xe,participantName:b,individualParticipantIds:F,participantType:L,homeVenueIds:V};V.forEach(H=>!o.includes(H)&&o.push(H)),s.push(...F),s.push(w);let W=Sn({participants:[k,...x],tournamentRecord:e});if(W.error)return W}let M={eventName:S,entries:m,eventType:Lt,tieFormat:y,category:g,eventId:T,gender:h};if(e.events||(e.events=[]),e.events.push(M),m.length){let R=(Zt(p.roundsCount)&&p.roundsCount)??p.roundsCount===JC?(P-1)*2:P-1,b=xa({automated:p.automated,tournamentRecord:e,drawType:$r,roundsCount:R,drawSize:P,event:M});if(b.error)return b;let{drawDefinition:v}=b;if(v){let O=v?.drawId;Cc({drawDefinition:v,event:M,suppressNotifications:!0}),i.push(O)}}c++}let u=o.map(p=>({venueId:p}));Pl({tournamentRecord:e,ignoreExistingVenues:!0,venueProfiles:u,uuids:a})}var H1=["Generated Tournament","CourtHive Challenge","Replication Crisis","Open Competition","Factory Follies","Mock Tournament","Atomic Culture","Racket Rally","Stats Fail"];function DM(t){let{startDate:e,endDate:r}=t??{},{tournamentName:n=tn(H1),ratingsParameters:o=we,tournamentExtensions:i,policyDefinitions:s,schedulingProfile:a,venueProfiles:c,uuids:u}=t??{},p=t?.isMock===!1?void 0:!0;if(e&&!Rr(e)||r&&!Rr(r))return{error:je};if(t.leagueProfiles&&!Array.isArray(t.leagueProfiles)||t.eventProfiles&&!Array.isArray(t.eventProfiles)||t.drawProfiles&&!Array.isArray(t.drawProfiles))return{error:G};if(!e){let S=new Date;e=Hn(r??S),r=Hn(S.setDate(S.getDate()+7))}if(!r){let S=new Date(e);r=Hn(S.setDate(S.getDate()+7))}let m=um({...t.tournamentAttributes??{},tournamentName:n,startDate:e,endDate:r,isMock:p}),d=c?.length?Pl({tournamentRecord:m,venueProfiles:c,uuids:u}):[];if(i?.length&&Array.isArray(i)){let S=i.filter(T=>wn({extension:T}));S?.length&&Object.assign(m,{extensions:S,isMock:p})}if(typeof s=="object")for(let S of Object.keys(s))Qi({policyDefinitions:{[S]:s[S]},tournamentRecord:m});if(!t?.leagueProfiles?.length||t.eventProfiles?.length||t.drawProfiles?.length||t.participantsProfile){let S=tA({tournamentRecord:m,...t});if(!S.success)return S}let l=[],f=[],g=[];if(t.leagueProfiles){let S=iw({allUniqueParticipantIds:l,tournamentRecord:m,...t,eventIds:f,venueIds:d,drawIds:g});if(S?.error)return S}if(t.drawProfiles){let S=W1({allUniqueParticipantIds:l,ratingsParameters:o,tournamentRecord:m,...t,eventIds:f,drawIds:g});if(S?.error)return S}if(t.eventProfiles){let S=j1({allUniqueParticipantIds:l,ratingsParameters:o,tournamentRecord:m,...t,eventIds:f,drawIds:g});if(S?.error)return S}let{scheduledRounds:I=void 0,schedulerResult:h={}}=a?Y1({...t,tournamentRecord:m}):{};return cf(),ot({...C,tournamentRecord:m,scheduledRounds:I,schedulerResult:h,eventIds:f,venueIds:d,drawIds:g})}function W1(t){let{tournamentRecord:e,drawProfiles:r,allUniqueParticipantIds:n,eventIds:o,drawIds:i}=t,s=0;for(let a of r){let c=dm({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=ra({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 j1(t){let{eventProfiles:e,allUniqueParticipantIds:r,eventIds:n,drawIds:o}=t,i=0;for(let s of e){let a=sA({...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 Y1(t){let{schedulingProfile:e,tournamentRecord:r,autoSchedule:n,periodLength:o,scheduleCompletedMatchUps:i}=t,s=rw({schedulingProfile:e,tournamentRecord:r});if(s.error)return s;let a=s.scheduledRounds;if(n){let{tournamentId:c}=r,u={[c]:r};return{schedulerResult:cm({scheduleCompletedMatchUps:i,tournamentRecords:u,periodLength:o}),scheduledRounds:a}}return{scheduledRounds:a}}var CM={};Xt(CM,{anonymizeTournamentRecord:()=>MM,modifyTournamentRecord:()=>RM});function MM({keepExtensions:t=[],anonymizeParticipantNames:e=!0,tournamentRecord:r,tournamentName:n,personIds:o=[],tournamentId:i}){if(!r)return{error:Y};let s=Array.isArray(t)?TU.concat(...t):TU,a=w=>Array.isArray(t)?w?.extensions?.filter(V=>s.includes(V.name)):w?.extensions,c={};r.extensions=a(r);let u=i||Dt();c[r.tournamentId]=u,r.tournamentId=u,r.createdAt=new Date().toISOString(),r.tournamentName=n||`Anonymized: ${Hn(new Date)}`,r.isMock=!0,delete r.parentOrganisation;for(let w of r.participants||[]){w.extensions=a(w),w.onlineResources=[];let V=Dt();c[w.participantId]=V,w.participantId=V}for(let w of r.participants||[])Array.isArray(w.individualParticipantIds)&&(w.individualParticipantIds=w.individualParticipantIds.map(V=>c[V]));let p=0;for(let w of r.venues||[]){w.venueAbbreviation=`V${p}`,w.extensions=a(w),w.venueName=`Venue #${p}`,w.onlineResources=[],w.addresses=[];let V=Dt();c[w.venueId]=V,w.isMock=!0,p+=1;let k=0;for(let W of w.courts||[])W.courtName=`V${p}C${k}`,W.extensions=a(W),W.onlineResources=[],W.isMock=!0,k+=1}let m=1;for(let w of r.events||[]){w.extensions=a(w),w.onlineResources=[],w.isMock=!0;let V=Dt();c[w.eventId]=V,w.eventId=V;let k=w.category?.categoryName||w.category?.ageCategoryCode||w.category?.ratingType||w.gender;if(w.eventName=`Event ${m} ${k}`,Array.isArray(w.entries))for(let H of w.entries)H.participantId=c[H.participantId];for(let H of w.drawDefinitions||[]){H.extensions=a(H);let K=Dt();if(c[H.drawId]=K,H.drawId=K,H.isMock=!0,Array.isArray(H.entries))for(let B of H.entries)B.participantId=c[B.participantId];let q=B=>{B.extensions=a(B);let $=Dt();c[B.structureId]=$,B.structureId=$;for(let z of B.positionAssignments||[])z.participantId&&(z.participantId=c[z.participantId]);for(let z of B.seedAssignments||[])z.participantId&&(z.participantId=c[z.participantId]);for(let z of B.matchUps||[]){z.isMock=!0;for(let j of z.sides||[])j.lineUp&&(j.lineUp=j.lineUp.map(({participantId:tt,collectionAssignments:Q})=>({participantId:c[tt],collectionAssignments:Q})))}};for(let B of H.structures||[])if(q(B),Array.isArray(B.structures))for(let $ of B.structures)q($);for(let B of H.links||[])B.source.structureId=c[B.source.structureId],B.target.structureId=c[B.target.structureId]}let{extension:W}=dt({name:un,element:w});Array.isArray(W?.value?.flights)&&W?.value.flights?.forEach(H=>{if(H.drawId=c[H.drawId],Array.isArray(H.drawEntries))for(let K of H.drawEntries)K.participantId=c[K.participantId]}),m+=1}let d=r.startDate||Hn(new Date),l=(r.participants||[]).filter(({participantType:w})=>w===Tt),f=l.reduce((w,V)=>{let k=V.person?.sex;return[$t,ne].includes(k)?w[k]+=1:w[os]+=1,w},{[$t]:0,[ne]:0,[os]:0}),g=Object.assign({},...Object.keys(f).map(w=>({[w]:Jy({category:{ageCategoryCode:"O18"},count:f[w],addressProps:{citiesCount:10},personExtensions:[],consideredDate:d,sex:w})?.persons||[]}))),I={[$t]:0,[ne]:0,[os]:0},h=l.length,S=l.reduce((w,V)=>{let k=V.person?.addresses?.[0]||{},{city:W,state:H,postalCode:K}=k;return w.cities.includes(W)||w.cities.push(W),w.states.includes(H)||w.states.push(H),w.postalCodes.includes(K)||w.postalCodes.push(K),w},{cities:[],postalCodes:[],states:[]}),T=S.postalCodes.length,y=S.cities.length,P=S.states.length,{cities:U}=$y({count:y||h,participantsCount:h}),{states:E}=Ky({count:P||h,participantsCount:h}),{postalCodes:A}=zy({count:T||h,participantsCount:h}),N={cities:U,states:E,postalCodes:A};l.forEach((w,V)=>{let k=w?.person,W=k?.sex||os,H=Et(k?.birthDate)?.split("-")[0],K=I[W],q=g[W][K];if(I[W]+=1,H){let[,B,$]=q?.birthDate?.split("-")||[],z=[H,B,$].join("-");q.birthDate=z}if(k?.addresses){let B=Qy({...N,participantIndex:V,nationalityCode:q.nationalityCode});q.addresses=[B]}q.personId=o?.[V]||Dt(),e?(q.standardFamilyName=q.lastName,q.standardGivenName=q.firstName,w.participantName=`${q.standardGivenName} ${q.standardFamilyName}`):(q.standardFamilyName=k?.standardFamilyName,q.standardGivenName=k?.standardGivenName),delete q.firstName,delete q.lastName,q.extensions=a(k),w.person=q,c[k?.personId]=q.personId}),(r.participants||[]).filter(({participantType:w})=>w===ft).forEach(w=>{let{individualParticipantIds:V}=w;w.participantName=q1({individualParticipantIds:V,individualParticipants:l})});let M=(r.participants||[]).filter(({participantType:w})=>w===Lt),R=M.length,b=mm({count:R}).names;M.forEach((w,V)=>{w.participantName=b[V]});let v=(r.participants||[]).filter(({participantType:w})=>w===zr),O=v.length,x=mm({count:O,nameRoot:"Group"}).names;v.forEach((w,V)=>{w.participantName=x[V]});let{extension:F}=dt({element:r,name:Sa});Array.isArray(F?.value)&&F?.value.forEach(w=>{w.tournamentId=c[w.tournamentId],w.structureId=c[w.structureId],w.eventId=c[w.eventId],w.drawId=c[w.drawId]});let{extension:L}=dt({element:r,name:ha});return Array.isArray(L?.value)&&L?.value.forEach(w=>{w.personId=c[w.personId]}),{...C}}function q1({individualParticipantIds:t,individualParticipants:e}){let r=e.filter(({participantId:n})=>t.includes(n)).map(({person:n})=>n?.standardFamilyName).filter(Boolean).sort().join("/");return t.length===1&&(r+="/Unknown"),r}function RM(t){let{ratingsParameters:e=we,participantsProfile:r={},matchUpStatusProfile:n,completeAllMatchUps:o,autoEntryPositions:i,hydrateCollections:s,randomWinningSide:a,schedulingProfile:c,tournamentRecord:u,autoSchedule:p,eventProfiles:m,periodLength:d,venueProfiles:l,drawProfiles:f,isMock:g,uuids:I}=t;if(!u)return{error:Y};let h=[],S=[],T=[];m?.forEach(D=>{let M=u.events?.find((R,b)=>D.eventIndex!==void 0&&b===D.eventIndex||D.eventName&&R.eventName===D.eventName||D.eventId&&R.eventId===D.eventId);M?.gender&&(D.gender=M.gender)});let y=u.participants?.length||void 0;y&&r?.idPrefix&&(r.idPrefix=`${r.idPrefix}-${y}`);let P=tA({startDate:u.startDate,participantsProfile:r,tournamentRecord:u,eventProfiles:m,drawProfiles:f,uuids:I});if(!P.success)return P;if(m){let D=u.events?.length||0;for(let M of m){let{ratingsParameters:R}=M,b=u.events?.find((v,O)=>M.eventIndex!==void 0&&O===M.eventIndex||M.eventName&&v.eventName===M.eventName||M.eventId&&v.eventId===M.eventId);if(b){let{gender:v,category:O,eventType:x}=b,{drawProfiles:F,publish:L}=M,w=ue(jn)(x)&&Tt||ue(qr)(x)&&ft||x;if(F){let{stageParticipantsCount:V,uniqueParticipantsCount:k,uniqueParticipantStages:W}=eA({drawProfiles:F,category:O,gender:v}),{uniqueDrawParticipants:H=[],uniqueParticipantIds:K=[]}=W?oA({event:{eventType:x,category:O,gender:v},uniqueParticipantsCount:k,participantsProfile:r,ratingsParameters:R,tournamentRecord:u,eventProfile:M,uuids:I}):{};h.push(...K);let{stageParticipants:q}=rA({targetParticipants:u.participants||[],allUniqueParticipantIds:h,stageParticipantsCount:V,eventParticipantType:w}),B=iA({uniqueDrawParticipants:H,autoEntryPositions:i,stageParticipants:q,tournamentRecord:u,drawProfiles:F,category:O,gender:v,event:b});if(B.error||(B=nA({matchUpStatusProfile:n,completeAllMatchUps:o,randomWinningSide:a,tournamentRecord:u,drawProfiles:F,isMock:g,event:b}),B.error))return B;T.push(...B.drawIds)}L&&oa({tournamentRecord:u,event:b})}else{let v=sA({startDate:u.startDate,allUniqueParticipantIds:h,matchUpStatusProfile:n,participantsProfile:r,completeAllMatchUps:o,autoEntryPositions:i,randomWinningSide:a,ratingsParameters:R,tournamentRecord:u,eventProfile:M,eventIndex:D,uuids:I});if(v.error)return v;let{eventId:O,drawIds:x,uniqueParticipantIds:F}=v;x&&T.push(...x),S.push(O),F?.length&&h.push(...F),D+=1}}}if(f){let D=(u.events||[]).map(M=>M.drawDefinitions?.map(()=>1)||[]).flat().reduce((M,R)=>M+R,0);for(let M of f){let R=dm({startDate:u.startDate,allUniqueParticipantIds:h,matchUpStatusProfile:n,participantsProfile:r,completeAllMatchUps:o,autoEntryPositions:i,hydrateCollections:s,randomWinningSide:a,ratingsParameters:e,tournamentRecord:u,drawProfile:M,drawIndex:D,uuids:I});if(R.error)return R;let{drawId:b,eventId:v,event:O,uniqueParticipantIds:x}=R;if(R=ra({tournamentRecord:u,event:O,internalUse:!0}),R.error)return R;b&&T.push(b),S.push(v),x?.length&&h.push(...x),D+=1}}let U=l?.length?Pl({tournamentRecord:u,venueProfiles:l}):[],E,A={};if(c?.length){let D={[u.tournamentId]:u},M=Mc({tournamentRecords:D,schedulingProfile:c});if(M.error)return M;if(p){let{tournamentId:R}=u,b={[R]:u};A=cm({tournamentRecords:b,periodLength:d})}}return{totalParticipantsCount:u.participants.length,scheduledRounds:E,schedulerResult:A,...C,eventIds:S,venueIds:U,drawIds:T}}var QM={};Xt(QM,{addDynamicRatings:()=>wg,addIndividualParticipantIds:()=>em,addParticipant:()=>bn,addParticipants:()=>Sn,addPenalty:()=>$M,addPersonRequests:()=>OM,addPersons:()=>KM,createGroupParticipant:()=>GM,createTeamsFromParticipantAttributes:()=>pI,deleteParticipants:()=>$i,filterParticipants:()=>yu,findParticipant:()=>kM,getCompetitionParticipants:()=>kT,getPairedParticipant:()=>In,getParticipantEventDetails:()=>GT,getParticipantMembership:()=>VT,getParticipantScaleItem:()=>Nc,getParticipantSchedules:()=>BT,getParticipantSignInStatus:()=>HT,getParticipantTimeItem:()=>Qh,getParticipants:()=>Gt,getScaleValues:()=>la,mergeParticipants:()=>qM,modifyIndividualParticipantIds:()=>_M,modifyParticipant:()=>rm,modifyParticipantName:()=>VM,modifyParticipantOtherName:()=>wM,modifyParticipantsSignInStatus:()=>xM,modifyPenalty:()=>jM,modifyPersonRequests:()=>bM,mutate:()=>zM,participantScaleItem:()=>yo,query:()=>iN,regenerateParticipantNames:()=>FM,removeIndividualParticipantIds:()=>cg,removeParticipantIdsFromAllTeams:()=>Rp,removePenalty:()=>WM,removePersonRequests:()=>vM,removeRatings:()=>HM,scaledTeamAssignment:()=>BM,setParticipantScaleItem:()=>Dc,setParticipantScaleItems:()=>mD,validateLineUp:()=>Td});var zM={};Xt(zM,{addDynamicRatings:()=>wg,addIndividualParticipantIds:()=>em,addParticipant:()=>bn,addParticipants:()=>Sn,addPenalty:()=>$M,addPersonRequests:()=>OM,addPersons:()=>KM,createGroupParticipant:()=>GM,createTeamsFromParticipantAttributes:()=>pI,deleteParticipants:()=>$i,findParticipant:()=>kM,mergeParticipants:()=>qM,modifyIndividualParticipantIds:()=>_M,modifyParticipant:()=>rm,modifyParticipantName:()=>VM,modifyParticipantOtherName:()=>wM,modifyParticipantsSignInStatus:()=>xM,modifyPenalty:()=>jM,modifyPersonRequests:()=>bM,regenerateParticipantNames:()=>FM,removeIndividualParticipantIds:()=>cg,removeParticipantIdsFromAllTeams:()=>Rp,removePenalty:()=>WM,removePersonRequests:()=>vM,removeRatings:()=>HM,scaledTeamAssignment:()=>BM,setParticipantScaleItem:()=>Dc,setParticipantScaleItems:()=>mD});function uA(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 pA({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===_c&&(i=Et(i),s=Kt(s),a=Kt(a),i&&s&&a)?{date:i,startTime:s,endTime:a,requestType:o.requestType}:o}).filter(Boolean);for(let o of n)o.requestId=uA(),t[e].push(o);return{mergeCount:n.length}}function Dl(t){let{tournamentRecords:e,personRequests:r}=t,n=rt(t,[{[Re]:!0}]);if(n.error)return n;if(!r)return{...C};let o=Object.values(e);for(let i of o){let s=i.participants??[],a=[];for(let c of Object.keys(r))if(Go({tournamentParticipants:s,personId:c})){let u=r[c];u.length&&a.push({personId:c,requests:u})}Object.keys(a).length&&At({element:i,extension:{value:a,name:ha}})}return{...C}}function bM(t){let{tournamentRecords:e,requests:r,personId:n}=t,o=rt(t,[{[Re]:!0},{requests:!0,[He]:Be,[Fr]:G}]);if(o.error)return o;let i=r.map(({requestId:u})=>u).filter(Boolean),{personRequests:s}=bi({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&&pA({personRequests:s,personId:n,requests:c}),Dl({tournamentRecords:e,personRequests:s})}function vM(t){let{tournamentRecords:e,requestType:r,requestId:n,personId:o,date:i}=t,s=rt(t,[{[Re]:!0}]);if(s.error)return s;let{personRequests:a}=bi({tournamentRecords:e}),c=p=>{a&&(a[p]=a[p].filter(m=>(!r||m.requestType!==r)&&(!n||m.requestId!==n)&&(!i||m.date!==i)),a?.[p]?.length||delete a[p])},u=!r&&!n&&!o&&!i;if(!u){if(o&&a?.[o])c(o);else if(a)for(let p of Object.keys(a))c(p)}return u||!a||!Object.keys(a).length?gr({name:ha,tournamentRecords:e,discover:!0}):Dl({tournamentRecords:e,personRequests:a})}function OM(t){let{tournamentRecords:e,personId:r,requests:n}=t,o=rt(t,[{[Re]:!0,[ob]:!0},{requests:!0,[He]:Be,[Fr]:G}]);if(o.error)return o;let{personRequests:i}=bi({tournamentRecords:e}),{mergeCount:s}=pA({personRequests:i,personId:r,requests:n});return s&&i?Dl({tournamentRecords:e,personRequests:i}):{error:G}}function _M({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:r}){let n="modifyIndividualParticipantIds";if(!r)return _({result:{error:Y},stack:n});if(!e||!t)return _({result:{error:st},stack:n});let o=r.participants||[],i=o.find(l=>l.participantId===e);if(!i)return _({result:{error:te},stack:n});if(![Lt,zr].includes(i.participantType))return _({result:{error:An},context:{participantType:i.participantType},stack:n});let s=t.filter(l=>o.find(g=>g.participantId===l)?.participantType!==Tt);if(s.length)return _({result:{error:wr,invalidParticipantIds:s},stack:n});let a=i.individualParticipantIds||[],c=t.filter(l=>!a.includes(l)),u=a.filter(l=>!t.includes(l)),p=em({individualParticipantIds:c,groupingParticipantId:e,tournamentRecord:r});if(p.error)return _({result:p,stack:n});let m=cg({individualParticipantIds:u,groupingParticipantId:e,tournamentRecord:r});if(m.error)return _({result:m,stack:n});let{topics:d}=Lr();if(d.includes(nr)){let l=o.find(({participantId:f})=>f===e);mt({topic:nr,payload:{tournamentId:r.tournamentId,participants:[l]}})}return{...p,...m}}function xM({tournamentRecord:t,participantIds:e,signInState:r}){if(!t)return{error:Y};if(!Array.isArray(e))return{error:st};if(![pu,LU].includes(r))return{error:G,signInState:r};let o=t.participants||[];if(!o.length)return{error:$a};let i=o.map(St),s=e.filter(p=>!i.includes(p));if(s.length)return{error:G,context:{invalidParticipantIds:s}};let a=[],c=new Date().toISOString();for(let p of o){let{participantId:m}=p;if(e.includes(m)){let l=Rg({duplicateValues:!1,tournamentRecord:t,participantId:m,timeItem:{itemType:sc,itemValue:r,createdAt:c}});if(l.error)return l;a.push(p)}}let{topics:u}=Lr();return a.length&&u.includes(nr)&&mt({topic:nr,payload:{tournamentId:t.tournamentId,participants:a}}),{...C}}function wM({tournamentRecord:t,participantId:e,participantOtherName:r}){if(!t)return{error:Y};if(!e)return{error:oe};let{participant:n}=To({tournamentRecord:t,participantId:e});if(!n)return{error:te};n.participantOtherName=r;let{topics:o}=Lr();return o.includes(nr)&&mt({topic:nr,payload:{tournamentId:t.tournamentId,participants:[n]}}),{...C}}function LM({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=AS(e?.standardGivenName??""),l=AS(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 sw({participantMap:t,participant:e,formats:r}){let{participantType:n,individualParticipantIds:o,person:i}=e,s=n&&r[n];if(n!==yr&&s){let{personFormat:a,doublesJoiner:c}=s;n===Tt&&(e.participantName=LM({person:i,personFormat:a})),n===ft&&(e.participantName=o?.map(u=>{let p=t[u]?.person;return LM({person:p,personFormat:a})}).filter(Boolean).join(c??"/"))}}function FM({tournamentRecord:t,formats:e}){if(!t)return{error:Y};if(!ht(e))return{error:st};let r=t.participants??[],n=RI(r,"participantId");for(let o of r)sw({participant:o,participantMap:n,formats:e});return{...C}}function kM(t){let{tournamentRecord:e,policyDefinitions:r,contextProfile:n,participantId:o,personId:i}=t,s=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(typeof o!="string"&&typeof i!="string")return{error:st,stack:"publicFindParticipant"};let a,c;for(let u of Object.values(s)){c=u.tournamentId;let p=u.participants||[];if(a=Go({tournamentParticipants:p,internalUse:!0,policyDefinitions:r,contextProfile:n,participantId:o,personId:i}),a)break}return{participant:a,tournamentId:c,...C}}function GM({individualParticipantIds:t=[],participantRoleResponsibilities:e,participantRole:r=aP,tournamentRecord:n,participantId:o,groupName:i}){if(!n)return{error:Y};if(!i)return{error:st,info:"Missing groupName"};if(!Array.isArray(t))return{info:"Invalid individualParticipantIds",error:G};let a=(Gt({participantFilters:{participantTypes:[Tt]},tournamentRecord:n}).participants??[]).map(m=>m.participantId);for(let m of t)if(!a.includes(m))return{error:An,participantId:m};let c=ot({participantId:o||Dt(),participantRoleResponsibilities:e,participantName:i,individualParticipantIds:t,participantType:zr,participantRole:r}),u=bn({participant:c,tournamentRecord:n});if(u.error)return u;let{topics:p}=Lr();return p.includes(Zo)&&mt({topic:Zo,payload:{tournamentId:n.tournamentId,participants:[c]}}),{...C,participant:J(c)}}function VM({tournamentRecord:t,participantName:e,participantId:r}){if(!t)return{error:Y};if(!r)return{error:oe};if(!e)return{error:st,info:"Missing participantName"};let{participant:n}=To({tournamentRecord:t,participantId:r});if(!n)return{error:te};n.participantName=e;let{topics:o}=Lr();return o.includes(nr)&&mt({topic:nr,payload:{tournamentId:t.tournamentId,participants:[n]}}),{...C}}function BM({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:Y};if(!Array.isArray(i)&&!It(u)&&!p||!It(n)||o&&!Array.isArray(o)||a&&(typeof a!="object"||!Object.keys(a).length))return{error:G};if(!a&&!o.length||!o&&!(e&&a))return{error:st,info:"Missing scaling details"};if(p&&!i){if(m?.eventType!==Cr)return{error:Bn};i=m?.entries?.filter(({entryStatus:h})=>h===kr).map(St)}if(!i?.length&&!u)return{info:"Missing teamParticipantIds or teamsCount",error:st};let d=e??o.map(({participantId:h})=>h);r&&(i?.reverse(),n+=1),n>(i?.length||0)-1&&(n=0);let l=i?.slice(n).concat(...i.slice(0,n))??[],f=[];for(let h of s.participants??[]){let{participantId:S,participantType:T}=h;if(l.includes(S)){if(T!==yr)return{error:An,participant:h};f.push(h)}}if(u&&f.length<u){let h=u-(f?.length||0),S=c??"Team",T=et(0,h).map(E=>({participantName:`${S} ${E+1}`,participantType:yr,participantRole:xe})),{participants:y=[]}=Sn({participants:T,returnParticipants:!0,tournamentRecord:s}),P=y.map(St),U=s.participants?.filter(({participantId:E})=>P.includes(E))??[];f.push(...U)}if(!f.length)return{error:ef};if(t)for(let h of f)h.individualParticipantIds=[];else{let h=f.map(S=>S).flat();e?.length?d=d.filter(S=>!h.includes(S)):o=o?.filter(({participantId:S})=>!h.includes(S))}if(!e?.length&&!o?.length)return{error:Qu,info:"Nothing to be done"};if(!o.length){for(let h of s.participants??[]){let{participantId:S,participantType:T}=h;if(!d.includes(S))continue;if(T!==Tt)return{error:An,participant:h};let y=yo({scaleAttributes:a,participant:h})?.scaleItem,P=a?.accessor?y?.scaleValue?.[a?.accessor]:y?.scaleValue,U={participantId:S,scaleValue:P};o.push(U)}if(!o.length)return{error:te}}o.sort((h,S)=>a?.sortOrder?(S?.scaleValue||0)-(h?.scaleValue||0):(h?.scaleValue||1/0)-(S?.scaleValue||1/0));for(let h of o)if(!h.participantId)return{error:G,scaledParticipant:h};let g=0;for(;g<o.length;){for(let h of f){if(g+1>o.length)break;let S=o[g];h.individualParticipantIds.push(S.participantId),g++}f.reverse()}let I=f.map(St);for(let h of s.events??[]){if(h.eventType!==Cr)continue;let S=(h.entries??[]).filter(T=>I.includes(T.participantId));for(let T of S){let y=T.participantId,U=f.find(A=>A.participantId===y)?.individualParticipantIds;h.entries=(h.entries??[]).filter(A=>!U.includes(A.participantId)),(h.drawDefinitions??[]).forEach(A=>{A.entries=(A.entries??[]).filter(N=>!U.includes(N.participantId))});let{flightProfile:E}=Ht({event:h});(E?.flights||[]).forEach(A=>{A.drawEntries=(A.drawEntries||[]).filter(N=>!U.includes(N.participantId))})}}return{...C,scaledParticipants:o}}function HM(t){let e=rt(t,[{[ie]:!0,[Pf]:!0},{ratingType:!1,[tr]:s=>we[s]}]);if(e.error)return e;let r=`${t.ratingType}.${Gm}`,n=t.asDynamic?r:t.ratingType,o=[Ii,gi,t.eventType,n].join("."),i=t.tournamentRecord.participants??[];for(let s of i)s.timeItems&&(s.timeItems=s.timeItems.filter(a=>a.itemType!==o));return{...C}}function WM(t){let{tournamentRecords:e}=t;if(typeof e!="object"||!Object.keys(e).length)return{error:wt};for(let r of Object.values(e)){let n=$1({...t,tournamentRecord:r});if(n.error&&n.error!==kc)return n}return{...C}}function $1({tournamentRecord:t,penaltyId:e}){if(!t)return{error:Y};if(!e)return{error:Xl};let r=t?.participants??[],n=[],o=!1,i;return r.forEach(s=>{let a=!1;s.penalties=(s.penalties??[]).filter(c=>(c.penaltyId===e&&(a=!0,o||(i=c,o=!0)),a&&n.push(s),c.penaltyId!==e))}),i&&mt({topic:nr,payload:{tournamentId:t.tournamentId,participants:n}}),i?{...C,penalty:i}:{error:kc}}var K1=({penaltyId:t=Dt()}={})=>({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}),mA=K1;function jM(t){let{tournamentRecords:e}=t;if(typeof e!="object"||!Object.keys(e).length)return{error:wt};for(let r of Object.values(e)){let n=z1({...t,tournamentRecord:r});if(n.error&&n.error!==kc||n.success)return n}return{error:kc}}function z1({tournamentRecord:t,modifications:e,penaltyId:r}){if(!t)return{error:Y};if(!e)return{error:G,modifications:e};if(!r)return{error:Xl};let n=t?.participants??[],o=Object.keys(mA()).filter(c=>c!=="penaltyId"),i=Object.keys(e).filter(c=>o.includes(c));if(!i.length)return{error:Ju};let s,a=[];return n.forEach(c=>{let u=!1;c.penalties=(c.penalties??[]).map(p=>(p.penaltyId===r&&(u=!0,i.forEach(m=>Object.assign(p,{[m]:e[m]})),s||(s=p)),p)),u&&a.push(c)}),s&&mt({topic:nr,payload:{tournamentId:t.tournamentId,participants:a}}),s?{...C,penalty:s}:{error:kc}}function YM(t,e,r){return!t&&e?e:t&&!e||typeof t!="object"||typeof e!="object"?t:ut(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=ut(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]=YM(t[i],e[i],r):o[i]=e[i];return o},{})}function qM({participants:t=[],tournamentRecord:e,arraysToMerge:r}){if(!e)return{error:Y};e.participants||(e.participants=[]);let n=t.filter(Br(ro)).map(u=>({[u.participantId]:u})),o=Object.assign({},...n),i=[];e.participants=e.participants.map(u=>{if(o[u.participantId]){let p=YM(u,o[u.participantId],r);return i.push(p),p}return u});let s=e.participants.map(Br(ro))||[],a=t.filter(({participantId:u})=>!s.includes(u)),{topics:c}=Lr();return a.length&&(e.participants=e.participants.concat(...a),c.includes(Zo)&&mt({topic:Zo,payload:{participants:a}})),i.length&&c.includes(nr)&&mt({topic:nr,payload:{tournamentId:e.tournamentId,participants:i}}),{modifiedParticipantsCount:i.length,newParticipantsCount:a.length,...C}}function $M(t){let{tournamentRecord:e,participantIds:r}=t,n=t.tournamentRecords??(e&&{[e.tournamentId]:e})??{},o;for(let i of Object.values(n)){let a=(Gt({tournamentRecord:i}).participants??[])?.map(St).filter(c=>r.includes(c));a.length&&(o=Q1({...t,penaltyId:t.penaltyId??o,tournamentRecord:i,participantIds:a}).penaltyId)}return o?{...C,penaltyId:o}:{error:te}}function Q1({refereeParticipantId:t,tournamentRecord:e,participantIds:r,penaltyCode:n,penaltyType:o,extensions:i,penaltyId:s,matchUpId:a,issuedAt:c,notes:u}){if(!e)return{error:Y};if(!r)return{error:oe};if(!o)return{error:gE};let m=(e?.participants??[]).filter(f=>r.includes(f.participantId));if(!m.length)return{error:te};let d=new Date().toISOString(),l=Object.assign(mA({penaltyId:s}),{refereeParticipantId:t,penaltyCode:n,penaltyType:o,matchUpId:a,createdAt:d,issuedAt:c,notes:u});return Array.isArray(i)&&i.forEach(f=>At({element:l,extension:f})),m.forEach(f=>{f.penalties||(f.penalties=[]),f.penalties.push(l)}),mt({topic:nr,payload:{tournamentId:e.tournamentId,participants:m}}),{...C,penaltyId:l.penaltyId}}function KM({participantRole:t=xe,tournamentRecord:e,persons:r}){if(!e)return{error:Y};if(!Array.isArray(r))return{error:G};if(!Object.keys(gd).includes(t))return{error:iE};let n=(e.participants||[]).map(({person:f})=>f?.personId).filter(Boolean),o=[],i=r.filter(f=>f&&(!f.personId||!n.includes(f.personId))).map(f=>(f.personId||(f.personId=Dt()),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=>ot({extensions:f.participantExtensions,timeItems:f.participantTimeItems,participantType:Tt,participantRole:t,person:s(f,["participantExtensions","participantTimeItems","pairedPersons"])})),c=0,u=0,p=Sn({participants:a,tournamentRecord:e});if(p.error)return p;u=p.addedCount||0;let m=[],d=Gt({participantFilters:{participantTypes:[Tt]},tournamentRecord:e})?.participants??[];if(t===xe&&r.filter(({pairedPersons:f})=>f).forEach(({personId:f,pairedPersons:g})=>{Array.isArray(g)&&g.forEach(I=>{let h=[f,I.personId].map(S=>Go({tournamentParticipants:d,personId:S})).filter(Boolean);if(h.length===2){let S=h.map(St);m.push(ot({extensions:I.participantExtensions,timeItems:I.timeItems,participantRole:xe,individualParticipantIds:S,participantType:ft}))}})}),m.length){if(p=Sn({participants:m,tournamentRecord:e}),p.error)return p;c=p.addedCount||0}let l=u+c;return{...C,addedCount:l,newPersonIds:o}}var iR={};Xt(iR,{bulkUpdatePublishedEventIds:()=>XT,getAllEventData:()=>JT,getCourtInfo:()=>ud,getDrawData:()=>Zd,getEventData:()=>tl,getEventPublishStatus:()=>Xr,getPublishState:()=>gs,getTournamentPublishStatus:()=>Su,getVenueData:()=>dc,mutate:()=>oR,publishEvent:()=>oa,publishEventSeeding:()=>XM,publishOrderOfPlay:()=>rR,publishParticipants:()=>eR,query:()=>lN,setEventDisplay:()=>ml,unPublishEvent:()=>nR,unPublishEventSeeding:()=>JM,unPublishOrderOfPlay:()=>tR,unPublishParticipants:()=>ZM});var oR={};Xt(oR,{publishEvent:()=>oa,publishEventSeeding:()=>XM,publishOrderOfPlay:()=>rR,publishParticipants:()=>eR,setEventDisplay:()=>ml,unPublishEvent:()=>nR,unPublishEventSeeding:()=>JM,unPublishOrderOfPlay:()=>tR,unPublishParticipants:()=>ZM});function XM({removePriorValues:t=!0,stageSeedingScaleNames:e,seedingScaleNames:r,tournamentRecord:n,status:o=Nr,drawIds:i=[],event:s}){if(!n)return{error:Y};if(!s)return{error:vt};let a=Xr({event:s,status:o}),c=(a?.seeding?.seedingScaleNames||r)&&{...a?.seeding?.seedingScaleNames,...r},u=(a?.seeding?.stageSeedingScaleNames||e)&&{...a?.seeding?.stageSeedingScaleNames,...e},p=ot({stageSeedingScaleNames:u,seedingScaleNames:c,published:!0,drawIds:i});return na({statusObject:{seeding:p},removePriorValues:t,status:o,event:s}),mt({topic:OU,payload:{tournamentId:n.tournamentId,eventId:s.eventId,drawIds:i}}),{...C}}function JM({removePriorValues:t=!0,seedingScaleNames:e,tournamentRecord:r,status:n=Nr,drawIds:o,stages:i,event:s}){if(!r)return{error:Y};if(!s)return{error:vt};let a=Xr({event:s});if(a){let c=a.seeding;if(Array.isArray(i)&&c.stageSeedingScaleNames)for(let u of i)c.stageSeedingScaleNames[u]&&delete c.stageSeedingScaleNames[u];Array.isArray(e)&&c?.seedingScaleNames&&(c.seedingScaleNames=c.seedingScaleNames.filter(u=>!e.includes(u))),Array.isArray(o)&&c?.drawIds&&(c.drawIds=c.drawIds.filter(u=>!o.includes(u))),(!Object.values(c.stageSeedingScaleNames??{}).length&&!c.seedingScaleNames?.length&&!c.drawIds?.length||!i&&!e&&!o?.length)&&(delete c.stageSeedingScaleNames,delete c.seedingScaleNames,delete c.drawIds,c.published=!1),na({statusObject:{seeding:c},removePriorValues:t,status:n,event:s})}return mt({topic:jf,payload:{tournamentId:r.tournamentId,eventId:s.eventId}}),{...C}}function ZM(t){let e=Dr(t);if(!Object.keys(e).length)return{error:wt};for(let r of Object.values(e)){let n=X1({tournamentRecord:r,...t});if(n.error)return n}return{...C}}function X1({removePriorValues:t=!0,tournamentRecord:e,status:r=Nr}){if(!e)return{error:Y};let n=`${_o}.${xo}`,{timeItem:o}=rn({element:e,itemType:n}),i=o?.itemValue||{[r]:{}};return i[r]&&delete i[r].participants,Qn({timeItem:{itemValue:i,itemType:n},element:e,removePriorValues:t}),mt({payload:{tournamentId:e.tournamentId},topic:Ib}),{...C}}function tR(t){let e=Dr(t);if(!Object.keys(e).length)return{error:wt};for(let r of Object.values(e)){let n=J1({tournamentRecord:r,...t});if(n.error)return n}return{...C}}function J1({removePriorValues:t=!0,tournamentRecord:e,status:r=Nr}){if(!e)return{error:Y};let n=`${_o}.${xo}`,{timeItem:o}=rn({element:e,itemType:n}),i=o?.itemValue||{[r]:{}};return i[r]&&delete i[r].orderOfPlay,Qn({timeItem:{itemValue:i,itemType:n},element:e,removePriorValues:t}),mt({topic:Yf,payload:{tournamentId:e.tournamentId}}),{...C}}function eR(t){let e=Dr(t);if(!Object.keys(e).length)return{error:wt};for(let r of Object.values(e)){let n=Z1({tournamentRecord:r,...t});if(n.error)return n}return{...C}}function Z1({removePriorValues:t,tournamentRecord:e,status:r=Nr}){if(!e)return{error:Y};let n=`${_o}.${xo}`,{timeItem:o}=rn({element:e,itemType:n}),i=o?.itemValue||{[r]:{}};return i[r].participants={published:!0},Qn({timeItem:{itemValue:i,itemType:n},element:e,removePriorValues:t}),mt({payload:{tournamentId:e.tournamentId},topic:xU}),{...C}}function rR(t){let e=Dr(t);if(!Object.keys(e).length)return{error:wt};for(let r of Object.values(e)){let n=t0({tournamentRecord:r,...t});if(n.error)return n}return{...C}}function t0({scheduledDates:t=[],removePriorValues:e,tournamentRecord:r,status:n=Nr,eventIds:o=[]}){if(!r)return{error:Y};let i=`${_o}.${xo}`,{timeItem:s}=rn({element:r,itemType:i}),a=s?.itemValue||{[n]:{}};return a[n].orderOfPlay={published:!0,scheduledDates:t,eventIds:o},Qn({timeItem:{itemValue:a,itemType:i},element:r,removePriorValues:e}),mt({topic:_U,payload:{tournamentId:r.tournamentId,scheduledDates:t,eventIds:o}}),{...C}}function nR({removePriorValues:t=!0,tournamentRecord:e,status:r=Nr,event:n}){if(!e)return{error:Y};if(!n)return{error:vt};let o=`${_o}.${xo}`,{timeItem:i}=du({itemType:o,event:n}),s=i?.itemValue||{[r]:{}};return delete s[r].structureIds,delete s[r].drawDetails,delete s[r].drawIds,zi({event:n,timeItem:{itemValue:s,itemType:o},removePriorValues:t}),na({statusObject:{structureIds:void 0,drawIds:void 0,seeding:void 0},removePriorValues:t,status:r,event:n}),mt({topic:Wf,payload:{tournamentId:e.tournamentId,eventId:n.eventId}}),{eventId:n.eventId,...C}}var sR={};Xt(sR,{getEntryStatusReports:()=>cw,getParticipantStats:()=>aw,getStructureReports:()=>pw,getVenuesReport:()=>mw});function aw({withCompetitiveProfiles:t,opponentParticipantId:e,withIndividualStats:r,teamParticipantId:n,tournamentRecord:o,withScaleValues:i,tallyPolicy:s,matchUps:a}){if(!o)return{error:Y};if(a&&!Array.isArray(a))return{error:dr};if(a=a??Te({tournamentRecord:o,participantsProfile:i?{withScaleValues:i}:void 0}).matchUps,!a?.length)return{error:Xn};let u=[];e&&u.push(e),n&&u.push(n);let p=u.length?{participantIds:u}:{participantTypes:[yr]},m=Gt({participantFilters:p,tournamentRecord:o}).participants??[];if(!m.every(({participantType:A})=>A===yr))return{error:wr};u.length||u.push(...m.map(St));let d=new Map,l=new Map,f=new Map,g=new Map,I=(A,N="")=>l.get(A)||l.set(A,{participantName:N,participantId:A,competitorIds:[],competitiveness:{},matchUpStatuses:{},tiebreaks:[0,0],matchUps:[0,0],points:[0,0],games:[0,0],sets:[0,0]})&&l.get(A);for(let A of m){let{participantId:N,individualParticipantIds:D}=A;g.set(N,D??[]),I(N,A.participantName)}if(n&&!g.get(n))return _({result:{error:te},context:{teamParticipantId:n}});if(e&&!g.get(e))return _({result:{error:te},context:{opponentParticipantId:e}});let h=[],S=A=>{let N=[[],[]];for(let M of A){let R=M.participant;if(R?.participantName){d.set(R.participantId,{participantName:R.participantName,ratings:R.ratings});let b=l.get(R.participantId);b&&(b.participantName=R.participantName)}}let D=({side:M,individualParticipantIds:R})=>M.participantId&&(!R?.length||R.includes(M.participantId))&&[M.participantId]||M.participant?.individualParticipantIds?.length&&(!R?.length||Yt(R,M.participant?.individualParticipantIds).length===M.participant?.individualParticipantIds?.length)&&M.participant.individualParticipantIds;if(g.size){let M=(R,b)=>{for(let v of A){if(!v.participant)continue;let O=D({individualParticipantIds:b,side:v});if(O?.length){let x=v.sideNumber;if(!x)continue;let F=[R];r&&F.push(...O),N[x-1]=F;let L=l.get(R);for(let w of O.filter(Boolean))L&&!L.competitorIds.includes(w)&&L.competitorIds.push(w)}}};if(n)(!e||A.every(b=>b.participant&&(D({individualParticipantIds:g.get(n),side:b})||D({individualParticipantIds:g.get(e),side:b}))))&&M(n,g.get(n));else for(let[R,b]of g)M(R,b)}else if(r)for(let M of A){if(!M.participant)continue;let R=D({individualParticipantIds:[],side:M}),b=M.sideNumber;b&&(N[b-1]=R)}return N};for(let A of a){if(!ht(A))return{error:dr};let{matchUpStatus:N,matchUpFormat:D,matchUpType:M,winningSide:R,score:b,sides:v}=A;if(!v||!b||M===xr||N===Nt)continue;let O=S(v);if(!O.filter(Boolean).length)continue;let x=t&&R&&gu({matchUp:A})?.competitiveness;h.push(A);let F=Dg({matchUpStatus:N,matchUpFormat:D,tallyPolicy:s,winningSide:R,score:b}),L=qS({matchUpStatus:N,matchUpFormat:D,tallyPolicy:s,winningSide:R,score:b}),{pointsTally:w,tiebreaksTally:V}=$S({matchUpFormat:D,score:b});O.forEach((k,W)=>{for(let H of k){let K=d.get(H)?.participantName,q=I(H,K);if(q){let B=(Q,X)=>X.forEach((lt,it)=>q[Q][it]+=lt),$=W?[...V].reverse():V,z=W?[...w].reverse():w,j=W?[...L].reverse():L,tt=W?[...F].reverse():F;if(B("tiebreaks",$),B("points",z),B("games",j),B("sets",tt),R){let Q=R-1===W?0:1;q.matchUps[Q]+=1}if(x){let Q=x.toLowerCase();q.competitiveness[Q]||(q.competitiveness[Q]=[0,0]),q.competitiveness[Q][W]+=1}if(N){let Q=N.toLowerCase();q.matchUpStatuses[Q]||(q.matchUpStatuses[Q]=0),q.matchUpStatuses[Q]+=1}}}})}let T=["tiebreaks","matchUps","points","games","sets"],y=["competitive","routine","decisive"],P=new Map,U=(A,N)=>(A??0)+(N??0);for(let[A,N]of l.entries()){for(let D of T){let M=N[D].reduce(U);if(M){let R=N[D][0]/M,b=`${D}Ratio`,v=parseFloat(R.toFixed(2));N[b]=v,f.set(A,!0),P.has(b)||P.set(b,[]),P.get(b)?.push(v)}}for(let D of y){let M=N.competitiveness?.[D]?.reduce(U);if(M){let R=N.competitiveness[D][0]/M,b=`${D}Ratio`,v=parseFloat(R.toFixed(2));N[b]=v}}}if(!n){let A=(N,D)=>D-N;for(let N of l.values())for(let D of T){let M=`${D}Ratio`;if(typeof N[M]=="number"){let R=P.get(M)?.sort(A).indexOf(N[M]);if(typeof R=="number"&&R>=0){let b=`${D}Rank`;N[b]=R+1}}}}let E={relevantMatchUps:h,...C};return n?(E.teamStats=l.get(n),e&&(E.opponentStats=l.get(e))):E.participatingTeamsCount=f.size,E.allParticipantStats=[...l.values()],E}function lm({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===Pg),s=i?.scaleValue,{wtnRating:a,confidence:c}=s||{};return{timeStamp:i?.scaleDate,personOtherId:n,confidence:c,wtnRating:a,personId:r,tennisId:o}}function cw({tournamentRecord:t}){if(!t)return{error:Y};let e=t.tournamentId,{participantMap:r}=Gt({withScaleValues:!0,withEvents:!0,withSeeding:!0,tournamentRecord:t,withDraws:!0}),o=(Te({matchUpFilters:{matchUpTypes:[aa,vi]},tournamentRecord:t}).matchUps??[]).flatMap(({sides:f,matchUpType:g})=>f?.flatMap(I=>g===vi?I?.participant?.individualParticipantIds:I?.participant?.participantId||I.participantId).filter(Boolean)).filter(Boolean),i=[],s={},a={},c={},u=0,p=({id:f,entry:g,eventId:I,eventType:h})=>{let{qualifyingSeeding:S,mainSeeding:T,entryStatus:y,entryStage:P,drawId:U}=g;s[f]||(s[f]=[]);let{participant:E,events:A}=r?.[f]??{},N=lm({participant:E,eventType:h}),D=A?.[I]?.ranking;y===Eg&&i.push(f),s[f].push({participantType:E?.participantType,participantId:f,tournamentId:e,eventType:h,eventId:I,drawId:U,entryStatus:y,entryStage:P,...N,ranking:D,mainSeeding:T,qualifyingSeeding:S})};for(let f of t.events??[]){let g={},I=N=>{g[N]||(g[N]={count:0}),g[N].count+=1},{drawDefinitions:h=[],eventType:S,eventId:T}=f,y=h.flatMap(N=>{let{drawId:D,entries:M}=N;u+=1;let R=({stage:F,stageSequence:L})=>F===nt&&L===1||F===ct,v=(N.structures??[]).filter(R).flatMap(({positionAssignments:F})=>F).filter(Boolean).map(({participantId:F})=>F),O=({participantId:F})=>v.includes(F),x=F=>{let{participantId:L,entryStatus:w,entryStage:V}=F;I(w);let k=r?.[L]?.draws?.[D]?.seedAssignments?.[nt];return{qualifyingSeeding:r?.[L]?.draws?.[D]?.seedAssignments?.[ct],participantId:L,mainSeeding:k,entryStatus:w,entryStage:V,drawId:D}};return M?.filter(O).map(x)}),P=N=>{let D=N.participantId,M=r?.[D].participant.individualParticipantIds?.filter(R=>o.includes(R));return D&&{[D]:{individualParticipantIds:M}}};S===ko?(()=>{let N=Object.assign({},...y.map(P).filter(Boolean)),D=M=>{N[M.participantId].individualParticipantIds.forEach(R=>{p({id:R,eventType:S,eventId:T,entry:M})})};y.forEach(D)})():y.forEach(N=>{p({id:N?.participantId,eventType:S,eventId:T,entry:N})});let E=Object.values(g).reduce((N,D)=>N+D.count,0);Object.keys(g).forEach(N=>{g[N].pct=g[N].count/E*100}),c[T]={tournamentId:e,eventId:T,entries:y,entryStatuses:g};let A=Object.assign({},...Qr.flatMap(N=>[{[N+"_count"]:g[N]?.count},{[N+"_pct"]:g[N]?.pct}]));a[T]={tournamentId:e,eventId:T,...A}}let m=Object.values(r??{}).filter(({participant:{participantType:f,participantRole:g}})=>f===Tt&&g===xe),d=m.filter(({participant:f})=>!o.includes(f.participantId)).map(({participant:f})=>f.participantId),l={nonParticipatingEntriesCount:d.length,individualParticipantsCount:m.length,eventsCount:Object.values(c).length,nonParticipatingParticipantIds:d,drawDefinitionsCount:u,tournamentId:e};return{entryStatusReports:Object.values(a).flat(),participantEntryReports:Object.values(s).flat(),eventReports:Object.values(c).flat(),withDrawnParticipantIds:i,tournamentEntryReport:l}}function uw({eventType:t,matchUps:e,eventId:r,drawId:n}){let o={},i=g=>{let I=g?.matchUpFormat;I&&(o[I]||(o[I]=0),o[I]+=1)},s=e.filter(g=>r?g.eventId===r:g.drawId===n).reduce((g,I)=>(i(I),(I.sides??[]).flatMap(h=>(h?.participant?.individualParticipants||[h?.participant]).filter(Boolean)).forEach(h=>g[h.participantId]=h),g),{}),a=Object.values(s),c=a.map(g=>lm({participant:g,eventType:t})).filter(({wtnRating:g})=>g),u=(a.length-c.length)/a.length*100,p=c.reduce((g,I)=>{let{wtnRating:h,confidence:S}=I;return g.totalWTN+=h,g.totalConfidence+=S,g},{totalWTN:0,totalConfidence:0}),m=c?.length?p.totalWTN/c.length:0,d=c?.length?p.totalConfidence/c.length:0,f=Object.values(o).reduce((g,I)=>g+(I||0),0);return{matchUpFormatCounts:o,matchUpsCount:f,avgConfidence:d,pctNoRating:u,avgWTN:m}}function pw(t){let{tournamentRecord:e,extensionProfiles:r,firstFlightOnly:n}=t;if(!e)return{error:ca};let o=[],i={},s={},a=[],c=Object.assign({},...(r??[]).map(({name:g,label:I,accessor:h})=>{let S=dt({element:e,name:g})?.extension?.value,T=h?ls({element:S,accessor:h})?.value:S;return{[I||g]:T}})),u=e?.tournamentId,m=Te({participantsProfile:{withScaleValues:!0},tournamentRecord:e}).matchUps??[],d=g=>rn({itemType:xf,itemSubTypes:[ho],element:{timeItems:g}})?.timeItem?.itemValue?.scaleBasis,l=({positionManipulations:g})=>{g?.forEach(I=>{let{structureId:h,name:S}=I,T=I.drawPositions||[I.drawPosition];i[h]||(i[h]=[]),i[h].push(`${S}: ${T.join("/")}`)})},f=e?.events?.flatMap(({timeItems:g,drawDefinitions:I=[],extensions:h,eventType:S,eventName:T,eventId:y,category:P})=>{let E=h?.find(O=>O.name===un)?.value?.flights?.map(O=>({[O.drawId]:O.flightNumber})),A=E&&Object.assign({},...E),N=h?.find(O=>O.name===Ia),D=g?.find(O=>O.itemType===Ia),M=N?.value?.length||D?.itemValue||0,R=Object.values(A??{}),b=A&&Math.min(...R),v=d(g);return s[y]={seedingBasis:v?JSON.stringify(v):void 0,totalPositionManipulations:0,maxPositionManipulations:0,generatedDrawsCount:0,drawDeletionsCount:M,tournamentId:u,eventId:y},I.filter(O=>!n||!E||A[O.drawId]===b).flatMap(O=>{let{matchUpFormat:x,tieFormat:F,timeItems:L,extensions:w,structures:V,drawName:k,drawType:W,drawId:H}=O,{matchUpFormatCounts:K,matchUpsCount:q,avgConfidence:B,pctNoRating:$,avgWTN:z}=uw({eventType:S,matchUps:m,drawId:H}),j=d(L)||v,tt=e0({extensions:w}),Q=tt?.length||0;return l({positionManipulations:tt}),s[y].totalPositionManipulations+=Q,s[y].generatedDrawsCount+=1,Q>s[y].maxPositionManipulations&&(s[y].maxPositionManipulations=Q),V?.filter(X=>X.stageSequence===1&&[ct,nt,qe,de].includes(X.stage)).map(X=>{let lt=[nt,de].includes(X.stage)?m.find(Ar=>Ar.structureId===X.structureId&&Ar.finishingRound===1&&Ar.winningSide):void 0;X.stage===nt&&o.push({eventName:T,drawName:k,structureId:X.structureId});let Rt=lt?.sides?.find(Ar=>Ar.sideNumber===lt.winningSide)?.participant,Ft=Rt?.participantType===yr&&Rt.participantId,Ue=Rt?.participantType===ft?Rt.individualParticipants:[],fe=lm({participant:Ue?.[0]||Rt,eventType:S}),{personId:Me,personOtherId:vr,tennisId:Zr,confidence:lr,wtnRating:Xe}=fe||{},ee=lm({participant:Ue?.[1],eventType:S}),{personId:Pt,personOtherId:ae,tennisId:re,confidence:pr,wtnRating:Jt}=ee||{},{ageCategoryCode:Wt,categoryName:mr,subType:zt}=P??{},pe=X.matchUpFormat||x,Or=(K[pe]||0)/q*100,{tieFormatName:Je,tieFormatDesc:De}=Jd(F),{tieFormatName:Ee,tieFormatDesc:ge}=Jd(X.tieFormat),_r=De===ge,fr=!_r&&Ee,uo=X.tieFormat&&!_r&&ge,be=tt?.filter(Ar=>Ar.structureId===X.structureId)?.length||0;return{...c,tournamentId:u,eventId:y,structureId:X.structureId,drawId:H,eventType:S,category:zt,categoryName:mr,ageCategoryCode:Wt,flightNumber:A?.[H],drawType:W,stage:X.stage,seedingBasis:j?JSON.stringify(j):void 0,winningPersonId:Me,winningPersonOtherId:vr,winningPersonTennisId:Zr,winningPersonWTNrating:Xe,winningPersonWTNconfidence:lr,winningPerson2Id:Pt,winningPerson2OtherId:ae,winningPerson2TennisId:re,winningPerson2WTNrating:Jt,winningPerson2WTNconfidence:pr,winningTeamId:Ft,positionManipulations:be,pctNoRating:$,matchUpFormat:pe,pctInitialMatchUpFormat:Or,matchUpsCount:q,drawTieFormatName:Je,drawTieFormatDesc:De,tieFormatName:fr,tieFormatDesc:uo,avgConfidence:B,avgWTN:z}})})});return o.forEach(({eventName:g,drawName:I,structureId:h})=>{i[h]?.length&&a.push({eventName:g,drawName:I,actions:i[h]})}),{eventStructureReports:Object.values(s),structureReports:f,flightReports:a}}function e0({extensions:t}){return t?.find(({name:e})=>e===nc)?.value?.slice(1)}function mw({ignoreDisabled:t=!0,tournamentRecords:e,tournamentId:r,venueIds:n=[],dates:o=[]}){if(!Array.isArray(o))return{error:G,dates:o};if(!Array.isArray(n))return{error:G,venueIds:n};if(!(e&&Object.keys(e).filter(l=>!r||l===r)||[]).length)return{error:wt};if(!o.every(Rr))return{error:je};let a=Ao({tournamentRecords:e,ignoreDisabled:t,dates:o});if(a.error)return a;let c=a?.venues?.filter(({venueId:l})=>!n?.length||n.includes(l)),u=a.courts?.reduce((l,f)=>(f.dateAvailability?.forEach(g=>{let I=g.date;l.includes(I)||l.push(I)}),l),[]).filter(l=>!o.length||o.includes(l)),p={venueIds:c?.map(({venueId:l})=>l)},{matchUps:m}=Un({afterRecoveryTimes:!0,tournamentRecords:e,matchUpFilters:p});return{venuesReport:c?.map(l=>r0(u,l,m))}}function r0(t,e,r){let{venueId:n,courts:o,venueName:i}=e,s={};return t.forEach(a=>{let c=0,u=0,p=0;for(let l of o){let f=l.dateAvailability.find(h=>h.date===a),I=(f&&Ns({courtDate:f}).timeSlots)?.reduce((h,S)=>{let{startTime:T,endTime:y}=S,P=qt(y)-qt(T);return h+P},0);I&&(p+=1),c+=I}let m=r.filter(({schedule:l})=>l.venueId===n&&Wn(a,l.scheduledDate));m.forEach(({schedule:l})=>{let f=Kt(l.scheduledTime),g=Yr(f,l.averageMinutes),I=qt(g)-qt(f);u+=I});let d=c?(u/c*100).toFixed(2):"100";s[a]={scheduledMatchUpsCount:m.length,availableCourts:p,availableMinutes:c,scheduledMinutes:u,percentUtilization:d}}),{venueId:n,venueName:i,venueReport:s}}var SR={};Xt(SR,{addMatchUpCourtOrder:()=>ky,addMatchUpEndTime:()=>Vy,addMatchUpOfficial:()=>cM,addMatchUpResumeTime:()=>Hy,addMatchUpScheduleItems:()=>im,addMatchUpScheduledDate:()=>nm,addMatchUpScheduledTime:()=>zo,addMatchUpStartTime:()=>Gy,addMatchUpStopTime:()=>By,addSchedulingProfileRound:()=>dI,allocateTeamMatchUpCourts:()=>om,assignMatchUpCourt:()=>Xi,assignMatchUpVenue:()=>ia,bulkRescheduleMatchUps:()=>lR,bulkScheduleMatchUps:()=>xc,bulkScheduleTournamentMatchUps:()=>Vu,bulkUpdateCourtAssignments:()=>uR,calculateScheduleTimes:()=>gI,clearMatchUpSchedule:()=>gR,clearScheduledMatchUps:()=>am,courtGridRows:()=>nl,findMatchUpFormatTiming:()=>Kp,findVenue:()=>Wo,generateBookings:()=>sm,generateVirtualCourts:()=>tm,getMatchUpsToSchedule:()=>el,getPersonRequests:()=>bi,getProfileRounds:()=>rl,getScheduledRoundsDetails:()=>Lu,getSchedulingProfile:()=>Ko,getSchedulingProfileIssues:()=>ty,matchUpScheduleChange:()=>fR,modifyMatchUpFormatTiming:()=>$g,mutate:()=>hR,proAutoSchedule:()=>cR,proConflicts:()=>mR,publicFindCourt:()=>lS,query:()=>hN,removeEventMatchUpFormatTiming:()=>pl,removeMatchUpCourtAssignment:()=>aR,reorderUpcomingMatchUps:()=>dR,scheduleMatchUps:()=>pR,scheduleProfileRounds:()=>cm,setMatchUpDailyLimits:()=>IR,setMatchUpHomeParticipantId:()=>oI,setSchedulingProfile:()=>Mc,toggleParticipantCheckInState:()=>ll,validateSchedulingProfile:()=>zp});var hR={};Xt(hR,{addMatchUpCourtOrder:()=>ky,addMatchUpEndTime:()=>Vy,addMatchUpOfficial:()=>cM,addMatchUpResumeTime:()=>Hy,addMatchUpScheduleItems:()=>im,addMatchUpScheduledDate:()=>nm,addMatchUpScheduledTime:()=>zo,addMatchUpStartTime:()=>Gy,addMatchUpStopTime:()=>By,addSchedulingProfileRound:()=>dI,allocateTeamMatchUpCourts:()=>om,assignMatchUpCourt:()=>Xi,assignMatchUpVenue:()=>ia,bulkRescheduleMatchUps:()=>lR,bulkScheduleMatchUps:()=>xc,bulkScheduleTournamentMatchUps:()=>Vu,bulkUpdateCourtAssignments:()=>uR,calculateScheduleTimes:()=>gI,clearMatchUpSchedule:()=>gR,clearScheduledMatchUps:()=>am,findMatchUpFormatTiming:()=>Kp,generateBookings:()=>sm,generateVirtualCourts:()=>tm,matchUpScheduleChange:()=>fR,modifyMatchUpFormatTiming:()=>$g,proAutoSchedule:()=>cR,proConflicts:()=>mR,removeEventMatchUpFormatTiming:()=>pl,removeMatchUpCourtAssignment:()=>aR,reorderUpcomingMatchUps:()=>dR,scheduleMatchUps:()=>pR,scheduleProfileRounds:()=>cm,setMatchUpDailyLimits:()=>IR,setMatchUpHomeParticipantId:()=>oI,setSchedulingProfile:()=>Mc,toggleParticipantCheckInState:()=>ll,validateSchedulingProfile:()=>zp});function gI({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:wt};s=s??ku({recoveryMinutes:e,averageMatchUpMinutes:r});let{courts:m,venues:d}=Ao({dates:[a],ignoreDisabled:!0,tournamentRecords:i}),l=m?.filter(M=>!u||u.includes(M.venueId));c||(c=l?.reduce((M,R)=>{let v=R.dateAvailability?.find(O=>!O.date||Wn(a,O.date))?.startTime??R.startTime;return v&&(!M||qt(v)<qt(M))?v:M},void 0)),p||(p=l?.reduce((M,R)=>{let v=R.dateAvailability?.find(O=>!O.date||Wn(a,O.date))?.endTime??R.endTime;return v&&(!M||qt(v)>qt(M))?v:M},void 0));let f=Object.values(i),g=Object.assign({},...f.map(M=>(M.events??[]).map(R=>{let{scheduleTiming:b}=ya({tournamentRecord:M,event:R});return{[R.eventId]:{event:R,scheduleTiming:b}}})).flat()),h=Fu({sortDateMatchUps:!1,tournamentRecords:i,matchUpFilters:{scheduledDate:a,venueIds:u}}),S=h?.dateMatchUps??[],T=h?.completedMatchUps??[],y=[];y.push(...S),y.push(...T);let P={averageTimes:[{minutes:{default:r}}],recoveryTimes:[{minutes:{default:e}}]},U=y?.map(({eventId:M,schedule:R,matchUpFormat:b})=>{let{event:v,scheduleTiming:O}=g[M],x=v?.eventType,F={...O,defaultTiming:P,matchUpFormat:b},{averageMinutes:L,recoveryMinutes:w}=Pp({eventType:x,timingDetails:F}),{courtId:V,venueId:k}=R,W=Kt(R.scheduledTime),H=Yr(W,L);return{recoveryMinutes:w,averageMinutes:L,periodLength:s,startTime:W,endTime:H,courtId:V,venueId:k}}),E={calculateStartTimeFromCourts:t,remainingScheduleTimes:n,averageMatchUpMinutes:r,date:a,clearScheduleDates:o,periodLength:s,startTime:c,endTime:p,bookings:U,courts:l},{scheduleTimes:A}=dl(E),N=u?.length===1&&u[0]||d?.length===1&&d[0].venueId||void 0,D=y.map(Ae);return{venueId:N,scheduleTimes:A,dateScheduledMatchUpIds:D}}function aR(t){let e=rt(t,[{[Re]:!0}]);if(e.error)return e;let{removePriorValues:r,tournamentRecords:n,tournamentId:o,courtDayDate:i,matchUpId:s,courtId:a,drawId:c}=t,u=n[o];if(!u)return{error:Y};let{drawDefinition:p,event:m}=wo({tournamentRecord:u,drawId:c});if(!p)return{error:Z};let d=Bt({drawDefinition:p,event:m,matchUpId:s});if(d.error)return d;if(d?.matchUp?.matchUpType===xr){let{itemValue:l}=Ho({timeItems:d.matchUp.timeItems??[],itemType:so}),f=a&&l.filter(I=>I.courtId!==a);return Jr({duplicateValues:!1,removePriorValues:r,tournamentRecord:u,drawDefinition:p,matchUpId:s,timeItem:{itemType:so,itemValue:f}})}else return Xi({tournamentRecord:u,drawDefinition:p,courtDayDate:i,courtId:"",matchUpId:s})}function cR({scheduleCompletedMatchUps:t,tournamentRecords:e,scheduledDate:r,matchUps:n}){if(!Vr(n))return{error:G};if(n.some(({hasContext:g})=>!g))return{info:"matchUps must have { inContext: true, nextMatchUps: true }",error:Gc};let i=Fu({courtCompletedMatchUps:!0,withCourtGridRows:!0,minCourtGridRows:10,tournamentRecords:e,matchUpFilters:{localPerspective:!0,scheduledDate:r}});if(i.error)return i;let{rows:s}=i,a=[],c=g=>[(g.sides||[]).map(I=>[I.participantId,I.participant?.individualParticipantIds]),(g.potentialParticipants||[]).flat().map(I=>[I.participantId,I.individualParticipantIds])].flat(1/0).filter(Boolean),u=s?.reduce((g,I)=>{let h=[],S=[];Object.values(I).forEach(y=>{if(ht(y)&&(y.matchUpId&&(h.push(y.matchUpId),a.push(y)),y.sides)){let P=c(y);S.push(...P)}});let T=Object.values(I).filter(y=>ht(y)&&!y.matchUpId);return g.concat({matchUpIds:h,availableCourts:T,rowId:I.rowId,participantIds:S})},[]);n.filter(({matchUpStatus:g})=>g&&g!==Nt&&(t||!ce.includes(g))).sort(Mi);let p=sn({matchUps:n.concat(a),includeParticipantDependencies:!0,tournamentRecords:e}).matchUpDependencies,m=[],d=[];for(;n.length&&u.length;){let g=u.shift(),I=[];for(;n.length&&g.availableCourts.length;){let h=n.concat(I).map(D=>D.matchUpId),S=n.shift(),T=S?.matchUpId,y=T&&p[T].matchUpIds.concat(p[T].dependentMatchUpIds),P=T&&h.some(D=>p[T].matchUpIds.includes(D)),U=T&&d.some(D=>p[T].dependentMatchUpIds.includes(D)),E=g.matchUpIds.some(D=>y.includes(D)),A=c(S),N=g.participantIds.some(D=>A.includes(D));if(S&&!E&&!P&&!N&&!U){let D=g.availableCourts.shift();Object.assign(S.schedule,D.schedule),Object.assign(D,S),m.push(S),g.participantIds.push(...A),g.matchUpIds.push(T)}else S&&I.push(S)}n.push(...I),d.push(...g.matchUpIds)}let l=m.map(({matchUpId:g,tournamentId:I,schedule:h,drawId:S})=>({tournamentId:I,matchUpId:g,drawId:S,schedule:{...h,scheduledDate:r}}));return i=xc({tournamentRecords:e,matchUpDetails:l}),{...i,scheduled:m,notScheduled:n}}function uR(t){let{courtDayDate:e}=t,r=rt(t,[{courtAssignments:!0,[He]:Be,[Fr]:st},{[Re]:!0}]);if(r.error)return r;let n=t.courtAssignments.reduce((s,a)=>{let{tournamentId:c}=a;return s[c]||(s[c]=[]),s[c].push(a),s},{}),o;return Object.keys(n).every(s=>{let a=t[Re][s];if(!a)return o={error:Y},!1;let c=n[s].reduce((p,m)=>{let{drawId:d}=m;return p[d]||(p[d]=[]),p[d].push(m),p},{});Object.keys(c).every(p=>{let{drawDefinition:m}=ze({tournamentRecord:a,drawId:p});return m?(c[p].every(d=>{let{matchUpId:l,courtId:f}=d,g=Xi({tournamentRecord:a,drawDefinition:m,courtDayDate:e,matchUpId:l,courtId:f});if(g.success)return g?.success;o={error:DE}}),!0):(o={error:Z},!1)})}),o||C}function pR(t){let{tournamentRecords:e,allDateMatchUpIds:r=[],averageMatchUpMinutes:n=90,recoveryMinutes:o=0,recoveryMinutesMap:i,matchUpPotentialParticipantIds:s={},individualParticipantProfiles:a={},matchUpNotBeforeTimes:c={},matchUpDailyLimits:u={},checkPotentialRequestConflicts:p=!0,remainingScheduleTimes:m,clearScheduleDates:d,periodLength:l=30,scheduleDate:f,matchUpIds:g,venueIds:I,startTime:h,endTime:S,dryRun:T}=t,y=rt(t,[{[Re]:!0,[ec]:!0},{[tr]:Rr,[Fr]:je,[eb]:!0},{[tr]:B=>!B||!isNaN(B),[ib]:!1,[Fr]:G,[sb]:!1,[ab]:!1}]);if(y.error)return y;let P=t.competitionMatchUps??Un({nextMatchUps:!0,tournamentRecords:e}).matchUps??[],U=t.matchUpDependencies??sn({includeParticipantDependencies:!0,matchUps:P,tournamentRecords:e}).matchUpDependencies;P.forEach(B=>{B.schedule?.scheduledDate&&Wn(f,Et(B.schedule.scheduledDate))&&ea({matchUpPotentialParticipantIds:s,matchUpNotBeforeTimes:c,matchUp:B})});let E=g.map(B=>P.find($=>$.matchUpId===B)).filter(Boolean),{venueId:A,scheduleTimes:N,dateScheduledMatchUpIds:D}=gI({tournamentRecords:e,remainingScheduleTimes:m,startTime:Kt(h),endTime:Kt(S),scheduleDate:Et(f),averageMatchUpMinutes:n,clearScheduleDates:d,periodLength:l,venueIds:I}),M={},R=[],b={},v={},O={};P.filter(({matchUpId:B})=>D?.includes(B)).forEach(B=>{uI({matchUpPotentialParticipantIds:s,individualParticipantProfiles:a,matchUp:B,value:1});let $=B.schedule?.scheduledTime;if($){b[B.matchUpId]=$;let z=i?.[B.matchUpId];Oc({recoveryMinutes:z||o,matchUpPotentialParticipantIds:s,individualParticipantProfiles:a,matchUpNotBeforeTimes:c,averageMatchUpMinutes:n,matchUpDependencies:U,scheduleTime:$,matchUp:B})}});let F=E.filter(B=>{let $=D?.includes(B.matchUpId),z=[Nt,Mt,le,br,rr,Ct].includes(B?.matchUpStatus);return!$&&!B.winningSide&&!z}),{matchUpMap:L,overLimitMatchUpIds:w,participantIdsAtLimit:V}=F.reduce((B,$)=>{let{drawId:z,tournamentId:j,matchUpType:tt}=$,{participantIdsAtLimit:Q,relevantParticipantIds:X}=yl({individualParticipantProfiles:a,matchUpPotentialParticipantIds:s,matchUpDailyLimits:u,matchUp:$});return Q?.length?(B.overLimitMatchUpIds.push($.matchUpId),B.participantIdsAtLimit.push(...Q),B):(X.forEach(lt=>{Fa({individualParticipantProfiles:a,participantId:lt});let it=a[lt].counters;it[tt]?it[tt]+=1:it[tt]=1,it[ao]?it[ao]+=1:it[ao]=1}),B.matchUpMap[j]||(B.matchUpMap[j]={}),B.matchUpMap[j][z]?B.matchUpMap[j][z].push($):B.matchUpMap[j][z]=[$],ea({matchUpPotentialParticipantIds:s,matchUpNotBeforeTimes:c,matchUp:$}),B)},{matchUpMap:{},overLimitMatchUpIds:[],participantIdsAtLimit:[]});F=F.filter(({matchUpId:B})=>!w.includes(B));let k=0,W=N?.length??0,{personRequests:H}=bi({tournamentRecords:e,requestType:_c});for(;N?.length&&F.length&&k<=W;){k++;let{scheduleTime:B}=N.shift(),$=F.find(z=>{let{matchUpId:j}=z,{dependenciesScheduled:tt,remainingDependencies:Q}=hl({matchUpScheduleTimes:b,matchUpDependencies:U,allDateMatchUpIds:r,matchUp:z});if(!tt)return O[j]||(O[j]=[]),O[j].push({scheduleTime:B,remainingDependencies:Q}),!1;let{enoughTime:X}=Tl({individualParticipantProfiles:a,matchUpNotBeforeTimes:c,matchUpDependencies:U,scheduleTime:B,matchUp:z});if(!X)return v[j]||(v[j]=[]),v[j].push({scheduleTime:B}),!1;let{conflicts:lt}=Sl({potentials:p,averageMatchUpMinutes:n,requestConflicts:M,personRequests:H,scheduleTime:B,scheduleDate:f,matchUp:z});if(lt?.length)return!1;let it=i?.[z.matchUpId];return Oc({recoveryMinutes:it||o,matchUpPotentialParticipantIds:s,individualParticipantProfiles:a,matchUpNotBeforeTimes:c,averageMatchUpMinutes:n,matchUpDependencies:U,scheduleTime:B,matchUp:z}),b[z.matchUpId]=B,!0});F=F.filter(({matchUpId:z})=>z!==$?.matchUpId),$||R.push(B)}F.forEach(B=>{uI({individualParticipantProfiles:a,matchUpPotentialParticipantIds:s,value:-1,matchUp:B})});let K=[];Object.keys(L).forEach(B=>{let $=e[B];$&&Object.keys(L[B]).forEach(z=>{let{drawDefinition:j}=wo({tournamentRecord:$,drawId:z});j&&L[B][z].forEach(({matchUpId:Q})=>{let X=b[Q];if(X){let lt=X.split(":").map(Jn).join(":"),it=`${Et(f)}T${lt}`;T?K.push(Q):(zo({drawDefinition:j,matchUpId:Q,scheduledTime:it}).success&&K.push(Q),A&&ia({tournamentRecords:e,tournamentRecord:$,drawDefinition:j,matchUpId:Q,venueId:A}))}})})});let q=$m(F);return{...C,requestConflicts:Object.values(M),remainingScheduleTimes:N?.map(({scheduleTime:B})=>B),individualParticipantProfiles:a,matchUpNotBeforeTimes:c,participantIdsAtLimit:V,skippedScheduleTimes:R,overLimitMatchUpIds:w,scheduledMatchUpIds:K,noTimeMatchUpIds:q,recoveryTimeDeferred:v,dependencyDeferred:O}}function mR({tournamentRecords:t,matchUps:e}){if(!Vr(e))return{error:Xn};if(e.some(({matchUpId:f,hasContext:g})=>f&&!g))return{info:"matchUps must have { inContext: true, nextMatchUps: true }",error:Gc};let r=Math.max(...e.map(({schedule:f})=>f?.courtOrder||1).map(f=>pt(f))),n=et(1,r+1).map(f=>e.filter(g=>pt(g.schedule?.courtOrder)===f)),o={},i={},s={};n.flat().filter(Boolean).sort(Mi).forEach(({schedule:f})=>delete f[ng]);let c=ut(e.map(({drawId:f})=>f)),u=sn({includeParticipantDependencies:!0,tournamentRecords:t,drawIds:c}).matchUpDependencies,p=n.map((f,g)=>f.reduce((I,h)=>{if(!h.matchUpId)return I;let{matchUpId:S,winnerMatchUpId:T,loserMatchUpId:y,schedule:P,sides:U,potentialParticipants:E}=h,A=P?.courtId;o[S]=g,i[A]=[],I.matchUpIds.push(S),s[S]=h;let N=u[S].matchUpIds;N.length&&I.sourceMatchUpIds.push(...N);let D=U?.map(R=>[R.participant?.individualParticipantIds,R.participantId]).flat().filter(Boolean)??[],M=E?.flat().map(({individualParticipantIds:R,participantId:b})=>[R,b]).flat().filter(Boolean)||[];return I.participantIds.push(...M,...D),T&&I.targetMatchUpIds.push(T),y&&I.targetMatchUpIds.push(y),I},{sourceMatchUpIds:[],targetMatchUpIds:[],participantIds:[],matchUpIds:[]})),m=(f,g)=>u[f].sources.reduce((I,h,S)=>h.includes(g)&&S+1||I,0),d=p.map(()=>[]),l=(f,g,I,h)=>{if(!s[f].schedule[ng]){s[f].schedule[ng]=g,s[f].schedule[qU]=h,d[o[f]].push({matchUpId:f,issueType:I,issueIds:h,issue:g});let S=s[f].schedule.courtId;i[S]||(i[S]=[]),i[S].push({matchUpId:f,issue:g,issueType:I,issueIds:h})}};return p.forEach((f,g)=>{let I=g?p[g-1]:void 0,h=p.slice(g+1),S={},T=Sr(f.participantIds),y=Object.keys(T).filter(E=>T[E]>1),P=f.matchUpIds.filter(E=>u[E].participantIds.some(A=>y.includes(A)));P.forEach(E=>{S[E]||(S[E]={}),S[E][uc]||(S[E][uc]=P.filter(A=>A!==E))});let U=I&&f.participantIds.filter(E=>I.participantIds.includes(E));U&&U.forEach(E=>{let A=f.matchUpIds.concat(I.matchUpIds).filter(N=>u[N].participantIds.includes(E));A.forEach(N=>{S[N]||(S[N]={}),S[N][pc]||(S[N][pc]=A.filter(D=>D!==N))})}),f.matchUpIds.forEach(E=>{let A=u[E].matchUpIds;for(let D of h){let M=D.matchUpIds.filter(R=>A.includes(R));M?.length&&(M.forEach(R=>l(R,uS,Aa,[E])),l(E,uS,Aa,M))}if(S[E]?.[uc]&&l(E,uc,cS,S[E][uc]),f.sourceMatchUpIds.includes(E)){let D=f.matchUpIds.filter(M=>u[M].matchUpIds.includes(E));l(E,uc,Aa,D),f.matchUpIds.filter(M=>u[M].matchUpIds.includes(E)).forEach(M=>l(M,uc,Aa,[E]))}let N=I?.matchUpIds?.filter(D=>m(E,D)>1);if(N?.length&&(l(E,pS,Aa,N),N.forEach(D=>l(D,pS,Aa,[E]))),S[E]?.[pc]&&l(E,pc,cS,S[E][pc]),I?.targetMatchUpIds?.includes(E)){let D=s[E].schedule.courtId,M=A.filter(b=>I.matchUpIds.includes(b));M.some(b=>s[b].schedule.courtId===D)||(M.forEach(b=>l(b,pc,Aa,[E])),l(E,pc,Aa,M))}})}),{courtIssues:i,rowIssues:d}}function dR(t){let e="reorderUpcomingMatchUps",{tournamentRecords:r}=t;if(typeof r!="object"||!Object.keys(r).length)return _({result:{error:wt},stack:e});let{matchUpsContextIds:n,firstToLast:o}=t;if(!n)return _({result:{error:st},stack:e});let i=n?.length;if(!i)return{...C};let s=0;return n.forEach((c,u)=>{let{tournamentId:p,drawId:m,matchUpId:d}=c,l=u+(o?-1:1);l<0&&(l=i-1),l===i&&(l=0);let f=n[l].schedule.scheduledTime,g=a({tournamentId:p,scheduledTime:f,matchUpId:d,drawId:m});if(g.success)s++;else return g}),s===i?C:_({result:{error:PE},stack:e});function a({tournamentId:c,scheduledTime:u,matchUpId:p,drawId:m}){let d=r[c],{drawDefinition:l}=wo({tournamentRecord:d,drawId:m});return l?zo({drawDefinition:l,scheduledTime:u,matchUpId:p}):{error:Mr}}}function lR(t){let{scheduleChange:e,matchUpIds:r,dryRun:n}=t;if(!r||!Array.isArray(r))return{error:rs};if(typeof e!="object")return{error:G};let o=Dr(t),i=[],s=[];for(let c of Object.values(o)){let u=n0({tournamentRecord:c,scheduleChange:e,matchUpIds:r,dryRun:n});if(u.error)return u;Array.isArray(u.notRescheduled)&&s.push(...u.notRescheduled);let p=$m(u.notRescheduled),m=[];u.rescheduled?.forEach(d=>{let{matchUpId:l}=d;p.includes(l)&&m.push(l),i.push(d)}),m.length&&(s=u?.notRescheduled?.filter(({matchUpId:d})=>!m.includes(d))||[])}let a=!!(i.length&&!s.length);return{...C,rescheduled:i,notRescheduled:s,allRescheduled:a}}function n0({tournamentRecord:t,scheduleChange:e,matchUpIds:r,dryRun:n}){if(!t)return{error:Y};if(!r||!Array.isArray(r))return{error:rs};if(typeof e!="object")return{error:G};let o=[],i=[],{minutesChange:s,daysChange:a}=e;if(!s&&!a)return{...C};if(s&&isNaN(s))return{error:G};if(a&&isNaN(a))return{error:G};let{matchUps:c}=Te({matchUpFilters:{matchUpIds:r},tournamentRecord:t}),u=({matchUpStatus:y})=>!ce.includes(y),p=c?.filter(y=>_a({schedule:y.schedule})).filter(y=>u({matchUpStatus:y.matchUpStatus}));if(!p?.length)return{...C};let{tournamentInfo:m}=Us({tournamentRecord:t}),{startDate:d,endDate:l}=m,f=p?.reduce((y,P)=>{let{matchUpId:U,drawId:E}=P;return y[E]?y[E].push(U):y[E]=[U],y},{}),g=1440;for(let y of Object.keys(f)){let P=wo({tournamentRecord:t,drawId:y});if(P.error)return P;let U=P.drawDefinition,E=f[y].filter(A=>r.includes(A));for(let A of E)if(A&&U){let D=p.find(x=>x.matchUpId===A)?.schedule,{scheduledTime:M,scheduledDate:R}=D,b,v,O;if(!b&&a&&R){let x=Et(R);O=sp(x,a),b=new Date(O)<new Date(d)||new Date(O)>new Date(l)}if(s&&M){let x=Et(M),L=qt(Kt(M))+s;if(b=L<0||L>g,!b){let w=Yr(M,s),V=x&&O||R===x&&x;v=V?`${V}T${w}`:w}}if(b)i.push(A);else{if(!n){if(v){let x=zo({scheduledTime:v,drawDefinition:U,matchUpId:A});if(x.error)return x}if(O){let x=nm({scheduledDate:O,drawDefinition:U,matchUpId:A});if(x.error)return x}}(v||O)&&o.push(A)}}}let I=Te({matchUpFilters:{matchUpIds:r},tournamentRecord:t}).matchUps??[],h=I.filter(({matchUpId:y})=>o.includes(y)),S=I.filter(({matchUpId:y})=>i.includes(y)),T=h.length&&!S.length;return{...C,rescheduled:h,notRescheduled:S,allRescheduled:T}}function fR(t){let e="matchUpScheduleChange",{tournamentRecords:r}=t;if(typeof r!="object"||!Object.keys(r).length)return{error:wt};let{sourceMatchUpContextIds:n,targetMatchUpContextIds:o,sourceCourtId:i,targetCourtId:s,courtDayDate:a}=t||{},{drawId:c,matchUpId:u,tournamentId:p}=n||{},{drawId:m,matchUpId:d,tournamentId:l}=o||{};if(!u&&!d)return _({result:{error:st},stack:e});let{matchUps:f}=Un({matchUpFilters:{matchUpIds:[u,d].filter(Boolean),drawIds:[c,m].filter(Boolean)},tournamentRecords:t.tournamentRecords}),g=f?.find(({matchUpId:y})=>y===u),I=f?.find(({matchUpId:y})=>y===d),h=0;if(s&&u&&!d){let y=S({tournamentId:p,matchUpId:u,courtId:s,matchUp:g,drawId:c,tournamentRecords:r,sourceCourtId:i,courtDayDate:a});if(y?.success&&h++,y.error)return _({result:y,stack:e})}else if(i&&s&&u&&d){let y=S({tournamentId:p,matchUpId:u,courtId:s,matchUp:g,drawId:c,tournamentRecords:r,sourceCourtId:i,courtDayDate:a});if(y.success&&h++,y.error)return _({result:y,stack:e,info:"source"});let P=S({tournamentId:l,sourceCourtId:s,matchUpId:d,matchUp:I,courtId:i,drawId:m,tournamentRecords:r,courtDayDate:a});if(P.success&&h++,P.error)return _({result:P,stack:e,info:"target"})}else return{error:st};return h?C:_({result:{error:_s},stack:e});function S(y){let{tournamentRecords:P,tournamentId:U,matchUp:E,drawId:A}=y,N=P[U],{drawDefinition:D}=wo({tournamentRecord:N,drawId:A});return E.matchUpType===jt?T({...y,tournamentRecord:N,drawDefinition:D}):Xi({...y,tournamentRecord:N,drawDefinition:D})}function T({removePriorValues:y,tournamentRecords:P,tournamentRecord:U,drawDefinition:E,sourceCourtId:A,courtDayDate:N,matchUpId:D,matchUp:M,courtId:R}){let b=[R].concat(M.schedule.allocatedCourts.map(({courtId:v})=>v).filter(v=>v!==A));return om({removePriorValues:y,tournamentRecords:P,tournamentRecord:U,drawDefinition:E,courtDayDate:N,matchUpId:D,courtIds:b})}}function gR({scheduleAttributes:t=[so,Bo,Hi,Wi,ji,Oo,Di,Pi,Yi],tournamentRecord:e,drawDefinition:r,matchUpId:n}){let o="clearMatchUpSchedule",i=r?or({matchUpFilters:{matchUpIds:[n]},inContext:!1,drawDefinition:r}).matchUps?.[0]:Te({matchUpFilters:{matchUpIds:[n]},tournamentRecord:e,inContext:!1}).matchUps?.[0];if(!i)return{error:Le};let s=(i.timeItems??[]).filter(a=>a?.itemType&&!t.includes(a?.itemType));return i.timeItems=s,gt({tournamentId:e.tournamentId,context:o,drawDefinition:r,matchUp:i}),{...C}}function IR(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:wt};if(typeof n!="object")return{error:lo};let i=Object.keys(o).filter(s=>!r||r===s);if(r&&!i.includes(r))return{error:G};for(let s of i){let a=o[s],c=At({extension:{name:ou,value:{dailyLimits:n}},element:a});if(c.error)return c}return{...C}}var RR={};Xt(RR,{addCollectionDefinition:()=>SI,addCollectionGroup:()=>UR,aggregateTieFormats:()=>NR,compareTieFormats:()=>$o,getTieFormat:()=>QT,modifyCollectionDefinition:()=>II,modifyTieFormat:()=>DR,mutate:()=>MR,orderCollectionDefinitions:()=>ER,query:()=>uN,removeCollectionDefinition:()=>hI,removeCollectionGroup:()=>yR,tieFormatGenderValidityCheck:()=>Mm,validateCollectionDefinition:()=>qc});var MR={};Xt(MR,{addCollectionDefinition:()=>SI,addCollectionGroup:()=>UR,aggregateTieFormats:()=>NR,modifyCollectionDefinition:()=>II,modifyTieFormat:()=>DR,orderCollectionDefinitions:()=>ER,removeCollectionDefinition:()=>hI,removeCollectionGroup:()=>yR});function ui({drawDefinition:t,structureId:e,matchUpId:r,structure:n,matchUp:o,eventId:i,event:s}){let a="getTieFormat",c;if(e=n?.structureId??e,r=o?.matchUpId??r,(r||e)&&!t)return{error:Z};if(i&&s)c=ni(s);else if(r){if(t&&(!o||!n)){let u=Bt({drawDefinition:t,matchUpId:r});if(u.error)return u;if(u.matchUp?.matchUpType!==xr)return _({result:{error:dr},stack:a});n||(n=u.structure),o||(o=u.matchUp)}c=Tp({item:o,drawDefinition:t,structure:n,event:s})||Tp({item:n,drawDefinition:t,structure:n,event:s})||ni(t)||ni(s)}else if(t&&e){if(!n){let u=at({drawDefinition:t,structureId:e});if(u.error)return u;n=u?.structure}c=Tp({item:n,drawDefinition:t,structure:n,event:s})||ni(t)||ni(s)}else c=ni(t)||ni(s);return c?{...C,structure:n,tieFormat:c,matchUp:o}:_({result:{error:bs},stack:a})}function Nl({matchUp:t,updateInProgressMatchUps:e}){return!t.winningSide&&![ce].includes(t.matchUpStatus)&&(e||t.matchUpStatus!==Ln&&!Ie(t))}function TR({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 lw({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((U,E)=>(U[E.collectionId]=(U[E.collectionId]||0)+E.matchUpCount,U),{}),I=({tieFormat:U})=>{let E=U?.collectionDefinitions.reduce((A,N)=>(A[N.collectionId]=(A[N.collectionId]||0)+N.matchUpCount,A),{});return TR({from:E,to:g}).equivalent},h=ui({drawDefinition:r})?.tieFormat,S=ui({event:a})?.tieFormat;if(a&&i){for(let U of a.drawDefinitions??[])T({drawDefinition:U});a.tieFormat=ir(o),f+=1}else if(s){if(!s.tieMatchUps)return _({result:{error:dr},stack:u});let U=Sr(s.tieMatchUps?.map(({collectionId:M})=>M)),E=TR({to:g,from:U}),{changes:A,changesArePossible:N,cannotChangeReaon:D}=dw({matchUp:s,check:E});if(E.equivalent)if(Nl({matchUp:s,updateInProgressMatchUps:t}))s.tieFormat=ir(o),f+=1;else return _({result:{error:$l},info:"matchUp is IN_PROGRESS or COMPLETE",stack:u});else if(N)P({tieFormat:o,matchUp:s,changes:A,uuids:c});else return _({context:{collectionMap:g,matchUpMap:U},result:{error:Lo},info:D||"specified changes not possible",stack:u});d+=1,gt({eventId:a?.eventId,context:u,drawDefinition:r,tournamentId:p,matchUp:s})}else if(n){let E=y({inheritedTieFormat:h??S,structure:n})?.modifiedMatchUpsCount;E&&(d+=E,m+=1,f+=1);let A=!n.tieFormat||$o({ancestor:n.tieFormat,descendant:o}).different;A&&(n.tieFormat=ir(o),m+=1,f+=1),(E||A)&&r&&Ot({structureIds:[n.structureId],eventId:a?.eventId,drawDefinition:r})}else if(r)T({drawDefinition:r}),r.tieFormat=ir(o),f+=1;else return{error:Z};return{modifiedStructuresCount:m,modifiedMatchUpsCount:d,addedMatchUpsCount:l,modifiedCount:f,...C,tieFormat:o};function T({drawDefinition:U}){let E=U.structures||[],A=[];for(let N of E){if(N.tieFormat)continue;let M=y({inheritedTieFormat:S,structure:N})?.modifiedMatchUpsCount;if(M){m+=1,d+=M;let R=N.structureId;A.push(R)}}return Ot({structureIds:A,eventId:a?.eventId,drawDefinition:U}),A.length}function y({inheritedTieFormat:U,structure:E}){let A=0,N=Ut({matchUpFilters:{matchUpTypes:[jt]},structure:E})?.matchUps||[];for(let D of N){let M=Nl({matchUp:D,updateInProgressMatchUps:t}),R=!1,b=Sr(D.tieMatchUps?.map(({collectionId:O})=>O)),v=TR({from:b,to:g});if(v.equivalent)D.tieFormat&&I(D)&&M&&(D.tieFormat=ir(o),R=!0);else{let{changes:O,changesArePossible:x}=dw({matchUp:D,check:v});if(x&&!D.tieFormat)P({changes:O,matchUp:D,tieFormat:o,uuids:c});else if(U)(!D.tieFormat||$o({ancestor:U,descendant:D.tieFormat}).different)&&(D.tieFormat=U,R=!0);else return _({result:{error:bs},stack:u})}R&&(A+=1,gt({tournamentId:e?.tournamentId,drawDefinition:r,context:u,eventId:i,matchUp:D}))}return{modifiedMatchUpsCount:A}}function P({uuids:U,matchUp:E,tieFormat:A,changes:N}){E.tieFormat=ir(A);let D=[],M=[];return N.forEach(R=>{if(R.countChange>0){let b=Math.max(0,...E.tieMatchUps.filter(x=>x.collectionId===R.collectionId).map(Br("collectionPosition"))),v=A.collectionDefinitions.find(x=>x.collectionId===R.collectionId),O=Du({matchUpsLimit:R.countChange,collectionPositionOffset:b,collectionDefinition:v,matchUp:E,uuids:U});M.push(...J(O,!1,!0)),l+=M.length,E.tieMatchUps.push(...O)}else{let b=R.toBePlayedTieMatchUpIds.slice(0,Math.abs(R.countChange));console.log("remove",b.length),D.push(...b),E.tieMatchUps=E.tieMatchUps.filter(({matchUpId:v})=>!b.includes(v))}}),M.length&&Co({matchUps:M,drawDefinition:r,tournamentId:p,eventId:i}),D.length&&Yn({matchUpIds:D,action:"updateTieFormat",drawDefinition:r,tournamentId:p,eventId:i}),{matchUpIdsRemoved:D,matchUpsAdded:M}}}function dw({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===Qt).map(Br("matchUpId")),c=a.length+s>=0||s>0;return!c&&s<0&&(r="Insufficient TO_BE_PLAYED matchUps"),n.push({toBePlayedTieMatchUpIds:a,collectionId:i,countChange:s}),c}),changes:n,cannotChangeReaon:r}}function Bu({appliedPolicies:t,drawDefinition:e,auditData:r}){if(!t?.audit?.[qm])return;let{extension:n}=dt({name:qm,element:e}),o={value:Array.isArray(n?.value)?n?.value.concat(r):[r],name:qm};At({element:e,extension:o})}function II({updateInProgressMatchUps:t=!1,tournamentRecord:e,collectionOrder:r,collectionName:n,tieFormatName:o,drawDefinition:i,matchUpFormat:s,matchUpCount:a,collectionId:c,matchUpType:u,structureId:p,matchUpId:m,category:d,eventId:l,gender:f,event:g,collectionValueProfiles:I,collectionValue:h,matchUpValue:S,scoreValue:T,setValue:y}){let P="modifyCollectionDefinition";if(s&&!Pr({matchUpFormat:s}))return _({result:{error:G},context:{matchUpFormat:s},stack:P});if(n&&typeof n!="string")return _({result:{error:G},context:{collectionName:n},stack:P});if(f&&!Object.values(Nm).includes(f))return _({result:{error:G},context:{gender:f},stack:P});if(d&&typeof d!="object")return _({result:{error:G},context:{category:d},stack:P});let U={collectionValueProfiles:I,collectionValue:h,matchUpValue:S,scoreValue:T,setValue:y};if(!Object.values(U).filter(Boolean).length&&!r&&!n&&!s&&!a&&!u)return _({result:{error:st},stack:P});if(Object.values(U).filter(Boolean).length>1)return _({info:"Only one value assignment allowed per collectionDefinition",result:{error:G},stack:P});let E=ui({drawDefinition:i,structureId:p,matchUpId:m,eventId:l,event:g});if(E.error)return _({result:E,stack:P});let{matchUp:A,structure:N,tieFormat:D}=E,M=ir(D),R=D?.collectionDefinitions.find(K=>K.collectionId===c),b=M?.collectionDefinitions.find(K=>K.collectionId===c);if(!R)return _({info:"source collectionDefinition",result:{error:ve},context:{collectionId:c},stack:P});let v=h??S??T??y;if(I?.length){let K=CI({matchUpCount:a??R?.matchUpCount??0,collectionValueProfiles:I});if(K.errors)return _({result:{error:G},info:K.errors,stack:P})}else if(v&&!It(v))return _({result:{error:G},info:"value is not an integer",context:{value:v},stack:P});let O=(K,q)=>Yt(Object.keys(K),Object.keys(q)).length===Object.keys(K).length&&Yt(Object.values(K),Object.values(q)).length===Object.values(K).length,x=I&&(!R.collectionValueProfiles||!O(R.collectionValueProfiles,I)),F=It(h)&&R.collectionValue!==h||It(S)&&R.matchUpValue!==S||It(T)&&R.scoreValue!==T||It(y)&&R.setValue!==y||x,L=[];if(F&&(b.collectionValueProfiles=void 0,b.collectionValue=void 0,b.matchUpValue=void 0,b.scoreValue=void 0,b.setValue=void 0,Object.assign(b,U),L.push({collectionId:c,...ot(U)})),(It(T)||It(y))&&b.collectionGroupNumber){let K=b.collectionGroupNumber;M.collectionDefinitions=M.collectionDefinitions.map(q=>{let{collectionGroupNumber:B,...$}=q;return B===K?$:q}),M.collectionGroups=M.collectionGroups.filter(({groupNumber:q})=>q!==K),L.push({collectionId:c,change:"collectionGroupNumber removed"})}let{aggregateValue:w,valueGoal:V}=Ps(M),k=ot({aggregateValue:w,valueGoal:V});if((k.aggregateValue!==D?.winCriteria.aggregateValue||k.valueGoal!==D?.winCriteria.valueGoal)&&(M.winCriteria=k,L.push({collectionId:c,winCriteria:k})),It(r)&&R.collectionOrder!==r&&(b.collectionOrder=r,L.push({collectionId:c,collectionOrder:r})),n&&R.collectionName!==n&&(b.collectionName=n,L.push({collectionId:c,collectionName:n})),s&&R.matchUpFormat!==s&&(b.matchUpFormat=s,L.push({collectionId:c,matchUpFormat:s})),It(a)&&R.matchUpCount!==a&&(b.matchUpCount=a,L.push({collectionId:c,matchUpCount:a})),u&&R.matchUpType!==u)return _({result:{error:Zu},context:{matchUpType:u},stack:P});d&&R.category!==d&&(b.category=d,L.push({collectionId:c,category:d})),f&&R.gender!==f&&(b.gender=f,L.push({collectionId:c,gender:f}));let W=ot(M);if(E=ar({tieFormat:W}),E.error)return _({result:E,stack:P});if(!L.length)return _({result:{...C,modifications:L}});if(D?.tieFormatName!==o?(W.tieFormatName=o,L.push({tieFormatName:o})):L.length&&(delete W.tieFormatName,L.push("tieFormatName removed: modifications without new tieFormatName")),E=lw({tieFormat:W,updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:i,structure:N,eventId:l,matchUp:A,event:g}),!E.error){let{appliedPolicies:K}=yt({tournamentRecord:e}),q=ot({collectionDefinition:b,drawId:i?.drawId,action:P,structureId:p,matchUpId:m,eventId:l});Bu({appliedPolicies:K,drawDefinition:i,auditData:q})}return _({result:{...E,modifications:L},stack:P})}function fw({updateInProgressMatchUps:t,drawDefinition:e,structureId:r,structure:n,matchUpId:o,matchUp:i}){let s=[];return o&&i?s=[i]:r&&n?s=Ut({matchUpFilters:{matchUpTypes:[jt]},structure:n})?.matchUps??[]:e&&(s=or({matchUpFilters:{matchUpTypes:[jt]},drawDefinition:e})?.matchUps??[]),{targetMatchUps:s.filter(c=>!c.winningSide&&c.matchUpStatus!==le&&(t||c.matchUpStatus!==Ln&&!Ie(c)))}}function gw({updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:r,targetMatchUps:n,tieFormat:o,event:i}){for(let s of n){let a=!!s.tieFormat;a&&(s.tieFormat=ir(o));let c;if(t){let u=yt({tournamentRecord:e,drawDefinition:r,event:i}).appliedPolicies,p=co({matchUpId:s.matchUpId,exitWhenNoValues:!0,tournamentRecord:e,appliedPolicies:u,drawDefinition:r,event:i});if(p.error)return p;c=p.score}a&&!c&>({tournamentId:e?.tournamentId,context:"updateTargetTeamMatchUps",eventId:i?.eventId,matchUp:s,drawDefinition:r})}return{...C}}function dA({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}=Ps(c);c.winCriteria=ot({aggregateValue:l,valueGoal:f}),(e&&e!==f||l&&!n)&&(o?c.tieFormatName=o:delete c.tieFormatName);let{targetMatchUps:g}=fw({updateInProgressMatchUps:t,drawDefinition:i,structureId:s,structure:a,matchUpId:u,matchUp:p});gw({updateInProgressMatchUps:t,tournamentRecord:r,targetMatchUps:g,drawDefinition:i,tieFormat:c,event:d});let I=ot(c),h=ar({tieFormat:I});if(h.error)return h;if(m&&d)d.tieFormat=I;else if(u&&p)p.tieFormat=c;else if(a)a.tieFormat=I;else if(i)i.tieFormat=I;else if(!p||!i)return{error:Z};return Ot({drawDefinition:i,eventId:d?.eventId}),{...C}}function yR({updateInProgressMatchUps:t=!0,collectionGroupNumber:e,tournamentRecord:r,drawDefinition:n,tieFormatName:o,structureId:i,matchUpId:s,matchUp:a,eventId:c,event:u}){if(!e)return{error:st};if(isNaN(e))return{error:G};let p="removeCollectionGroup",m=a?void 0:ui({drawDefinition:n,structureId:i,matchUpId:s,eventId:c,event:u});if(m?.error)return _({result:m,stack:p});let d=m?.structure;a=a??m?.matchUp;let l=m?.tieFormat,f=l?.winCriteria.valueGoal,g=l?.winCriteria.aggregateValue,I=ir(l);if(m=ar({tieFormat:I}),m.error)return _({result:m,stack:p});let h=[];if(I.collectionDefinitions=I.collectionDefinitions.map(S=>{let{collectionGroupNumber:T,...y}=S;return T!==e?S:(h.push(S.collectionId),y)}),I.collectionGroups=I.collectionGroups.filter(({groupNumber:S})=>S!==e),m=dA({updateInProgressMatchUps:t,originalValueGoal:f,wasAggregateValue:g,tournamentRecord:r,drawDefinition:n,tieFormatName:o,structureId:i,structure:d,tieFormat:I,matchUpId:s,matchUp:a,eventId:c,event:u}),!m.error){let{appliedPolicies:S}=yt({tournamentRecord:r}),T=ot({drawId:n?.drawId,collectionGroupNumber:e,action:p,structureId:i,matchUpId:s,eventId:c});Bu({appliedPolicies:S,drawDefinition:n,auditData:T})}return _({result:{...m,modifiedCollectionIds:h},stack:p})}function Ml({tieFormat:t,orderMap:e}){let r=ir(t);return r.collectionDefinitions.forEach(n=>{let o=e[n.collectionId];o&&(n.collectionOrder=o)}),r.collectionDefinitions?.sort((n,o)=>Ba(n.collectionOrder)-Ba(o.collectionOrder)),r}function ER({tournamentRecord:t,drawDefinition:e,structureId:r,matchUpId:n,orderMap:o,eventId:i,matchUp:s,event:a}){if(typeof o!="object"||!Object.values(o).every(c=>It(c)))return _({result:{error:G},context:{orderMap:o}});if(i&&a?.tieFormat)Iw({tournamentRecord:t,event:a,orderMap:o});else if(n){let c=e&&Bt({drawDefinition:e,matchUpId:n});if(c?.error)return c;if(s=c.matchUp,!s)return{error:hr};s?.tieFormat&&(s.tieFormat=Ml({tieFormat:s.tieFormat,orderMap:o}),gt({tournamentId:t?.tournamentId,eventId:a?.eventId,drawDefinition:e,matchUp:s}))}else if(r){let c=at({drawDefinition:e,structureId:r});if(c.error)return c;let u=c.structure;if(u?.tieFormat)u.tieFormat=Ml({tieFormat:u.tieFormat,orderMap:o}),hw({eventId:a?.eventId,tournamentRecord:t,drawDefinition:e,structure:u,orderMap:o}),Ot({drawDefinition:e,structureIds:[u.structureId]});else if(e.tieFormat)AR({structureIds:[r],tournamentRecord:t,drawDefinition:e,orderMap:o,event:a});else if(a?.tieFormat)Iw({structureIds:[r],tournamentRecord:t,orderMap:o,event:a});else return{error:ve}}else if(e?.tieFormat)AR({tournamentRecord:t,drawDefinition:e,orderMap:o,event:a});else return{error:ve};return{...C}}function Iw({tournamentRecord:t,structureIds:e,orderMap:r,event:n}){let o=Ml({tieFormat:n.tieFormat,orderMap:r});e?.length||(n.tieFormat=o);for(let i of n.drawDefinitions??[])AR({tournamentRecord:t,drawDefinition:i,structureIds:e,orderMap:r,event:n})}function AR({tournamentRecord:t,drawDefinition:e,structureIds:r,orderMap:n,event:o}){let i=e.tieFormat??o?.tieFormat,s=Ml({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=Ml({tieFormat:c.tieFormat??e.tieFormat??o?.tieFormat,orderMap:n})),hw({eventId:o?.eventId,tournamentRecord:t,drawDefinition:e,structure:c,orderMap:n}),a.push(c.structureId));Ot({drawDefinition:e,structureIds:a})}function hw({tournamentRecord:t,drawDefinition:e,structure:r,orderMap:n,eventId:o}){let i=Ut({matchUpFilters:{matchUpTypes:[jt]},structure:r})?.matchUps;for(let s of i)s.tieFormat&&(s.tieFormat=Ml({tieFormat:s.tieFormat,orderMap:n}),gt({tournamentId:t?.tournamentId,drawDefinition:e,eventId:o,matchUp:s}))}function hI({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:ui({drawDefinition:n,structureId:s,matchUpId:a,eventId:c,event:p});if(d?.error)return _({result:d,stack:m});let l=d?.structure;u=u??d?.matchUp;let f=d?.tieFormat,g=ir(f);if(d=ar({tieFormat:g}),d.error)return _({result:d,stack:m});let I=g?.collectionDefinitions?.find(M=>M.collectionId===i);if(!I)return _({result:{error:ve,collectionId:i}});g.collectionDefinitions=g.collectionDefinitions.filter(M=>M.collectionId!==i),I.collectionGroupNumber&&(g.collectionDefinitions=g.collectionDefinitions.map(M=>{let{collectionGroupNumber:R,...b}=M;return b}),g.collectionGroups=g.collectionGroups.filter(({groupNumber:M})=>M!==I.collectionGroupNumber));let{aggregateValue:h,valueGoal:S}=Ps(g);g.winCriteria=ot({aggregateValue:h,valueGoal:S});let T=f?.winCriteria.valueGoal,y=f?.winCriteria.aggregateValue;(T&&T!==S||h&&!y)&&(o?g.tieFormatName=o:delete g.tieFormatName);let P=[];a&&u?P=[u]:s&&l?P=Ut({matchUpFilters:{matchUpTypes:[jt]},structure:l})?.matchUps??[]:n?P=or({matchUpFilters:{matchUpTypes:[jt]},drawDefinition:n})?.matchUps??[]:p&&(P=$n({matchUpFilters:{matchUpTypes:[jt]},drawDefinition:n})?.matchUps??[]);let U=(P||[]).filter(M=>{let b=M.tieMatchUps?.filter(O=>O.collectionId===i)?.some(Ie),v=e&&M.tieFormat?$o({descendant:M.tieFormat,ancestor:g})?.different:!1;return t&&!b||!M.winningSide&&M.matchUpStatus!==le&&(t||M.matchUpStatus!==Ln&&!Ie(M)&&!v)});if(!U.length)return{error:_s};let{appliedPolicies:E}=yt({tournamentRecord:r});if(a&&u&&t){let M=u.tieMatchUps?.filter(R=>R.collectionId===i);for(let R of M??[]){let b=La({matchUpId:R.matchUpId,tieMatchUpId:u?.matchUpId,winningSide:void 0,removeScore:!0,tournamentRecord:r,appliedPolicies:E,drawDefinition:n,event:p});if(b.error||(b=Bt({drawDefinition:n,matchUpId:a}),b.error))return b;u=b?.matchUp}}let A=[];for(let M of U){for(let R of M?.sides??[])R.lineUp=(R.lineUp??[]).map(b=>({participantId:b.participantId,collectionAssignments:(b?.collectionAssignments??[]).filter(v=>v.collectionId!==i)}));if(M.tieMatchUps=(M.tieMatchUps??[]).filter(R=>{let b=R.collectionId===i;return b&&A.push(R.matchUpId),!b}),M.tieFormat&&(M.tieFormat=ir(g)),t){let R=co({matchUpId:M.matchUpId,exitWhenNoValues:!0,tournamentRecord:r,appliedPolicies:E,drawDefinition:n,event:p});if(R.error)return R}gt({tournamentId:r?.tournamentId,eventId:p?.eventId,drawDefinition:n,context:m,matchUp:M})}A.length&&Yn({tournamentId:r?.tournamentId,matchUpIds:A,eventId:p?.eventId,drawDefinition:n});let N=ot(g);if(d=ar({tieFormat:N}),d.error)return _({result:d,stack:m});if(c&&p)p.tieFormat=N;else if(a&&u)u.tieFormat=N;else if(l)l.tieFormat=N;else if(n)n.tieFormat=N;else if(!u||!n)return{error:Z};Ot({drawDefinition:n,eventId:p?.eventId});let D=ot({drawId:n?.drawId,action:m,collectionId:i,structureId:s,matchUpId:a,eventId:c});return Bu({appliedPolicies:E,drawDefinition:n,auditData:D}),{tieFormat:N,deletedMatchUpIds:A,targetMatchUps:U,...C}}function UR({updateInProgressMatchUps:t=!0,tournamentRecord:e,groupDefinition:r,drawDefinition:n,collectionIds:o,tieFormatName:i,structureId:s,matchUpId:a,matchUp:c,eventId:u,event:p}){let m="addCollectionGroup";if(!Array.isArray(o))return _({result:{error:st},stack:m});let d=c?void 0:ui({drawDefinition:n,structureId:s,matchUpId:a,eventId:u,event:p});if(d?.error)return _({result:d,stack:m});let l=d?.structure;c=c||d?.matchUp;let f=d?.tieFormat,g=f?.winCriteria.valueGoal,I=ir(f);if(d=ar({tieFormat:I}),d.error)return _({result:d,stack:m});for(let T of I.collectionDefinitions){let{collectionId:y,collectionGroupNumber:P}=T;if(P&&o.includes(y))return _({info:"collectionIds cannot be part of other collectionGroups",result:{error:G},stack:m})}let S=(I.collectionGroups||[]).reduce((T,y)=>y.groupNumber>T?y.groupNumber:T,0)+1;return r.groupNumber=S,I.collectionDefinitions=I.collectionDefinitions.map(T=>o.includes(T.collectionId)?{...T,collectionGroupNumber:S}:T),I.collectionGroups=[...I.collecitonGroups||[],r],dA({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 SI({updateInProgressMatchUps:t=!0,collectionDefinition:e,referenceCategory:r,tournamentRecord:n,policyDefinitions:o,enforceCategory:i,referenceGender:s,drawDefinition:a,tieFormatName:c,enforceGender:u,structureId:p,matchUpId:m,matchUp:d,eventId:l,uuids:f,event:g}){let I="addCollectionDefinition",h=yt({tournamentRecord:n,drawDefinition:a,event:g}).appliedPolicies??{},S=o?.[er]??h?.[er];i=i??S?.participants?.enforceCategory;let T=(u??S?.participants?.enforceGender)!==!1,y=!!((r??g?.category)&&i!==!1),P=!!((s??g?.gender)&&T),U=qc({referenceCategory:r??g?.category,collectionDefinition:e,referenceGender:s,checkCategory:y,checkGender:P,event:g});if(U.error)return _({result:U,stack:I});let E=d?.tieFormat?void 0:ui({drawDefinition:a,structureId:p,matchUpId:m,eventId:l,event:g});if(E?.error)return _({result:{error:E.error},stack:I});let A=E?.structure;d=d??E?.matchUp;let N=d?.tieFormat??E?.tieFormat,D=ir(N);if(E=ar({tieFormat:D}),E?.error)return _({result:{error:E.error},stack:I});if(!e.collectionId)e.collectionId=Dt();else if(D.collectionDefinitions.map(({collectionId:k})=>k).includes(e.collectionId))return _({context:{collectionId:e.collectionId},result:{error:RE}});D.collectionDefinitions.push(e),D.collectionDefinitions.sort((V,k)=>(V.collectionOrder||0)-(k.collectionOrder||0)).forEach((V,k)=>V.collectionOrder=k+1);let{aggregateValue:M,valueGoal:R}=Ps(D);D.winCriteria=ot({aggregateValue:M,valueGoal:R});let b=N?.winCriteria.valueGoal,v=N?.winCriteria.aggregateValue;(b&&b!==R||M&&!v)&&(c?D.tieFormatName=c:delete D.tieFormatName);let O=[],x=[],F=[],L=ot(D);if(E=ar({tieFormat:L}),E?.error)return _({result:{error:E.error},stack:I});if(l&&g){g.tieFormat=L;for(let V of g.drawDefinitions??[])if(!V.tieFormat)for(let k of V.structures??[]){if(k.tieFormat)continue;let W=PR({updateInProgressMatchUps:t,collectionDefinition:e,structure:k,uuids:f});x.push(...W.newMatchUps),F.push(...W.targetMatchUps),O.push(k.structureId)}lA({modifiedMatchUps:F,eventId:g?.eventId,modifiedStructureIds:O,tournamentRecord:n,drawDefinition:a,addedMatchUps:x,stack:I})}else if(p&&A){A.tieFormat=L;let V=PR({updateInProgressMatchUps:t,collectionDefinition:e,structure:A,uuids:f});x.push(...V.newMatchUps),F=V.targetMatchUps,lA({modifiedMatchUps:F,eventId:g?.eventId,modifiedStructureIds:O,tournamentRecord:n,drawDefinition:a,addedMatchUps:x,stack:I})}else if(m&&d){if(!Nl({matchUp:d,updateInProgressMatchUps:t}))return _({result:{error:$l},stack:I});d.tieFormat=L;let V=Du({collectionDefinition:e,matchUp:d,uuids:f});Array.isArray(d.tieMatchUps)||(d.tieMatchUps=[]),d.tieMatchUps.push(...V),x.push(...V),lA({modifiedMatchUps:[d],eventId:g?.eventId,modifiedStructureIds:O,tournamentRecord:n,drawDefinition:a,addedMatchUps:x,stack:I})}else if(a){a.tieFormat=L;for(let V of a.structures??[]){let k=PR({updateInProgressMatchUps:t,collectionDefinition:e,structure:V,uuids:f});O.push(V.structureId),x.push(...k.newMatchUps),F.push(...k.targetMatchUps)}lA({modifiedMatchUps:F,eventId:g?.eventId,tournamentRecord:n,drawDefinition:a,addedMatchUps:x,stack:I})}else return{error:Z};let w=ot({drawId:a?.drawId,collectionDefinition:e,action:I,structureId:p,matchUpId:m,eventId:l});return Bu({appliedPolicies:h,drawDefinition:a,auditData:w}),{tieFormat:L,targetMatchUps:F,addedMatchUps:x,...C}}function PR({updateInProgressMatchUps:t,collectionDefinition:e,structure:r,uuids:n}){let o=[],s=(Ut({matchUpFilters:{matchUpTypes:[jt]},structure:r})?.matchUps).filter(a=>Nl({matchUp:a,updateInProgressMatchUps:t})&&!a.tieFormat);for(let a of s){let c=Du({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 lA({modifiedStructureIds:t,tournamentRecord:e,modifiedMatchUps:r,drawDefinition:n,addedMatchUps:o,eventId:i,stack:s}){Co({tournamentId:e?.tournamentId,matchUps:o,drawDefinition:n,eventId:i}),r?.forEach(a=>{gt({tournamentId:e?.tournamentId,drawDefinition:n,context:s,matchUp:a,eventId:i})}),Ot({structureIds:t,drawDefinition:n,eventId:i})}function DR({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(!ar({tieFormat:r}).valid)return _({result:{error:Lo},info:"falied validation",stack:m});let d=ui({drawDefinition:i,structureId:s,matchUpId:a,eventId:c,event:p});if(d.error)return _({result:d,stack:m});let{matchUp:l,tieFormat:f}=d,g=ir(f),I=$o({descendant:r,ancestor:g,considerations:o});if(I.invalid)return _({context:{invalid:I.invalid},result:{error:Lo},stack:m});if(!I?.different)return _({result:{...C},info:"Nothing to do",stack:m});let h=g.collectionDefinitions.map(({collectionId:D})=>D),S=r.collectionDefinitions.map(({collectionId:D})=>D),T=h.filter(D=>!S.includes(D)),y=r.collectionDefinitions.filter(({collectionId:D})=>!h.includes(D)),P=y.map(Br("collectionId")),U=[],E,A=r.tieFormatName;for(let D of r.collectionDefinitions){if(P.includes(D.collectionId))continue;let M=II({updateInProgressMatchUps:t,...D,tournamentRecord:n,tieFormatName:A,drawDefinition:i,structureId:s,matchUpId:a,eventId:c,event:p});if(M.modifications&&U.push(...M.modifications),M.error)return _({result:M,stack:m});M.tieFormat&&(E=M.tieFormat)}for(let D of y){let M=SI({updateInProgressMatchUps:t,collectionDefinition:D,tournamentRecord:n,drawDefinition:i,tieFormatName:A,structureId:s,matchUpId:a,matchUp:l,eventId:c,uuids:u,event:p});if(M.error)return _({result:M,stack:m});M.tieFormat&&(E=M.tieFormat)}for(let D of T){let M=hI({updateInProgressMatchUps:t,tieFormatComparison:e,tournamentRecord:n,drawDefinition:i,tieFormatName:A,collectionId:D,structureId:s,matchUpId:a,eventId:c,matchUp:l,event:p});if(M.error)return _({result:M,stack:m});M.tieFormat&&(E=M.tieFormat)}return f?.tieFormatName!==A?(E.tieFormatName=A,U.push({tieFormatName:A})):(U.length||P.length||T.length)&&(delete E.tieFormatName,U.push("tieFormatName removed: modifications without new tieFormatName")),E.collectionDefinitions=E.collectionDefinitions.sort((D,M)=>Ba(D.collectionOrder)-Ba(M.collectionOrder)).map((D,M)=>({...D,collectionOrder:M+1})),{processedTieFormat:ir(E),modifications:U,...C}}function NR({tournamentRecord:t}){if(!t)return{error:Y};let e=0;for(let r of t.events??[]){let n=r.tieFormats??[],o=p=>{if(!p.tieFormat)return;let m;for(let d of n)$o({descendant:p.tieFormat,ancestor:d}).different||(m=d.tieFormatId);if(m)p.tieFormatId=m,delete p.tieFormat;else{let d=J(p.tieFormat,void 0,!0);d.tieFormatId||(d.tieFormatId=Dt()),p.tieFormatId=d.tieFormatId,delete p.tieFormat,n.push(d),e+=1}},i=r.eventType;o({tieFormat:r.tieFormat,eventType:i});for(let p of r.drawDefinitions??[]){o({tieFormat:p.tieFormat,eventType:i});for(let m of p.structures??[])o({tieFormat:m.tieFormat,eventType:i})}let s=(p,m)=>{let d=c.matchUps?.find(l=>l.matchUpId===p);d&&(d.tieFormatId=m,delete d.tieFormat,gt({tournamentId:t?.tournamentId,eventId:r.eventId,matchUp:d}))},a=p=>{let m=J(p.tieFormat,void 0,!0);m.tieFormatId||(m.tieFormatId=Dt()),n.push(m),e+=1,s(p.matchUpId,m.tieFormatId)},c=$n({matchUpFilters:{matchUpTypes:[xr]},event:r}),u=c.matchUps??[];for(let p of u){let m;for(let d of n)p.tieFormat&&$o({descendant:p.tieFormat,ancestor:d}).different||(m=d.tieFormatId);m?s(p.matchUpId,m):a(p)}n.length&&(r.tieFormats=n)}return{...C,addedCount:e}}var VR={};Xt(VR,{addDrawDefinitionExtension:()=>fp,addEventExtension:()=>Mo,addEventTimeItem:()=>zi,addExtension:()=>At,addNotes:()=>Fp,addOnlineResource:()=>_R,addParticipantExtension:()=>gU,addParticipantTimeItem:()=>Rg,addTimeItem:()=>Qn,addTournamentExtension:()=>Cf,addTournamentTimeItem:()=>Pc,analyzeDraws:()=>Cu,analyzeTournament:()=>KT,copyTournamentRecord:()=>CR,createTournamentRecord:()=>um,generate:()=>bR,getAggregateTeamResults:()=>$T,getAllowedDrawTypes:()=>Kd,getAllowedMatchUpFormats:()=>WT,getAppliedPolicies:()=>yt,getCompetitionDateRange:()=>Qd,getCompetitionPenalties:()=>jT,getPolicyDefinitions:()=>vo,getTournamentInfo:()=>Us,getTournamentPenalties:()=>zd,getTournamentPersons:()=>qT,getTournamentPoints:()=>Xd,getTournamentStructures:()=>vS,getTournamentTimeItem:()=>Jm,mutate:()=>GR,query:()=>aN,removeDrawDefinitionExtension:()=>IU,removeEventExtension:()=>gp,removeExtension:()=>gr,removeNotes:()=>Ng,removeOnlineResource:()=>OR,removeParticipantExtension:()=>hU,removeTournamentExtension:()=>bf,setTournamentCategories:()=>LR,setTournamentDates:()=>TI,setTournamentEndDate:()=>kR,setTournamentName:()=>xR,setTournamentNotes:()=>wR,setTournamentStartDate:()=>FR,setTournamentStatus:()=>vR});var bR={};Xt(bR,{copyTournamentRecord:()=>CR,createTournamentRecord:()=>um});function CR(t){let e=rt(t,[{tournamentRecord:!0,startDate:!0,endDate:!1,tournamentName:!0}]);if(e.error)return e;let{startDate:r,endDate:n}=t.tournamentRecord,o=24*60*60*1e3,s=(r&&n?new Date(Et(n)).getTime()-new Date(Et(r)).getTime():0)/o,a=t.endDate||JI(t.startDate,s),c=l=>l?.filter(({itemType:f})=>t.itemTypeList?.includes(f)),u=l=>l?.filter(({name:f})=>t.extensionList?.includes(f)),p=l=>{let{timeItems:f,extensions:g,...I}=l;return J({...I,timeItems:c(f),extensions:u(g)},!1,!0)},m=l=>{let{drawDefinitions:f,timeItems:g,extensions:I,startDate:h,endDate:S,...T}=l;return J({extensions:u(I),timeItems:c(g),startDate:t.startDate,endDate:a,...T},!1,!0)},d={participants:t.copyParticipants?t.tournamentRecord.participants?.map(p)??[]:[],parentOrganisation:J({...t.tournamentRecord.parentOrganisation},!1,!0),venues:J(t.tournamentRecord.venues??[],!1,!0),extensions:u(t.tournamentRecord.extensions),timeItems:c(t.tournamentRecord.timeItems),events:t.tournamentRecord.events?.map(m)??[],weekdays:[...t.tournamentRecord.weekdays??[]],tournamentName:t.tournamentName,startDate:t.startDate,tournamentId:Dt(),endDate:a};return{...C,tournamentRecord:d}}var GR={};Xt(GR,{addDrawDefinitionExtension:()=>fp,addEventExtension:()=>Mo,addEventTimeItem:()=>zi,addExtension:()=>At,addNotes:()=>Fp,addOnlineResource:()=>_R,addParticipantExtension:()=>gU,addParticipantTimeItem:()=>Rg,addTimeItem:()=>Qn,addTournamentExtension:()=>Cf,addTournamentTimeItem:()=>Pc,removeDrawDefinitionExtension:()=>IU,removeEventExtension:()=>gp,removeExtension:()=>gr,removeNotes:()=>Ng,removeOnlineResource:()=>OR,removeParticipantExtension:()=>hU,removeTournamentExtension:()=>bf,setTournamentCategories:()=>LR,setTournamentDates:()=>TI,setTournamentEndDate:()=>kR,setTournamentName:()=>xR,setTournamentNotes:()=>wR,setTournamentStartDate:()=>FR,setTournamentStatus:()=>vR});var o0="ABANDONED",i0="ACTIVE",s0="CANCELLED",a0="COMPLETED",c0="IN_PROGRESS",fA={ABANDONED:o0,ACTIVE:i0,CANCELLED:s0,COMPLETED:a0,IN_PROGRESS:c0};function vR({tournamentRecord:t,status:e}){return t?e&&!Object.keys(fA).includes(e)?{error:G,info:"Unknown status"}:(t.tournamentStatus=e,{...C}):{error:Y}}function OR(t){let e=rt(t,[{tournamentRecord:!0,onlineResource:!0}]);if(e.error)return e;let{tournamentRecord:r,onlineResource:n,organisationId:o,participantId:i,personId:s,courtId:a,venueId:c}=t;if(o){if(r.parentOrganisation?.parentOrganisationId!==o)return _({result:{error:ve}});Rl({element:r.parentOrganisation,onlineResource:n})}else if(i||s){let u=(r.participants??[]).find(p=>s&&p.person?.personId===s||p.participantId===i);if(!u)return s?_({result:{error:ve}}):_({result:{error:te}});if(s){if(u.person?.personId!==s)return _({result:{error:xi}});Rl({element:u.person,onlineResource:n})}else Rl({element:u,onlineResource:n})}else if(a){let u=(r.venues??[]).filter(p=>!c||p.venueId===c).flatMap(p=>(p.courts??[]).filter(m=>m.courtId===a))?.[0];if(!u)return _({result:{error:Os}});Rl({element:u,onlineResource:n})}else if(c){let u=(r.venues??[]).find(p=>p.venueId===c);if(!u)return _({result:{error:Li}});Rl({element:u,onlineResource:n})}else Rl({element:r,onlineResource:n}),mt({payload:{parentOrganisation:r.parentOrganisation,onlineResources:r.onlineResources,tournamentId:r.tournamentId},topic:Bi});return{...C}}function Rl({element:t,onlineResource:e}){let r=(t.onlineResources??[]).filter(n=>!(n?.[Ja]===e[Ja]&&n?.[Za]===e[Za]&&n?.[tc]===e[tc]));t.onlineResources=r}function _R(t){let e=rt(t,[{tournamentRecord:!0,onlineResource:!0}]);if(e.error)return e;let{tournamentRecord:r,onlineResource:n,organisationId:o,participantId:i,personId:s,courtId:a,venueId:c}=t;if(o){if(r.parentOrganisation?.parentOrganisationId!==o)return _({result:{error:ve}});Cl({element:r.parentOrganisation,onlineResource:n})}else if(i||s){let u=(r.participants??[]).find(p=>s&&p.person?.personId===s||p.participantId===i);if(!u)return s?_({result:{error:ve}}):_({result:{error:te}});if(s){if(u.person?.personId!==s)return _({result:{error:xi}});Cl({element:u.person,onlineResource:n})}else Cl({element:u,onlineResource:n})}else if(a){let u=(r.venues??[]).filter(p=>!c||p.venueId===c).flatMap(p=>(p.courts??[]).filter(m=>m.courtId===a))?.[0];if(!u)return _({result:{error:Os}});Cl({element:u,onlineResource:n})}else if(c){let u=(r.venues??[]).find(p=>p.venueId===c);if(!u)return _({result:{error:Li}});Cl({element:u,onlineResource:n})}else Cl({element:r,onlineResource:n}),mt({payload:{parentOrganisation:r.parentOrganisation,onlineResources:r.onlineResources,tournamentId:r.tournamentId},topic:Bi});return{...C}}function Cl({element:t,onlineResource:e}){let r=(t.onlineResources??[]).filter(n=>n?.[Ja]!==e[Ja]&&n?.[Za]!==e[Za]&&n?.[tc]!==e[tc]);return r.push(e),t.onlineResources=r,{...C}}function xR({tournamentRecord:t,promotionalName:e,tournamentName:r,formalName:n}){if(!t)return{error:Y};let o=t.tournamentId,i={tournamentId:o};return r&&r!==t.tournamentName&&(t.tournamentName=r,i.tournamentName=r),e&&e!==t.promotionalName&&(t.promotionalName=e,i.promotionalName=e),n&&n!==t.formalName&&(t.formalName=n,i.formalName=n),t.promotionalName===t.tournamentName&&(delete t.promotionalName,i.promotionalName=""),t.formalName===t.tournamentName&&(delete t.formalName,i.formalName=""),Object.keys(i).length>1&&mt({topic:Bi,payload:{parentOrganisation:t.parentOrganisation,tournamentId:o,...i}}),{...C}}function wR({tournamentRecord:t,notes:e}){if(!t)return{error:Y};let r=e?Fp({element:t,notes:e}):Ng({element:t});return r.error?r:(mt({topic:Bi,payload:{parentOrganisation:t.parentOrganisation,tournamentId:t.tournamentId,notes:e??""}}),{...C})}function LR({tournamentRecord:t,categories:e}){return t?(e=(e||[]).filter(r=>r.categoryName&&r.type),t.tournamentCategories=e,mt({topic:Bi,payload:{parentOrganisation:t.parentOrganisation,tournamentId:t.tournamentId,categories:e}}),{...C}):{error:Y}}function Sw({tournamentRecord:t}){if(!t)return{error:Y};let{startDate:e,endDate:r}=t,n=ws(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=qt(p.startTime),l=qt(p.endTime);return m.startTime&&qt(m.startTime)<d&&(p.startTime=m.startTime),m.endTime&&qt(m.endTime)>l&&(p.endTime=m.endTime),p},{startTime:"08:00",endTime:"18:00"}),c=n.map(p=>i.dateAvailability?.find(d=>d.date===p)??{date:p,startTime:s,endTime:a}),u=i.dateAvailability?.find(p=>!p.date);u&&c.unshift(u),i.dateAvailability=c}return{...C}}function TI(t){let{tournamentRecord:e,startDate:r,endDate:n,weekdays:o}=t,i=t.activeDates?.filter(Boolean),s=rt(t,[{tournamentRecord:!0},{[tr]:l=>Po.test(l),[Fr]:je,startDate:!1,endDate:!1},{[tr]:l=>l.filter(Boolean).every(f=>Po.test(f)),[Fr]:je,activeDates:!1},{[tr]:Dy,weekdays:!1}]);if(s.error)return s;if(n&&r&&new Date(n)<new Date(r))return{error:G};if(n&&r&&new Date(r)>new Date(n))return{error:G};if(i?.length){let l=r||e.startDate,f=n||e.endDate,g=!l||i.every(h=>new Date(h)>=new Date(l)),I=!f||i.every(h=>new Date(h)<=new Date(f));if(!g||!I)return{error:je}}let a;(r&&e.startDate&&new Date(r)>new Date(e.startDate)||n&&e.endDate&&new Date(n)<new Date(e.endDate))&&(a=!0);let c=ws(e.startDate,e.endDate);r&&(e.startDate=r),n&&(e.endDate=n);let u=ws(e.startDate,e.endDate),p=c.filter(l=>!u.includes(l)),m=u.filter(l=>!c.includes(l));for(let l of e.events??[])r&&l.startDate&&new Date(l.startDate)<new Date(r)&&(l.startDate=r),n&&l.startDate&&new Date(l.startDate)>new Date(n)&&(l.startDate=r??n),n&&l.endDate&&new Date(l.endDate)>new Date(n)&&(l.endDate=n),r&&l.endDate&&new Date(l.endDate)<new Date(r)&&(l.endDate=n??r);r&&e.endDate&&new Date(r)>new Date(e.endDate)&&(e.endDate=r),n&&e.startDate&&new Date(n)<new Date(e.startDate)&&(e.startDate=n),i&&(e.activeDates=i),o&&(e.weekdays=o);let d=a&&u0({tournamentRecord:e})?.unscheduledMatchUpIds;return Sw({tournamentRecord:e}),mt({payload:ot({parentOrganisation:e.parentOrganisation,tournamentId:e.tournamentId,activeDates:i,startDate:r,weekdays:o,endDate:n}),topic:Bi}),{...C,unscheduledMatchUpIds:d,datesAdded:m,datesRemoved:p}}function FR({tournamentRecord:t,startDate:e}){return e?TI({tournamentRecord:t,startDate:e}):{error:je}}function kR({tournamentRecord:t,endDate:e}){return e?TI({tournamentRecord:t,endDate:e}):{error:je}}function u0({tournamentRecord:t}){let e=Te({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&&!am({scheduledDates:o,tournamentRecord:t}).clearedScheduleCount?{error:bA}:{unscheduledMatchUpIds:i}}var QR={};Xt(QR,{addCourt:()=>Ul,addCourts:()=>lI,addVenue:()=>mc,deleteCourt:()=>$R,deleteVenue:()=>IA,deleteVenues:()=>HR,disableCourts:()=>WR,disableVenues:()=>jR,enableCourts:()=>YR,enableVenues:()=>qR,generate:()=>BR,generateCourts:()=>Zg,getCompetitionVenues:()=>$p,getCourts:()=>gy,getVenuesAndCourts:()=>Ao,modifyCourt:()=>AI,modifyCourtAvailability:()=>yI,modifyVenue:()=>KR,mutate:()=>zR,publicFindVenue:()=>dS,query:()=>UN});var BR={};Xt(BR,{generateCourts:()=>Zg});var zR={};Xt(zR,{addCourt:()=>Ul,addCourts:()=>lI,addVenue:()=>mc,deleteCourt:()=>$R,deleteVenue:()=>IA,deleteVenues:()=>HR,disableCourts:()=>WR,disableVenues:()=>jR,enableCourts:()=>YR,enableVenues:()=>qR,modifyCourt:()=>AI,modifyCourtAvailability:()=>yI,modifyVenue:()=>KR});function bl(t){if(!t?.tournamentRecord&&!Array.isArray(t?.venueMatchUps))return{error:Y};if(!t?.courtId)return{error:_i};let{scheduleVisibilityFilters:e,tournamentRecord:r,matchUpFilters:n,venueMatchUps:o,courtId:i}=t,{schedulingProfile:s}=Ko({tournamentRecord:r});if(Array.isArray(o))return{matchUps:u({matchUps:o,courtId:i})};let{matchUps:a}=Te({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 sl({matchUps:d,schedulingProfile:s})}}function Tw({scheduleVisibilityFilters:t,tournamentRecord:e,matchUpFilters:r,venueId:n}){if(!e)return{error:Y};if(!n)return{error:Xo};let{schedulingProfile:o}=Ko({tournamentRecord:e}),{matchUps:i}=Te({scheduleVisibilityFilters:t,tournamentRecord:e,matchUpFilters:r});return{matchUps:a({matchUps:i,venueId:n})};function a({matchUps:c,venueId:u}){let p=c.filter(m=>{let d=m.schedule?.allocatedCourts?.map(({venueId:l})=>l);return m.schedule?.venueId===u||d?.includes(u)});return sl({matchUps:p,schedulingProfile:o})}}function yI({tournamentRecord:t,dateAvailability:e,disableNotice:r,venueMatchUps:n,courtId:o,force:i}){if(!t)return{error:Y};if(!o)return{error:_i};let s=cA({dateAvailability:e});if(s.error)return s;let{updatedDateAvailability:a,totalMergeCount:c}=p0(e);e=a;let u=ps({tournamentRecord:t,courtId:o});if(u.error)return u;let{court:p,venue:m}=u,{matchUps:d}=bl({tournamentRecord:t,venueMatchUps:n,courtId:o});if(d?.length){let l=yt({tournamentRecord:t})?.appliedPolicies,f=i??l?.[No]?.allowDeletionWithScoresPresent?.courts,g=[];g.length&&(f||console.log("throw error: scheduled court matchUps",g.length))}return p&&(p.dateAvailability=e,!r&&m&&mt({payload:{venue:m,tournamentId:t.tournamentId},topic:yi,key:m.venueId})),{...C,totalMergeCount:c}}function p0(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(ow);let{mergedAvailability:i,mergeCount:s}=m0(r[o]);n.push(...i.map(a=>({date:o,...a}))),e+=s}),{updatedDateAvailability:n,totalMergeCount:e}}function m0(t){let e,r,n,o=t.length,i=0,s=[];for(;t.length&&o;){let c=t.shift(),{startTime:u,endTime:p,bookings:m}=c;if(o-=1,!e)e=u,n=m,r=p;else if(ma(ke(r),ke(u),!1)>0){let l={startTime:e,endTime:r};n?.length&&(l.bookings=n),s.push(l),e=u,n=m,r=p}else m&&(n?n.push(m):n=m),r=p,i+=1}let a={startTime:e,endTime:r};return n?.length&&(a.bookings=n),s.push(a),{mergedAvailability:s,mergeCount:i}}function vl({matchUpsCount:t=0}){let r=`Schedule would be deleted from ${t} ${t===1?"matchUp":"matchUps"}; use { force: true }`;return{error:_E,info:r}}function gA({tournamentRecord:t,drawDefinition:e,matchUpId:r,drawId:n}){let o="removeCourtAssignment";if(!r)return{error:sr};if(!e&&!n)return{error:an};let i;if(!e){if(!t)return{error:Y};({drawDefinition:e}=ze({tournamentRecord:t,drawId:n}))}if(e)({matchUp:i}=Bt({drawDefinition:e,matchUpId:r}));else{if(!t)return{error:Y};let s=Te({tournamentRecord:t,inContext:!1}).matchUps??[];({matchUp:i}=zS({matchUps:s,matchUpId:r}))}return i?(i.timeItems&&i.timeItems.find(a=>[Bo,so].includes(a.itemType))&&(i.timeItems=i.timeItems.filter(({itemType:a})=>![Bo,so].includes(a)),gt({tournamentId:t?.tournamentId,context:o,drawDefinition:e,matchUp:i})),{...C}):{error:Le}}function IA(t){if(typeof t?.venueId!="string")return{error:Xo};let{tournamentRecord:e,venueId:r,force:n}=t,o=t.tournamentRecords||e&&{[e.tournamentId]:e}||{};if(!Object.keys(o).length)return{error:Y};let s=Un({tournamentRecords:o,contextFilters:{venueIds:[r]}}).matchUps??[],a=yt({tournamentRecord:e})?.appliedPolicies,c=n??a?.[No]?.allowDeletionWithScoresPresent?.venues;if(!s.length||c)for(let u of Object.values(o)){for(let m of s){let d=gA({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&&mt({payload:{venueId:r,tournamentId:u.tournamentId},topic:Lf,key:r})}else return vl({matchUpsCount:s.length});return Rc({tournamentRecords:o}),{...C}}function HR({tournamentRecord:t,venueIds:e,force:r}){if(!t)return{error:Y};if(!Array.isArray(e))return{error:G};for(let n of t.venues||[]){let{venueId:o}=n;if(e.includes(o)){let{venueId:i}=n,s=IA({tournamentRecord:t,venueId:i,force:r});if(s.error)return s}}return{...C}}function WR(t){let{courtIds:e,dates:r}=t,n=Dr(t),o=[{[Re]:!0,[dp]:!0}],i=rt(t,o);if(i.error)return i;for(let s of Object.values(n))d0({tournamentRecord:s,courtIds:e,dates:r});return{...C}}function d0({tournamentRecord:t,courtIds:e,dates:r}){let n=Array.isArray(r)&&r.length?{dates:r}:!0,o=i=>At({extension:{value:n,name:no},creationTime:!1,element:i});for(let i of t.venues||[])for(let s of i.courts||[])if(e?.includes(s.courtId)){let a=o(s);if(a.error)return a}return{...C}}function jR(t){let{tournamentRecords:e,tournamentId:r,venueIds:n}=t,o=[{[Re]:!0,[lp]:!0}],i=rt(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];l0({tournamentRecord:c,venueIds:n})}return{...C}}function l0({tournamentRecord:t,venueIds:e}){for(let r of t.venues||[])if(e?.includes(r.venueId)){let n=At({creationTime:!1,element:r,extension:{name:no,value:!0}});if(n.error)return n}return{...C}}function YR(t){let e=Dr(t),r=[{[Re]:!0}];!t.enableAll&&r.push({[dp]:!0});let n=rt(t,r);if(n.error)return n;let{enableAll:o,courtIds:i,dates:s}=t;for(let a of Object.values(e))f0({tournamentRecord:a,courtIds:i,enableAll:o,dates:s});return{...C}}function f0({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}=dt({element:i,name:no});if(s){let a=s.value;Array.isArray(a.dates)&&(a.dates=a.dates.filter(c=>!n.includes(c))),At({extension:{name:no,value:a},creationTime:!1,element:i})}}else gr({element:i,name:no});return{...C}}function qR(t){let e=Dr(t),r=[{[Re]:!0}];!t.enableAll&&r.push({[lp]:!0});let n=rt(t,r);if(n.error)return n;let{venueIds:o,enableAll:i}=t;for(let s of Object.values(e))for(let a of s.venues||[])(i||o?.includes(a.venueId))&&gr({element:a,name:no});return{...C}}function $R(t){let{courtId:e,disableNotice:r,force:n}=t,o=Dr(t),i=rt(t,[{[Re]:!0,[Mh]:!0}]);if(i.error)return i;let s,a;for(let c of Object.values(o)){if(a=g0({tournamentRecord:c,disableNotice:r,courtId:e,force:n}),a.error&&a.error!==Os)return a;a.success&&(s=!0)}return s?{...C}:a}function g0({tournamentRecord:t,disableNotice:e,courtId:r,force:n}){let o=ps({tournamentRecord:t,courtId:r});if(o.error)return o;let i=o.venue,{matchUps:s}=bl({tournamentRecord:t,courtId:r}),a=yt({tournamentRecord:t})?.appliedPolicies,c=n??a?.[No]?.allowDeletionWithScoresPresent?.courts;if(!s?.length||c){for(let u of s??[]){let p=gA({matchUpId:u.matchUpId,drawId:u.drawId,tournamentRecord:t});if(p.error)return p}i&&(i.courts=(i.courts??[]).filter(u=>u.courtId!==r),e||mt({payload:{venue:i,tournamentId:t.tournamentId},topic:yi,key:i.venueId}))}else return vl({matchUpsCount:s.length});return{...C}}function AI(t){let{disableNotice:e,modifications:r,courtId:n,force:o,venueMatchUps:i}=t,s=Dr(t);if(!Object.keys(s).length)return{error:wt};let a,c;for(let u of Object.values(s)){let p=I0({tournamentRecord:u,disableNotice:e,venueMatchUps:i,modifications:r,courtId:n,force:o});if(p?.error)return p;a=!0}return a?{...C}:c}function I0({tournamentRecord:t,disableNotice:e,venueMatchUps:r,modifications:n,courtId:o,force:i}){if(!t)return{error:Y};if(!o)return{error:_i};if(!n||typeof n!="object")return{error:lo};let s=ps({tournamentRecord:t,courtId:o});if(s.error)return s;let{venue:a,court:c}=s,u=Object.keys(nw()).filter(l=>l!=="courtId");if(!Object.keys(n).filter(l=>u.includes(l)).length)return{error:Ju};let m=u.filter(l=>!["dateAvailability"].includes(l)),d=Object.keys(n).filter(l=>m.includes(l));if(c&&d.forEach(l=>Object.assign(c,{[l]:n[l]})),n.dateAvailability){let l=yI({dateAvailability:n.dateAvailability,tournamentRecord:t,venueMatchUps:r,disableNotice:e,courtId:o,force:i});if(l.error)return l}return e||mt({payload:{venue:a,tournamentId:t.tournamentId},topic:yi,key:a?.venueId}),{...C,court:J(c)}}var h0=()=>({venueId:void 0,venueName:"",venueAbbreviation:"",onlineResources:[],venueType:void 0,addresses:[],contacts:[],courts:[],roles:[]}),yw=h0;function KR(t){let{modifications:e,venueId:r,force:n}=t,o=Dr(t);if(!Object.keys(o).length)return{error:wt};if(typeof r!="string")return{error:Xo};let i,s;for(let a of Object.values(o)){let c=S0({tournamentRecord:a,modifications:e,venueId:r,force:n});if(c.success&&(s=!0),c.error&&(i=c.error),c.error&&c.error!==Li)return c}return Rc({tournamentRecords:o}),s?{...C}:{error:i}}function S0({tournamentRecord:t,modifications:e,venueId:r,force:n}){if(!t)return{error:Y};if(!e||typeof e!="object")return{error:lo};if(!r)return{error:Xo};let o=yt({tournamentRecord:t})?.appliedPolicies,i=n??o?.[No]?.allowDeletionWithScoresPresent?.venues,{matchUps:s}=Tw({tournamentRecord:t,venueId:r}),a=Wo({tournamentRecord:t,venueId:r});if(a.error)return a;let c=a.venue,u=Object.keys(yw()).filter(h=>h!=="venueId");if(!Object.keys(e).filter(h=>u.includes(h)).length)return{error:Ju};let m=u.filter(h=>!["courts","onlineResources"].includes(h)),d=Object.keys(e).filter(h=>m.includes(h));c&&d.forEach(h=>Object.assign(c,{[h]:e[h]}));let l=c?.courts?.map(h=>h.courtId)??[],f=e.courts?.map(h=>h.courtId)||[],g=f.length?l.filter(h=>!f.includes(h)):e?.courts&&l,I=[];if(g?.length){let S=c?.courts?.filter(T=>g.includes(T.courtId))?.map(T=>{let y=bl({courtId:T.courtId,tournamentRecord:t,venueMatchUps:s});for(let P of y.matchUps??[])I.push({matchUpId:P.matchUpId,drawId:P.drawId});return y.matchUps?.length??0}).reduce((T,y)=>T+y);if(c&&(!S||i))c.courts=c.courts?.filter(T=>f.includes(T.courtId)),Vu({schedule:{courtId:"",scheduledDate:""},matchUpDetails:I,removePriorValues:!0,tournamentRecord:t});else return vl({matchUpsCount:S})}if(e.courts)for(let h of e.courts){let{courtId:S}=h||{},T=AI({modifications:h,disableNotice:!0,tournamentRecord:t,venueMatchUps:s,courtId:S,force:n});if(T.error===Os&&(T=Ul({disableNotice:!0,tournamentRecord:t,venueId:r,court:h})),T.error)return T}return Rc({tournamentRecord:t}),c&&mt({payload:{venue:c,tournamentId:t.tournamentId},topic:yi,key:c?.venueId}),{...C,venue:J(c)}}var XR={};Xt(XR,{JSON2CSV:()=>Nw,UUID:()=>Dt,UUIDS:()=>th,allNumeric:()=>DI,attributeFilter:()=>Vi,chunkArray:()=>ye,chunkByNth:()=>xl,chunkSizeProfile:()=>DA,constantToString:()=>Qe,countValues:()=>pC,createMap:()=>RI,dateTime:()=>ZI,definedAttributes:()=>ot,dehydrateMatchUps:()=>Dw,extractAttributes:()=>QU,flattenJSON:()=>SA,generateDateRange:()=>ws,generateHashCode:()=>hC,generateRange:()=>et,generateTimeCode:()=>uA,groupValues:()=>UA,hasAttributeValues:()=>IC,instanceCount:()=>Sr,intersection:()=>Yt,isConvertableInteger:()=>It,isNumeric:()=>Zt,isOdd:()=>UI,isPowerOf2:()=>vn,makeDeepCopy:()=>J,matchUpScheduleSort:()=>Pw,matchUpSort:()=>Mi,nearestPowerOf2:()=>Sm,nextPowerOf2:()=>es,noNulls:()=>uC,noNumeric:()=>NI,numericSort:()=>me,occurrences:()=>mC,overlap:()=>Fe,randomMember:()=>yn,randomPop:()=>tn,shuffleArray:()=>Ir,structureSort:()=>Si,subSort:()=>dC,undefinedToNull:()=>MI,unique:()=>ut,visualizeScheduledMatchUps:()=>Aw});function Aw({scheduledMatchUps:t,showGlobalLog:e}){rv();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=>{Rn({color:"blue",method:"draw",structure:n[o],keyColors:{structure:"magenta"}},!0);let i=t.filter(a=>a.structureId===o),s=Ke({matchUps:i})?.roundMatchUps||[];Object.keys(s).forEach(a=>{Rn({roundNumber:a,keyColors:{roundNumber:"brightcyan"}},!0),s[a].forEach(({matchUpId:c,schedule:u})=>{let p=Kt(u.scheduledTime);Rn({matchUpId:c,time:p,date:u.scheduledDate,venue:u.venueId,keyColors:{time:"brightcyan",date:"brightcyan",matchUpId:"yellow",venue:"magenta"}},!0)})})}),e&&ev()}var{extractTime:Ew,timeStringMinutes:Uw}=ZI;function Pw(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=Uw(Ew(r.scheduledTime)),i=Uw(Ew(n.scheduledTime));return o-i}}return new Date(r.scheduledDate).getTime()-new Date(n.scheduledDate).getTime()}return 0}function Dw({tournamentRecord:t}){if(!t)return{error:Y};if(typeof t!="object"||!t.tournamentId)return{error:G};let{matchUps:e}=Te({tournamentRecord:t,inContext:!1});if(e?.length){let r=T0({tournamentRecord:t});A0(e,r)}return{...C}}function T0({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 y0=["collectionId","collectionPosition","drawPositions","extensions","finishingPositionRange","finishingRound","isMock","matchUpId","matchUpStatus","matchUpStatusCodes","orderOfFinish","processCodes","roundNumber","tieFormat","tieMatchUps","roundPosition","score","sides","winnerMatchUpId","loserMatchUpId","matchUpDuration","winningSide"];function A0(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))y0.includes(c)||delete r[c];r.sides&&r.drawPositions&&!r.tieMatchUps&&delete r.sides,a&&(r.matchUpFormat=a)}}function Nw(t,e){if(e&&typeof e!="object")return{error:G};let{columnTransform:r={}}=e||{},{includeTransformAccessors:n,includeHeaderRow:o=!0,returnTransformedJSON:i,removeEmptyColumns:s,onlyHeaderRow:a,columnAccessors:c=[],functionMap:u={},columnMap:p={},valuesMap:m={},context:d={},delimiter:l='"',columnJoiner:f=",",rowJoiner:g=`\r
|
|
27
27
|
`,keyJoiner:I="."}=e||{};if(!Array.isArray(t)||!Array.isArray(c)||typeof d!="object"||typeof p!="object"||typeof r!="object"||typeof u!="object"||typeof m!="object"||typeof f!="string"||typeof g!="string"||typeof I!="string"||typeof l!="string")return{error:G};r=Object.assign({},...Object.keys(r).reverse().map(v=>({[v]:Array.isArray(r[v])?r[v]:[typeof r[v]=="string"&&r[v]].filter(Boolean)})));let h=t.filter(Boolean).map(v=>SA(v,I)),S=Object.values(r).flat();n&&c.push(...S);let T=h.reduce((v,O)=>Object.keys(O).every(x=>!v.includes(x)&&v.push(x)||!0)&&v,[]).filter(v=>!c?.length||c.includes(v)),y=Object.assign({},...Object.keys(r).reverse().map(v=>r[v].map(O=>({[O]:v})).flat()).flat()),P=(v,O)=>e?.sortOrder?e.sortOrder.includes(v)&&e.sortOrder.includes(O)&&e.sortOrder.indexOf(v)-e.sortOrder.indexOf(O)||!e.sortOrder.includes(O)&&-1:0,U=T.reduce((v,O)=>{let x=y[O];return x?v.includes(x)||v.push(x):v.push(O),v},[]).sort(P);Object.keys(p).forEach(v=>!U.includes(v)&&U.unshift(v)),Object.keys(r).forEach(v=>!U.includes(v)&&U.unshift(v)),typeof d=="object"&&Object.keys(d).forEach(v=>!U.includes(v)&&U.unshift(v));let E=U.map(v=>p[v]||v);if(a)return[E];let A=v=>`${l}${v}${l}`,N=[],D=v=>Object.values(U.reduce((O,x,F)=>{let L=r[x],w=(L?.length?v[L.find(W=>v[W])]:v[x])||d?.[x]||"",V=m[x]?.[w]||w,k=Wr(u[x])?u[x](V):V;return O[x]=A(k),k&&(N[F]=(N[F]||0)+1),O},{})),M=h.map(D),R=s&&[...N].map((v,O)=>!v&&O).filter(Zt).reverse();if(R){let v=O=>O.filter((x,F)=>!R.includes(F));M=M.map(v),E=v(E)}let b=M.map(v=>v.join(f));return i?b.map(v=>{let O=v.split(f);return Object.assign({},...O.map((x,F)=>({[E[F]]:x})))}):o?[E.map(A).join(f),...b].join(g):b.join(g)}function SA(t,e=".",r=[]){return typeof t=="object"&&Object.keys(t).reduce((n,o)=>typeof t[o]!="object"?(n[r.concat(o).join(e)]=t[o],n):Object.assign(n,SA(t[o],e,r.concat(o))),{})}var E0={};var{FACTORY:Mw}=xh;function Rw({tournamentRecord:t,value:e}){let{extension:r}=dt({element:t,name:Mw}),n={name:Mw,value:{...r?.value,...e}};At({element:t,extension:n})}function Hu({timeStamp:t}){let e=Fo(),r=cf();return r&&Object.values(e).forEach(n=>{Rw({tournamentRecord:n,value:{version:Va(),timeStamp:t}})}),r}function TA({engineType:t,methodName:e,elapsed:r,params:n,result:o}){let i=Ur();if(typeof i!="object")return;let s={method:e},a=o?.error&&(i.errors===!0||Array.isArray(i.errors)&&i.errors.includes(e)),c=Array.isArray(i.params)&&i.params?.includes(e),u=i.params&&!Array.isArray(i.params)||c,p=Array.isArray(i.exclude)&&i.exclude.includes(e);!p&&![void 0,!1].includes(i.perf)&&!isNaN(i.perf)&&r>=i.perf&&(s.elapsed=r),!p&&(a||u)&&(s.params=n),!p&&(a||i.result&&!Array.isArray(i.result)&&(!Array.isArray(i.params)||c)||Array.isArray(i.result)&&i.result?.includes(e))&&(s.result=o),Object.keys(s).length>1&&GE(s,t)}function ka({methodName:t,params:e,start:r}){let n={error:za,methodName:t},o=r?Date.now()-r:0;return TA({result:n,methodName:t,elapsed:o,params:e,engineType:"sync"}),n}function Cw(t,e){if(e._middleware===!1)return e;if(e.tournamentId&&!t[e.tournamentId])return{error:Y};let r=e.drawId||e.matchUp?.drawId;if(r){let{event:i,drawDefinition:s,tournamentId:a}=ze({tournamentRecords:t,drawId:r});s&&(e.drawDefinition=s),a&&(e.tournamentId=a),i&&(e.event=i)}if(e.eventId&&!e.event){let{event:i,tournamentId:s}=ze({eventId:e.eventId,tournamentRecords:t});if(!i)return{error:jr};e.tournamentId=s,e.event=i}let n=e.tournamentId??ns();if(!n&&e)return e;let o=t[n];return n&&!o?{error:Y}:(o&&(e.tournamentRecord=o),e)}function Ga(t,e,r,n,o){delete t.success,delete t.error;let i=Date.now(),s=ns();r&&(r.activeTournamentId=s);let a=r?.tournamentRecord||pf(s),c=typeof r?.tournamentRecord=="object"&&{[r?.tournamentRecord.tournamentId]:r.tournamentRecord}||Fo(),u=r?J(r,void 0,!0):void 0,p=r?Cw(c,r):void 0;if(p?.error)return p;let m=U0({params:p,tournamentRecords:c,tournamentRecord:a,methodName:n,method:e}),d=Date.now()-i;return TA({result:m,methodName:n,elapsed:d,params:u,engineType:o}),m}function U0({tournamentRecords:t,tournamentRecord:e,params:r,methodName:n,method:o}){if(Ur())return o({tournamentRecords:t,tournamentRecord:e,...r});try{return o({tournamentRecords:t,tournamentRecord:e,...r})}catch(i){return op({engineName:"engine",methodName:n,params:r,err:i})}}function Wu(t){let{mutationStatus:e,tournamentId:r,directives:n,timeStamp:o}=t||{},{topics:i}=Lr();for(let s of[...i].sort(vw)){let a=jI({topic:s});a?.length&&Pm({topic:s,notices:a})}e&&o&&i.includes(zm)&&Pm({notices:[{tournamentId:r,directives:n,timeStamp:o}],topic:zm})}async function yA(t){let{mutationStatus:e,tournamentId:r,directives:n,timeStamp:o}=t||{},{topics:i}=Lr();for(let s of[...i].sort(vw)){let a=jI({topic:s});a&&await Pm({topic:s,notices:a})}e&&o&&i.includes(zm)&&Pm({notices:[{tournamentId:r,directives:n,timeStamp:o}],topic:zm})}var bw={[jf]:5,[Wf]:5,[Yf]:5,[Hf]:5,[Bf]:5,[Gf]:5,[bU]:5,[vU]:5,[Vf]:1,[Sp]:1,[nr]:5,[yi]:5,[kf]:4,[wf]:4,[Lf]:4,[Ff]:4,[hp]:3,[_f]:2};function vw(t,e){return(bw[e]||0)-(bw[t]||0)}function Ow({convertExtensions:t,removeExtensions:e}){let r=Fo();return{tournamentId:ns(),tournamentRecords:J(r,t,!1,e)}}function _w(t){let{convertExtensions:e=!1,removeExtensions:r=!1}=t??{},n=t?.tournamentId??ns();if(typeof n!="string")return{};let o=pf(n);return{tournamentRecord:J(o,e,!1,r)}}function xw(){let t=Fo(),{extension:e}=dt({name:Bs,tournamentRecords:t,discover:!0}),r=e?.value?.tournamentIds||[];return Object.keys(t).forEach(n=>{r.includes(n)||delete t[n]}),Dm(t)}function JR(t,e=!0){return typeof t!="object"||Array.isArray(t)?{error:lo}:t?.tournamentId?FE(e?J(t):t):{error:G}}function Ji(t,e=!0){if(typeof t!="object")return{error:lo};if(np(),Array.isArray(t)){if(!(t.filter(n=>n?.tournamentId).length===t.length))return{error:vI};t=Object.assign({},...t.map(n=>({[n.tournamentId]:n})))}else if(t?.tournamentId)t={[t.tournamentId]:t},np(t.tournamentId);else if(!Object.keys(t).every(n=>t[n].tournamentId===n))return{error:vI};return Dm(e?J(t):t)}async function ww(t,e,r){if(!Array.isArray(e))return{error:G,message:"directives must be an array"};let n=uf(),o=Date.now(),i=r&&J(Fo(),!1,!0),s=[];for(let p of e){if(typeof p!="object")return{error:G,message:"directive must be an object"};let{method:m,pipe:d}=p,l=p.params?{...p.params}:{};if(!n[m])return ka({methodName:m,start:o,params:l});if(d){let g=s[s.length-1],I=Object.keys(d);for(let h of I)g[h]&&(l[h]=g[h])}let f=Ga(t,n[m],l,m,"async");if(f?.error)return i&&Ji(i),{...f,rolledBack:!!i};s.push({...f,methodName:m})}let a=Date.now(),c=Hu({timeStamp:a});return await yA({directives:e,mutationStatus:c,timeStamp:a}),Fi(),{success:s.every(p=>p.success),results:s}}async function ZR(t,e){if(!ht(e))return{error:G,message:"args must be an object"};let r=Object.values(e).filter(Wr).length;if(r>1)return{message:"there must be only one arg with typeof function",error:G};let n=r?Object.keys(e).find(l=>Wr(e[l])):Vt(e.method)&&e.method;if(!n)return{error:za};let{[n]:o,...i}=e,s=e?.params?{...e.params}:{...i},a=s.rollbackOnError&&J(Fo(),!1,!0),c=o||t[n]||ep()[n];if(!c)return ka({methodName:n,params:s});let u=await Ga(t,c,s,n,"async")??{};u?.error&&a&&Ji(a);let p=Date.now(),m=Hu({timeStamp:p}),d=u?.success&&s?.delayNotify!==!0&&s?.doNotNotify!==!0;return d&&await yA({directives:[{method:c,params:s}],mutationStatus:m,timeStamp:p}),(d||!u?.success||s?.doNotNotify)&&Fi(),u}function Lw(t,e,r,n,o,i){let s=VE(r,n,o,i);if(s.error)return s;let a=s.methods??[];return Object.keys(a).filter(u=>Wr(a[u])).forEach(u=>{t[u]=p=>{let m=()=>e(t,{[u]:a[u],...p});if(Ur())return m();try{return m()}catch(d){op({engineName:"engine",methodName:u,params:p,err:d})}}}),{...C,...t}}function fm(t,e){return e?.error?(t.error=e.error,t.success=!1):(t.error=void 0,t.success=!0),t}function Ol(t,e){t.importMethods=(r,n,o,i)=>Lw(t,e,r,n,o,i),t.getTournament=r=>_w(r),t.getState=r=>Ow({convertExtensions:r?.convertExtensions,removeExtensions:r?.removeExtensions}),t.version=()=>Va(),t.reset=()=>(Dm({}),fm(t)),t.devContext=r=>(Bc(r),fm(t)),t.getDevContext=r=>Ur(r),t.newTournamentRecord=(r={})=>{let n=um(r),o=n.tournamentId;return n.error?n:(JR(n),np(o),{...C,tournamentId:o})},t.setState=(r,n,o)=>{Hc(n,o);let i=Ji(r,n);return fm(t,i)},t.setTournamentId=r=>np(r),t.getTournamentId=()=>ns(),t.setTournamentRecord=(r,n,o)=>{Hc(n,o);let i=JR(r,n);return fm(t,i)},t.removeTournamentRecord=r=>{let n=kE(r);return fm(t,n)},t.removeUnlinkedTournamentRecords=()=>{let r=xw();return fm(t,r)}}function P0(t){let e=wE();if(e.error&&!t)return e;let r={executionQueue:(n,o)=>ww(r,n,o),execute:n=>ZR(r,n)};return Ol(r,ZR),r}function Fw(t,e,r){if(!Array.isArray(e))return{error:G,message:"directives must be an array"};let n=uf(),o=Date.now(),i=r&&J(Fo(),!1,!0),s=[];for(let p of e){if(typeof p!="object")return{error:G,message:"directive must be an object"};if(p.params&&typeof p.params!="object")return{error:G,message:"params must be an object"};let{method:m,pipe:d}=p,l=p.params?{...p.params}:{};if(!n[m])return ka({methodName:m,start:o,params:l});if(d){let g=s[s.length-1],I=Object.keys(d);for(let h of I)g[h]&&(l[h]=g[h])}let f=Ga(t,n[m],l,m,"sync");if(f?.error)return i&&Ji(i),{...f,rolledBack:!!i};s.push({...f,methodName:m})}let a=Date.now(),c=Hu({timeStamp:a});return Wu({directives:e,mutationStatus:c,timeStamp:a}),Fi(),{success:s.every(p=>p.success),results:s}}function tC(t,e){if(!ht(e))return{error:G,message:"args must be an object"};let r=Object.values(e).filter(Wr).length;if(r>1)return{message:"there must be only one arg with typeof function",error:G};let n=r?Object.keys(e).find(l=>Wr(e[l])):Vt(e.method)&&e.method;if(!n)return{error:za};let{[n]:o,...i}=e,s=e?.params?{...e.params}:{...i},a=s.rollbackOnError&&J(Fo(),!1,!0),c=o||t[n]||ep()[n];if(!c)return ka({methodName:n,params:s});let u=Ga(t,c,s,n,"sync")??{};u?.error&&a&&Ji(a);let p=Date.now(),m=Hu({timeStamp:p}),d=u?.success&&s?.delayNotify!==!0&&s?.doNotNotify!==!0;return d&&Wu({directives:[{method:c,params:s}],mutationStatus:m,timeStamp:p}),(d||!u?.success||s?.doNotNotify)&&Fi(),u}var kw=(()=>{let t={executionQueue:(e,r)=>Fw(t,e,r),execute:e=>tC(t,e)};return Ol(t,tC),t})(),gm=kw;function eC(t,e){if(!ht(e))return{error:G,message:"args must be an object"};let r=Object.values(e).filter(Wr).length;if(r>1)return{message:"there must be only one arg with typeof function",error:G};let n=r?Object.keys(e).find(c=>Wr(e[c])):Vt(e.method)&&e.method;if(!n)return{error:za};let{[n]:o,...i}=e,s=e?.params?{...e.params}:{...i},a=o||t[n]||ep()[n];return a?Ga(t,a,s,n,"ask"):ka({methodName:n,params:s})}var D0=(()=>{let t={execute:e=>eC(t,e)};return Ol(t,eC),t})();var Im={},wc;function rC(t,e=!0){if(!t)return{error:st};if(typeof t!="object")return{error:lo};if(t.matchUpId)wc=t.matchUpId,Im[wc]=e?J(t):t;else if(Array.isArray(t))for(let r of t.reverse())r.matchUpId&&(Im[r.matchUpId]=e?J(r):r,wc||(wc=r.matchUpId));else for(let r of Object.values(t))r.matchUpId&&(Im[r.matchUpId]=e?J(r):r,wc||(wc=r.matchUpId));return e?J(t):t}function Gw(){return Im[wc]}function Vw(){return Object.values(Im)}function Bw(){wc=void 0,Im={}}function Hw(t){return J(Im[wc],t?.convertExtensions,!1,t?.removeExtensions)}var N0=(()=>{let t={getState:o=>Hw(o),version:()=>Va(),reset:()=>(Bw(),{...C}),drawId:void 0,error:void 0,success:!1,devContext:o=>(Bc(o),t),setState:(o,i,s)=>{Hc(i,s);let a=rC(o);return e(a)}};function e(o){return o?.error?(t.error=o.error,t.success=!1):(t.error=void 0,t.success=!0,t.drawId=o.drawId),t}return r([Hg]),t;function r(o){o.forEach(i=>{Object.keys(i).forEach(s=>{t[s]=a=>{if(Ur())return n({params:a,governor:i,methodName:s});try{return n({params:a,governor:i,methodName:s})}catch(c){op({engineName:"matchUpEngine",methodName:s,params:a,err:c})}}})})}function n({params:o,governor:i,methodName:s}){t.error=void 0,t.success=!1;let a=o?.matchUp||Gw(),c=o?.matchUps||Vw(),u=o?.rollbackOnError&&J(a,!1,!0);o={...o,matchUpId:a?.matchUpId,matchUps:c,matchUp:a};let p=i[s](o);if(p?.error)return u&&rC(u),{...p,rolledBack:!!u};let m=p?.success&&o?.delayNotify!==!0&&o?.doNotNotify!==!0;return m&&Wu(),(m||!p?.success||o?.doNotNotify)&&Fi(),p}})();var nC=!1,M0=(()=>{let t={version:()=>Va(),setDeepCopy:(n,o)=>(Hc(n,o),t),devContext:n=>(Bc(n),nC=!0,t)};return r([fI]),t;function e(n,o){let i=n({...o});return i?.error||Wu(),Fi(),nC&&(Bc(!1),nC=!1),i}function r(n){n.forEach(o=>{Object.keys(o).forEach(i=>{t[i]=s=>{if(Ur()){let a=e(o[i],s);return!a?.error&&s?.setState&&a?.tournamentRecord&&Ji(a.tournamentRecord),a}else try{let a=e(o[i],s);return!a?.error&&s?.setState&&a?.tournamentRecord&&Ji(a.tournamentRecord),a}catch(a){let c;typeof a=="string"?c=a.toUpperCase():a instanceof Error&&(c=a.message),console.log("ERROR",{params:JSON.stringify(s),method:i,error:c})}}})})}})();gm.importMethods(hA,!0,1);var R0=gm,C0=gm;var b0={getTournamentPoints:Xd},Ww=b0;var v0={calculateNewRatings:ET,generateDynamicRatings:UT},jw=v0;var O0={...Ww,...jw};gm.importMethods(O0);var _0=gm;var Yw={[ru]:{roundsToSeparate:void 0,policyName:"Nationality Code",policyAttributes:[{key:"person.nationalityCode"},{key:"individualParticipants.person.nationalityCode"}]}};var qw={[So]:{policyName:"positionActionsUnrestricted",enabledStructures:[],otherFlightEntries:!0,disableRoundRestrictions:!0,activePositionOverrides:[zs,xp]}};var $w={[So]:{policyName:"positionActionsNoMovement",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[zs,Uu,Qs],disabledActions:[]}]}};var Kw={[So]:{policyName:"positionActionsDisabled",enabledStructures:!1}};var zw={[Vs]:{policyName:"Participant Privacy Policy",participant:{contacts:!1,individualParticipants:{onlineResources:!1,participantName:!0,participantOtherName:!0,participantId:!0,participantRole:!0,participantStatus:!0,penalties:!1,rankings:!0,ratings:!0,representing:!0,participantRoleResponsibilities:!1,participantType:!0,person:{addresses:!1,biographicalInformation:!1,birthDate:!1,contacts:!1,nationalityCode:!0,nativeFamilyName:!1,nativeGivenName:!1,onlineResources:!1,otherNames:!0,parentOrganisationId:!1,passportFamilyName:!1,passportGivenName:!1,personId:!1,personOtherIds:!1,previousNames:!1,sex:!1,standardFamilyName:!0,standardGivenName:!0,status:!1,tennisId:!1,wheelchair:!0}},individualParticipantIds:!0,onlineResources:!1,participantName:!0,participantOtherName:!0,participantId:!0,participantRole:!0,participantStatus:!0,penalties:!1,rankings:!0,ratings:!0,representing:!0,participantRoleResponsibilities:!1,participantType:!0,person:{addresses:!1,biographicalInformation:!1,birthDate:!1,contacts:!1,nationalityCode:!0,nativeFamilyName:!1,nativeGivenName:!1,onlineResources:!1,otherNames:!0,parentOrganisationId:!1,passportFamilyName:!1,passportGivenName:!1,personId:!1,personOtherIds:!1,previousNames:!1,sex:!1,standardFamilyName:!0,standardGivenName:!0,status:!1,tennisId:!1,wheelchair:!0}}}};var Qw={[en]:{processCodes:{incompleteAssignmentsOnDefault:["RANKING.IGNORE"]},defaultMatchUpFormat:Dn,allowDeletionWithScoresPresent:{drawDefinitions:!1,structures:!1},requireParticipantsForScoring:!1,requireAllPositionsAssigned:void 0,allowChangePropagation:!1,stage:{[nt]:{stageSequence:{1:{requireAllPositionsAssigned:!0}}}},matchUpFormats:[],matchUpStatusCodes:{[br]:[],[oo]:[],[Mt]:[],[pn]:[],[rr]:[],[Ct]:[]}}};var oC="Personal circumstance",Xw={[en]:{requireAllPositionsAssigned:!1,stage:{[nt]:{stageSequence:{1:{requireAllPositionsAssigned:!0}}}},defaultMatchUpFormat:Dn,matchUpFormats:[{description:"Best of 3 tiebreak sets",matchUpFormat:Dn,categoryNames:[],categoryTypes:[]},{description:"Two tiebreak sets, 7-point match tiebreak at one set all",matchUpFormat:"SET3-S:6/TB7-F:TB7"},{description:"Two tiebreak sets, 10-point match tiebreak at one set all",matchUpFormat:"SET3-S:6/TB7-F:TB10"},{description:"One standard tiebreak set to 6, 7-point tiebreak at 6 games all",matchUpFormat:"SET1-S:6/TB7"},{description:"Best of 3 sets to 4",matchUpFormat:"SET3-S:4/TB7"},{description:"Two out of three short sets to 4 with 5-point tiebreak at 3 games all",matchUpFormat:"SET3-S:4/TB5@3"},{description:"One short set to 4, 7-point tiebreak at 4 games all",matchUpFormat:"SET1-S:4/TB7"},{description:"One short set to 4, 5-point tiebreak at 3 games all",matchUpFormat:"SET1-S:4/TB5@3"},{description:"Two short sets to 4, 10-point match tiebreak at one set all",matchUpFormat:"SET3-S:4/TB7-F:TB10"},{description:"Two short sets to 4, 7-point match tiebreak at one set all",matchUpFormat:"SET3-S:4/TB7-F:TB7"},{description:"One no advantage set to 5, tiebreak to 9 at 4-4",matchUpFormat:"SET1-S:5/TB9@4"},{description:"One set to 6 with deciding game at 5 games all",matchUpFormat:"SET1-S:6NOAD"},{description:"One short set to 4, deciding game is played at 3 games all",matchUpFormat:"SET1-S:4NOAD"},{description:"Two short sets to 4 with deciding game at 3-3, 7-point match tiebreak at one set all",matchUpFormat:"SET3-S:4NOAD-F:TB7"},{description:"8 game pro-set with 7 point tiebreak at 8 games all",matchUpFormat:"SET1-S:8/TB7"},{description:"8 game pro-set with 7 point tiebreak at 7 games all",matchUpFormat:"SET1-S:8/TB7@7"},{description:"Best of 3 10-point tiebreak games",matchUpFormat:"SET3-S:TB10"},{description:"One 10-point tiebreak game",matchUpFormat:"SET1-S:TB10"},{description:"Timed 20 minute game - game based",matchUpFormat:"SET1-S:T20"}],matchUpStatusCodes:{[br]:[{matchUpStatusCodeDisplay:"Abandoned",label:"Abandoned match",matchUpStatusCode:"OA"}],[oo]:[{matchUpStatusCodeDisplay:"Unplayed or Cancelled",label:"Cancelled match",matchUpStatusCode:"OC"}],[pn]:[{matchUpStatusCodeDisplay:"Incomplete",label:"Incomplete match",matchUpStatusCode:"OI"}],[Mt]:[{description:"Disqualification for cause or ineligibility",label:"Disqualification (ineligibility)",matchUpStatusCodeDisplay:"Def [dq]",matchUpStatusCode:"DQ"},{description:"Misconduct before or between matches",label:"Misconduct",matchUpStatusCodeDisplay:"Def [cond]",matchUpStatusCode:"DM"},{description:"Failure to start match because of adult discipline",label:"Fail. (adult discipline)",matchUpStatusCodeDisplay:"Def [ad]",matchUpStatusCode:"D5"},{description:"Refusal to start match for reason other than adult discipline, injury, illness, or personal circumstance. (After the Referee has conclusively confirmed that a player refuses to play a match, the Referee need not wait until the scheduled time of the match to records the result.)",label:"Refusal to start match",matchUpStatusCodeDisplay:"Def [refsl]",matchUpStatusCode:"D4"},{label:"Not showing up",matchUpStatusCodeDisplay:"Def [ns]",matchUpStatusCode:"D6"},{description:"Lateness for match including, but not limited to, intending to play but mistakenly arriving at the wrong time, location, or without proper equipment",label:"Lateness for match",matchUpStatusCodeDisplay:"Score + Def [late]",matchUpStatusCode:"D7"},{label:"Double default",matchUpStatusCodeDisplay:"Def/Def",matchUpStatusCode:"DD"},{description:"Refusal to continue playing a match for reason other than injury, illness, personal circumstance, or adult discipline",label:"Refusal to continue match",matchUpStatusCodeDisplay:"Def [refsl]",matchUpStatusCode:"D9"},{description:"Default for receiving an injection, IV, or supplemental oxygen",label:"Default (PEDs)",matchUpStatusCodeDisplay:"Def [med]",matchUpStatusCode:"DI"},{description:"Default under Point Penalty System",label:"Default (Point Penalty System)",matchUpStatusCodeDisplay:"Def [pps]",matchUpStatusCode:"DP"}],[Ct]:[{matchUpStatusCodeDisplay:"Wo [inj]",matchUpStatusCode:"W1",label:"Injury"},{matchUpStatusCodeDisplay:"Wo [ill]",matchUpStatusCode:"W2",label:"Illness"},{matchUpStatusCodeDisplay:"Wo [pc]",label:oC,matchUpStatusCode:"W3"},{matchUpStatusCodeDisplay:"Wo/Wo",matchUpStatusCode:"WOWO",label:"Double walkover"},{matchUpStatusCodeDisplay:"Wo [Tae]",label:"Tournament Administrative Error",matchUpStatusCode:"W4"},{matchUpStatusCodeDisplay:"Wo/Withdrawn",matchUpStatusCode:"W5",label:"Withdrawn"}],[rr]:[{matchUpStatusCodeDisplay:"Ret [inj]",matchUpStatusCode:"RJ",label:"Injury"},{matchUpStatusCodeDisplay:"Ret [ill]",matchUpStatusCode:"RI",label:"Illness"},{matchUpStatusCodeDisplay:"Ret [pc]",label:oC,matchUpStatusCode:"RC"},{description:"Retirement because of adult discipline",label:"Ret. (adult discipline)",matchUpStatusCodeDisplay:"Ret [ad]",matchUpStatusCode:"RD"},{description:"A player who retires from a match remains eligible for consolations, place playoffs, doubles and subsequent round robin matches",matchUpStatusCodeDisplay:"Ret [elg]",label:"Ret. (eligible)",matchUpStatusCode:"RU"}],[io]:[{matchUpStatusCodeDisplay:"Wd [inj]",matchUpStatusCode:"WD.INJ",label:"Injury"},{matchUpStatusCodeDisplay:"Wd [ill]",matchUpStatusCode:"WD.ILL",label:"Illness"},{matchUpStatusCodeDisplay:"Wd [pc]",label:oC,matchUpStatusCode:"WD.PC"},{matchUpStatusCodeDisplay:"Wd/Wd",matchUpStatusCode:"WD.WD",label:"Double withdrawal"},{label:"Tournament Administrative Error",matchUpStatusCodeDisplay:"Wd [Tae]",matchUpStatusCode:"WD.TAE"}]}}};var Jw={[xn]:{seedingProfile:{positioning:Kc},validSeedPositions:{ignore:!0},duplicateSeedNumbers:!0,drawSizeProgression:!0,policyName:"ITF SEEDING",seedsCountThresholds:[{drawSize:4,minimumParticipantCount:3,seedsCount:2},{drawSize:16,minimumParticipantCount:12,seedsCount:4},{drawSize:32,minimumParticipantCount:24,seedsCount:8},{drawSize:64,minimumParticipantCount:48,seedsCount:16},{drawSize:128,minimumParticipantCount:97,seedsCount:32},{drawSize:256,minimumParticipantCount:192,seedsCount:64}]}};var Zw={POLICY_AVOIDANCE_COUNTRY:Yw,POLICY_POSITION_ACTIONS_DEFAULT:iT,POLICY_POSITION_ACTIONS_DISABLED:Kw,POLICY_POSITION_ACTIONS_NO_MOVEMENT:$w,POLICY_POSITION_ACTIONS_UNRESTRICTED:qw,POLICY_PRIVACY_DEFAULT:zw,POLICY_ROUND_NAMING_DEFAULT:tg,POLICY_SCHEDULING_DEFAULT:AN,POLICY_SCORING_DEFAULT:Qw,POLICY_SCORING_USTA:Xw,POLICY_SEEDING_ITF:Jw,POLICY_SEEDING_DEFAULT:oN};var x0={ratingsParameters:we,matchUpFormats:jC,countryToFlag:FU,tieFormats:Ey,countries:ti,policies:Zw,flagIOC:Ab};var nL={};Xt(nL,{activeMatchUpStatuses:()=>Km,auditConstants:()=>nx,completedMatchUpStatuses:()=>ce,directingMatchUpStatuses:()=>Fh,displayConstants:()=>H_,drawDefinitionConstants:()=>lU,entryStatusConstants:()=>Ub,errorConditionConstants:()=>PC,eventConstants:()=>KC,extensionConstants:()=>xh,flightConstants:()=>cx,genderConstants:()=>Nm,keyValueConstants:()=>JO,matchUpActionConstants:()=>DO,matchUpStatusConstants:()=>Vh,matchUpTypes:()=>sC,nonDirectingMatchUpStatuses:()=>kh,particicipantsRequiredMatchUpStatuses:()=>wh,participantConstants:()=>yb,participantRoles:()=>gd,participantTypes:()=>mu,penaltyConstants:()=>tL,policyConstants:()=>db,positionActionConstants:()=>Zv,ratingConstants:()=>sO,recoveryTimeRequiredMatchUpStatuses:()=>gb,requestConstants:()=>Hx,resourceContants:()=>WC,resultConstants:()=>SC,scaleConstants:()=>mb,scheduleConstants:()=>Vb,sortingConstants:()=>fx,surfaceConstants:()=>eL,tieFormatConstants:()=>YC,timeItemConstants:()=>Fb,topicConstants:()=>hb,tournamentConstants:()=>fA,upcomingMatchUpStatuses:()=>Gh,validMatchUpStatuses:()=>Lh,venueConstants:()=>rL,weekdayConstants:()=>Py});var w0="Coaching",L0="Ball Abuse",F0="Racket Abuse",k0="Verbal Abuse",G0="INELIGIBILITY",V0="Physical Abuse",B0="Unsportmanlike Conduct",H0="Dress Code Violation",W0="Equipment Violation",j0="Leaving the court",Y0="Failure to complete",q0="No Show",$0="Other",K0="REFUSAL_TO_PLAY",z0="PROHIBITED_SUBSTANCE",Q0="Puncuality",X0="Failure to sign in",tL={COACHING:w0,BALL_ABUSE:L0,RACKET_ABUSE:F0,VERBAL_ABUSE:k0,PHYSICAL_ABUSE:V0,INELIGIBILITY:G0,UNSPORTSMANLIKE_CONDUCT:B0,PROHIBITED_SUBSTANCE:z0,DRESS_CODE_VIOLATION:H0,EQUIMENT_VIOLATION:W0,LEAVING_THE_COURT:j0,REFUSAL_TO_PLAY:K0,FAILURE_TO_COMPLETE:Y0,NO_SHOW:q0,OTHER:$0,PUNCTUALITY:Q0,FAILUIRE_TO_SIGN_IN:X0};var J0="CLAY",Z0="HARD",tB="GRASS",eB="CARPET",rB="ARTIFICIAL",eL={CLAY:J0,HARD:Z0,GRASS:tB,CARPET:eB,ARTIFICIAL:rB};var nB="INDOOR",oB="OUTDOOR",rL={INDOOR:nB,OUTDOOR:oB};export{Km as activeMatchUpStatuses,D0 as askEngine,P0 as asyncEngine,nx as auditConstants,R0 as competitionEngine,DU as competitionGovernor,ce as completedMatchUpStatuses,Fh as directingMatchUpStatuses,H_ as displayConstants,lU as drawDefinitionConstants,MN as drawsGovernor,xN as entriesGovernor,Ub as entryStatusConstants,PC as errorConditionConstants,KC as eventConstants,$N as eventGovernor,xh as extensionConstants,nL as factoryConstants,x0 as fixtures,cx as flightConstants,E0 as forge,Nm as genderConstants,ZN as generationGovernor,bC as globalState,hA as governors,JO as keyValueConstants,DO as matchUpActionConstants,N0 as matchUpEngine,Oy as matchUpFormatCode,Oy as matchUpFormatGovernor,yM as matchUpGovernor,Vh as matchUpStatusConstants,sC as matchUpTypes,M0 as mocksEngine,fI as mocksGovernor,kh as nonDirectingMatchUpStatuses,wh as particicipantsRequiredMatchUpStatuses,yb as participantConstants,QM as participantGovernor,gd as participantRoles,mu as participantTypes,tL as penaltyConstants,db as policyConstants,nN as policyGovernor,Zv as positionActionConstants,iR as publishingGovernor,DN as queryGovernor,sO as ratingConstants,gb as recoveryTimeRequiredMatchUpStatuses,sR as reportGovernor,Hx as requestConstants,WC as resourceContants,SC as resultConstants,mb as scaleConstants,_0 as scaleEngine,Vb as scheduleConstants,SR as scheduleGovernor,Hg as scoreGovernor,fx as sortingConstants,eL as surfaceConstants,kw as syncEngine,YC as tieFormatConstants,RR as tieFormatGovernor,Fb as timeItemConstants,XR as tools,hb as topicConstants,fA as tournamentConstants,C0 as tournamentEngine,VR as tournamentGovernor,Gh as upcomingMatchUpStatuses,XR as utilities,Lh as validMatchUpStatuses,rL as venueConstants,QR as venueGovernor,Va as version,Py as weekdayConstants};
|