courthive-components 0.7.14 → 0.7.15

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.
@@ -2,7 +2,7 @@
2
2
  Copyright (c) 2018 Jed Watson.
3
3
  Licensed under the MIT License (MIT), see
4
4
  http://jedwatson.github.io/classnames
5
- */(function(t){(function(){var e={}.hasOwnProperty;function n(){for(var r=[],s=0;s<arguments.length;s++){var i=arguments[s];if(i){var o=typeof i;if(o==="string"||o==="number")r.push(i);else if(Array.isArray(i)){if(i.length){var c=n.apply(null,i);c&&r.push(c)}}else if(o==="object"){if(i.toString!==Object.prototype.toString&&!i.toString.toString().includes("[native code]")){r.push(i.toString());continue}for(var a in i)e.call(i,a)&&i[a]&&r.push(a)}}}return r.join(" ")}t.exports?(n.default=n,t.exports=n):window.classNames=n})()})(Mm);var i1=Mm.exports;const ji=Om(i1);function o1({individualParticipant:t,className:e}){var c,a;const{city:n,state:r,countryCode:s}=((a=(c=t==null?void 0:t.person)==null?void 0:c.addresses)==null?void 0:a[0])||{},i=[n,r,s].filter(Boolean).join(", ")||" ",o=document.createElement("div");return o.className=ji(Um(),e),o.innerHTML=i,o}function c1({individualParticipant:t,className:e}){var s,i;const n=((i=(s=t==null?void 0:t.teams)==null?void 0:s[0])==null?void 0:i.participantName)||" ",r=document.createElement("div");return r.className=ji(Um(),e),r.classList.add("tmx-tm"),n!=null&&n.participantId&&r.setAttribute("id",n.participantId),r.innerHTML=n,r}function a1(t){var s,i,o,c;const e=(i=(s=t==null?void 0:t.composition)==null?void 0:s.configuration)==null?void 0:i.participantDetail;return((c=(o=t==null?void 0:t.composition)==null?void 0:o.configuration)==null?void 0:c.showAddress)??e==="ADDRESS"?o1(t):e==="TEAM"?c1(t):document.createElement("div")}const u1=zt({color:"$participant$seed",marginInlineStart:".5rem",textTransform:"uppercase",fontSize:"0.75rem",lineHeight:"1rem"});function l1({className:t,composition:e,side:n}){const r=(n==null?void 0:n.seedValue)||(n==null?void 0:n.seedNumber);if(!r)return"";const s=(e==null?void 0:e.configuration)||{},{bracketedSeeds:i}=s,o=typeof i=="boolean"&&["(",")"]||i==="square"&&["[","]"]||["",""],c=`${o[0]}${r}${o[1]}`,a=s.seedingElement==="sup"?"sup":"span",u=document.createElement(a);return u.className=t,u.innerHTML=c,u}const d1=zt({WebkitBoxSizing:"border-box",marginInlineEnd:".5em",boxSizing:"border-box",display:"inline-block",position:"relative",fontSize:"smaller",fontWeight:"bold",borderRadius:2,color:"blue",variants:{color:{green:{color:"green"},red:{color:"red"}}}});function f1({individualParticipant:t,composition:e,className:n,matchUp:r,spacer:s}){var b,N,A,C,v,P,U;const i=e==null?void 0:e.configuration,o=((b=i==null?void 0:i.scaleAttributes)==null?void 0:b.eventType)||(r==null?void 0:r.matchUpType)||"SINGLES",c=t==null?void 0:t.rankings,a=t==null?void 0:t.ratings,u=i==null?void 0:i.scaleAttributes,l=u==null?void 0:u.scaleType,f=u==null?void 0:u.scaleName,p=u==null?void 0:u.accessor,h=l==="RATING"?a:c,d=(A=(N=h==null?void 0:h.SINGLES)==null?void 0:N.find(O=>(O==null?void 0:O.scaleName)===f))==null?void 0:A.scaleValue,m=(v=(C=h==null?void 0:h.DOUBLES)==null?void 0:C.find(O=>(O==null?void 0:O.scaleName)===f))==null?void 0:v.scaleValue,g=d&&p?d[p]:d||"",I=m&&p?m[p]:m||"",S=o==="SINGLES"?g:I,T=(P=i==null?void 0:i.scaleAttributes)==null?void 0:P.fallback,E=!s&&(S||T&&(g||I)),y=document.createElement("span");return E&&(y.className=ji(n,d1({color:(U=i==null?void 0:i.scaleAttributes)==null?void 0:U.scaleColor}))),y.innerHTML=E||"",y}const p1="normal",Dm="timed",h1="final",Dd="NOAD",Iu="SET",m1={S:p1,F:h1};function wd(t,e){if(typeof t=="object"){if(t.timed&&!isNaN(t.minutes))return kd(t);if(t.bestOf&&t.setFormat)return g1(t,e)}}function Su(t){return!isNaN(Number(t))&&Number(t)}function kd(t){let e=`T${t.minutes}`;return t.based&&(e+=t.based),t.modifier&&(e+=`@${t.modifier}`),e}function g1(t,e){var u;const n=Su(t.bestOf);if((u=t.setFormat)!=null&&u.timed&&t.simplified&&n===1)return kd(t.setFormat);const r=n&&`${Iu}${n}`||"",s=wm(t.setFormat,e),i=s&&`S:${s}`||"",o=wm(t.finalSetFormat,e),c=n&&n>1&&o&&s!==o&&`F:${o}`||"";if(r&&s)return[r,i,c].filter(l=>l).join("-")}function wm(t,e){if(typeof t=="object"&&Object.keys(t).length){if(t.timed)return kd(t);if(t.tiebreakSet)return km(t.tiebreakSet);const n=Su(t.setTo);if(n){const r=t.NoAD&&Dd||"",s=km(t.tiebreakFormat),i=s&&`/${s}`||"",o=Su(t.tiebreakAt),c=o&&(o!==n||e)&&`@${o}`||"";if(s!==!1)return`${n}${r}${i}${c}`}}}function km(t){if(t){if(typeof t=="object"&&!t.tiebreakTo)return"";if(typeof t=="object"&&Su(t.tiebreakTo)){let e=`TB${t.tiebreakTo}${t.NoAD?Dd:""}`;return t.modifier&&(e+=`@${t.modifier}`),e}else return!1}}function vt(t){return parseInt(typeof t=="number"?t.toString():t)}function mr(t){return isNaN(t)?!1:t&&(t&t-1)===0}function I1(t){if(!mr(t))return!1;let e=t,n=1;for(;e!==2;)n+=1,e=e/2;return n}function _d(t){return isNaN(t)?0:t%2&&t+1||t}function Fd(t){return Math.pow(2,Math.round(Math.log(t)/Math.log(2)))}function Me(t){return!isNaN(parseFloat(t))}function S1(t){const e=vt(t);if(!isNaN(e))return e===0?!1:(e&-e)===1}function Vo(t){if(isNaN(t))return!1;for(;!mr(t);)t++;return t}function Wn(t,e){return t=Math.ceil(t),e=Math.floor(e),Math.floor(Math.random()*(e-t+1))+t}function oe(t){return Number.isSafeInteger(typeof t=="string"?+t:t)}function T1(t=1,e=3,n=!0){let r=0;for(let s=0;s<e;s++)r+=Math.random()*(t/e);return n&&t>1?Math.round(r):r}function y1(t,e){e||(e=1);const n=1/e;return Math.round(t*n)/n}function _m(t,e,n,r,s=2){const i=1-Math.random(),o=1-Math.random();let c=Math.sqrt(-2*Math.log(i))*Math.cos(2*Math.PI*o);return c=c/10+.5,c>1||c<0?c=_m(t,e,n):(c=Math.pow(c,n),c*=e-t,c+=t),r&&(c=y1(c,r)),parseFloat(c.toFixed(s))}function yn(t){if(typeof t=="string"){const e=t.startsWith("T")&&Dm||t.startsWith(Iu)&&Iu||"";if(e===Dm){const r={simplified:!0,setFormat:Bm(t),bestOf:1};if(r.setFormat)return r}if(e===Iu)return E1(t)}}function E1(t){const e=t.split("-"),n=Vc(e[0].slice(3)),r=e&&Fm(e[1]),s=e&&Fm(e[2]),i=n&&n<6,o=!e[2]||s,c=r,a={bestOf:n,setFormat:r};if(s&&(a.finalSetFormat=s),i&&c&&o)return a}function Fm(t){if((t==null?void 0:t[1])===":"){const e=t.split(":"),n=m1[e[0]],r=e[1];if(n&&r){if(r.indexOf("TB")===0){const g=Rm(r);return g===!1?!1:typeof g=="object"?{tiebreakSet:g}:void 0}if(r.indexOf("T")===0)return Bm(r);const o=t.match(/^[FS]:(\d+)([A-Za-z]*)/),c=o&&xm(o[2])||!1,a=!(o!=null&&o[2])||c,u=o?Vc(o[1]):void 0,l=Lm(r),f=l!==!1,p=f&&l||u,h=Rm(r.split("/")[1]),d=h!==!1,m={setTo:u};return c&&(m.NoAD=!0),h?(m.tiebreakFormat=h,m.tiebreakAt=p):m.noTiebreak=!0,u&&a&&d&&f&&m||!1}}}function Lm(t,e=!0){const n=(t==null?void 0:t.indexOf("@"))>0&&t.split("@");if(n)return(e?Vc(n[1]):n[1])||!1}function Rm(t){if(t)if(t.startsWith("TB")){const e=Lm(t,!1),n=t.match(/^TB(\d+)([A-Za-z]*)/),r=n==null?void 0:n[1],s=n&&xm(n[2]),i=!(n!=null&&n[2])||s,o=Vc(r);if(o&&i){const c={tiebreakTo:o};return e&&typeof e=="string"&&!oe(e)&&(c.modifier=e),s&&(c.NoAD=!0),c}else return!1}else return!1}function Bm(t){var c;const e=t.slice(1),n=e.match(/^(\d+)(@?[A-Za-z]*)/),r=Vc(n==null?void 0:n[1]);if(!r)return;const s={timed:!0,minutes:r},i=n==null?void 0:n[2],o=[void 0,"P","G"].includes(i);if(i&&!o){const a=(c=e.match(/^(\d+)(@)([A-Za-z]+)$/))==null?void 0:c[3];return a?(s.modifier=a,s):void 0}return i&&(s.based=n[2]),s}function xm(t){return t&&t.indexOf(Dd)>=0}function Vc(t){return isNaN(Number(t))?0:Number(t)}function nr(t){if(typeof t!="string")return!1;const e=yn(t),n=t.match(/-S:([1-9])+\/TB([0-9]{1,2})@?([1-9]?)*/),r=n==null?void 0:n[1],s=n==null?void 0:n[2],i=n==null?void 0:n[3],o=t.match(/-F:([1-9])+\/TB([0-9]{1,2})@?([1-9]?)*/),c=o==null?void 0:o[1],a=o==null?void 0:o[2],u=o==null?void 0:o[3];return wd(e,!!(n&&s&&r===i||o&&a&&c===u))===t}const b1={isValidMatchUpFormat:nr,stringify:wd,isValid:nr,parse:yn};function Es(){return"1.7.8"}function Bs(t){if(!t)return;const{tieFormatId:e,tieFormats:n}=t;if(t.tieFormat)return t.tieFormat;if(e&&Array.isArray(n))return n.find(r=>r.tieFormatId===e)}function jc({item:t,drawDefinition:e,structure:n,event:r}){var s,i,o;if(t){if(t.tieFormat)return t.tieFormat;if(t.tieFormatId){if(e.tieFormat)return e.tieFormat;const c=(s=e.tieFormats)==null?void 0:s.find(a=>t.tieFormatId===a.tieFormatId);return c||(r.tieFormat?r.tieFormat:(i=r.tieFormats)==null?void 0:i.find(a=>t.tieFormatId===a.tieFormatId))}if(n.tieFormat)return n.tieFormat;if(n.tieFormatId){const c=(o=e.tieFormats)==null?void 0:o.find(a=>n.tieFormatId===a.tieFormatId);if(c)return c}}}function hn({drawDefinition:t,structure:e,matchUp:n,event:r}){return{tieFormat:jc({item:n,drawDefinition:t,structure:e,event:r})||jc({item:e,drawDefinition:t,structure:e,event:r})||Bs(t)||Bs(r)}}function sn(t){return`${t} must be an array`}function Vt(t){return t.filter((e,n,r)=>r.lastIndexOf(e)===n)}function on(t){return t.map(e=>[Math.random(),e]).sort((e,n)=>e[0]-n[0]).map(e=>e[1])}function jo(t){return oe(t)?t:1/0}function Mn(t){return t.reduce((e,n)=>(e[n]||(e[n]=0),e[n]++,e),{})}function N1(t){return A1(Mn(t))}function A1(t){return Object.keys(t).reduce((e,n)=>{const r=t[n];return e[r]?e[r].push(n):e[r]=[n],e},{})}function v1(t,e,n){return n.indexOf(t)===e}function $m(t){return t.filter(v1)}function cn(t){return Array.isArray(t)&&t.length?t.splice(Math.floor(Math.random()*t.length),1)[0]:void 0}function Dn(t){const e=Math.floor(Math.random()*t.length);return t[e]}function ht(t,e){return Array.from({length:e-t},(n,r)=>r+t)}function Br(t,e){return e.reduce((n,r,s)=>(r===t&&n.push(s),n),[])}function qe(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(n=>e.indexOf(n)!==-1).filter((n,r,s)=>s.indexOf(n)===r)}function Vm(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(n=>!e.includes(n))}function tn(t,e){return!Array.isArray(t)||!Array.isArray(e)?!1:t.some(n=>e.includes(n))}function Ge(t,e){return t.reduce((n,r,s)=>{const i=Math.floor(s/e);return n[i]=[].concat(n[i]||[],r),n},[])}function C1(t){return t.reduce((e,n)=>{const r=e[e.length-1];return(!r||r[r.length-1]!==n-1)&&e.push([]),e[e.length-1].push(n),e},[])}function P1(t){return t.reduce((e,n)=>!isNaN(parseInt(n))&&e,!0)}function U1(t){return t.reduce((e,n)=>isNaN(parseInt(n))&&e,!0)}function jm(t,e,n){return t.reduce((r,s,i)=>{const o=n?!!(Math.floor(i/e)%2):!1,c=i%e,a=o?e-1-c:c;return r[a]||(r[a]=[]),r[a].push(s),r},[])}function O1(t,e=1){if(!Array.isArray(t)||!t.every(oe))return[];const n=Math.min(...t,e),r=Math.max(...t);return ht(n,r+1).filter(s=>!t.includes(s))}const $={success:!0},Gm={message:"Chronological error; time violation.",code:"ANACHRONISM"},M1={message:"Cannot remove main structure",code:"ERR_CANNOT_REMOVE_MAIN_STRUCTURE"},Wm={message:"records must be an object with tournamentId keys",code:"ERR_INVALID_TOURNAMENTS"},Gt={message:"Missing tournamentRecords",code:"ERR_MISSING_TOURNAMENTS"},et={message:"Missing tournamentRecord",code:"ERR_MISSING_TOURNAMENT"},Tu={message:"Invalid tournamentRecord",code:"ERR_INVALID_TOURNAMENT"},is={message:"Missing tournamentId",code:"ERR_MISSING_TOURNAMENT_ID"},Gi={message:"Invalid drawDefinition",code:"ERR_INVALID_DRAWDEF"},lt={message:"Missing drawDefinition",code:"ERR_MISSING_DRAWDEF"},D1={message:"Existing drawDefinition(s)",code:"ERR_EXISTING_DRAWDEFS"},rr={message:"drawDefinition not found",code:"ERR_NOT_FOUND_DRAWDEF"},Go={message:"Invalid structure",code:"ERR_INVALID_STRUCTURE"},Hm={message:"Incomplete source structure",code:"ERR_INCOMPLETE_STRUCTURE"},qm={message:"Invalid drawPosition for seedAssignment",code:"ERR_INVALID_SEEDING_POSITION"},Gc={message:"drawPosition already assigned",code:"ERR_EXISTING_POSITION_ASSIGNMENT"},w1={message:"Schedule not cleared",code:"ERR_UNCHANGED_SCHEDULE_NOT_CLEARED"},k1={message:"drawPosition not cleared",code:"ERR_FAILURE_POSITION_NOT_CLEARED"},Ym={message:"Unrecognized drawType",code:"ERR_UNRECOGNIZED_DRAW_TYPE"},Ld={message:"Missing drawPositions",code:"ERR_MISSING_DRAW_POSITIONS"},Rd={message:"drawPosition is active",code:"ERR_ACTIVE_DRAW_POSITION"},Wo={message:"Invlid drawPosition",code:"ERR_INVALID_DRAW_POSITION"},Wc={message:"Missing drawPosition",code:"ERR_MISSING_DRAW_POSITION"},Bd={message:"Invalid drawType",code:"ERR_INVALID_DRAW_TYPE"},xd={message:"Invalid drawSize",code:"ERR_INVALID_DRAW_SIZE"},yu={message:"Cannot set drawSize to be less than existing entries",code:"ERR_INVALID_DRAW_SIZE_MISMATCH"},Eu={message:"Missing drawSize",code:"ERR_MISSING_DRAW_SIZE"},Hn={message:"Missing drawId",code:"ERR_MISSING_DRAW_ID"},_1={message:"drawId exists",code:"ERR_EXISTING_DRAW_ID"},F1={message:"participantId cannot be assigned to multiple seedNumbers",code:"INVALID_PARTICIPANT_SEEDING"},L1={message:"seedsCount greater than drawSize",code:"ERR_INVALID_SEED_COUNT"},R1={message:"Missing seedCountThresholds",code:"ERR_MISSING_SEED_COUNT_THRESHOLD"},B1={message:"Invalid action",code:"ERR_INVALID_ACTION"},zm={message:"Invalid assignment",code:"ERR_INVALID_ASSIGNMENT"},x1={message:"Missing seedAssignments",code:"ERR_MISSING_SEED_ASSIGNMENTS"},$1={message:"Invalid seedNumber",code:"ERR_INVALID_SEED_NUMBER"},V1={message:"Invalid seedPosition",code:"ERR_INVALID_SEED_POSITION"},Km={message:"Missing targetLink",code:"ERR_MISSING_LINK_TARGET"},j1={message:"Existing round",code:"ERR_EXISTING_ROUND"},En={message:"Missing structureId",code:"ERR_MISSING_STRUCTURE_ID"},Te={message:"structure not found",code:"ERR_NOT_FOUND_STRUCTURE"},G1={message:"Missing structures",code:"ERR_MISSING_STRUCTURES"},Wi={message:"Missing structure",code:"ERR_MISSING_STRUCTURE"},W1={message:"drawDefinition contains unlinked structures",code:"ERR_MISSING_STRUCTURE_LINKS"},ui={message:"Invalid eventType",code:"ERR_INVALID_EVENT_TYPE"},Wt={message:"Missing event / eventId",code:"ERR_MISSING_EVENT_ID"},wn={message:"Event not found",code:"ERR_NOT_FOUND_EVENT"},H1={message:"Event exists",code:"ERR_EXISTING_EVENT"},q1={message:"Missing entries",code:"ERR_MISSING_ENTRIES"},Y1={message:"Invalid entries",code:"ERR_INVALID_ENTRIES"},Jm={message:"Missing assignments",code:"ERR_MISSING_ASSIGNMENTS"},Qm={message:"Missing stage",code:"ERR_MISSING_STAGE"},xs={message:"Invalid stage",code:"ERR_INVALID_STAGE"},z1={message:"Missing positionAssignments",code:"ERR_MISSING_POSITION_ASSIGNMENTS"},K1={message:"Cannot Assign BYE status if no assignment: { bye: true }",code:"ERR_UNCHANGED_CANNOT_ASSIGN_BYE"},Zm={message:"Unrecognized matchUpStatus",code:"ERR_UNRECOGNIZED_MATCHUP_STATUS"},bu={message:"Unrecognized matchUpFormat",code:"ERR_UNRECOGNIZED_MATCHUP_FORMAT"},$d={message:"Incompatible matchUpStatus",code:"ERR_INCOMPATIBLE_MATCHUP_STATUS"},Hc={message:"Invalid matchUpStatus",code:"ERR_INVALID_MATCHUP_STATUS"},li={message:"Invalid tieFormat",code:"ERR_INVALID_TIE_FORMAT"},Xm={message:"Invalid matchUpFormat",code:"ERR_INVALID_MATCHUP_FORMAT"},Vd={message:"Missing matchUpFormat",code:"ERR_MISSING_MATCHUP_FORMAT"},J1={message:"Missing collectionDefinition",code:"ERR_MISSING_COLLECTION_DEFINITION"},Nu={message:"Missing tieFormat",code:"ERR_MISSING_TIE_FORMAT"},$e={message:"Missing matchUpId",code:"ERR_MISSING_MATCHUP_ID"},qc={message:"Missing matchUpIds",code:"ERR_MISSING_MATCHUP_IDS"},Ye={message:"matchUp not found",code:"ERR_NOT_FOUND_MATCHUP"},$s={message:"Missing matchUps",code:"ERR_MISSING_MATCHUPS"},Rn={message:"Missing matchUp",code:"ERR_MISSING_MATCHUP"},qn={message:"Invalid matchUp",code:"ERR_INVALID_MATCHUP"},tg={message:"Missing policyType",code:"ERR_MISSING_POLICY_TYPE"},Au={message:"Missing policyDefinitions",code:"ERR_MISSING_POLICY_DEFINITIONS"},Q1={message:"Missing avoidance policy",code:"ERR_MISSING_POLICY_AVOIDANCE"},eg={message:"Missing policy attributes",code:"ERR_MISSING_POLICY_ATTRIBUTES"},Z1={message:"Invalid policyDefinitions",code:"ERR_INVALID_POLICY_DEFINITIONS"},ng={message:"existing policyType",code:"ERR_EXISTING_POLICY_TYPE"},X1={message:"Policy not attached",code:"ERR_FAILURE_POLICY_NOT_ATTACHED"},jd={message:"Policy not found",code:"ERR_NOT_FOUND_POLICY"},tv={message:"Missing scoring policy / matchUpFormats",code:"ERR_MISSING_POLICY_SCORING_MATCHUP_FORMATS"},rg={message:"Invalid sideNumber",code:"ERR_INVALID_SIDE_NUMBER"},Gd={message:"Missing setObject",code:"ERR_MISSING_SET_ATTRIBUTE"},Ho={message:"Missing courtId",code:"ERR_MISSING_COURT_ID"},Tt={message:"Missing value",code:"ERR_MISSING_VALUE"},sg={message:"Missing date",code:"ERR_MISSING_DATE"},ev={message:"No valid dates",code:"ERR_NO_VALID_DATES"},Wd={message:"Invalid bookings",code:"ERR_INVALID_BOOKINGS"},Hd={message:"Invalid dateAvailability",code:"ERR_INVALID_DATE_AVAILABILITY"},nv={message:"Missing dateAvailability",code:"ERR_MISSING_DATE_AVAILABILITY"},bn={message:"Invalid Date",code:"ERR_INVALID_DATE"},sr={message:"Invalid time",code:"ERR_INVALID_TIME"},rv={message:"Invalid tournament dates",code:"ERR_INVALID_DATES_TOURNAMENT"},ig={message:"Invalid game scores",code:"ERR_INVALID_SCORES_GAME"},sv={message:"Invalid score",code:"ERR_INVALID_SCORE"},og={message:"Invalid winningSide",code:"ERR_INVALID_WINNING_SIDE"},iv={message:"No participants generated",code:"ERR_NO_PARTICIPANTS_GENERATED"},cg={message:"Cannot modify tieFormat",code:"ERR_UNCHANGED_CANNOT_MODIFY_TIEFORMAT"},ov={message:"Cannot modify participantType",code:"ERR_UNCHANGED_CANNOT_MODIFY_PARTICIPANT_TYPE"},qd={message:"Cannot remove participants",code:"ERR_UNCHANGED_CANNOT_REMOVE_PARTICIPANTS"},ag={message:"Cannot change winningSide",code:"ERR_UNCHANGED_CANNOT_CHANGE_WINNING_SIDE"},vu={message:"Invalid participant",code:"ERR_INVALID_PARTICIPANT"},bs={message:"Invalid participantId",code:"ERR_INVALID_PARTICIPANT_ID"},gr={message:"Invalid participantIds",code:"ERR_INVALID_PARTICIPANT_IDS"},cv={message:"Invalid participantRole",code:"ERR_INVALID_PARTICIPANT_ROLE"},xr={message:"Invalid participantType",code:"ERR_INVALID_PARTICIPANT_TYPE"},av={message:"Missing participantRole",code:"ERR_MISSING_PARTICIPANT_ROLE"},qo={message:"Missing participant",code:"ERR_MISSING_PARTICIPANT"},Yc={message:"Missing participants",code:"ERR_MISSING_PARTICIPANTS"},Ce={message:"Missing participantId",code:"ERR_MISSING_PARTICIPANT_ID"},_e={message:"Participant Not Found",code:"ERR_NOT_FOUND_PARTICIPANT"},uv={message:"participantId exists",code:"ERR_EXISTING_PARTICIPANT_ID"},lv={message:"No participant removed",code:"ERR_UNCHANGED_NO_PARTICIPANT_REMOVED"},Ns={message:"Missing participantIds",code:"ERR_MISSING_PARTICIPANT_IDS"},dv={message:"Missing participantsCount",code:"ERR_MISSING_PARTICIPANT_COUNT"},fv={message:"Participant not checked in",code:"ERR_UNCHANGED_PARTICIPANT_NOT_CHECKED_IN"},ug={message:"Participant already checked in",code:"ERR_UNCHANGED_PARTICIPANT_CHECKED_IN"},pv={message:"Missing person details",code:"ERR_MISSING_PERSON_DETAILS"},Yo={message:"Existing participant drawPosition assignment",code:"ERR_EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT"},Yd={message:"Existing participant",code:"ERR_EXISTING_PARTICIPANT"},lg={message:"participantsCount exceeds drawSize",code:"ERR_INVALID_PARTICIPANT_COUNT"},zd={message:"Invalid entry status",code:"ERR_INVALID_ENTRY_STATUS"},dg={message:"Participant Entry Not Found",code:"ERR_NOT_FOUND_PARTICIPANT_ENTRY"},hv={message:"Participant not entered in stage",code:"ERR_UNCHANGED_PARTICIPANT_NOT_ENTERED"},mv={message:"Participant not found in stageSequence",code:"ERR_NOT_FOUND_PARTICIPANT_IN_STAGE"},gv={message:"entryStatus not allowed in stage",code:"ERR_INVALID_ENTRY_STATUS_IN_STAGE"},Iv={message:"entryStatus not allowed for event",code:"ERR_INVALID_ENTRY_STATUS_IN_EVENT"},fg={message:"No stage space available for entryStatus",code:"ERR_UNCHANGED_NO_AVAILABLE_STAGE_SPACE"},Sv={message:"Insufficient drawPositions to accommodate qualifiers",code:"ERR_UNCHANGED_NO_DRAW_POSITIONS_FOR_QUALIFIERS"},pg={message:"Insufficient drawPositions to accommodate entries",code:"ERR_INSUFFICIENT_DRAW_POSITIONS"},Tv={message:"Missing penaltyType",code:"ERR_MISSING_PENALTY_TYPE"},hg={message:"Missing penaltyId",code:"ERR_MISSING_PENALTY_ID"},Cu={message:"Penalty not found",code:"ERR_NOT_FOUND_PENALTY"},yv={message:"Missing courtsCount/courtNames",code:"ERR_MISSING_COURTS_INFO"},Kd={message:"Court not found",code:"ERR_NOT_FOUND_COURT"},Ev={message:"Court exists",code:"ERR_EXISTING_COURT"},bv={message:"Venue exists",code:"ERR_EXISTING_VENUE"},di={message:"Venue not found",code:"ERR_NOT_FOUND_VENUE"},Vs={message:"Missing venueId",code:"ERR_MISSING_VENUE_ID"},mg={message:"Invalid endTime",code:"ERR_INVALID_END_TIME"},gg={message:"Existing endTime",code:"ERR_EXISTING_END_TIME"},Nv={message:"Invalid stopTime",code:"ERR_INVALID_STOP_TIME"},Av={message:"Invalid startTime",code:"ERR_INVALID_START_TIME"},vv={message:"Invalid resumeTime",code:"ERR_INVALID_RESUME_TIME"},Ig={message:"Invalid timeItem",code:"ERR_INVALID_TIME_ITEMS"},Sg={message:"Missing timeItem",code:"ERR_MISSING_TIME_ITEM"},Tg={message:"Missing timeItems",code:"ERR_MISSING_TIME_ITEMS"},Pu={message:"Missing context",code:"ERR_MISSING_CONTEXT"},Cv={message:"Missing schedule",code:"ERR_MISSING_SCHEDULE"},Uu={message:"Invalid scaleItem",code:"ERR_INVALID_SCALE_ITEM"},Pv={message:"No scaleItem found",code:"ERR_NOT_FOUND_SCALE_ITEM"},Uv={message:"Modifications failed",code:"ERR_FAILURE_MODIFICATIONS"},zc={message:"No modifications applied",code:"ERR_UNCHANGED_NO_MODIFICATIONS_APPLIED"},Ov={message:"Unable to assign court",code:"ERR_UNCHANGED_COURT_NOT_ASSIGNED"},Jd={message:"No Candidates",code:"ERR_UNCHANGED_NO_CANDIDATES"},Mv={message:"Invalid configuration",code:"ERR_INVALID_CONFIG"},Ir={message:"Invalid object",code:"ERR_INVALID_OBJECT"},tt={message:"Invalid values",code:"ERR_INVALID_VALUES"},Dv={message:"Duplicate value",code:"ERR_DUPLICATE_VALUE"},yg={message:"Team not found",code:"ERR_NOT_FOUND_TEAM"},wv={message:"No valid actions",code:"ERR_NO_VALID_ACTIONS"},Qd={message:"No valid attributes",code:"ERR_NO_VALID_ATTRIBUTES"},Eg={message:"Value unchanged",code:"ABORT_UNCHANGED"},an={message:"Not found",code:"ERR_NOT_FOUND"},bg={message:"Not implemented",code:"ERR_NOT_IMPLEMENTED"},kv={message:"Existing flight",code:"ERR_EXISTING_FLIGHT"},Ng={message:"Existing flight profile",code:"ERR_EXISTING_FLIGHT_PROFILE"},_v={message:"Existing outcome",code:"ERR_EXISTING_OUTCOME"},Fv={message:"Existing matchUpId",code:"ERR_EXISTING_MATCHUP_ID"},Ag={message:"Existing stage",code:"ERR_EXISTING_STAGE"},Lv={message:"Existing structure",code:"ERR_EXISTING_STRUCTURE"},vg={message:"Method not found",code:"ERR_NOT_FOUND_METHOD"},Rv={message:"Scheduled matchUps",code:"ERR_SCHEDULED_MATCHUPS"},ye={disableNotifications:!1,tournamentId:void 0,tournamentRecords:{},subscriptions:{},modified:!1,notices:[]};var Cg={addNotice:zv,callListener:Xv,cycleMutationStatus:Yv,deleteNotice:Qv,deleteNotices:Jv,disableNotifications:Bv,enableNotifications:xv,getNotices:Kv,getTopics:Zv,getTournamentId:Pg,getTournamentRecord:$v,getTournamentRecords:Vv,removeTournamentRecord:Hv,setSubscriptions:qv,setTournamentId:Gv,setTournamentRecord:jv,setTournamentRecords:Wv,handleCaughtError:tC};function Bv(){ye.disableNotifications=!0}function xv(){ye.disableNotifications=!1}function Pg(){return ye.tournamentId}function $v(t){return ye.tournamentRecords[t]}function Vv(){return ye.tournamentRecords}function jv(t){const e=t==null?void 0:t.tournamentId;return e?(ye.tournamentRecords[e]=t,{success:!0}):{error:Tu}}function Gv(t){return ye.tournamentRecords[t]?(ye.tournamentId=t,{success:!0}):{error:et}}function Wv(t){ye.tournamentRecords=t;const e=Object.keys(t);e.length===1?ye.tournamentId=e[0]:e.length||(ye.tournamentId=void 0)}function Hv(t){if(typeof t!="string")return{error:tt};if(!ye.tournamentRecords[t])return{error:an};delete ye.tournamentRecords[t];const e=Object.keys(ye.tournamentRecords);return e.length===1?ye.tournamentId=e[0]:e.length||(ye.tournamentId=void 0),{success:!0}}function qv(t){return typeof t.subscriptions!="object"?{error:tt}:(Object.keys(t.subscriptions).forEach(e=>{ye.subscriptions[e]=t.subscriptions[e]}),{...$})}function Yv(){const t=ye.modified;return ye.modified=!1,t}function zv({topic:t,payload:e,key:n}){ye.modified=!0,!(typeof t!="string"||typeof e!="object")&&(ye.disableNotifications||!ye.subscriptions[t]||(n&&(ye.notices=ye.notices.filter(r=>!(r.topic===t&&r.key===n))),ye.notices.push({topic:t,payload:e,key:n})))}function Kv({topic:t}){const e=ye.notices.filter(n=>n.topic===t).map(n=>n.payload);return e.length&&e}function Jv(){ye.notices=[]}function Qv({topic:t,key:e}){ye.notices=ye.notices.filter(n=>(!t||n.topic===t)&&n.key!==e)}function Zv(){return{topics:Object.keys(ye.subscriptions)}}function Xv({topic:t,notices:e}){const n=ye.subscriptions[t];n&&typeof n=="function"&&n(e)}function tC({engineName:t,methodName:e,params:n,err:r}){let s;typeof r=="string"?s=r.toUpperCase():r instanceof Error&&(s=r.message),console.log("ERROR",{tournamentId:Pg(),params:JSON.stringify(n),engine:t,methodName:e,error:s})}const ir={tournamentFactoryVersion:"0.0.0",timers:{default:{elapsedTime:0}},iterators:{makeDeepCopy:0},deepCopyAttributes:{stringify:[],ignore:[],toJSON:[]},deepCopy:!0};let Nn=Cg;function ze(t){return!t||typeof t!="object"?ir.devContext??!1:typeof ir.devContext!="object"?!1:Object.keys(t).every(e=>{var n;return((n=ir.devContext)==null?void 0:n[e])===t[e]})&&ir.devContext}function zo(t){ir.devContext=t}function eC(t){ir.iterators.makeDeepCopy=t}function nC(){return ir.iterators.makeDeepCopy}function rC(){Nn.disableNotifications()}function Zd(){Nn.enableNotifications()}function Hi(t,e){typeof t=="boolean"&&(ir.deepCopy=t),typeof e=="object"&&(Array.isArray(e.ignore)&&(ir.deepCopyAttributes.ignore=e.ignore),Array.isArray(e.toJSON)&&(ir.deepCopyAttributes.toJSON=e.toJSON),Array.isArray(e.stringify)&&(ir.deepCopyAttributes.stringify=e.stringify),e.threshold&&(ir.deepCopyAttributes.threshold=e.threshold))}function Ug(){return{enabled:ir.deepCopy,...ir.deepCopyAttributes}}function Kc(){return Nn.cycleMutationStatus()}function Ht(t){return Nn.addNotice(t)}function sC(t){return Nn.getNotices(t)}function Og({key:t,topic:e}){return Nn.deleteNotice({key:t,topic:e})}function fi(){return Nn.deleteNotices()}function $r(){return Nn.getTopics()}async function Mg(t){return Nn.callListener(t)}function os(){return Nn.getTournamentId()}function Jc(t){return Nn.getTournamentRecord(t)}function Ou(){return Nn.getTournamentRecords()}function Dg(t){return Nn.setTournamentRecord(t)}function Qc(t){return Nn.setTournamentRecords(t)}function Zc(t){return Nn.setTournamentId(t)}function Xd(t){return Nn.removeTournamentRecord(t)}function Xc({engineName:t,methodName:e,params:n,err:r}){return(typeof Nn.handleCaughtError=="function"&&Nn.handleCaughtError||Cg.handleCaughtError)({engineName:t,methodName:e,params:n,err:r})}const Mu=/^[\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1])$/,wg=/^((0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)([.,][0-9]{3})?$/,Vr=/^([\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?$/,pi=/^([\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 Du(t){let{scheduledDate:e}=t;if(!e&&t.scheduledTime&&(e=Bt(t.scheduledTime)),!e)return;const n=de(t.scheduledTime);let r=Bt(e);return r&&n&&(r+=`T${n}`),r}function iC(t){return typeof t!="object"||Array.isArray(t)?!1:Object.prototype.toString.call(t)==="[object Date]"}function Ko(t){const e=typeof t=="string"?t==null?void 0:t.split(" "):[];return t&&(e==null?void 0:e.length)>1&&!["AM","PM"].includes(e[1].toUpperCase())?!1:!!(!t||pi.test(qi(t,!0,!0)))}function Yn(t){return hi(t)||Mu.test(t)}function oC(t){const e=new Date(t),n=e.getSeconds()+60*e.getMinutes()+60*60*e.getHours();return cC(n,{displaySeconds:!1})}function cC(t,e){const n=parseInt(t,10),r=Math.floor(n/3600),s=Math.floor((n-r*3600)/60),i=n-r*3600-s*60;return(!e||(e==null?void 0:e.displaySeconds)?r+":"+s+":"+i:r+":"+s).split(":").map(cs).join(":")}const tf=t=>{const e=ta(t)||hi(t)?new Date(t):new Date,n=e.getUTCMonth()+1,r=n<10?`0${n}`:`${n}`;return`${e.getUTCFullYear()}-${cs(r)}-${cs(e.getUTCDate())}`};function aC(t){const e=ta(t)||hi(t)?new Date(t):new Date;return Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())}function Sr(t,e="-",n="YMD"){if(!t)return"";typeof t=="string"&&t.indexOf("T")<0&&(t=t+"T00:00");const r=new Date(t);let s=""+(r.getMonth()+1),i=""+r.getDate();const o=r.getFullYear();return s.length<2&&(s="0"+s),i.length<2&&(i="0"+i),n==="DMY"?[i,s,o].join(e):n==="MDY"?[s,i,o].join(e):n==="YDM"?[o,i,s].join(e):n==="DYM"?[i,o,s].join(e):n==="MYD"?[s,o,i].join(e):[o,s,i].join(e)}function wu(t){const e=t?new Date(t):new Date,n=e.getTimezoneOffset();return new Date(e.getTime()-n*60*1e3)}function uC(t){return wu(t).getTime()}function ta(t){if(typeof t=="boolean")return!1;const e=t instanceof Date&&t||!isNaN(t)&&new Date(t)||!1;return e&&!isNaN(e.valueOf())}function ef(t,e){if(!Yn(t)||!Yn(e))return[];const n=Bt(t)+"T00:00",r=Bt(e)+"T00:00",s=new Date(n),i=new Date(r),o=ta(i)&&ta(s)&&u(s,i),c=[];let a=0;if(o){const l=s;let f=l.getTime();for(;f<=i.getTime()&&a<300;)a+=1,c.push(new Date(l)),f=l.setDate(l.getDate()+1)}return c.map(l=>Sr(l));function u(l,f){return l<=f}}const lC=/^([+-]?\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 hi(t){return typeof t!="string"?!1:lC.test(t)}function kg(t){if(typeof t!="string")return!1;const n=t.split("Z")[0].split(":"),r=n.every(i=>!isNaN(parseInt(i)));return!(n.length<2||!r||parseInt(n[0])>23||parseInt(n[1])>60)}function jt(t){const e=de(t);if(!e)return 0;const[n,r]=e.split(":").map(s=>parseInt(s));return n*60+r}function dC(t){let e=Math.floor(t/60);const n=t-e*60;return e>23&&(e=e%24),[cs(e),cs(n)].join(":")}function ku(t){return kg(t)?t.split(":").slice(0,2).map(cs).join(":"):void 0}function de(t){return hi(t)&&t.indexOf("T")>0?ku(t.split("T").reverse()[0]):ku(t)}function Bt(t){return hi(t)||Vr.test(t)?t.split("T")[0]:void 0}function fC(t,e){const n=new Date(t);return n.setDate(n.getDate()+e),Bt(n.toISOString())}function _u(t){t=typeof t!="string"?"00:00":t;const e={},n={};return{0:e.time,1:e.ampm}=t.split(" ")||[],{0:n.hours,1:n.minutes}=e.time.split(":")||[],n.ampm=e.ampm,isNaN(n.hours)||isNaN(n.minutes)||n.ampm&&!["AM","PM"].includes(n.ampm.toUpperCase())?{}:n}function pC(t){const e=_u(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(cs).join(":")}function hC(t){var n;const e=_u(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"),((n=e.hours)==null?void 0:n[0])==="0"&&(e.hours=e.hours.slice(1)),`${e.hours||"12"}:${e.minutes||"00"} ${e.ampm}`)}function qi(t,e,n){const r=Bt(t),s=de(t),i=r?s:t;return t?e&&(r&&n&&t||pC(i))||hC(i):void 0}function _g(t,e){const n=_u(t),r=_u(e);if(parseInt(n.hours)<parseInt(r.hours))return-1;if(parseInt(n.hours)>parseInt(r.hours))return 1;if(n.hours===r.hours){if(parseInt(n.minutes)<parseInt(r.minutes))return-1;if(parseInt(n.minutes)>parseInt(r.minutes))return 1}return 0}function Fg(t,e=7){const n=Bt(t)+"T00:00",r=new Date(n),s=new Date(r.setDate(r.getDate()+e));return Sr(s)}function mC(t){return Fg(t)}function gC(t,e,n,r=!1){const s=new Date(e,0,1+(t-1)*7),i=r?0:1;return s.setDate(s.getDate()+(i-s.getDay())),Sr(s,n)}function IC(t,e,n){const r=new Date(t,0);return Sr(new Date(r.setDate(e)),n)}function Pe(t,e=void 0){const[n,r]=(t||"00:00").split(":").map(cs),s=wu(e).setHours(n,r,0,0);return wu(s)}function ea(t,e,n=!0){const r=new Date(t),i=(new Date(e).getTime()-r.getTime())/1e3/60;return n?Math.abs(Math.round(i)):Math.round(i)}function An(t,e){const n=de(t);if(!n)return"00:00";const r=isNaN(e)?0:e;return de(nf(Pe(n),r).toISOString())}function nf(t,e){const n=new Date(t);return new Date(n.getTime()+e*6e4)}function cs(t){return t.toString()[1]?t:"0"+t}function as(t,e){const n=new Date(t),r=new Date(e);return n.getFullYear()===r.getFullYear()&&n.getMonth()===r.getMonth()&&n.getDate()===r.getDate()}const SC={addDays:Fg,addWeek:mC,addMinutesToTimeString:An,convertTime:qi,getIsoDateString:Du,getUTCdateString:tf,DateHHMM:oC,extractDate:Bt,extractTime:de,formatDate:Sr,getDateByWeek:gC,isISODateString:hi,isDate:ta,isTimeString:kg,offsetDate:wu,offsetTime:uC,sameDay:as,timeStringMinutes:jt,timeToDate:Pe,timeUTC:aC,validTimeValue:Ko,validDateString:Mu,timeValidation:pi,dateValidation:Vr};function pt(t,e,n,r,s=0){const i=Ug(),{stringify:o,toJSON:c,ignore:a,modulate:u}=i||{};if(!(i!=null&&i.enabled)&&!n||typeof t!="object"||typeof t=="function"||t===null||typeof(i==null?void 0:i.threshold)=="number"&&s>=i.threshold)return t;const l=ze({makeDeepCopy:!0});l&&(eC(s),typeof l=="object"&&(s>(l.iterationThreshold||15)||l.firstIteration&&s===0)&&l.log&&(!l.notInternalUse||l.notInternalUse&&!n)&&console.log({devContext:l,iteration:s,internalUse:n},t));const f=Array.isArray(t)?[]:{},p=Object.keys(t).filter(d=>!n||!a||Array.isArray(a)&&!a.includes(d)||typeof a=="function"&&!a(d)),h=(d,m)=>{f[d]=typeof(m==null?void 0:m.toString)=="function"?m.toString():JSON.stringify(m)};for(const d of p){const m=t[d],g=typeof u=="function"?u(m):void 0;if(g!==void 0)f[d]=g;else if(e&&d==="extensions"&&Array.isArray(m)){const I=rf(m);Object.assign(f,...I)}else r&&d==="extensions"?f[d]=[]:Array.isArray(o)&&o.includes(d)?h(d,m):Array.isArray(c)&&c.includes(d)&&typeof(m==null?void 0:m.toJSON)=="function"?f[d]=m.toJSON():m===null?f[d]=void 0:iC(m)?f[d]=new Date(m).toISOString():f[d]=pt(m,e,n,r,s+1)}return f}function rf(t){return t==null?void 0:t.map(e=>{const{name:n,value:r}=e;return n&&r&&{[`_${n}`]:r}}).filter(Boolean)}function Yi({element:t,accessor:e}){if(typeof e!="string")return{values:[]};const n=pt(t),r=e.split("."),s=[];let i;c({targetElement:n,attributes:r});const o={value:i};return s.length&&(o.values=s),o;function c({targetElement:a,attributes:u=[],significantCharacters:l}){for(const[p,h]of u.entries())if(a!=null&&a[h]){const d=u.slice(p+1);d.length?Array.isArray(a[h])?a[h].forEach(g=>c({targetElement:g,attributes:d})):(a=a[h],f({targetElement:a,index:p})):(i||(i=a[h]),s.includes(a[h])||s.push(a[h]))}function f({targetElement:p,index:h}){if(p&&h===u.length-1&&["string","number"].includes(typeof p)){const d=l?p.slice(0,l):p;i?s.includes(d)||s.push(d):(i=d,s.push(d))}}}}function TC(t){return typeof t=="string"}function or(t){return typeof t=="object"}function yC(t,e){return Array.isArray(t)?Object.assign({},...(t??[]).filter(or).map(n=>n[e]&&{[n[e]]:n}).filter(Boolean)):{}}const EC=t=>e=>Object.keys(t).every(n=>e[n]===t[n]),kn=t=>e=>{var n;return!t||typeof e!="object"?void 0:Array.isArray(t)&&t.map(r=>{var s;return{[r]:(s=Yi({element:e,accessor:r}))==null?void 0:s.value}})||typeof t=="object"&&Object.keys(t).map(r=>{var s;return{[r]:(s=Yi({element:e,accessor:r}))==null?void 0:s.value}})||((n=typeof t=="string"&&Yi({element:e,accessor:t}))==null?void 0:n.value)};function bt(t,e,n,r){if(typeof t!="object"||t===null)return t;const s=Ug();s!=null&&s.enabled||(r=!0);const i=["",void 0,null];e&&i.push(!1);const o=Object.keys(t).filter(c=>!i.includes(t[c])&&(!n||(Array.isArray(t[c])?t[c].length:!0)));return Object.assign({},...o.map(c=>Array.isArray(t[c])?{[c]:r?t[c]:t[c].map(a=>bt(a))}:{[c]:r?t[c]:bt(t[c])}))}function sf(t){return Array.isArray(t)?t.length+t.map(sf).reduce((e,n)=>e+n,0):typeof t=="object"&&t!==null?Object.keys(t).length+Object.keys(t).map(e=>sf(t[e])).reduce((e,n)=>e+n,0):0}function bC(t){if(t===null||typeof t!="object")return;const e=JSON.stringify(t),n=sf(t),r=e.split("").reduce((s,i)=>s+i.charCodeAt(0),0);return[e.length,n,r].map(s=>s.toString(36)).join("")}function Fu(t){if(t===null)return{};const{source:e,template:n}=t||{};if(!n)return e;const r={};return s(e,n,r),r;function s(i,o,c){if(!i||!o)return;const a=Object.keys(i),u=Object.keys(o),l=Object.assign({},...u.filter(h=>h.indexOf("||")).map(h=>h.split("||").map(d=>({[d]:h}))).flat()),f=u.concat(...Object.keys(l)),p=f.includes("*");for(const h of a)if(f.indexOf(h)>=0||p){const d=l[h]||h,m=o[d]||p,g=i[h];if(typeof m=="object"&&typeof g!="function"&&!Array.isArray(m))if(Array.isArray(g)){const I=g.map(S=>{const T={};return s(S,m,T)!==!1?T:void 0}).filter(Boolean);c[h]=I}else g&&(c[h]={},s(g,m,c[h]));else{const I=i[h];if(Array.isArray(m)&&!m.includes(I))return!1;(o[h]||p&&o[h]!==!1)&&(c[h]=I)}}}}function Lg(t=0){const e=new Date;return e.setHours(e.getHours()+t),e.getTime().toString(36).slice(-6).toUpperCase()}function Ve(t,e){return t-e}function NC(t,e){if(e&&typeof e!="object")return tt;let{columnTransform:n={}}=e||{};const{includeTransformAccessors:r,includeHeaderRow:s=!0,returnTransformedJSON:i,removeEmptyColumns:o,onlyHeaderRow:c,columnAccessors:a=[],functionMap:u={},columnMap:l={},valuesMap:f={},context:p={},delimiter:h='"',columnJoiner:d=",",rowJoiner:m=`\r
5
+ */(function(t){(function(){var e={}.hasOwnProperty;function n(){for(var r=[],s=0;s<arguments.length;s++){var i=arguments[s];if(i){var o=typeof i;if(o==="string"||o==="number")r.push(i);else if(Array.isArray(i)){if(i.length){var c=n.apply(null,i);c&&r.push(c)}}else if(o==="object"){if(i.toString!==Object.prototype.toString&&!i.toString.toString().includes("[native code]")){r.push(i.toString());continue}for(var a in i)e.call(i,a)&&i[a]&&r.push(a)}}}return r.join(" ")}t.exports?(n.default=n,t.exports=n):window.classNames=n})()})(Mm);var i1=Mm.exports;const ji=Om(i1);function o1({individualParticipant:t,className:e}){var c,a;const{city:n,state:r,countryCode:s}=((a=(c=t==null?void 0:t.person)==null?void 0:c.addresses)==null?void 0:a[0])||{},i=[n,r,s].filter(Boolean).join(", ")||" ",o=document.createElement("div");return o.className=ji(Um(),e),o.innerHTML=i,o}function c1({individualParticipant:t,className:e}){var i;const n=(i=t==null?void 0:t.teams)==null?void 0:i[0],r=(n==null?void 0:n.participantName)||" ",s=document.createElement("div");return s.className=ji(Um(),e),s.classList.add("tmx-tm"),s.setAttribute("id",n==null?void 0:n.participantId),s.innerHTML=r,s}function a1(t){var s,i,o,c;const e=(i=(s=t==null?void 0:t.composition)==null?void 0:s.configuration)==null?void 0:i.participantDetail;return((c=(o=t==null?void 0:t.composition)==null?void 0:o.configuration)==null?void 0:c.showAddress)??e==="ADDRESS"?o1(t):e==="TEAM"?c1(t):document.createElement("div")}const u1=zt({color:"$participant$seed",marginInlineStart:".5rem",textTransform:"uppercase",fontSize:"0.75rem",lineHeight:"1rem"});function l1({className:t,composition:e,side:n}){const r=(n==null?void 0:n.seedValue)||(n==null?void 0:n.seedNumber);if(!r)return"";const s=(e==null?void 0:e.configuration)||{},{bracketedSeeds:i}=s,o=typeof i=="boolean"&&["(",")"]||i==="square"&&["[","]"]||["",""],c=`${o[0]}${r}${o[1]}`,a=s.seedingElement==="sup"?"sup":"span",u=document.createElement(a);return u.className=t,u.innerHTML=c,u}const d1=zt({WebkitBoxSizing:"border-box",marginInlineEnd:".5em",boxSizing:"border-box",display:"inline-block",position:"relative",fontSize:"smaller",fontWeight:"bold",borderRadius:2,color:"blue",variants:{color:{green:{color:"green"},red:{color:"red"}}}});function f1({individualParticipant:t,composition:e,className:n,matchUp:r,spacer:s}){var b,N,A,C,v,P,U;const i=e==null?void 0:e.configuration,o=((b=i==null?void 0:i.scaleAttributes)==null?void 0:b.eventType)||(r==null?void 0:r.matchUpType)||"SINGLES",c=t==null?void 0:t.rankings,a=t==null?void 0:t.ratings,u=i==null?void 0:i.scaleAttributes,l=u==null?void 0:u.scaleType,f=u==null?void 0:u.scaleName,p=u==null?void 0:u.accessor,h=l==="RATING"?a:c,d=(A=(N=h==null?void 0:h.SINGLES)==null?void 0:N.find(O=>(O==null?void 0:O.scaleName)===f))==null?void 0:A.scaleValue,m=(v=(C=h==null?void 0:h.DOUBLES)==null?void 0:C.find(O=>(O==null?void 0:O.scaleName)===f))==null?void 0:v.scaleValue,g=d&&p?d[p]:d||"",I=m&&p?m[p]:m||"",S=o==="SINGLES"?g:I,T=(P=i==null?void 0:i.scaleAttributes)==null?void 0:P.fallback,E=!s&&(S||T&&(g||I)),y=document.createElement("span");return E&&(y.className=ji(n,d1({color:(U=i==null?void 0:i.scaleAttributes)==null?void 0:U.scaleColor}))),y.innerHTML=E||"",y}const p1="normal",Dm="timed",h1="final",Dd="NOAD",Iu="SET",m1={S:p1,F:h1};function wd(t,e){if(typeof t=="object"){if(t.timed&&!isNaN(t.minutes))return kd(t);if(t.bestOf&&t.setFormat)return g1(t,e)}}function Su(t){return!isNaN(Number(t))&&Number(t)}function kd(t){let e=`T${t.minutes}`;return t.based&&(e+=t.based),t.modifier&&(e+=`@${t.modifier}`),e}function g1(t,e){var u;const n=Su(t.bestOf);if((u=t.setFormat)!=null&&u.timed&&t.simplified&&n===1)return kd(t.setFormat);const r=n&&`${Iu}${n}`||"",s=wm(t.setFormat,e),i=s&&`S:${s}`||"",o=wm(t.finalSetFormat,e),c=n&&n>1&&o&&s!==o&&`F:${o}`||"";if(r&&s)return[r,i,c].filter(l=>l).join("-")}function wm(t,e){if(typeof t=="object"&&Object.keys(t).length){if(t.timed)return kd(t);if(t.tiebreakSet)return km(t.tiebreakSet);const n=Su(t.setTo);if(n){const r=t.NoAD&&Dd||"",s=km(t.tiebreakFormat),i=s&&`/${s}`||"",o=Su(t.tiebreakAt),c=o&&(o!==n||e)&&`@${o}`||"";if(s!==!1)return`${n}${r}${i}${c}`}}}function km(t){if(t){if(typeof t=="object"&&!t.tiebreakTo)return"";if(typeof t=="object"&&Su(t.tiebreakTo)){let e=`TB${t.tiebreakTo}${t.NoAD?Dd:""}`;return t.modifier&&(e+=`@${t.modifier}`),e}else return!1}}function vt(t){return parseInt(typeof t=="number"?t.toString():t)}function mr(t){return isNaN(t)?!1:t&&(t&t-1)===0}function I1(t){if(!mr(t))return!1;let e=t,n=1;for(;e!==2;)n+=1,e=e/2;return n}function _d(t){return isNaN(t)?0:t%2&&t+1||t}function Fd(t){return Math.pow(2,Math.round(Math.log(t)/Math.log(2)))}function Me(t){return!isNaN(parseFloat(t))}function S1(t){const e=vt(t);if(!isNaN(e))return e===0?!1:(e&-e)===1}function Vo(t){if(isNaN(t))return!1;for(;!mr(t);)t++;return t}function Wn(t,e){return t=Math.ceil(t),e=Math.floor(e),Math.floor(Math.random()*(e-t+1))+t}function oe(t){return Number.isSafeInteger(typeof t=="string"?+t:t)}function T1(t=1,e=3,n=!0){let r=0;for(let s=0;s<e;s++)r+=Math.random()*(t/e);return n&&t>1?Math.round(r):r}function y1(t,e){e||(e=1);const n=1/e;return Math.round(t*n)/n}function _m(t,e,n,r,s=2){const i=1-Math.random(),o=1-Math.random();let c=Math.sqrt(-2*Math.log(i))*Math.cos(2*Math.PI*o);return c=c/10+.5,c>1||c<0?c=_m(t,e,n):(c=Math.pow(c,n),c*=e-t,c+=t),r&&(c=y1(c,r)),parseFloat(c.toFixed(s))}function yn(t){if(typeof t=="string"){const e=t.startsWith("T")&&Dm||t.startsWith(Iu)&&Iu||"";if(e===Dm){const r={simplified:!0,setFormat:Bm(t),bestOf:1};if(r.setFormat)return r}if(e===Iu)return E1(t)}}function E1(t){const e=t.split("-"),n=Vc(e[0].slice(3)),r=e&&Fm(e[1]),s=e&&Fm(e[2]),i=n&&n<6,o=!e[2]||s,c=r,a={bestOf:n,setFormat:r};if(s&&(a.finalSetFormat=s),i&&c&&o)return a}function Fm(t){if((t==null?void 0:t[1])===":"){const e=t.split(":"),n=m1[e[0]],r=e[1];if(n&&r){if(r.indexOf("TB")===0){const g=Rm(r);return g===!1?!1:typeof g=="object"?{tiebreakSet:g}:void 0}if(r.indexOf("T")===0)return Bm(r);const o=t.match(/^[FS]:(\d+)([A-Za-z]*)/),c=o&&xm(o[2])||!1,a=!(o!=null&&o[2])||c,u=o?Vc(o[1]):void 0,l=Lm(r),f=l!==!1,p=f&&l||u,h=Rm(r.split("/")[1]),d=h!==!1,m={setTo:u};return c&&(m.NoAD=!0),h?(m.tiebreakFormat=h,m.tiebreakAt=p):m.noTiebreak=!0,u&&a&&d&&f&&m||!1}}}function Lm(t,e=!0){const n=(t==null?void 0:t.indexOf("@"))>0&&t.split("@");if(n)return(e?Vc(n[1]):n[1])||!1}function Rm(t){if(t)if(t.startsWith("TB")){const e=Lm(t,!1),n=t.match(/^TB(\d+)([A-Za-z]*)/),r=n==null?void 0:n[1],s=n&&xm(n[2]),i=!(n!=null&&n[2])||s,o=Vc(r);if(o&&i){const c={tiebreakTo:o};return e&&typeof e=="string"&&!oe(e)&&(c.modifier=e),s&&(c.NoAD=!0),c}else return!1}else return!1}function Bm(t){var c;const e=t.slice(1),n=e.match(/^(\d+)(@?[A-Za-z]*)/),r=Vc(n==null?void 0:n[1]);if(!r)return;const s={timed:!0,minutes:r},i=n==null?void 0:n[2],o=[void 0,"P","G"].includes(i);if(i&&!o){const a=(c=e.match(/^(\d+)(@)([A-Za-z]+)$/))==null?void 0:c[3];return a?(s.modifier=a,s):void 0}return i&&(s.based=n[2]),s}function xm(t){return t&&t.indexOf(Dd)>=0}function Vc(t){return isNaN(Number(t))?0:Number(t)}function nr(t){if(typeof t!="string")return!1;const e=yn(t),n=t.match(/-S:([1-9])+\/TB([0-9]{1,2})@?([1-9]?)*/),r=n==null?void 0:n[1],s=n==null?void 0:n[2],i=n==null?void 0:n[3],o=t.match(/-F:([1-9])+\/TB([0-9]{1,2})@?([1-9]?)*/),c=o==null?void 0:o[1],a=o==null?void 0:o[2],u=o==null?void 0:o[3];return wd(e,!!(n&&s&&r===i||o&&a&&c===u))===t}const b1={isValidMatchUpFormat:nr,stringify:wd,isValid:nr,parse:yn};function Es(){return"1.7.8"}function Bs(t){if(!t)return;const{tieFormatId:e,tieFormats:n}=t;if(t.tieFormat)return t.tieFormat;if(e&&Array.isArray(n))return n.find(r=>r.tieFormatId===e)}function jc({item:t,drawDefinition:e,structure:n,event:r}){var s,i,o;if(t){if(t.tieFormat)return t.tieFormat;if(t.tieFormatId){if(e.tieFormat)return e.tieFormat;const c=(s=e.tieFormats)==null?void 0:s.find(a=>t.tieFormatId===a.tieFormatId);return c||(r.tieFormat?r.tieFormat:(i=r.tieFormats)==null?void 0:i.find(a=>t.tieFormatId===a.tieFormatId))}if(n.tieFormat)return n.tieFormat;if(n.tieFormatId){const c=(o=e.tieFormats)==null?void 0:o.find(a=>n.tieFormatId===a.tieFormatId);if(c)return c}}}function hn({drawDefinition:t,structure:e,matchUp:n,event:r}){return{tieFormat:jc({item:n,drawDefinition:t,structure:e,event:r})||jc({item:e,drawDefinition:t,structure:e,event:r})||Bs(t)||Bs(r)}}function sn(t){return`${t} must be an array`}function Vt(t){return t.filter((e,n,r)=>r.lastIndexOf(e)===n)}function on(t){return t.map(e=>[Math.random(),e]).sort((e,n)=>e[0]-n[0]).map(e=>e[1])}function jo(t){return oe(t)?t:1/0}function Mn(t){return t.reduce((e,n)=>(e[n]||(e[n]=0),e[n]++,e),{})}function N1(t){return A1(Mn(t))}function A1(t){return Object.keys(t).reduce((e,n)=>{const r=t[n];return e[r]?e[r].push(n):e[r]=[n],e},{})}function v1(t,e,n){return n.indexOf(t)===e}function $m(t){return t.filter(v1)}function cn(t){return Array.isArray(t)&&t.length?t.splice(Math.floor(Math.random()*t.length),1)[0]:void 0}function Dn(t){const e=Math.floor(Math.random()*t.length);return t[e]}function ht(t,e){return Array.from({length:e-t},(n,r)=>r+t)}function Br(t,e){return e.reduce((n,r,s)=>(r===t&&n.push(s),n),[])}function qe(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(n=>e.indexOf(n)!==-1).filter((n,r,s)=>s.indexOf(n)===r)}function Vm(t,e){return!Array.isArray(t)||!Array.isArray(e)?[]:t.filter(n=>!e.includes(n))}function tn(t,e){return!Array.isArray(t)||!Array.isArray(e)?!1:t.some(n=>e.includes(n))}function Ge(t,e){return t.reduce((n,r,s)=>{const i=Math.floor(s/e);return n[i]=[].concat(n[i]||[],r),n},[])}function C1(t){return t.reduce((e,n)=>{const r=e[e.length-1];return(!r||r[r.length-1]!==n-1)&&e.push([]),e[e.length-1].push(n),e},[])}function P1(t){return t.reduce((e,n)=>!isNaN(parseInt(n))&&e,!0)}function U1(t){return t.reduce((e,n)=>isNaN(parseInt(n))&&e,!0)}function jm(t,e,n){return t.reduce((r,s,i)=>{const o=n?!!(Math.floor(i/e)%2):!1,c=i%e,a=o?e-1-c:c;return r[a]||(r[a]=[]),r[a].push(s),r},[])}function O1(t,e=1){if(!Array.isArray(t)||!t.every(oe))return[];const n=Math.min(...t,e),r=Math.max(...t);return ht(n,r+1).filter(s=>!t.includes(s))}const $={success:!0},Gm={message:"Chronological error; time violation.",code:"ANACHRONISM"},M1={message:"Cannot remove main structure",code:"ERR_CANNOT_REMOVE_MAIN_STRUCTURE"},Wm={message:"records must be an object with tournamentId keys",code:"ERR_INVALID_TOURNAMENTS"},Gt={message:"Missing tournamentRecords",code:"ERR_MISSING_TOURNAMENTS"},et={message:"Missing tournamentRecord",code:"ERR_MISSING_TOURNAMENT"},Tu={message:"Invalid tournamentRecord",code:"ERR_INVALID_TOURNAMENT"},is={message:"Missing tournamentId",code:"ERR_MISSING_TOURNAMENT_ID"},Gi={message:"Invalid drawDefinition",code:"ERR_INVALID_DRAWDEF"},lt={message:"Missing drawDefinition",code:"ERR_MISSING_DRAWDEF"},D1={message:"Existing drawDefinition(s)",code:"ERR_EXISTING_DRAWDEFS"},rr={message:"drawDefinition not found",code:"ERR_NOT_FOUND_DRAWDEF"},Go={message:"Invalid structure",code:"ERR_INVALID_STRUCTURE"},Hm={message:"Incomplete source structure",code:"ERR_INCOMPLETE_STRUCTURE"},qm={message:"Invalid drawPosition for seedAssignment",code:"ERR_INVALID_SEEDING_POSITION"},Gc={message:"drawPosition already assigned",code:"ERR_EXISTING_POSITION_ASSIGNMENT"},w1={message:"Schedule not cleared",code:"ERR_UNCHANGED_SCHEDULE_NOT_CLEARED"},k1={message:"drawPosition not cleared",code:"ERR_FAILURE_POSITION_NOT_CLEARED"},Ym={message:"Unrecognized drawType",code:"ERR_UNRECOGNIZED_DRAW_TYPE"},Ld={message:"Missing drawPositions",code:"ERR_MISSING_DRAW_POSITIONS"},Rd={message:"drawPosition is active",code:"ERR_ACTIVE_DRAW_POSITION"},Wo={message:"Invlid drawPosition",code:"ERR_INVALID_DRAW_POSITION"},Wc={message:"Missing drawPosition",code:"ERR_MISSING_DRAW_POSITION"},Bd={message:"Invalid drawType",code:"ERR_INVALID_DRAW_TYPE"},xd={message:"Invalid drawSize",code:"ERR_INVALID_DRAW_SIZE"},yu={message:"Cannot set drawSize to be less than existing entries",code:"ERR_INVALID_DRAW_SIZE_MISMATCH"},Eu={message:"Missing drawSize",code:"ERR_MISSING_DRAW_SIZE"},Hn={message:"Missing drawId",code:"ERR_MISSING_DRAW_ID"},_1={message:"drawId exists",code:"ERR_EXISTING_DRAW_ID"},F1={message:"participantId cannot be assigned to multiple seedNumbers",code:"INVALID_PARTICIPANT_SEEDING"},L1={message:"seedsCount greater than drawSize",code:"ERR_INVALID_SEED_COUNT"},R1={message:"Missing seedCountThresholds",code:"ERR_MISSING_SEED_COUNT_THRESHOLD"},B1={message:"Invalid action",code:"ERR_INVALID_ACTION"},zm={message:"Invalid assignment",code:"ERR_INVALID_ASSIGNMENT"},x1={message:"Missing seedAssignments",code:"ERR_MISSING_SEED_ASSIGNMENTS"},$1={message:"Invalid seedNumber",code:"ERR_INVALID_SEED_NUMBER"},V1={message:"Invalid seedPosition",code:"ERR_INVALID_SEED_POSITION"},Km={message:"Missing targetLink",code:"ERR_MISSING_LINK_TARGET"},j1={message:"Existing round",code:"ERR_EXISTING_ROUND"},En={message:"Missing structureId",code:"ERR_MISSING_STRUCTURE_ID"},Te={message:"structure not found",code:"ERR_NOT_FOUND_STRUCTURE"},G1={message:"Missing structures",code:"ERR_MISSING_STRUCTURES"},Wi={message:"Missing structure",code:"ERR_MISSING_STRUCTURE"},W1={message:"drawDefinition contains unlinked structures",code:"ERR_MISSING_STRUCTURE_LINKS"},ui={message:"Invalid eventType",code:"ERR_INVALID_EVENT_TYPE"},Wt={message:"Missing event / eventId",code:"ERR_MISSING_EVENT_ID"},wn={message:"Event not found",code:"ERR_NOT_FOUND_EVENT"},H1={message:"Event exists",code:"ERR_EXISTING_EVENT"},q1={message:"Missing entries",code:"ERR_MISSING_ENTRIES"},Y1={message:"Invalid entries",code:"ERR_INVALID_ENTRIES"},Jm={message:"Missing assignments",code:"ERR_MISSING_ASSIGNMENTS"},Qm={message:"Missing stage",code:"ERR_MISSING_STAGE"},xs={message:"Invalid stage",code:"ERR_INVALID_STAGE"},z1={message:"Missing positionAssignments",code:"ERR_MISSING_POSITION_ASSIGNMENTS"},K1={message:"Cannot Assign BYE status if no assignment: { bye: true }",code:"ERR_UNCHANGED_CANNOT_ASSIGN_BYE"},Zm={message:"Unrecognized matchUpStatus",code:"ERR_UNRECOGNIZED_MATCHUP_STATUS"},bu={message:"Unrecognized matchUpFormat",code:"ERR_UNRECOGNIZED_MATCHUP_FORMAT"},$d={message:"Incompatible matchUpStatus",code:"ERR_INCOMPATIBLE_MATCHUP_STATUS"},Hc={message:"Invalid matchUpStatus",code:"ERR_INVALID_MATCHUP_STATUS"},li={message:"Invalid tieFormat",code:"ERR_INVALID_TIE_FORMAT"},Xm={message:"Invalid matchUpFormat",code:"ERR_INVALID_MATCHUP_FORMAT"},Vd={message:"Missing matchUpFormat",code:"ERR_MISSING_MATCHUP_FORMAT"},J1={message:"Missing collectionDefinition",code:"ERR_MISSING_COLLECTION_DEFINITION"},Nu={message:"Missing tieFormat",code:"ERR_MISSING_TIE_FORMAT"},$e={message:"Missing matchUpId",code:"ERR_MISSING_MATCHUP_ID"},qc={message:"Missing matchUpIds",code:"ERR_MISSING_MATCHUP_IDS"},Ye={message:"matchUp not found",code:"ERR_NOT_FOUND_MATCHUP"},$s={message:"Missing matchUps",code:"ERR_MISSING_MATCHUPS"},Rn={message:"Missing matchUp",code:"ERR_MISSING_MATCHUP"},qn={message:"Invalid matchUp",code:"ERR_INVALID_MATCHUP"},tg={message:"Missing policyType",code:"ERR_MISSING_POLICY_TYPE"},Au={message:"Missing policyDefinitions",code:"ERR_MISSING_POLICY_DEFINITIONS"},Q1={message:"Missing avoidance policy",code:"ERR_MISSING_POLICY_AVOIDANCE"},eg={message:"Missing policy attributes",code:"ERR_MISSING_POLICY_ATTRIBUTES"},Z1={message:"Invalid policyDefinitions",code:"ERR_INVALID_POLICY_DEFINITIONS"},ng={message:"existing policyType",code:"ERR_EXISTING_POLICY_TYPE"},X1={message:"Policy not attached",code:"ERR_FAILURE_POLICY_NOT_ATTACHED"},jd={message:"Policy not found",code:"ERR_NOT_FOUND_POLICY"},tv={message:"Missing scoring policy / matchUpFormats",code:"ERR_MISSING_POLICY_SCORING_MATCHUP_FORMATS"},rg={message:"Invalid sideNumber",code:"ERR_INVALID_SIDE_NUMBER"},Gd={message:"Missing setObject",code:"ERR_MISSING_SET_ATTRIBUTE"},Ho={message:"Missing courtId",code:"ERR_MISSING_COURT_ID"},Tt={message:"Missing value",code:"ERR_MISSING_VALUE"},sg={message:"Missing date",code:"ERR_MISSING_DATE"},ev={message:"No valid dates",code:"ERR_NO_VALID_DATES"},Wd={message:"Invalid bookings",code:"ERR_INVALID_BOOKINGS"},Hd={message:"Invalid dateAvailability",code:"ERR_INVALID_DATE_AVAILABILITY"},nv={message:"Missing dateAvailability",code:"ERR_MISSING_DATE_AVAILABILITY"},bn={message:"Invalid Date",code:"ERR_INVALID_DATE"},sr={message:"Invalid time",code:"ERR_INVALID_TIME"},rv={message:"Invalid tournament dates",code:"ERR_INVALID_DATES_TOURNAMENT"},ig={message:"Invalid game scores",code:"ERR_INVALID_SCORES_GAME"},sv={message:"Invalid score",code:"ERR_INVALID_SCORE"},og={message:"Invalid winningSide",code:"ERR_INVALID_WINNING_SIDE"},iv={message:"No participants generated",code:"ERR_NO_PARTICIPANTS_GENERATED"},cg={message:"Cannot modify tieFormat",code:"ERR_UNCHANGED_CANNOT_MODIFY_TIEFORMAT"},ov={message:"Cannot modify participantType",code:"ERR_UNCHANGED_CANNOT_MODIFY_PARTICIPANT_TYPE"},qd={message:"Cannot remove participants",code:"ERR_UNCHANGED_CANNOT_REMOVE_PARTICIPANTS"},ag={message:"Cannot change winningSide",code:"ERR_UNCHANGED_CANNOT_CHANGE_WINNING_SIDE"},vu={message:"Invalid participant",code:"ERR_INVALID_PARTICIPANT"},bs={message:"Invalid participantId",code:"ERR_INVALID_PARTICIPANT_ID"},gr={message:"Invalid participantIds",code:"ERR_INVALID_PARTICIPANT_IDS"},cv={message:"Invalid participantRole",code:"ERR_INVALID_PARTICIPANT_ROLE"},xr={message:"Invalid participantType",code:"ERR_INVALID_PARTICIPANT_TYPE"},av={message:"Missing participantRole",code:"ERR_MISSING_PARTICIPANT_ROLE"},qo={message:"Missing participant",code:"ERR_MISSING_PARTICIPANT"},Yc={message:"Missing participants",code:"ERR_MISSING_PARTICIPANTS"},Ce={message:"Missing participantId",code:"ERR_MISSING_PARTICIPANT_ID"},_e={message:"Participant Not Found",code:"ERR_NOT_FOUND_PARTICIPANT"},uv={message:"participantId exists",code:"ERR_EXISTING_PARTICIPANT_ID"},lv={message:"No participant removed",code:"ERR_UNCHANGED_NO_PARTICIPANT_REMOVED"},Ns={message:"Missing participantIds",code:"ERR_MISSING_PARTICIPANT_IDS"},dv={message:"Missing participantsCount",code:"ERR_MISSING_PARTICIPANT_COUNT"},fv={message:"Participant not checked in",code:"ERR_UNCHANGED_PARTICIPANT_NOT_CHECKED_IN"},ug={message:"Participant already checked in",code:"ERR_UNCHANGED_PARTICIPANT_CHECKED_IN"},pv={message:"Missing person details",code:"ERR_MISSING_PERSON_DETAILS"},Yo={message:"Existing participant drawPosition assignment",code:"ERR_EXISTING_PARTICIPANT_DRAW_POSITION_ASSIGNMENT"},Yd={message:"Existing participant",code:"ERR_EXISTING_PARTICIPANT"},lg={message:"participantsCount exceeds drawSize",code:"ERR_INVALID_PARTICIPANT_COUNT"},zd={message:"Invalid entry status",code:"ERR_INVALID_ENTRY_STATUS"},dg={message:"Participant Entry Not Found",code:"ERR_NOT_FOUND_PARTICIPANT_ENTRY"},hv={message:"Participant not entered in stage",code:"ERR_UNCHANGED_PARTICIPANT_NOT_ENTERED"},mv={message:"Participant not found in stageSequence",code:"ERR_NOT_FOUND_PARTICIPANT_IN_STAGE"},gv={message:"entryStatus not allowed in stage",code:"ERR_INVALID_ENTRY_STATUS_IN_STAGE"},Iv={message:"entryStatus not allowed for event",code:"ERR_INVALID_ENTRY_STATUS_IN_EVENT"},fg={message:"No stage space available for entryStatus",code:"ERR_UNCHANGED_NO_AVAILABLE_STAGE_SPACE"},Sv={message:"Insufficient drawPositions to accommodate qualifiers",code:"ERR_UNCHANGED_NO_DRAW_POSITIONS_FOR_QUALIFIERS"},pg={message:"Insufficient drawPositions to accommodate entries",code:"ERR_INSUFFICIENT_DRAW_POSITIONS"},Tv={message:"Missing penaltyType",code:"ERR_MISSING_PENALTY_TYPE"},hg={message:"Missing penaltyId",code:"ERR_MISSING_PENALTY_ID"},Cu={message:"Penalty not found",code:"ERR_NOT_FOUND_PENALTY"},yv={message:"Missing courtsCount/courtNames",code:"ERR_MISSING_COURTS_INFO"},Kd={message:"Court not found",code:"ERR_NOT_FOUND_COURT"},Ev={message:"Court exists",code:"ERR_EXISTING_COURT"},bv={message:"Venue exists",code:"ERR_EXISTING_VENUE"},di={message:"Venue not found",code:"ERR_NOT_FOUND_VENUE"},Vs={message:"Missing venueId",code:"ERR_MISSING_VENUE_ID"},mg={message:"Invalid endTime",code:"ERR_INVALID_END_TIME"},gg={message:"Existing endTime",code:"ERR_EXISTING_END_TIME"},Nv={message:"Invalid stopTime",code:"ERR_INVALID_STOP_TIME"},Av={message:"Invalid startTime",code:"ERR_INVALID_START_TIME"},vv={message:"Invalid resumeTime",code:"ERR_INVALID_RESUME_TIME"},Ig={message:"Invalid timeItem",code:"ERR_INVALID_TIME_ITEMS"},Sg={message:"Missing timeItem",code:"ERR_MISSING_TIME_ITEM"},Tg={message:"Missing timeItems",code:"ERR_MISSING_TIME_ITEMS"},Pu={message:"Missing context",code:"ERR_MISSING_CONTEXT"},Cv={message:"Missing schedule",code:"ERR_MISSING_SCHEDULE"},Uu={message:"Invalid scaleItem",code:"ERR_INVALID_SCALE_ITEM"},Pv={message:"No scaleItem found",code:"ERR_NOT_FOUND_SCALE_ITEM"},Uv={message:"Modifications failed",code:"ERR_FAILURE_MODIFICATIONS"},zc={message:"No modifications applied",code:"ERR_UNCHANGED_NO_MODIFICATIONS_APPLIED"},Ov={message:"Unable to assign court",code:"ERR_UNCHANGED_COURT_NOT_ASSIGNED"},Jd={message:"No Candidates",code:"ERR_UNCHANGED_NO_CANDIDATES"},Mv={message:"Invalid configuration",code:"ERR_INVALID_CONFIG"},Ir={message:"Invalid object",code:"ERR_INVALID_OBJECT"},tt={message:"Invalid values",code:"ERR_INVALID_VALUES"},Dv={message:"Duplicate value",code:"ERR_DUPLICATE_VALUE"},yg={message:"Team not found",code:"ERR_NOT_FOUND_TEAM"},wv={message:"No valid actions",code:"ERR_NO_VALID_ACTIONS"},Qd={message:"No valid attributes",code:"ERR_NO_VALID_ATTRIBUTES"},Eg={message:"Value unchanged",code:"ABORT_UNCHANGED"},an={message:"Not found",code:"ERR_NOT_FOUND"},bg={message:"Not implemented",code:"ERR_NOT_IMPLEMENTED"},kv={message:"Existing flight",code:"ERR_EXISTING_FLIGHT"},Ng={message:"Existing flight profile",code:"ERR_EXISTING_FLIGHT_PROFILE"},_v={message:"Existing outcome",code:"ERR_EXISTING_OUTCOME"},Fv={message:"Existing matchUpId",code:"ERR_EXISTING_MATCHUP_ID"},Ag={message:"Existing stage",code:"ERR_EXISTING_STAGE"},Lv={message:"Existing structure",code:"ERR_EXISTING_STRUCTURE"},vg={message:"Method not found",code:"ERR_NOT_FOUND_METHOD"},Rv={message:"Scheduled matchUps",code:"ERR_SCHEDULED_MATCHUPS"},ye={disableNotifications:!1,tournamentId:void 0,tournamentRecords:{},subscriptions:{},modified:!1,notices:[]};var Cg={addNotice:zv,callListener:Xv,cycleMutationStatus:Yv,deleteNotice:Qv,deleteNotices:Jv,disableNotifications:Bv,enableNotifications:xv,getNotices:Kv,getTopics:Zv,getTournamentId:Pg,getTournamentRecord:$v,getTournamentRecords:Vv,removeTournamentRecord:Hv,setSubscriptions:qv,setTournamentId:Gv,setTournamentRecord:jv,setTournamentRecords:Wv,handleCaughtError:tC};function Bv(){ye.disableNotifications=!0}function xv(){ye.disableNotifications=!1}function Pg(){return ye.tournamentId}function $v(t){return ye.tournamentRecords[t]}function Vv(){return ye.tournamentRecords}function jv(t){const e=t==null?void 0:t.tournamentId;return e?(ye.tournamentRecords[e]=t,{success:!0}):{error:Tu}}function Gv(t){return ye.tournamentRecords[t]?(ye.tournamentId=t,{success:!0}):{error:et}}function Wv(t){ye.tournamentRecords=t;const e=Object.keys(t);e.length===1?ye.tournamentId=e[0]:e.length||(ye.tournamentId=void 0)}function Hv(t){if(typeof t!="string")return{error:tt};if(!ye.tournamentRecords[t])return{error:an};delete ye.tournamentRecords[t];const e=Object.keys(ye.tournamentRecords);return e.length===1?ye.tournamentId=e[0]:e.length||(ye.tournamentId=void 0),{success:!0}}function qv(t){return typeof t.subscriptions!="object"?{error:tt}:(Object.keys(t.subscriptions).forEach(e=>{ye.subscriptions[e]=t.subscriptions[e]}),{...$})}function Yv(){const t=ye.modified;return ye.modified=!1,t}function zv({topic:t,payload:e,key:n}){ye.modified=!0,!(typeof t!="string"||typeof e!="object")&&(ye.disableNotifications||!ye.subscriptions[t]||(n&&(ye.notices=ye.notices.filter(r=>!(r.topic===t&&r.key===n))),ye.notices.push({topic:t,payload:e,key:n})))}function Kv({topic:t}){const e=ye.notices.filter(n=>n.topic===t).map(n=>n.payload);return e.length&&e}function Jv(){ye.notices=[]}function Qv({topic:t,key:e}){ye.notices=ye.notices.filter(n=>(!t||n.topic===t)&&n.key!==e)}function Zv(){return{topics:Object.keys(ye.subscriptions)}}function Xv({topic:t,notices:e}){const n=ye.subscriptions[t];n&&typeof n=="function"&&n(e)}function tC({engineName:t,methodName:e,params:n,err:r}){let s;typeof r=="string"?s=r.toUpperCase():r instanceof Error&&(s=r.message),console.log("ERROR",{tournamentId:Pg(),params:JSON.stringify(n),engine:t,methodName:e,error:s})}const ir={tournamentFactoryVersion:"0.0.0",timers:{default:{elapsedTime:0}},iterators:{makeDeepCopy:0},deepCopyAttributes:{stringify:[],ignore:[],toJSON:[]},deepCopy:!0};let Nn=Cg;function ze(t){return!t||typeof t!="object"?ir.devContext??!1:typeof ir.devContext!="object"?!1:Object.keys(t).every(e=>{var n;return((n=ir.devContext)==null?void 0:n[e])===t[e]})&&ir.devContext}function zo(t){ir.devContext=t}function eC(t){ir.iterators.makeDeepCopy=t}function nC(){return ir.iterators.makeDeepCopy}function rC(){Nn.disableNotifications()}function Zd(){Nn.enableNotifications()}function Hi(t,e){typeof t=="boolean"&&(ir.deepCopy=t),typeof e=="object"&&(Array.isArray(e.ignore)&&(ir.deepCopyAttributes.ignore=e.ignore),Array.isArray(e.toJSON)&&(ir.deepCopyAttributes.toJSON=e.toJSON),Array.isArray(e.stringify)&&(ir.deepCopyAttributes.stringify=e.stringify),e.threshold&&(ir.deepCopyAttributes.threshold=e.threshold))}function Ug(){return{enabled:ir.deepCopy,...ir.deepCopyAttributes}}function Kc(){return Nn.cycleMutationStatus()}function Ht(t){return Nn.addNotice(t)}function sC(t){return Nn.getNotices(t)}function Og({key:t,topic:e}){return Nn.deleteNotice({key:t,topic:e})}function fi(){return Nn.deleteNotices()}function $r(){return Nn.getTopics()}async function Mg(t){return Nn.callListener(t)}function os(){return Nn.getTournamentId()}function Jc(t){return Nn.getTournamentRecord(t)}function Ou(){return Nn.getTournamentRecords()}function Dg(t){return Nn.setTournamentRecord(t)}function Qc(t){return Nn.setTournamentRecords(t)}function Zc(t){return Nn.setTournamentId(t)}function Xd(t){return Nn.removeTournamentRecord(t)}function Xc({engineName:t,methodName:e,params:n,err:r}){return(typeof Nn.handleCaughtError=="function"&&Nn.handleCaughtError||Cg.handleCaughtError)({engineName:t,methodName:e,params:n,err:r})}const Mu=/^[\d]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][\d]|3[0-1])$/,wg=/^((0[\d]|1[\d]|2[0-3]):[0-5][\d](:[0-5][\d])?)([.,][0-9]{3})?$/,Vr=/^([\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?$/,pi=/^([\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 Du(t){let{scheduledDate:e}=t;if(!e&&t.scheduledTime&&(e=Bt(t.scheduledTime)),!e)return;const n=de(t.scheduledTime);let r=Bt(e);return r&&n&&(r+=`T${n}`),r}function iC(t){return typeof t!="object"||Array.isArray(t)?!1:Object.prototype.toString.call(t)==="[object Date]"}function Ko(t){const e=typeof t=="string"?t==null?void 0:t.split(" "):[];return t&&(e==null?void 0:e.length)>1&&!["AM","PM"].includes(e[1].toUpperCase())?!1:!!(!t||pi.test(qi(t,!0,!0)))}function Yn(t){return hi(t)||Mu.test(t)}function oC(t){const e=new Date(t),n=e.getSeconds()+60*e.getMinutes()+60*60*e.getHours();return cC(n,{displaySeconds:!1})}function cC(t,e){const n=parseInt(t,10),r=Math.floor(n/3600),s=Math.floor((n-r*3600)/60),i=n-r*3600-s*60;return(!e||(e==null?void 0:e.displaySeconds)?r+":"+s+":"+i:r+":"+s).split(":").map(cs).join(":")}const tf=t=>{const e=ta(t)||hi(t)?new Date(t):new Date,n=e.getUTCMonth()+1,r=n<10?`0${n}`:`${n}`;return`${e.getUTCFullYear()}-${cs(r)}-${cs(e.getUTCDate())}`};function aC(t){const e=ta(t)||hi(t)?new Date(t):new Date;return Date.UTC(e.getFullYear(),e.getMonth(),e.getDate())}function Sr(t,e="-",n="YMD"){if(!t)return"";typeof t=="string"&&t.indexOf("T")<0&&(t=t+"T00:00");const r=new Date(t);let s=""+(r.getMonth()+1),i=""+r.getDate();const o=r.getFullYear();return s.length<2&&(s="0"+s),i.length<2&&(i="0"+i),n==="DMY"?[i,s,o].join(e):n==="MDY"?[s,i,o].join(e):n==="YDM"?[o,i,s].join(e):n==="DYM"?[i,o,s].join(e):n==="MYD"?[s,o,i].join(e):[o,s,i].join(e)}function wu(t){const e=t?new Date(t):new Date,n=e.getTimezoneOffset();return new Date(e.getTime()-n*60*1e3)}function uC(t){return wu(t).getTime()}function ta(t){if(typeof t=="boolean")return!1;const e=t instanceof Date&&t||!isNaN(t)&&new Date(t)||!1;return e&&!isNaN(e.valueOf())}function ef(t,e){if(!Yn(t)||!Yn(e))return[];const n=Bt(t)+"T00:00",r=Bt(e)+"T00:00",s=new Date(n),i=new Date(r),o=ta(i)&&ta(s)&&u(s,i),c=[];let a=0;if(o){const l=s;let f=l.getTime();for(;f<=i.getTime()&&a<300;)a+=1,c.push(new Date(l)),f=l.setDate(l.getDate()+1)}return c.map(l=>Sr(l));function u(l,f){return l<=f}}const lC=/^([+-]?\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 hi(t){return typeof t!="string"?!1:lC.test(t)}function kg(t){if(typeof t!="string")return!1;const n=t.split("Z")[0].split(":"),r=n.every(i=>!isNaN(parseInt(i)));return!(n.length<2||!r||parseInt(n[0])>23||parseInt(n[1])>60)}function jt(t){const e=de(t);if(!e)return 0;const[n,r]=e.split(":").map(s=>parseInt(s));return n*60+r}function dC(t){let e=Math.floor(t/60);const n=t-e*60;return e>23&&(e=e%24),[cs(e),cs(n)].join(":")}function ku(t){return kg(t)?t.split(":").slice(0,2).map(cs).join(":"):void 0}function de(t){return hi(t)&&t.indexOf("T")>0?ku(t.split("T").reverse()[0]):ku(t)}function Bt(t){return hi(t)||Vr.test(t)?t.split("T")[0]:void 0}function fC(t,e){const n=new Date(t);return n.setDate(n.getDate()+e),Bt(n.toISOString())}function _u(t){t=typeof t!="string"?"00:00":t;const e={},n={};return{0:e.time,1:e.ampm}=t.split(" ")||[],{0:n.hours,1:n.minutes}=e.time.split(":")||[],n.ampm=e.ampm,isNaN(n.hours)||isNaN(n.minutes)||n.ampm&&!["AM","PM"].includes(n.ampm.toUpperCase())?{}:n}function pC(t){const e=_u(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(cs).join(":")}function hC(t){var n;const e=_u(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"),((n=e.hours)==null?void 0:n[0])==="0"&&(e.hours=e.hours.slice(1)),`${e.hours||"12"}:${e.minutes||"00"} ${e.ampm}`)}function qi(t,e,n){const r=Bt(t),s=de(t),i=r?s:t;return t?e&&(r&&n&&t||pC(i))||hC(i):void 0}function _g(t,e){const n=_u(t),r=_u(e);if(parseInt(n.hours)<parseInt(r.hours))return-1;if(parseInt(n.hours)>parseInt(r.hours))return 1;if(n.hours===r.hours){if(parseInt(n.minutes)<parseInt(r.minutes))return-1;if(parseInt(n.minutes)>parseInt(r.minutes))return 1}return 0}function Fg(t,e=7){const n=Bt(t)+"T00:00",r=new Date(n),s=new Date(r.setDate(r.getDate()+e));return Sr(s)}function mC(t){return Fg(t)}function gC(t,e,n,r=!1){const s=new Date(e,0,1+(t-1)*7),i=r?0:1;return s.setDate(s.getDate()+(i-s.getDay())),Sr(s,n)}function IC(t,e,n){const r=new Date(t,0);return Sr(new Date(r.setDate(e)),n)}function Pe(t,e=void 0){const[n,r]=(t||"00:00").split(":").map(cs),s=wu(e).setHours(n,r,0,0);return wu(s)}function ea(t,e,n=!0){const r=new Date(t),i=(new Date(e).getTime()-r.getTime())/1e3/60;return n?Math.abs(Math.round(i)):Math.round(i)}function An(t,e){const n=de(t);if(!n)return"00:00";const r=isNaN(e)?0:e;return de(nf(Pe(n),r).toISOString())}function nf(t,e){const n=new Date(t);return new Date(n.getTime()+e*6e4)}function cs(t){return t.toString()[1]?t:"0"+t}function as(t,e){const n=new Date(t),r=new Date(e);return n.getFullYear()===r.getFullYear()&&n.getMonth()===r.getMonth()&&n.getDate()===r.getDate()}const SC={addDays:Fg,addWeek:mC,addMinutesToTimeString:An,convertTime:qi,getIsoDateString:Du,getUTCdateString:tf,DateHHMM:oC,extractDate:Bt,extractTime:de,formatDate:Sr,getDateByWeek:gC,isISODateString:hi,isDate:ta,isTimeString:kg,offsetDate:wu,offsetTime:uC,sameDay:as,timeStringMinutes:jt,timeToDate:Pe,timeUTC:aC,validTimeValue:Ko,validDateString:Mu,timeValidation:pi,dateValidation:Vr};function pt(t,e,n,r,s=0){const i=Ug(),{stringify:o,toJSON:c,ignore:a,modulate:u}=i||{};if(!(i!=null&&i.enabled)&&!n||typeof t!="object"||typeof t=="function"||t===null||typeof(i==null?void 0:i.threshold)=="number"&&s>=i.threshold)return t;const l=ze({makeDeepCopy:!0});l&&(eC(s),typeof l=="object"&&(s>(l.iterationThreshold||15)||l.firstIteration&&s===0)&&l.log&&(!l.notInternalUse||l.notInternalUse&&!n)&&console.log({devContext:l,iteration:s,internalUse:n},t));const f=Array.isArray(t)?[]:{},p=Object.keys(t).filter(d=>!n||!a||Array.isArray(a)&&!a.includes(d)||typeof a=="function"&&!a(d)),h=(d,m)=>{f[d]=typeof(m==null?void 0:m.toString)=="function"?m.toString():JSON.stringify(m)};for(const d of p){const m=t[d],g=typeof u=="function"?u(m):void 0;if(g!==void 0)f[d]=g;else if(e&&d==="extensions"&&Array.isArray(m)){const I=rf(m);Object.assign(f,...I)}else r&&d==="extensions"?f[d]=[]:Array.isArray(o)&&o.includes(d)?h(d,m):Array.isArray(c)&&c.includes(d)&&typeof(m==null?void 0:m.toJSON)=="function"?f[d]=m.toJSON():m===null?f[d]=void 0:iC(m)?f[d]=new Date(m).toISOString():f[d]=pt(m,e,n,r,s+1)}return f}function rf(t){return t==null?void 0:t.map(e=>{const{name:n,value:r}=e;return n&&r&&{[`_${n}`]:r}}).filter(Boolean)}function Yi({element:t,accessor:e}){if(typeof e!="string")return{values:[]};const n=pt(t),r=e.split("."),s=[];let i;c({targetElement:n,attributes:r});const o={value:i};return s.length&&(o.values=s),o;function c({targetElement:a,attributes:u=[],significantCharacters:l}){for(const[p,h]of u.entries())if(a!=null&&a[h]){const d=u.slice(p+1);d.length?Array.isArray(a[h])?a[h].forEach(g=>c({targetElement:g,attributes:d})):(a=a[h],f({targetElement:a,index:p})):(i||(i=a[h]),s.includes(a[h])||s.push(a[h]))}function f({targetElement:p,index:h}){if(p&&h===u.length-1&&["string","number"].includes(typeof p)){const d=l?p.slice(0,l):p;i?s.includes(d)||s.push(d):(i=d,s.push(d))}}}}function TC(t){return typeof t=="string"}function or(t){return typeof t=="object"}function yC(t,e){return Array.isArray(t)?Object.assign({},...(t??[]).filter(or).map(n=>n[e]&&{[n[e]]:n}).filter(Boolean)):{}}const EC=t=>e=>Object.keys(t).every(n=>e[n]===t[n]),kn=t=>e=>{var n;return!t||typeof e!="object"?void 0:Array.isArray(t)&&t.map(r=>{var s;return{[r]:(s=Yi({element:e,accessor:r}))==null?void 0:s.value}})||typeof t=="object"&&Object.keys(t).map(r=>{var s;return{[r]:(s=Yi({element:e,accessor:r}))==null?void 0:s.value}})||((n=typeof t=="string"&&Yi({element:e,accessor:t}))==null?void 0:n.value)};function bt(t,e,n,r){if(typeof t!="object"||t===null)return t;const s=Ug();s!=null&&s.enabled||(r=!0);const i=["",void 0,null];e&&i.push(!1);const o=Object.keys(t).filter(c=>!i.includes(t[c])&&(!n||(Array.isArray(t[c])?t[c].length:!0)));return Object.assign({},...o.map(c=>Array.isArray(t[c])?{[c]:r?t[c]:t[c].map(a=>bt(a))}:{[c]:r?t[c]:bt(t[c])}))}function sf(t){return Array.isArray(t)?t.length+t.map(sf).reduce((e,n)=>e+n,0):typeof t=="object"&&t!==null?Object.keys(t).length+Object.keys(t).map(e=>sf(t[e])).reduce((e,n)=>e+n,0):0}function bC(t){if(t===null||typeof t!="object")return;const e=JSON.stringify(t),n=sf(t),r=e.split("").reduce((s,i)=>s+i.charCodeAt(0),0);return[e.length,n,r].map(s=>s.toString(36)).join("")}function Fu(t){if(t===null)return{};const{source:e,template:n}=t||{};if(!n)return e;const r={};return s(e,n,r),r;function s(i,o,c){if(!i||!o)return;const a=Object.keys(i),u=Object.keys(o),l=Object.assign({},...u.filter(h=>h.indexOf("||")).map(h=>h.split("||").map(d=>({[d]:h}))).flat()),f=u.concat(...Object.keys(l)),p=f.includes("*");for(const h of a)if(f.indexOf(h)>=0||p){const d=l[h]||h,m=o[d]||p,g=i[h];if(typeof m=="object"&&typeof g!="function"&&!Array.isArray(m))if(Array.isArray(g)){const I=g.map(S=>{const T={};return s(S,m,T)!==!1?T:void 0}).filter(Boolean);c[h]=I}else g&&(c[h]={},s(g,m,c[h]));else{const I=i[h];if(Array.isArray(m)&&!m.includes(I))return!1;(o[h]||p&&o[h]!==!1)&&(c[h]=I)}}}}function Lg(t=0){const e=new Date;return e.setHours(e.getHours()+t),e.getTime().toString(36).slice(-6).toUpperCase()}function Ve(t,e){return t-e}function NC(t,e){if(e&&typeof e!="object")return tt;let{columnTransform:n={}}=e||{};const{includeTransformAccessors:r,includeHeaderRow:s=!0,returnTransformedJSON:i,removeEmptyColumns:o,onlyHeaderRow:c,columnAccessors:a=[],functionMap:u={},columnMap:l={},valuesMap:f={},context:p={},delimiter:h='"',columnJoiner:d=",",rowJoiner:m=`\r
6
6
  `,keyJoiner:g="."}=e||{};if(!Array.isArray(t)||!Array.isArray(a)||typeof p!="object"||typeof l!="object"||typeof n!="object"||typeof u!="object"||typeof f!="object"||typeof d!="string"||typeof m!="string"||typeof g!="string"||typeof h!="string")return tt;n=Object.assign({},...Object.keys(n).reverse().map(D=>({[D]:Array.isArray(n[D])?n[D]:[typeof n[D]=="string"&&n[D]].filter(Boolean)})));const I=t.filter(Boolean).map(D=>of(D,g)),S=Object.values(n).flat();r&&a.push(...S);const T=I.reduce((D,M)=>Object.keys(M).every(w=>!D.includes(w)&&D.push(w)||!0)&&D,[]).filter(D=>!(a!=null&&a.length)||a.includes(D)),E=Object.assign({},...Object.keys(n).reverse().map(D=>n[D].map(M=>({[M]:D})).flat()).flat()),y=(D,M)=>e!=null&&e.sortOrder?e.sortOrder.includes(D)&&e.sortOrder.includes(M)&&e.sortOrder.indexOf(D)-e.sortOrder.indexOf(M)||!e.sortOrder.includes(M)&&-1:0,b=T.reduce((D,M)=>{const w=E[M];return w?D.includes(w)||D.push(w):D.push(M),D},[]).sort(y);Object.keys(l).forEach(D=>!b.includes(D)&&b.unshift(D)),Object.keys(n).forEach(D=>!b.includes(D)&&b.unshift(D)),typeof p=="object"&&Object.keys(p).forEach(D=>!b.includes(D)&&b.unshift(D));let N=b.map(D=>l[D]||D);if(c)return[N];const A=D=>`${h}${D}${h}`,C=[],v=D=>Object.values(b.reduce((M,w,k)=>{var j;const _=n[w],F=(_!=null&&_.length?D[_.find(H=>D[H])]:D[w])||(p==null?void 0:p[w])||"",L=((j=f[w])==null?void 0:j[F])||F,W=typeof u[w]=="function"?u[w](L):L;return M[w]=A(W),W&&(C[k]=(C[k]||0)+1),M},{}));let P=I.map(v);const U=o&&[...C].map((D,M)=>!D&&M).filter(Me).reverse();if(U){const D=M=>M.filter((w,k)=>!U.includes(k));P=P.map(D),N=D(N)}const O=P.map(D=>D.join(d));return i?O.map(D=>{const M=D.split(d);return Object.assign({},...M.map((w,k)=>({[N[k]]:w})))}):s?[N.map(A).join(d),...O].join(m):O.join(m)}function of(t,e,n=[]){return typeof t=="object"&&Object.keys(t).reduce((r,s)=>typeof t[s]!="object"?(r[n.concat(s).join(e)]=t[s],r):Object.assign(r,of(t[s],e,n.concat(s))),{})}function AC(t=1){return ht(0,t).map(Yt)}function Yt(){const t=[];for(let i=0;i<256;i++)t[i]=(i<16?"0":"")+i.toString(16);const e=Math.random()*4294967295|0,n=Math.random()*4294967295|0,r=Math.random()*4294967295|0,s=Math.random()*4294967295|0;return t[e&255]+t[e>>8&255]+t[e>>16&255]+t[e>>24&255]+"-"+t[n&255]+t[n>>8&255]+"-"+t[n>>16&15|64]+t[n>>24&255]+"-"+t[r&63|128]+t[r>>8&255]+"-"+t[r>>16&255]+t[r>>24&255]+t[s&255]+t[s>>8&255]+t[s>>16&255]+t[s>>24&255]}function G({context:t,result:e,stack:n,info:r}){return e&&!Array.isArray(e==null?void 0:e.stack)&&(e.stack=[]),e&&Array.isArray(e==null?void 0:e.stack)&&typeof n=="string"&&e.stack.push(n),r&&(e!=null&&e.error)&&(e.error.info=r),e&&typeof t=="object"&&Object.keys(t).length&&Object.assign(e,bt(t)),e&&!(e!=null&&e.error)&&!(e!=null&&e.success)&&Object.assign(e,{...$}),e??{success:!0}}var na=(t=>(t.AdHoc="AD_HOC",t.Compass="COMPASS",t.CurtisConsolation="CURTIS_CONSOLATION",t.DoubleElimination="DOUBLE_ELIMINATION",t.FeedIn="FEED_IN",t.FeedInChampionship="FEED_IN_CHAMPIONSHIP",t.FeedInChampionshipToQf="FEED_IN_CHAMPIONSHIP_TO_QF",t.FeedInChampionshipToR16="FEED_IN_CHAMPIONSHIP_TO_R16",t.FeedInChampionshipToSf="FEED_IN_CHAMPIONSHIP_TO_SF",t.FirstMatchLoserConsolation="FIRST_MATCH_LOSER_CONSOLATION",t.FirstRoundLoserConsolation="FIRST_ROUND_LOSER_CONSOLATION",t.ModifiedFeedInChampionship="MODIFIED_FEED_IN_CHAMPIONSHIP",t.Lucky="LUCKY_DRAW",t.Olympic="OLYMPIC",t.Other="OTHER",t.Playoff="PLAYOFF",t.RoundRobin="ROUND_ROBIN",t.RoundRobinWithPlayoff="ROUND_ROBIN_WITH_PLAYOFF",t.SingleElimination="SINGLE_ELIMINATION",t))(na||{}),As=(t=>(t.Consolation="CONSOLATION",t.Main="MAIN",t.PlayOff="PLAY_OFF",t.Qualifying="QUALIFYING",t.VoluntaryConsolation="VOLUNTARY_CONSOLATION",t))(As||{}),un=(t=>(t.Alternate="ALTERNATE",t.Confirmed="CONFIRMED",t.DirectAcceptance="DIRECT_ACCEPTANCE",t.FeedIn="FEED_IN",t.JuniorExempt="JUNIOR_EXEMPT",t.LuckyLoser="LUCKY_LOSER",t.OrganiserAcceptance="ORGANISER_ACCEPTANCE",t.Qualifier="QUALIFIER",t.SpecialExempt="SPECIAL_EXEMPT",t.Registered="Registered",t.Ungrouped="UNGROUPED",t.Unpaired="UNPAIRED",t.Wildcard="WILDCARD",t.Withdrawn="WITHDRAWN",t))(un||{}),js=(t=>(t.Loser="LOSER",t.Position="POSITION",t.Winner="WINNER",t))(js||{}),ra=(t=>(t.BottomUp="BOTTOM_UP",t.Draw="DRAW",t.LossPosition="LOSS_POSITION",t.Random="RANDOM",t.TopDown="TOP_DOWN",t.Waterfall="WATERFALL",t))(ra||{}),_n=(t=>(t.Doubles="DOUBLES",t.Singles="SINGLES",t.Team="TEAM",t))(_n||{}),pe=(t=>(t.Abandoned="ABANDONED",t.AwaitingResult="AWAITING_RESULT",t.Bye="BYE",t.Cancelled="CANCELLED",t.Completed="COMPLETED",t.DeadRubber="DEAD_RUBBER",t.Defaulted="DEFAULTED",t.DoubleDefault="DOUBLE_DEFAULT",t.DoubleWalkover="DOUBLE_WALKOVER",t.InProgress="IN_PROGRESS",t.Incomplete="INCOMPLETE",t.NotPlayed="NOT_PLAYED",t.Retired="RETIRED",t.Suspended="SUSPENDED",t.ToBePlayed="TO_BE_PLAYED",t.Walkover="WALKOVER",t))(pe||{}),sa=(t=>(t.Any="ANY",t.Female="FEMALE",t.Male="MALE",t.Mixed="MIXED",t))(sa||{}),Rg=(t=>(t.Administration="ADMINISTRATION",t.Captain="CAPTAIN",t.Coach="COACH",t.Competitor="COMPETITOR",t.Media="MEDIA",t.Medical="MEDICAL",t.Official="OFFICIAL",t.Other="OTHER",t.Security="SECURITY",t))(Rg||{}),jr=(t=>(t.Group="GROUP",t.Individual="INDIVIDUAL",t.Pair="PAIR",t.Team="TEAM",t))(jr||{});function vn(t){var h,d,m,g;const e=!!((t==null?void 0:t.enforceGender)!==!1&&(t!=null&&t.gender)),n=t==null?void 0:t.checkCollectionIds,r=t==null?void 0:t.tieFormat,s="validateTieFormat",i=[];if(typeof r!="object")return i.push("tieFormat must be an object"),G({result:{context:{tieFormat:r,errors:i},error:li,stack:s}});if(typeof r.winCriteria!="object")return i.push("tieFormat.winCriteria must be an object"),G({result:{context:{tieFormat:r,errors:i},error:li,stack:s}});if(!Array.isArray(r.collectionDefinitions))return i.push(sn("tieFormat.collectionDefinitions")),G({result:{context:{tieFormat:r,errors:i},error:li,stack:s}});let o;const c=r.collectionDefinitions.every(I=>{const{setValue:S,scoreValue:T,collectionValue:E}=I;(S||T)&&!E&&(o=!0);const{valid:y,errors:b}=cf({referenceGender:t.gender,collectionDefinition:I,checkCollectionIds:n,checkGender:e});return y?!0:(Array.isArray(b)&&i.push(...b),!1)}),a=typeof((h=r.winCriteria)==null?void 0:h.valueGoal)=="number"&&((d=r.winCriteria)==null?void 0:d.valueGoal)>0&&!o||((m=r.winCriteria)==null?void 0:m.aggregateValue);if(!(a||(g=r.winCriteria)!=null&&g.aggregateValue))return o?i.push("aggregateValue is required"):i.push("Either non-zero valueGoal, or { aggregateValue: true } must be specified in winCriteria"),G({result:{context:{tieFormat:r,errors:i,aggregateValueImperative:o},error:li,stack:s}});const u=r.collectionDefinitions.map(({collectionId:I})=>I),l=!n||u.length===Vt(u).length,f=c&&a&&l,p={valid:f,errors:i};return f?p:G({result:{context:{tieFormat:r,errors:i},error:li,stack:s}})}function cf({collectionDefinition:t,checkCollectionIds:e,checkGender:n=!0,referenceGender:r,event:s}){r=r??(s==null?void 0:s.gender);const i=[];if(typeof t!="object")return i.push(`collectionDefinition must be an object: ${t}`),{errors:i,error:Ir};const{collectionValueProfiles:o,collectionGroupNumber:c,collectionValue:a,collectionId:u,matchUpCount:l,matchUpFormat:f,matchUpValue:p,matchUpType:h,scoreValue:d,setValue:m,gender:g}=t;if(e&&typeof u!="string"&&i.push(`collectionId is not type string: ${u}`),typeof l!="number"&&i.push(`matchUpCount is not type number: ${l}`),h&&![_n.Singles,_n.Doubles].includes(h)&&i.push(`matchUpType must be SINGLES or DOUBLES: ${h}`),[!!(o!=null&&o.length)].concat([p,a,d,m].map(oe)).filter(Boolean).length!==1&&i.push("Missing value definition for matchUps: matchUpValue, collectionValue, or collectionValueProfiles"),p&&typeof p!="number"&&i.push(`matchUpValue is not type number: ${p}`),a&&typeof a!="number"&&i.push(`collectionValue is not type number: ${a}`),o){const S=Bg({collectionValueProfiles:o,matchUpCount:l});S.errors&&i.push(...S.errors)}return c&&typeof c!="number"&&i.push(`collectionGroupNumber is not type number: ${a}`),f&&!b1.isValid(f)&&i.push(`Invalid matchUpFormat: ${f}`),n&&r&&g&&[sa.Male,sa.Female].includes(r)&&r!==g&&i.push(`Invalid gender: ${g}`),i.length?{errors:i,error:Ir}:{valid:!0}}function vC(t){const e=vn({tieFormat:t,checkCollectionIds:!1});if(e.error)return e;for(const n of t.collectionDefinitions)n.collectionId||(n.collectionId=Yt());return{tieFormat:t}}function Bg({collectionValueProfiles:t,matchUpCount:e}){const n=[];if(!Array.isArray(t))return n.push(`collectionValueProfiles is not an array: ${t}`),{errors:n};if(t.length&&t.length!==e)return n.push("collectionValueProfiles do not align with matchUpsCount"),{errors:n};for(const s of t){if(typeof s!="object")return n.push(`valueProfile is not type object: ${s}`),{errors:n};const{value:i,collectionPosition:o}=s;if(typeof i!="number"||typeof o!="number"||o>e||o<1)return n.push("Invalid value profile: value and collectionPosition must be numeric. collectionPosition cannot be greater than matchUpCount"),{errors:n}}const r=t.map(s=>s.collectionPosition);return r.length!==Vt(r).length?(n.push("collectionPositions are not unique"),{errors:n}):{...$}}const zn="ABANDONED",Jo="AWAITING_RESULT",re="BYE",Gs="CANCELLED",De="COMPLETED",ia="DEAD_RUBBER",te="DEFAULTED",en="DOUBLE_DEFAULT",Fe="DOUBLE_WALKOVER",Gr="IN_PROGRESS",us="INCOMPLETE",af="NOT_PLAYED",In="RETIRED",mi="SUSPENDED",Le="TO_BE_PLAYED",ce="WALKOVER",CC=[Jo,De,te,Fe,en,Gr,us,In,mi,ce],PC=[zn,Jo,re,Gs,De,ia,te,Fe,en,Gr,us,af,In,mi,Le,ce],UC=[re,Fe,en,De,te,In,ce],OC=[zn,Jo,Gs,ia,Gr,us,af,mi,Le,void 0],We=[pe.Cancelled,pe.Abandoned,pe.Completed,pe.DeadRubber,pe.Defaulted,pe.DoubleWalkover,pe.DoubleDefault,pe.Retired,pe.Walkover],xg=[zn,De,te,Fe,en,Gr,In,ce],MC=[Gr,us,mi,Le],DC={ABANDONED:zn,AWAITING_RESULT:Jo,BYE:re,CANCELLED:Gs,COMPLETED:De,DEAD_RUBBER:ia,DEFAULTED:te,DOUBLE_WALKOVER:Fe,DOUBLE_DEFAULT:en,IN_PROGRESS:Gr,INCOMPLETE:us,NOT_PLAYED:af,RETIRED:In,SUSPENDED:mi,TO_BE_PLAYED:Le,WALKOVER:ce};function Qo({matchUp:t}){return We.includes(t==null?void 0:t.matchUpStatus)||(t==null?void 0:t.winningSide)}function $g(t){if(!or(t))return!1;const{matchUpId:e,drawPositions:n}=t,r=typeof e=="string",s=!n||Array.isArray(n)&&n.length<=2&&n.every(i=>oe(i)||i===void 0||i===null);return r&&s}function cr(t){return Array.isArray(t)?t.every($g):!1}const Kn="SET3-S:6/TB7",wC="SET3-S:6NOAD",Vg="SET3-S:6/TB7-F:TB10",kC={FORMAT_STANDARD:Kn,FORMAT_STANDARD_NOAD:wC,FORMAT_ATP_DOUBLES:Vg,FORMAT_SHORT_SETS:"SET3-S:4/TB7",FORMAT_FAST4:"SET3-S:4/TB5@3",FORMAT_PRO_SET:"SET1-S:8/TB7",FORMAT_COLLEGE_PRO_SET:"SET1-S:8/TB7@7",TIMED20:"SET1-S:T20"};function jg({winningSide:t,matchUpFormat:e=Kn,matchUpStatus:n,tallyPolicy:r,score:s}){const i=[0,0],{sets:o}=s||{},c=t-1,a=yn(e),u=uf((a==null?void 0:a.bestOf)??1);if(n===te&&(r!=null&&r.setsCreditForDefaults)||n===ce&&(r!=null&&r.setsCreditForWalkovers))i[c]=u;else for(const l of o||[]){const{winningSide:f}=l;f&&(i[f-1]+=1)}return n===In&&(+i[1-c]===u&&(i[1-c]-=1),r!=null&&r.setsCreditForRetirements&&(i[c]=u)),i}function _C({matchUpFormat:t=Kn,winningSide:e,matchUpStatus:n,tallyPolicy:r,score:s}){var p,h;const{sets:i}=s||{};if(!i)return[0,0];const o=e-1,c=yn(t),a=(c==null?void 0:c.bestOf)??1,u=uf(a),l=((p=c==null?void 0:c.setFormat)==null?void 0:p.tiebreakAt)||0,f=[[],[]];if(n===te&&(r!=null&&r.gamesCreditForDefaults)||n===ce&&(r!=null&&r.gamesCreditForWalkovers)){const d=((h=c==null?void 0:c.setFormat)==null?void 0:h.setTo)||0,m=u*d;f[o].push(m)}else i.forEach((d,m)=>{var b;const I=(d.setNumber||m+1)>u&&(c!=null&&c.finalSetFormat)?"finalSetFormat":"setFormat",S=(b=c==null?void 0:c[I])==null?void 0:b.based,T=c==null?void 0:c[I].tiebreakSet,{side1Score:E,side2Score:y}=d;Wg(S)&&(f[0].push(vt(E||0)),f[1].push(vt(y||0))),T&&d.winningSide&&(r==null?void 0:r.gamesCreditForTiebreakSets)!==!1&&f[d.winningSide-1].push(1)});if(n===In){const d=i.length>u&&(c!=null&&c.finalSetFormat)?"finalSetFormat":"setFormat",m=c==null?void 0:c[d];if(Wg(m.based)){const g=(m==null?void 0:m.setTo)||0,I=E=>{if(!(!c||E===""))return+E===l-1||+E===l?vt(l||0)+1:+E<l?g:l},S=jg({winningSide:e,score:{sets:i},matchUpStatus:n,matchUpFormat:t,tallyPolicy:r});if(f.map(E=>E[o]<=E[1-o]).reduce((E,y)=>E+(y?1:0),0)>S[1-o]){const E=f[o].length,y=I(f[1-o][E-1]);y&&(f[o][E-1]=y)}u>f[o].length&&(r!=null&&r.gamesCreditForRetirements)&&f[o].push(g)}}return[f[0].reduce((d,m)=>d+m,0),f[1].reduce((d,m)=>d+m,0)]}function FC({matchUpFormat:t,score:e}){var o;const n=yn(t),r=(n==null?void 0:n.bestOf)??1,s=uf(r),i=[0,0];return(o=e==null?void 0:e.sets)==null||o.forEach((c,a)=>{var p;const l=(c.setNumber||a+1)>s&&(n!=null&&n.finalSetFormat)?"finalSetFormat":"setFormat",f=(p=n==null?void 0:n[l])==null?void 0:p.based;if(Gg(f)){const{side1Score:h,side2Score:d}=c;h&&(i[0]+=vt(h||0)),d&&(i[1]+=vt(d||0))}else c.side1TiebreakScore&&(i[0]+=vt(c.side1TiebreakScore||0)),c.side2TiebreakScore&&(i[1]+=vt(c.side2TiebreakScore||0))}),i}function uf(t){return t&&Math.ceil(t/2)||1}function Gg(t){return t==="P"}function Wg(t){return!Gg(t)}function LC({participantResults:t,matchUpFormat:e,tallyPolicy:n,perPlayer:r,totalSets:s}){var u;const i=e&&yn(e)||{},o=i.bestOf,c=o&&Math.ceil(o/2)||1,a=(u=i.setFormat)==null?void 0:u.setTo;Object.keys(t).forEach(l=>{const f=t[l].setsWon,p=t[l].setsLost,h=n!=null&&n.groupTotalSetsPlayed?s:r*(c||0)||f+p;let d=Math.round(f/h*1e3)/1e3;(d===1/0||isNaN(d))&&(d=h);const m=t[l].tieMatchUpsWon,g=t[l].tieMatchUpsLost,I=m+g;let S=Math.round(m/I*1e3)/1e3;(S===1/0||isNaN(S))&&(S=m);const T=t[l].matchUpsWon,E=t[l].matchUpsLost,y=T+E;let b=Math.round(T/y*1e3)/1e3;(b===1/0||isNaN(b))&&(b=T);const N=t[l].gamesWon||0,A=t[l].gamesLost||0,C=(r||0)*(c||0)*(a||0),v=Math.max(C,N+A);let P=Math.round(N/v*1e3)/1e3;(P===1/0||isNaN(P))&&(P=0);let U=Math.round(t[l].pointsWon/t[l].pointsLost*1e3)/1e3;(U===1/0||isNaN(U))&&(U=0),t[l].setsWon=f,t[l].setsLost=p,t[l].setsPct=d,t[l].tieMatchUpsWon=m,t[l].tieMatchUpsPct=S,t[l].matchUpsPct=b,t[l].gamesWon=N,t[l].gamesLost=A,t[l].gamesPct=P,t[l].pointsPct=U,t[l].result=`${t[l].matchUpsWon}/${t[l].matchUpsLost}`})}const gi="SINGLES",Oe="SINGLES",Tr="DOUBLES",me="DOUBLES",yr="TEAM",Jt="TEAM";function Hg({participantIds:t,matchUpFormat:e,tallyPolicy:n,perPlayer:r,matchUps:s}){var l,f,p,h;const i={},o=(n==null?void 0:n.excludeMatchUpStatuses)||[],c=s.filter(d=>(d.tieMatchUps||!o.includes(d.matchUpStatus))&&(!(t!=null&&t.length)||qe(t,[Zo(d,0),Zo(d,1)]).length===2)),u=c.flatMap(({score:d,tieMatchUps:m})=>{var g;return m?m.filter(({matchUpStatus:I})=>!o.includes(I)).flatMap(({score:I})=>{var S;return((S=I==null?void 0:I.sets)==null?void 0:S.length)||0}):((g=d==null?void 0:d.sets)==null?void 0:g.length)||0}).reduce((d,m)=>d+m,0);for(const d of c){const{matchUpStatus:m,tieMatchUps:g,tieFormat:I,score:S,winningSide:T,sides:E}=d,y=I&&d._disableAutoCalc&&I.collectionDefinitions.every(({scoreValue:A})=>A),b=T&&RC(d),N=T&&BC(d);if(!b&&!N)if(We.includes(m)){const A=Zo(d,0),C=Zo(d,1);A&&(Ws(i,A),i[A].matchUpsCancelled+=1),C&&(Ws(i,C),i[C].matchUpsCancelled+=1)}else if(g!=null&&g.length){r=0;for(const A of g){if(A.winningSide){const C=(l=E.find(({sideNumber:P})=>P===A.winningSide))==null?void 0:l.participantId,v=(f=E.find(({sideNumber:P})=>P===A.winningSide))==null?void 0:f.participantId;C&&v&&(Ws(i,C),Ws(i,v),i[C].tieMatchUpsWon+=1,i[v].tieMatchUpsLost+=1,A.matchUpType===Oe?(i[C].tieSinglesWon+=1,i[v].tieSinglesLost+=1):A.matchUpType===me&&(i[C].tieDoublesWon+=1,i[v].tieDoublesLost+=1))}qg({score:A.score,manualGamesOverride:y,participantResults:i,sides:E})}}else qg({manualGamesOverride:y,participantResults:i,score:S,sides:E});else if(Ws(i,b),Ws(i,N),g!=null&&g.length){r=0;for(const A of g){const{matchUpType:C}=A,v=C===me,P=C===Oe;A.winningSide&&(A.winningSide===T?(b&&(i[b].tieMatchUpsWon+=1,P&&(i[b].tieSinglesWon+=1),v&&(i[b].tieDoublesWon+=1)),N&&(i[N].tieMatchUpsLost+=1,P&&(i[N].tieSinglesLost+=1),v&&(i[N].tieDoublesLost+=1))):A.winningSide!==T&&(N&&(i[N].tieMatchUpsWon+=1,P&&(i[N].tieSinglesWon+=1),v&&(i[N].tieDoublesWon+=1)),b&&(i[b].tieMatchUpsLost+=1,P&&(i[b].tieSinglesLost+=1),v&&(i[b].tieDoublesLost+=1)))),Yg({matchUpFormat:A.matchUpFormat,matchUpStatus:A.matchUpStatus,score:A.score,winningParticipantId:b,losingParticipantId:N,participantResults:i,isTieMatchUp:!0,manualGamesOverride:y,tallyPolicy:n,winningSide:T})}zg({winningParticipantId:b,losingParticipantId:N,participantResults:i,matchUpStatus:m})}else Yg({matchUpFormat:d.matchUpFormat||e,isTieMatchUp:void 0,winningParticipantId:b,manualGamesOverride:y,losingParticipantId:N,participantResults:i,matchUpStatus:m,tallyPolicy:n,winningSide:T,score:S});if(y){const A=(p=E.find(({sideNumber:U})=>U===1))==null?void 0:p.participantId,C=(h=E.find(({sideNumber:U})=>U===2))==null?void 0:h.participantId;Ws(i,A),Ws(i,C);const v=S.sets.reduce((U,O)=>U+O.side1Score,0),P=S.sets.reduce((U,O)=>U+O.side2Score,0);i[A].gamesWon+=v,i[C].gamesWon+=P,i[A].gamesLost+=P,i[C].gamesLost+=v}}return LC({participantResults:i,matchUpFormat:e,tallyPolicy:n,perPlayer:r,totalSets:u}),{participantResults:i}}function RC(t){const e=t.winningSide-1;return Zo(t,e)}function BC(t){const e=1-(t.winningSide-1);return Zo(t,e)}function Zo(t,e){if(!(t!=null&&t.sides))return console.log("no sides:",{matchUp:t}),"foo";const n=t.sides[e];return n?n.participantId:(console.log("No Side",{matchUp:t,index:e}),"foo")}function Ws(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,retirements:0,setsLost:0,setsWon:0,tieSinglesWon:0,tieSinglesLost:0,tieDoublesWon:0,tieDoublesLost:0,tieMatchUpsLost:0,tieMatchUpsWon:0,victories:[],walkovers:0})}function qg({manualGamesOverride:t,participantResults:e,score:n,sides:r}){const{sets:s}=n||{},i=[[],[]],o=[0,0];for(const a of s||[]){const{winningSide:u,side1Score:l,side2Score:f}=a;u&&(o[u-1]+=1),i[0].push(vt(l||0)),i[1].push(vt(f||0))}const c=[i[0].reduce((a,u)=>a+u,0),i[1].reduce((a,u)=>a+u,0)];r.forEach((a,u)=>{const{participantId:l}=a;l&&(Ws(e,l),e[l].setsWon+=o[u],e[l].setsLost+=o[1-u],t||(e[l].gamesWon+=c[u],e[l].gamesLost+=c[1-u]))})}function Yg({winningParticipantId:t,losingParticipantId:e,participantResults:n,manualGamesOverride:r,matchUpFormat:s,matchUpStatus:i,isTieMatchUp:o,tallyPolicy:c,winningSide:a,score:u}){const l=a&&a-1,f=1-l;o||zg({winningParticipantId:t,losingParticipantId:e,participantResults:n,matchUpStatus:i});const p=jg({matchUpStatus:i,matchUpFormat:s,tallyPolicy:c,winningSide:a,score:u}),h=_C({matchUpStatus:i,matchUpFormat:s,tallyPolicy:c,winningSide:a,score:u}),d=FC({score:u,matchUpFormat:s});t&&(n[t].setsWon+=p[l],n[t].setsLost+=p[f],r||(n[t].gamesWon+=h[l],n[t].gamesLost+=h[f]),n[t].pointsWon+=d[l],n[t].pointsLost+=d[f]),e&&(n[e].setsWon+=p[f],n[e].setsLost+=p[l],r||(n[e].gamesWon+=h[f],n[e].gamesLost+=h[l]),n[e].pointsWon+=d[f],n[e].pointsLost+=d[l])}function zg({winningParticipantId:t,losingParticipantId:e,participantResults:n,matchUpStatus:r}){e&&(r===ce&&(n[e].walkovers+=1),r===te&&(n[e].defaults+=1),r===In&&(n[e].retirements+=1),[te,In,ce].includes(r)&&(n[e].allDefaults+=1),n[e].matchUpsLost+=1),t&&(n[t].matchUpsWon+=1),e&&t&&(n[e].defeats.push(t),n[t].victories.push(e))}function xC({matchUps:t,order:e,report:n}){const r={};t.forEach(({sides:i})=>{i.forEach(o=>{o.participantId&&o.participant&&(r[o.participantId]=o.participant.participantName)})});const s=[];return Array.isArray(n)&&n.forEach((i,o)=>{var c;if((c=i.excludedDirectives)!=null&&c.length){const a=i.excludedDirectives.map(({attribute:f})=>f).join(", "),u=`${a.length} directives were excluded due to participants limit}`;s.push(u);const l=`Excluded: ${a}`;s.push(l)}else{const a=(h,d)=>parseFloat(i.reversed?h:d)-parseFloat(i.reversed?d:h),u=h=>{Object.keys(h.groups).sort(a).forEach(d=>{const m=h.groups[d].map(I=>r[I]).join(", "),g=`${d} ${h.attribute}: ${m}`;s.push(g)})},l=i.reversed?" in reverse order":"",f=Object.values(i.groups).flat(1/0).length,p=`Step ${o+1}: ${f} particiants were grouped${l} by ${i.attribute}`;if(s.push(p),i.idsFilter){const h=`${i.attribute} was calculated considering ONLY TIED PARTICIPANTS`;s.push(h)}u(i)}s.push("----------------------")}),s.push("Final Order:"),e.forEach(i=>{const{participantId:o,resolved:c}=i,a=i.groupOrder||i.provisionalOrder;s.push(`${a}: ${r[o]} => resolved: ${c}`)}),s.join(`\r
7
7
  `)}function Kg({participantResults:t,participantIds:e,attribute:n}){return Jg({participantResults:t,participantIds:e}).reduce((s,i)=>{const{participantId:o,results:c}=i,a=c==null?void 0:c[n];return!isNaN(a)&&o&&(s[a]?s[a].push(o):s[a]=[o]),s},{})}function Jg(t){return(t.participantIds||Object.keys(t.participantResults)).reduce((n,r,s)=>(n.push({participantId:r,i:s,results:t.participantResults[r]}),n),[])}const $C=[{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}],lf={matchUpsPct:20,tieMatchUpsPct:16,setsPct:12,gamesPct:8,pointsPct:4};function Qg(t){const{requireCompletion:e=!0,participantResults:n,subOrderMap:r,tallyPolicy:s}=t,i=[];if(e&&!VC(t))return{};const o=["tieMatchUpsWon","tieSinglesWon","tieDoublesWon","matchUpsWon","pointsWon","gamesWon","setsWon","gamesPct","setsPct","pointsPct","matchUpsPct"].includes(s==null?void 0:s.groupOrderKey)?s.groupOrderKey:"matchUpsWon",c=Kg({participantResults:n,attribute:o});i.push({attribute:o,groups:c});const a=Object.keys(c).map(d=>parseFloat(d)).sort((d,m)=>m-d).map(d=>c[d]).map(d=>{const m=Zg({participantIds:d,...t});return i.push(m.report),m.order}).flat(1/0);let u=1,l;a.forEach((d,m)=>{m&&(d.resolved||l&&!d.resolved)&&(u+=1),l=d.resolved,d.resolved?(d.position=m+1,u=d.position):d.position=u});const f=a.map(({position:d})=>d),p=Mn(f);return a.forEach(d=>{const{participantId:m,position:g}=d||{},I=n[m];d.GEMscore=h(I);const S=p[g];(d==null?void 0:d.position)!==void 0&&(S>1&&(d.ties=S,r&&(d.subOrder=r[m])),d.rankOrder=g,d.groupOrder=g+(d.subOrder||1)-1)}),{groupOrder:a,report:i.flat(1/0).filter(Boolean)};function h(d){return(Array.isArray(s==null?void 0:s.GEMscore)?Object.keys(lf).filter(I=>s.GEMscore.includes(I)):Object.keys(lf)).map(I=>(d[I]||0)*Math.pow(10,lf[I].toFixed(3))).reduce((I,S)=>I+S,0)}}function VC({participantResults:t,participantsCount:e}){const r=Jg({participantResults:t}).filter(s=>e-1===s.results.matchUpsWon+s.results.matchUpsLost+s.results.matchUpsCancelled);return e===r.length}function jC({disableHeadToHead:t,participantIds:e,matchUpFormat:n,tallyPolicy:r,attribute:s,idsFilter:i,matchUps:o,reversed:c}){const{participantResults:a}=Hg({participantIds:i&&e,matchUpFormat:n,tallyPolicy:r,matchUps:o}),u=Kg({participantResults:a,participantIds:e,attribute:s}),l=[{attribute:s,reversed:c,groups:u,idsFilter:i}];let f;return Object.keys(u).length>1&&e.length&&(f=Object.keys(u).map(p=>parseFloat(p)).sort((p,h)=>c?p-h:h-p).map(p=>u[p]).map(p=>{const h=Zg({participantResults:a,disableHeadToHead:t,participantIds:p,matchUpFormat:n,tallyPolicy:r,matchUps:o});return l.push(h.report),h.order}).flat(1/0)),{order:f,report:l}}function Zg({participantResults:t,disableHeadToHead:e,participantIds:n,matchUpFormat:r,tallyPolicy:s,matchUps:i}){if((n==null?void 0:n.length)===1)return{order:[{resolved:!0,participantId:n[0]}]};if((n==null?void 0:n.length)===2&&(!(s!=null&&s.headToHead)||!s.headToHead.disabled&&!e)){const f=GC({participantIds:n,participantResults:t});if(f)return{order:[f],headToHeadWinner:f[0].participantId}}const o=(s==null?void 0:s.tallyDirectives)||$C,c=[],a=[];let u;const l=o.filter(f=>{const p=!(Me(f.maxParticipants)&&(n==null?void 0:n.length)>f.maxParticipants);return p||c.push(f),p});return c.length&&a.push({excludedDirectives:c,participantIds:n}),l.every(({attribute:f,reversed:p,idsFilter:h,disableHeadToHead:d})=>(u=jC({disableHeadToHead:d,participantIds:n,matchUpFormat:r,tallyPolicy:s,attribute:f,idsFilter:h,matchUps:i,reversed:p}),a.push(u.report),!u.order)),u.order?{order:u.order,report:a}:{order:n==null?void 0:n.map(f=>({participantId:f})),report:a}}function GC({participantIds:t,participantResults:e}){if(t){if(e[t[0]].victories.includes(t[1]))return t.map(n=>({resolved:!0,participantId:n}));if(e[t[1]].victories.includes(t[0]))return t.reverse().map(n=>({resolved:!0,participantId:n}))}}const Xg="voluntaryConsolation",Hs="competitiveBands",tI="roundRobinTally",vs="positionActions",Jn="matchUpActions",df="rankingPoints",Lu="roundNaming",oa="participant",Ru="progression",ff="scheduling",WC="avoidance",HC="display",Xo="scoring",tc="seeding",Bu="feedIn",pf="draws";function hf({policyDefinitions:t,generateReport:e,matchUpFormat:n,matchUps:r=[],subOrderMap:s,perPlayer:i}){if(!cr(r))return{error:$s};if(r.reduce((T,{structureId:E})=>T.includes(E)?T:T.concat(E),[]).length!==1)return{error:tt,info:"Maximum one structureId"};const c=r.filter(T=>T&&T.matchUpStatus!==re),a=c.length&&Vt(c.map(({drawPositions:T})=>T).flat()).length,u=c.filter(T=>Qo({matchUp:T})).length===c.length;u||(i=0);const l=r.every(({matchUpType:T,tieMatchUps:E})=>T===Jt&&E.every(y=>Qo({matchUp:y}))),f=t==null?void 0:t[tI],p=r.filter(T=>Qo({matchUp:T})||T.matchUpType===Jt),{participantResults:h}=Hg({matchUps:p,matchUpFormat:n,tallyPolicy:f,perPlayer:i});let d,m;const{groupOrder:g,report:I}=Qg({matchUps:p,participantResults:h,participantsCount:a,matchUpFormat:n,tallyPolicy:f,subOrderMap:s});if(u&&g)d=I,m=g,g.forEach(T=>{const{participantId:E,groupOrder:y,rankOrder:b,subOrder:N,ties:A,GEMscore:C}=T,v=h[E];Object.assign(v,{groupOrder:y,rankOrder:b,GEMscore:C,subOrder:N,ties:A})});else{const{groupOrder:T,report:E}=Qg({requireCompletion:!1,participantResults:h,participantsCount:a,matchUpFormat:n,tallyPolicy:f,subOrderMap:s,matchUps:r});d=E,m=T,T&&T.forEach(y=>{const{participantId:b,groupOrder:N,GEMscore:A}=y,C=h[b];Object.assign(C,{provisionalOrder:N,GEMscore:A})})}const S={completedTieMatchUps:l,readableReport:"",participantResults:h,bracketComplete:u,order:[],report:d};if((u||l)&&(S.order=m),e||ze({tally:!0})){const T=xC({matchUps:r,report:d,order:m});ze({tally:!0})&&console.log(T),S.readableReport=T}return S}function qC({collectionDefinition:t,groupValueNumbers:e,groupValueGroups:n,sideTieValues:r,tieMatchUps:s}){const i=s.filter(S=>S.collectionId===t.collectionId),o=[0,0];let c=[0,0];const a=i.every(S=>We.includes(S.matchUpStatus)),{collectionValueProfiles:u,collectionGroupNumber:l,collectionValue:f,matchUpValue:p,winCriteria:h,scoreValue:d,setValue:m}=t,g=l&&e.includes(l),I=[0,0];if(i.forEach(S=>{S.winningSide&&(I[S.winningSide-1]+=1)}),p?i.forEach(S=>{S.winningSide&&(o[S.winningSide-1]+=p)}):m?i.forEach(S=>{var T,E;(E=(T=S.score)==null?void 0:T.sets)==null||E.forEach(y=>{y.winningSide&&(o[y.winningSide-1]+=m)})}):d?i.forEach(S=>{var T,E;(E=(T=S.score)==null?void 0:T.sets)==null||E.forEach(y=>{const{side1TiebreakScore:b=0,side2TiebreakScore:N=0,side1Score:A=0,side2Score:C=0}=y;(S.matchUpStatus===De||S.winningSide||y.winningSide)&&(A||C?(o[0]+=A,o[1]+=C):(b||N)&&y.winningSide&&(o[y.winningSide-1]+=1))})}):Array.isArray(u)&&i.forEach(S=>{if(S.winningSide){const T=S.collectionPosition,E=YC({collectionDefinition:t,collectionPosition:T});o[S.winningSide-1]+=E}}),f){let S;if(h!=null&&h.aggregateValue)a&&((p||m||d)&&o[0]!==o[1]?S=o[0]>o[1]?1:2:I[0]!==I[1]&&(S=I[0]>I[1]?1:2));else if(h!=null&&h.valueGoal)S=o.reduce((T,E,y)=>E>=h.valueGoal?y+1:T,0);else{const T=Math.floor(t.matchUpCount/2)+1;S=I.reduce((E,y,b)=>y>=T?b+1:E,0)}S&&(g?n[l].values[S-1]+=f:c[S-1]+=f)}else g?(n[l].values[0]+=o[0]||0,n[l].values[1]+=o[1]||0):c=o;g?(n[l].sideWins[0]+=I[0]||0,n[l].sideWins[1]+=I[1]||0,n[l].allGroupMatchUpsCompleted=n[l].allGroupMatchUpsCompleted&&a,n[l].matchUpsCount+=i.length):c.forEach((S,T)=>r[T]+=S)}function YC({collectionDefinition:t,collectionPosition:e}){const n=t.collectionValueProfiles||[],r=n==null?void 0:n.find(s=>s.collectionPosition===e);return r==null?void 0:r.matchUpValue}const zi="appliedPolicies",xu="positionActions",eI="context",$u="delegatedOutcome",Er="disabled",Vu="disableLinks",ec="disableAutoCalc",ju="drawDeletions",zC="drawProfile",Gu="entryProfile",KC="eventProfile",JC="factory",ar="flightProfile",mf="groupingAttribute",Wr="lineUps",Ki="linkedTournamentsIds",Wu="matchUpHistory",gf="participantRepresentatives",nc="personRequests",nI="rankingPoints",Hr="roundTarget",Ji="scheduleLimits",qr="scheduleTiming",qs="schedulingProfile",QC="statusDetail",rc="subOrder",Ys="tally",Qi="tieFormatModification",rI={APPLIED_POLICIES:zi,AUDIT_POSITION_ACTIONS:xu,CONTEXT:eI,DELEGATED_OUTCOME:$u,DISABLED:Er,DISABLE_LINKS:Vu,DISABLE_AUTO_CALC:ec,DRAW_DELETIONS:ju,DRAW_PROFILE:zC,ENTRY_PROFILE:Gu,EVENT_PROFILE:KC,FLIGHT_PROFILE:ar,GROUPING_ATTRIBUTE:mf,LINEUPS:Wr,LINKED_TOURNAMENTS:Ki,MATCHUP_HISTORY:Wu,PARTICIPANT_REPRESENTATIVES:gf,PERSON_REQUESTS:nc,RANKING_POINTS:nI,ROUND_TARGET:Hr,SCHEDULE_LIMITS:Ji,SCHEDULE_TIMING:qr,SCHEDULING_PROFILE:qs,STATUS_DETAIL:QC,SUB_ORDER:rc,TALLY:Ys,TIE_FORMAT_MODIFICATIONS:Qi,FACTORY:JC},sI=[$u,Er,Vu,ar,Wr,Wu,gf,nc,Hr,Ji,qr,qs,rc,Ys];function ge({onlySpecifiedPolicyTypes:t=!1,policyTypes:e=[],tournamentRecord:n,drawDefinition:r,structure:s,event:i}){if(!Array.isArray(e))return{error:tg};const o={};return n&&c(n),i&&c(i),r&&c(r),s&&c(s),{appliedPolicies:o,...$};function c(a){var f;const u=a==null?void 0:a.extensions,l=(f=u==null?void 0:u.find(p=>p.name===zi))==null?void 0:f.value;if(l)for(const p of Object.keys(l))(t?e.includes(p):!e.length||e.includes(p))&&(o[p]=pt(l[p],!1,!0))}}function Zi({policyTypes:t=[],tournamentRecord:e,drawDefinition:n,structure:r,event:s}){if(!Array.isArray(t))return{error:tg};const{appliedPolicies:i}=ge({tournamentRecord:e,drawDefinition:n,structure:r,event:s}),o={};for(const c of t){const a=i==null?void 0:i[c];a&&(o[c]=a)}return Object.keys(o).length?{policyDefinitions:o}:{error:jd}}const iI="WALKOVER",oI="RETIRED",If="COMPETITIVE",ca="ROUTINE",aa="DECISIVE",ua="winRatio",Sf={[Hs]:{policyName:"Competitive Bands Default",profileBands:{[aa]:20,[ca]:50}}};function Cs({policyDefinitions:t,tournamentRecord:e,contextProfile:n,drawDefinition:r,event:s}){const i={policies:{}};if(!n)return i;const o=Zi({tournamentRecord:e,drawDefinition:r,event:s}).policyDefinitions;if(n.withCompetitiveness){const c=(t==null?void 0:t[Hs])||(o==null?void 0:o[Hs])||Sf[Hs];i.policies[Hs]=c}return i}function cI({matchUps:t,matchUpId:e}){return{matchUp:(t||[]).find(r=>r.matchUpId===e)}}function ZC({matchUps:t}){const e=t.reduce((r,s)=>!s.collectionPosition||r.includes(s.collectionPosition)?r:r.concat(s.collectionPosition),[]).map(r=>({[r]:t.filter(s=>s.collectionPosition===r)}));return{collectionPositionMatchUps:Object.assign({},...e)}}const XC=(t,e)=>(t||0)+(e||0);function aI(t,e){const n=Array.isArray(t)?t[0]:t;return isNaN(n)&&iI||n<=e[aa]&&aa||n<=e[ca]&&ca||If}function uI({score:t}){const e=(t==null?void 0:t.sets)||[],n=e.reduce((s,i)=>(s[0]+=i.side1Score||0,s[1]+=i.side2Score||0,s),[0,0]),r=e.reduce((s,i)=>(s[0]+=i.side1TiebreakScore||0,s[1]+=i.side2TiebreakScore||0,s),[0,0]);return r.reduce(XC)&&(n[r[0]>r[1]?0:1]+=1),{sets:e,games:n,score:t}}function tP(t){const e=Math.min(...t.games),n=Math.max(...t.games);return Math.round(e/n*100)}function lI(t){return t.map(tP).sort().map(e=>parseFloat(e.toFixed(2)))}function Xi({tournamentRecord:t,drawDefinition:e,policyType:n,structure:r,event:s}){if(!t)return{error:et};const{appliedPolicies:i}=ge({tournamentRecord:t,drawDefinition:e,structure:r,event:s});return i!=null&&i[n]?{policy:i[n]}:{error:jd}}function dI({profileBands:t,tournamentRecord:e,matchUp:n}){if(!n)return{error:Rn};const{score:r,winningSide:s}=n;if(!s)return{error:tt};const i=!t&&e&&Xi({policyType:Hs,tournamentRecord:e}).policy,o=t||(i==null?void 0:i.profileBands)||Sf[Hs].profileBands,c=uI({score:r}),a=lI([c]),u=aI(a,o),l=Array.isArray(a)?a[0]:a;return{...$,competitiveness:u,pctSpread:l}}function la(t){const{matchUpAverageTimes:e,matchUpFormat:n}=t||{},r=(e==null?void 0:e.map(({matchUpFormatCodes:c})=>c==null?void 0:c.filter(a=>a===n)).flat().filter(Boolean).sort((c,a)=>((c==null?void 0:c.length)||0)-((a==null?void 0:a.length)||0)))||[],i=r.includes(n)?n:r[0],o=e==null?void 0:e.find(({matchUpFormatCodes:c,averageTimes:a})=>(c==null?void 0:c.find(u=>i===u))&&a);return o==null?void 0:o.averageTimes}function da(t){var s;const{matchUpRecoveryTimes:e,averageMinutes:n,matchUpFormat:r}=t||{};return(s=e==null?void 0:e.find(({matchUpFormatCodes:i,averageTimes:o,recoveryTimes:c})=>{if(o&&n){const{greaterThan:a=0,lessThan:u=360}=o;if(n>a&&n<u)return!0}return(i==null?void 0:i.find(a=>a===r))&&c}))==null?void 0:s.recoveryTimes}function fI({timesBlockArray:t,categoryName:e,categoryType:n}){return t.filter(r=>Array.isArray(r)).map(r=>r.sort((s,i)=>{var o,c;return(((o=i.categoryNames)==null?void 0:o.length)||0)-(((c=s.categoryNames)==null?void 0:c.length)||0)}).find(({categoryTypes:s,categoryNames:i})=>!(i!=null&&i.length)&&!(s!=null&&s.length)||(i==null?void 0:i.includes(e))||(s==null?void 0:s.includes(n)))).find(Boolean)}function eP({tournamentScheduling:t,eventScheduling:e,averageMinutes:n,defaultTiming:r,matchUpFormat:s,categoryName:i,categoryType:o,policy:c}){var p;const a=(e==null?void 0:e.matchUpRecoveryTimes)&&da({...e,averageMinutes:n,matchUpFormat:s}),u=(t==null?void 0:t.matchUpRecoveryTimes)&&da({...t,averageMinutes:n,matchUpFormat:s}),l=(c==null?void 0:c.matchUpRecoveryTimes)&&da({...c,averageMinutes:n,matchUpFormat:s}),f=[a,u,l,(p=c==null?void 0:c.defaultTimes)==null?void 0:p.recoveryTimes,r==null?void 0:r.recoveryTimes];return fI({categoryName:i,categoryType:o,timesBlockArray:f})}function nP({matchUpFormat:t,categoryName:e,categoryType:n,defaultTiming:r,tournamentScheduling:s,eventScheduling:i,policy:o}){var f;const c=(i==null?void 0:i.matchUpAverageTimes)&&la({...i,matchUpFormat:t}),a=(s==null?void 0:s.matchUpAverageTimes)&&la({...s,matchUpFormat:t}),u=(o==null?void 0:o.matchUpAverageTimes)&&la({...o,matchUpFormat:t}),l=[c,a,u,(f=o==null?void 0:o.defaultTimes)==null?void 0:f.averageTimes,r==null?void 0:r.averageTimes];return fI({categoryName:e,categoryType:n,timesBlockArray:l})}const pI="DYNAMIC",Ii="RANKING",to="RATING",eo="SCALE",br="SEEDING";function sc({participant:t}){var r;const e=(r=t.timeItems)==null?void 0:r.filter(({itemType:s})=>(s==null?void 0:s.startsWith(eo))&&[Ii,to,br].includes(s.split(".")[1])),n={ratings:{},rankings:{},seedings:{}};if(e!=null&&e.length){const s=o=>e.filter(c=>(c==null?void 0:c.itemType)===o).sort((c,a)=>new Date(c.createdAt||void 0).getTime()-new Date(a.createdAt||void 0).getTime()).pop(),i=Vt(e.map(({itemType:o})=>o));for(const o of i){const c=s(o);if(c){const[,a,u,l,f]=c.itemType.split("."),p=f?`${l}.${f}`:l,h=a===br&&"seedings"||a===Ii&&"rankings"||"ratings";n[h][u]||(n[h][u]=[]),n[h][u].push({scaleValue:c.itemValue,scaleDate:c.itemDate,scaleName:p})}}}return{...$,...n}}function Ps({tournamentParticipants:t=[],policyDefinitions:e={},contextProfile:n,participantId:r,internalUse:s,personId:i}){const o=t.find(a=>r&&a.participantId===r||i&&a.person&&a.person.personId===i),c=pt(o,!1,s);if(c){const a=e==null?void 0:e[oa];if(n!=null&&n.withScaleValues){const{ratings:u,rankings:l}=sc({participant:c});c.rankings=l,c.ratings=u}if(a!=null&&a.participant)return Fu({template:a.participant,source:c})}return c}function zs({tournamentRecord:t,participantId:e}){return{participant:(t.participants||[]).reduce((s,i)=>i.participantId===e?i:s,void 0)}}function rP({tournamentRecord:t,policyDefinitions:e,convertExtensions:n,participantId:r,personId:s}){if(!t)return{error:et};if(typeof r!="string"&&typeof s!="string")return{error:Tt};const i=t.participants||[],o=Ps({tournamentParticipants:i,policyDefinitions:e,participantId:r,personId:s});return{participant:pt(o,n,!0)}}const fa="extensionQueries";function Ke({element:t,name:e}){if(!t||!e)return G({result:{error:Tt},stack:fa});if(!Array.isArray(t.extensions))return{info:an};const n=t.extensions.find(s=>(s==null?void 0:s.name)===e);return{extension:n,info:n?void 0:an}}function Bn({tournamentRecord:t,name:e}){return Ke({element:t,name:e})}function Us({event:t,name:e}){return t?Ke({element:t,name:e}):G({result:{error:Wt},stack:fa})}function Hu({drawDefinition:t,name:e}){return t?Ke({element:t,name:e}):G({result:{error:lt},stack:fa})}function sP({tournamentRecord:t,participantId:e,name:n}){if(!t)return G({result:{error:et},stack:fa});if(!e)return G({result:{error:Ce},stack:fa});const{participant:r}=zs({tournamentRecord:t,participantId:e});return Ke({element:r,name:n})}function pa({tournamentRecord:t,categoryName:e,categoryType:n,event:r}){var l,f,p,h;e=e??((l=r==null?void 0:r.category)==null?void 0:l.categoryName)??((f=r==null?void 0:r.category)==null?void 0:f.ageCategoryCode),n=n??((p=r==null?void 0:r.category)==null?void 0:p.categoryType)??((h=r==null?void 0:r.category)==null?void 0:h.subType);const{policy:s}=Xi({policyType:ff,tournamentRecord:t,event:r}),i=t?Bn({name:qr,tournamentRecord:t}).extension:void 0,o=i==null?void 0:i.value,c=r&&Us({name:qr,event:r}).extension,a=c==null?void 0:c.value;return{scheduleTiming:{tournamentScheduling:o,eventScheduling:a,categoryName:e,categoryType:n,policy:s}}}const iP="DOUBLES_SINGLES",oP="SINGLES_DOUBLES",Nr="total",hI="participantConflict",Si="matchUpConflict",cP="ISSUE_IDS",no="CONFLICT",ro="WARNING",mI="ERROR",gI="ISSUE",Tf="STATE";function yf({defaultAverageMinutes:t=90,defaultRecoveryMinutes:e=0,tournamentRecord:n,matchUpFormat:r,categoryName:s,categoryType:i,eventType:o,event:c}){if(!n)return{error:et};o=o||(c==null?void 0:c.eventType)||_n.Singles;const a={averageTimes:[{minutes:{default:t}}],recoveryTimes:[{minutes:{default:e}}]},{scheduleTiming:u}=pa({tournamentRecord:n,categoryName:s,categoryType:i,event:c}),l={...u,matchUpFormat:r,categoryType:i,defaultTiming:a};return qu({eventType:o,timingDetails:l})}function qu({timingDetails:t,eventType:e}){const n=nP(t),r=Object.keys((n==null?void 0:n.minutes)||{}),s=(n==null?void 0:n.minutes)&&((r==null?void 0:r.includes(e))&&n.minutes[e]||n.minutes.default),i=eP({...t,averageMinutes:s}),o=Object.keys((i==null?void 0:i.minutes)||{}),c=(i==null?void 0:i.minutes)&&((o==null?void 0:o.includes(e))&&i.minutes[e]||i.minutes.default),a=e===Oe?oP:iP,u=(i==null?void 0:i.minutes)&&((o==null?void 0:o.includes(a))&&i.minutes[a]||c);return{averageMinutes:s,recoveryMinutes:c,typeChangeRecoveryMinutes:u}}function ur({requiredAttributes:t=["name","value"],extension:e}){if(!e||typeof e!="object"||typeof e.name!="string")return!1;const n=Object.keys(e);return t.filter(r=>n.includes(r)).length===t.length}function be({event:t,eventId:e}){var i;if(!t)return{error:Wt};const n=Us({name:ar,event:t}),r=n==null?void 0:n.extension,s=e?pt(r==null?void 0:r.value,!1,!0):r==null?void 0:r.value;return e&&((i=t.drawDefinitions)==null||i.forEach(o=>{var c;(c=s==null?void 0:s.flights)==null||c.forEach(a=>{a.drawId===o.drawId&&Object.assign(a,{drawDefinition:o})})})),{flightProfile:s}}function aP({tournamentRecord:t,drawDefinition:e,event:n,context:r}){var o;if(!t)return{error:et};if(!n)return{error:Wt};const s=pt(n);r&&Object.assign(s,r);const i=e&&((o=s.drawDefinitions)==null?void 0:o.find(({drawId:c})=>e.drawId===c));return bt({event:s,drawDefinition:i})}function uP({tournamentRecord:t,context:e,inContext:n}){if(!t)return{error:et};const{tournamentId:r}=t;return{events:(t.events||[]).map(i=>{const o=pt(i);return e&&Object.assign(o,e),n&&Object.assign(o,{tournamentId:r}),o})}}function Je({tournamentRecord:t,eventId:e,drawId:n}){const r="findEvent";if(!t)return{event:void 0,drawDefinition:void 0,...G({result:{error:et},stack:r})};const s=(t==null?void 0:t.events)||[];if(n){let i;const o=s.find(c=>{var l;const u=((c==null?void 0:c.drawDefinitions)||[]).find(f=>f.drawId===n);if(u)i=u;else{const{flightProfile:f}=be({event:c}),p=(l=f==null?void 0:f.flights)==null?void 0:l.find(h=>h.drawId===n);if(p)return{drawId:n,entries:p.drawEntries,drawName:p.drawName}}return u});if(o)return{event:o,drawDefinition:i}}if(e){const i=s.find(o=>o.eventId===e);return i?{event:i,drawDefinition:void 0}:{event:void 0,drawDefinition:void 0,...G({result:{error:wn},stack:r})}}return{event:void 0,drawDefinition:void 0,...G({result:{error:rr},context:{drawId:n,eventId:e},stack:r})}}function Ks({tournamentRecord:t,drawId:e}){if(!t)return{error:et};if(!e)return{error:Hn};const n=(t.events||[]).reduce((r,s)=>{const i=(s.drawDefinitions||[]).reduce((o,c)=>c.drawId===e?c:o,void 0);return i&&i.drawId===e?{event:s,drawDefinition:i}:r},void 0);return n?{...n,SUCCESS:$}:G({result:{error:rr},stack:"getDrawDefinition"})}function ae(t){if(typeof t!="object")return{error:Tt};const e="addExtension";if(!(t!=null&&t.element))return G({result:{error:Tt},stack:e});if(typeof t.element!="object")return G({result:{error:tt},stack:e});if(!ur({extension:t.extension}))return G({result:{error:tt,info:"invalid extension"},stack:e});if(t.element.extensions||(t.element.extensions=[]),t.creationTime!==void 0?t.creationTime:!0){const s=new Date().toISOString();Object.assign(t.extension,{createdAt:s})}const r=t.element.extensions.find(({name:s})=>s===t.extension.name);return r?r.value=t.extension.value:t.extension.value&&t.element.extensions.push(t.extension),{...$}}const Ef="element required",bf="missing name";function Ar(t){return!t||typeof t!="object"?{error:Tt}:t!=null&&t.element?typeof(t==null?void 0:t.element)!="object"?{error:tt}:t!=null&&t.name?t!=null&&t.element.extensions?(t.element.extensions=t.element.extensions.filter(e=>(e==null?void 0:e.name)!==t.name),{...$}):{...$,info:an}:{error:Tt,info:bf}:{error:Tt,info:Ef}}function Ti(t){return!t||typeof t!="object"?{error:Tt}:t.tournamentRecord?ae({creationTime:t.creationTime,element:t.tournamentRecord,extension:t.extension}):{error:et}}function Nf(t){return!t||typeof t!="object"?{error:Tt}:t.drawDefinition?ae({creationTime:t.creationTime,element:t.drawDefinition,extension:t.extension}):{error:rr}}function Yr(t){return!t||typeof t!="object"?{error:Tt}:t.event?ae({creationTime:t.creationTime,extension:t.extension,element:t.event}):{error:Wt}}function lP(t){var r;if(!t||typeof t!="object")return{error:Tt};if(!t.participantId)return{error:Ce};const e=((r=t.tournamentRecord)==null?void 0:r.participants)||[],n=Ps({participantId:t.participantId,tournamentParticipants:e});return n?ae({creationTime:t.creationTime,extension:t.extension,element:n}):{error:_e}}function Af(t){return!t||typeof t!="object"?{error:Tt}:t.tournamentRecord?Ar({element:t.tournamentRecord,name:t.name}):{error:et}}function dP(t){return!t||typeof t!="object"?{error:Tt}:t.drawDefinition?Ar({element:t.drawDefinition,name:t.name}):{error:rr}}function Yu(t){return!t||typeof t!="object"?{error:Tt}:t!=null&&t.event?Ar({element:t.event,name:t.name}):{error:wn}}function fP(t){var r;if(!t||typeof t!="object")return{error:Tt};if(!t.participantId)return{error:Ce};const e=((r=t.tournamentRecord)==null?void 0:r.participants)||[],n=Ps({participantId:t.participantId,tournamentParticipants:e});return n?Ar({element:n,name:t.name}):{error:_e}}function vf({tournamentRecords:t,extension:e}){if(!ur({extension:e}))return{error:tt};const n="addExtension";for(const r of Object.values(t)){const s=Ti({tournamentRecord:r,extension:e});if(s.error)return G({result:s,stack:n})}return{...$}}function zu({tournamentRecords:t,name:e}){if(!e)return{error:Tt,info:bf};let n;return Object.keys(t).find(s=>{const i=t[s],{extension:o}=Bn({tournamentRecord:i,name:e});return n=o,!!o})?{extension:n}:{error:an}}function Ku({tournamentRecords:t,name:e}){if(!e)return{error:Tt,info:bf};let n=0;for(const r of Object.keys(t)){const s=t[r],i=Af({tournamentRecord:s,name:e});if(i.error)return G({result:i,stack:"removeExtension"});i.info!==an&&n++}return{...$,removed:n}}function pP({tournamentRecords:t,eventId:e,extension:n}){if(typeof e!="string")return{error:Wt};if(!ur({extension:n}))return{error:tt};for(const r of Object.values(t)){const{event:s}=Je({tournamentRecord:r,eventId:e});if(s)return Yr({event:s,extension:n})}return{error:wn}}function Cf({tournamentRecords:t}){return typeof t!="object"||!Object.keys(t).length?{error:Gt}:{linkedTournamentIds:Object.assign({},...Object.keys(t).map(n=>{var c;const r=t[n],s=r==null?void 0:r.tournamentId,{extension:i}=Bn({tournamentRecord:r,name:Ki}),o=(((c=i==null?void 0:i.value)==null?void 0:c.tournamentIds)||[]).filter(a=>a!==s);return{[n]:o}}))}}function hP({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:Gt};const e=II(t),{tournamentIds:n}=e;return(n==null?void 0:n.length)>1?vf({tournamentRecords:t,extension:{name:Ki,value:{tournamentIds:n}}}):{...$}}function mP({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:Gt};const e=Ku({name:Ki,tournamentRecords:t});return G({result:e,stack:"unlinkTournaments"})}function gP({tournamentRecords:t,tournamentId:e}){if(typeof t!="object")return{error:tt};if(!e)return{error:is};const n=II(t),{tournamentIds:r}=n;if(!r.includes(e))return{error:is};let s;return r.every(i=>{var f;const o=t[i],{extension:c}=Bn({tournamentRecord:o,name:Ki});if(!c)return!0;const a=((f=c==null?void 0:c.value)==null?void 0:f.tournamentIds)||[];if(!(a!=null&&a.length)||a.length===1&&a.includes(e)||i===e){const p=Af({name:Ki,tournamentRecord:o});return p.error&&(s=p.error),p.success}const u=a.filter(p=>p!==e);c.value={tournamentIds:u};const l=Ti({tournamentRecord:o,extension:c});return l.error&&(s=l.error),l.success}),s?{error:s}:{...$}}function II(t){return{tournamentIds:Object.keys(t).filter(Boolean)}}function SI({extension:t,dates:e=[]}){if(!t)return!1;if(typeof t.value=="boolean"&&t.value)return!0;if(typeof t.value=="object"&&Array.isArray(t.value.dates))return e.length?!!e.filter(r=>t.value.dates.includes(r)).length:!0}function xn({element:t,name:e}){const n="findExtension";if(!t||!e)return G({result:{error:Tt},stack:n});if(!Array.isArray(t.extensions))return G({result:{error:an},stack:n});const r=t.extensions.find(s=>(s==null?void 0:s.name)===e);return r?{extension:r}:G({result:{error:an},stack:n})}function TI({convertExtensions:t,ignoreDisabled:e,venue:n,court:r}){const s={...pt(r,t,!0),venueId:n.venueId},{extension:i}=xn({name:Er,element:r});if(e&&i){const o=typeof i.value=="object"&&i.value.dates||[],c=i.value===!0?[]:s.dateAvailability.map(a=>{const u=a.date;if(!(!u||o.includes(u)))return a}).filter(Boolean);s.dateAvailability=c}return{inContextCourt:s}}const yI="addDrawDefinition",Pf="addMatchUps",yi="addParticipants",EI="addScaleItems",bI="addVenue",ha="audit",NI="deleteParticipants",AI="deleteVenue",vI="deletedDrawIds",CI="deletedMatchUpIds",PI="modifyDrawDefinition",IP="modifyDrawEntries",SP="modifyEventEntries",UI="modifyMatchUp",nn="modifyParticipants",OI="modifyPositionAssignments",MI="modifySeedAssignments",TP="modifyTournamentDetail",so="modifyVenue",DI="mutations",yP="publishEvent",EP="publishEventSeeding",bP="publishOrderOfPlay",wI="unPublishEvent",kI="unPublishEventSeeding",_I="unPublishOrderOfPlay",Uf="updateInContextMatchUp";function ma({tournamentRecord:t,disableNotice:e,context:n,venue:r}){return t?r?(t.venues||(t.venues=[]),r.venueId||(r.venueId=Yt()),t.venues.reduce((i,o)=>i||o.venueId===r.venueId,void 0)?{error:bv}:(n&&ae({element:r,extension:{value:n,name:eI}}),t.venues.push(r),e||Ht({payload:{venue:r,tournamentId:t.tournamentId},topic:bI}),{...$,venue:pt(r)})):{error:Tt,info:"missing venue"}:{error:et}}function Of({convertExtensions:t,tournamentRecord:e,ignoreDisabled:n,dates:r}){if(!e)return{error:et};const s=pt(e.venues??[],t).filter(o=>{if(!n)return o;const{extension:c}=xn({name:Er,element:o});return!(c!=null&&c.value)&&o}).filter(Boolean),i=s.reduce((o,c)=>{const a=((c==null?void 0:c.courts)||[]).filter(u=>{if(!n&&!(r!=null&&r.length))return u;const{extension:l}=xn({name:Er,element:u});return SI({extension:l,dates:r})}).filter(Boolean).map(u=>{const{inContextCourt:l}=TI({convertExtensions:t,ignoreDisabled:n,venue:c,court:u});return l});return a.length?o.concat(a):o},[]);return{venues:s,courts:i}}function Js({tournamentRecords:t,tournamentRecord:e,venueId:n}){if(!e)return{error:et};if(!n)return{error:Vs};const s=(e.venues??[]).reduce((i,o)=>o.venueId===n?o:i,void 0);if(!s&&t){const o=(Cf({tournamentRecords:t}).linkedTournamentIds||[])[e.tournamentId];for(const c of o){const a=t[c],u=Js({tournamentRecord:a,venueId:n});if(u.success&&u.venue)return ma({tournamentRecord:e,venue:u.venue}),{...$,venue:s}}}return s?{...$,venue:s}:{error:di}}function NP({convertExtensions:t,...e}){const{tournamentRecords:n,tournamentRecord:r,venueId:s}=e,i=Js({tournamentRecords:n,tournamentRecord:r,venueId:s});return pt(i,t,!0)}function io({tournamentRecords:t,tournamentRecord:e,courtId:n}){if(!e)return{error:et};if(!n)return{error:Ho};const r="findCourt";let s,i;if((e.venues??[]).forEach(o=>{(o.courts??[]).forEach(c=>{c.courtId===n&&(s=c,i=o)})}),s)return{...$,court:s,venue:i};if(t){const c=(Cf({tournamentRecords:t}).linkedTournamentIds||[])[e.tournamentId];for(const a of c){const u=t[a],l=io({tournamentRecord:u,courtId:n});if(l.success)return l.venue&&ma({tournamentRecord:e,venue:l.venue}),{...$,court:s,venue:i}}}return G({result:{error:Kd},stack:r})}function AP(t){return pt(io(t),!1,!0)}function vP({tournamentRecord:t,venueId:e,venueIds:n}){return t?{courts:(t.venues||[]).filter(s=>e?s.venueId===e:n?n.includes(s.venueId):!0).map(s=>{const{venueId:i}=s,o=pt(s.courts||[]);return o.forEach(c=>Object.assign(c,{venueId:i})),o}).flat()}:{error:et}}function FI({tournamentRecord:t,internalUse:e,courtId:n}){if(!t)return{error:et};if(!n)return{error:Ho};const r=io({tournamentRecord:t,courtId:n});if(r.error)return r;const s=r.court&&(({altitude:i,courtId:o,courtName:c,courtDimensions:a,latitude:u,longitude:l,surfaceCategory:f,surfaceType:p,surfacedDate:h,pace:d,notes:m})=>({altitude:i,courtId:o,courtName:c,courtDimensions:a,latitude:u,longitude:l,surfaceCategory:f,surfaceType:p,surfacedDate:h,pace:d,notes:m}))(r.court);return{...$,courtInfo:pt(s,!1,e)}}function Ju({tournamentRecord:t,venueId:e}){var c;if(!t)return{error:et};if(!e)return{error:Vs};const n=Js({tournamentRecord:t,venueId:e});if(n.error)return n;const s=(((c=n.venue)==null?void 0:c.courts)??[]).map(a=>(({courtInfo:u})=>({...u}))(FI({courtId:a.courtId,internalUse:!0,tournamentRecord:t}))),i=n.venue&&(({venueId:a,venueName:u,venueAbbreviation:l})=>({venueAbbreviation:l,venueName:u,venueId:a}))(n.venue),o=i&&{...i,courtsInfo:s};return{...$,venueData:pt(o,!1,!0)}}const Mf="CHECK_IN",Df="CHECK_OUT",ga="SCHEDULE.ASSIGNMENT.VENUE",Qs="SCHEDULE.ALLOCATION.COURTS",oo="SCHEDULE.ASSIGNMENT.COURT",LI="SCHEDULE.COURT.ORDER",Ia="SCHEDULE.DATE",CP="SCHEDULE.ASSIGN.OFFICIAL",Sa="SCHEDULE.TIME.SCHEDULED",zr="SCHEDULE.TIME.START",Zs="SCHEDULE.TIME.STOP",Os="SCHEDULE.TIME.RESUME",Xs="SCHEDULE.TIME.END",RI="SCHEDULE.TIME.MODIFIERS",BI=["TO_BE_ANNOUNCED","NEXT_AVAILABLE","FOLLOWED_BY","AFTER_REST","RAIN_DELAY"],PP="SCALE",UP="RATING",OP="RANKING",xI="SEEDING",Qn="PUBLISH",Kr="PUBLIC",Zn="STATUS";function Qu(t){return t.createdAt?new Date(t.createdAt).getTime():0}function Ei({visibilityThreshold:t,timeItems:e,itemType:n}){const r=e.filter(i=>i&&i.itemType===n&&(!t||Qu(i)<new Date(t).getTime())).sort((i,o)=>Qu(i)-Qu(o)).pop(),s=r&&Qu(r);return{itemValue:r==null?void 0:r.itemValue,timeStamp:s}}function wf({visibilityThreshold:t,timeStamp:e,schedule:n,matchUp:r}){const{itemValue:s,timeStamp:i}=Ei({timeItems:(r==null?void 0:r.timeItems)||[],itemType:Sa,visibilityThreshold:t});return!n||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{scheduledTime:s}:n}function bi({visibilityThreshold:t,timeStamp:e,schedule:n,matchUp:r}){const{itemValue:s,timeStamp:i}=Ei({timeItems:(r==null?void 0:r.timeItems)||[],itemType:Ia,visibilityThreshold:t});return!n||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{scheduledDate:s}:n}function $I({visibilityThreshold:t,timeStamp:e,schedule:n,matchUp:r}){const{itemValue:s,timeStamp:i}=Ei({timeItems:(r==null?void 0:r.timeItems)||[],itemType:Qs,visibilityThreshold:t});return!n||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{allocatedCourts:pt(s,!1,!0)}:n}function VI({visibilityThreshold:t,timeStamp:e,schedule:n,matchUp:r}){const{itemValue:s,timeStamp:i}=Ei({timeItems:(r==null?void 0:r.timeItems)||[],itemType:oo,visibilityThreshold:t});return!n||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{courtId:s}:n}function jI({visibilityThreshold:t,timeStamp:e,schedule:n,matchUp:r}){const{itemValue:s,timeStamp:i}=Ei({timeItems:(r==null?void 0:r.timeItems)||[],itemType:ga,visibilityThreshold:t});return!n||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{venueId:s}:n}function kf({visibilityThreshold:t,timeStamp:e,schedule:n,matchUp:r}){const{itemValue:s,timeStamp:i}=Ei({timeItems:(r==null?void 0:r.timeItems)||[],itemType:RI,visibilityThreshold:t});return!n||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{timeModifiers:s}:n}function co(t){if(wg.test(t)){const e=tf();return new Date(`${e}T${t}`)}else return new Date(t)}function GI({matchUp:t}){if(!t)return{error:Rn};if(!t.timeItems)return{error:Tg};const e=t.timeItems.filter(r=>[zr,Zs,Os,Xs].includes(r==null?void 0:r.itemType)).sort((r,s)=>co(r.itemValue).getTime()-co(s.itemValue).getTime()),n=e.reduce((r,s)=>{var u,l;let i;const o=(u=s==null?void 0:s.itemType)==null?void 0:u.split("."),a=`SCHEDULE.TIME.${((l=s==null?void 0:s.itemType)==null?void 0:l.startsWith("SCHEDULE.TIME"))&&o[2]}`;switch(a){case zr:i=0;break;case Xs:if(r.lastValue&&[zr,Os].includes(r.lastType)){const f=co(s.itemValue).getTime()-co(r.lastValue).getTime();i=r.milliseconds+f}else i=r.milliseconds;break;case Zs:if([zr,"SCHECULE.TIME.RESUME"].includes(r.lastType)){const f=co(s.itemValue).getTime()-co(r.lastValue).getTime();i=r.milliseconds+f}else i=r.milliseconds;break;default:i=r.milliseconds;break}return{milliseconds:i,lastType:a,lastValue:s.itemValue}},{milliseconds:0,lastType:void 0,lastValue:void 0});if([zr,Os].includes(n.lastType)){const r=new Date().getTime()-co(n.lastValue).getTime();n.milliseconds+=r}return{milliseconds:n.milliseconds,time:MP(n.milliseconds),relevantTimeItems:e}}function MP(t){const e=(n,r=2)=>("00"+n).slice(-r);return e(t/36e5|0)+":"+e(t%36e5/6e4|0)+":"+e(t%6e4/1e3|0)}function DP({visibilityThreshold:t,timeStamp:e,schedule:n,matchUp:r}){const{itemValue:s,timeStamp:i}=Ei({timeItems:(r==null?void 0:r.timeItems)||[],itemType:LI,visibilityThreshold:t});return!n||i&&e&&new Date(i).getTime()>new Date(e).getTime()?{courtOrder:s}:n}function wP({matchUp:t}){const e=(t==null?void 0:t.timeItems)||[],n=i=>i.createdAt?new Date(i.createdAt).getTime():0,r=e.reduce((i,o)=>{const c=o.itemType===zr&&o;return c&&(!i||n(c)<n(i))?c:i},void 0);return{startTime:r==null?void 0:r.itemValue}}function kP({matchUp:t}){const e=(t==null?void 0:t.timeItems)||[],n=i=>i.createdAt?new Date(i.createdAt).getTime():0,r=e.reduce((i,o)=>{const c=o.itemType===Xs&&o;return c&&(!i||n(c)>n(i))?c:i},void 0);return{endTime:r==null?void 0:r.itemValue}}const ls="SINGLES",WI="SINGLES",$n="DOUBLES",Zu="DOUBLES",we="TEAM",ds="TEAM";function _f({scheduleVisibilityFilters:t,afterRecoveryTimes:e,tournamentRecord:n,scheduleTiming:r,matchUpFormat:s,matchUpType:i,matchUp:o,event:c}){var E,y,b,N,A;if(!o)return{error:Rn};if(e&&!o.matchUpType&&!i&&(c||n)&&o.drawId){let C=(E=c==null?void 0:c.drawDefinitions)==null?void 0:E.find(P=>P.drawId===o.drawId);!C&&n&&({drawDefinition:C,event:c}=Je({tournamentRecord:n,drawId:o.drawId}));const v=o.structureId&&((y=C==null?void 0:C.structures)==null?void 0:y.find(({structureId:P})=>P===o.structureId));i=(v==null?void 0:v.matchUpType)||(C==null?void 0:C.matchUpType)||(c==null?void 0:c.eventType)!==we&&(c==null?void 0:c.eventType)}const{milliseconds:a,time:u}=GI({matchUp:o}),{startTime:l}=wP({matchUp:o}),{endTime:f}=kP({matchUp:o});let p;const{visibilityThreshold:h,eventIds:d,drawIds:m}=t??{};if((!d||d.includes(o.eventId))&&(!m||m.includes(o.drawId))){const C={matchUp:o,visibilityThreshold:h},{allocatedCourts:v}=$I(C),{scheduledTime:P}=wf(C);let{scheduledDate:U}=bi(C);const{venueId:O}=jI(C),{courtId:D}=VI(C),{courtOrder:M}=DP(C),{timeModifiers:w}=kf(C);let k,_,F,L,W;const j=o.matchUpType??i;if(r&&P&&e&&j){const J={matchUpFormat:o.matchUpFormat??s,...r};({averageMinutes:_=0,recoveryMinutes:F=0,typeChangeRecoveryMinutes:L=0}=qu({timingDetails:J,eventType:j})),(_||F)&&(k=f?An(de(f),F):An(P,_+F)),L&&(W=f?An(de(f),L):An(P,_+L))}!U&&P&&(U=Bt(P));const H=Du({scheduledDate:U,scheduledTime:P}),B={},R=((b=n&&O&&Ju({tournamentRecord:n,venueId:O}))==null?void 0:b.venueData)||{};O&&(B[O]=R);const{venueName:x,venueAbbreviation:q,courtsInfo:V}=R,Y=D&&(V==null?void 0:V.find(J=>J.courtId===D)),z=Y==null?void 0:Y.courtName;for(const J of v||[]){if(!n)break;J.venueId&&!B[J.venueid]&&(B[J.venueId]=(N=Ju({venueId:J.venueId,tournamentRecord:n}))==null?void 0:N.venueData);const Q=B[J.venueId];J.venueName=Q==null?void 0:Q.venueName;const X=(A=Q==null?void 0:Q.courtsInfo)==null?void 0:A.find(Z=>Z.courtId===J.courtId);J.courtName=X==null?void 0:X.courtName}p=bt({typeChangeTimeAfterRecovery:W,timeAfterRecovery:k,scheduledDate:U,scheduledTime:P,isoDateString:H,allocatedCourts:v,timeModifiers:w,venueAbbreviation:q,venueName:x,venueId:O,courtOrder:M,courtName:z,courtId:D,typeChangeRecoveryMinutes:L,recoveryMinutes:F,averageMinutes:_,milliseconds:a,startTime:l,endTime:f,time:u})}else p=bt({time:u,startTime:l,endTime:f,milliseconds:a});const g=o.matchUpStatus&&We.includes(o.matchUpStatus),{scheduledDate:I}=bi({matchUp:o}),{scheduledTime:S}=wf({matchUp:o}),T=g&&(Bt(f)||Bt(I)||Bt(S))||void 0;return{schedule:p,endDate:T}}function Xu({collectionPosition:t,collectionId:e,lineUp:n}){let r=[];const s=[];if(n){const i=c=>c===void 0?-1:c,o=n.map(c=>{const{collectionAssignments:a,participantId:u}=c,l=a==null?void 0:a.find(f=>f.collectionPosition===t&&f.collectionId===e);return l&&{participantId:u,...l}}).filter(Boolean).sort((c,a)=>i(c.substitutionOrder)-i(a.substitutionOrder));for(const c of o){const{participantId:a,previousParticipantId:u,substitutionOrder:l}=c;r.includes(a)||(u&&s.push({previousParticipantId:u,substitutionOrder:l,participantId:a}),r=r.filter(f=>f!==u),r.push(a))}}return{assignedParticipantIds:r,substitutions:s}}const Ta="SIGN_IN_STATUS",xt=jr.Individual,Fn=jr.Group,_t=jr.Pair,se=jr.Team,vr=jr.Team,ya="SIGNED_IN",_P="SIGNED_OUT",Ea={TEAM_PARTICIPANT:vr,INDIVIDUAL:xt,GROUP:Fn,TEAM:se,PAIR:_t};function Jr({tournamentParticipants:t,tournamentRecord:e,participantIds:n}){const r="getPairedParticipant";if(!t&&!e)return{error:et};if(!Array.isArray(n)||n.length>2)return{error:gr};if(!n.length)return G({result:{error:Ns},stack:r});t=t||(e==null?void 0:e.participants)||[];const s=t.filter(c=>c.participantType===_t&&qe(n,c.individualParticipantIds).length===n.length&&c.individualParticipantIds.length===n.length),i=s[0];if(!i)return G({result:{error:_e},stack:r});const o=pt(s.slice(1),!1,!0);return{participant:pt(i),duplicatedPairParticipants:o,...$}}function ba({drawDefinition:t,participantId:e}){if(typeof t!="object")return{error:lt};if(typeof e!="string")return{error:Ce};const{extension:n}=Ke({element:t,name:Wr});return{lineUp:((n==null?void 0:n.value)||{})[e]}}function FP({tournamentParticipants:t,positionAssignments:e,collectionPosition:n,drawPositions:r=[],participantMap:s,drawDefinition:i,collectionId:o,sideLineUps:c,matchUpType:a}){if(!o||!n)return;const u=(r==null?void 0:r.map(l=>{var I,S,T,E,y,b;const f=(I=e.find(N=>N.drawPosition===l))==null?void 0:I.participantId,p=c==null?void 0:c.find(N=>(N==null?void 0:N.drawPosition)===l),h=(p==null?void 0:p.teamParticipant)||f&&((S=s==null?void 0:s[f])==null?void 0:S.participant)||(t==null?void 0:t.find(({participantId:N})=>N===f)),d=(p==null?void 0:p.lineUp)||((T=ba({participantId:f,drawDefinition:i}))==null?void 0:T.lineUp),{assignedParticipantIds:m,substitutions:g}=Xu({collectionPosition:n,collectionId:o,lineUp:d});if(a===me){if((m==null?void 0:m.length)<=2){const N=(y=(E=s==null?void 0:s[m[0]])==null?void 0:E.pairIdMap)==null?void 0:y[m[1]],C=N&&((b=s[N])==null?void 0:b.participant)||Jr({participantIds:m,tournamentParticipants:t}).participant,v=C==null?void 0:C.participantId;return{[l]:{participantId:v,teamParticipant:h,substitutions:g}}}else if((m==null?void 0:m.length)>2)return{[l]:{teamParticipant:h,substitutions:g}}}else{const N=m==null?void 0:m[0];return N&&{[l]:{participantId:N,teamParticipant:h,substitutions:g}}}}).filter(Boolean))||{};return Object.assign({},...u)}function Cn({matchUps:t=[],interpolate:e}){var p;if(!cr(t))return{roundMatchUps:[],error:tt};const n=t.reduce((h,d)=>{const m=typeof d.roundNumber=="string"?vt(d.roundNumber):d.roundNumber;return!d.roundNumber||h.includes(m)?h:h.concat(m)},[]).sort(Ve).map(h=>{const d=t.filter(S=>S.roundNumber===h),g=d.find(({matchUpType:S})=>S===Jt)?d.filter(({matchUpType:S})=>S===Jt):d,I=S=>S.sort((T,E)=>Ve(T.roundPosition,E.roundPosition));return{[h]:I(g)}}),r=t.reduce((h,d)=>{const m=typeof d.roundNumber=="string"?vt(d.roundNumber):d.roundNumber;return h[m]||(h[m]=bt({abbreviatedRoundName:d.abbreviatedRoundName,finishingRound:d.finishingRound,roundName:d.roundName})),h},{}),s=Object.assign({},...n);if(e){const h=Math.max(...Object.keys(s).map(m=>vt(m)).filter(m=>!isNaN(m))),d=(p=s[h])==null?void 0:p.length;if(d>1&&mr(d)){const m=h+1,g=m+d/2;ht(m,g).forEach((S,T)=>{s[S]=ht(0,d/(2+T*2)).map(()=>({}))})}}let i=0;const o=Object.assign({},...Object.keys(s).map(h=>{var I,S,T;const d=(I=s[h])==null?void 0:I.length,m=(T=(S=s[h])==null?void 0:S.filter(E=>{var y;return!We.includes(E.matchUpStatus)&&!((y=E.score)!=null&&y.scoreStringSide1)}))==null?void 0:T.length,g=d&&d===m;return i=Math.max(i,d),{[h]:{matchUpsCount:d,inactiveCount:m,inactiveRound:g}}}));let c=0,a=0;const u=Object.keys(s).map(h=>vt(h)).filter(h=>!isNaN(h));u.forEach(h=>{var g,I,S,T,E;const d=s[h].sort((y,b)=>y.roundPosition-b.roundPosition),m=d.map(y=>(y==null?void 0:y.drawPositions)||[]).flat();if(o[h].roundNumber=h,o[h].roundFactor=o[h].matchUpsCount?i/o[h].matchUpsCount:1,o[h].finishingRound=(g=r[h])==null?void 0:g.finishingRound,o[h].roundName=(I=r[h])==null?void 0:I.roundName,o[h].abbreviatedRoundName=(S=r[h])==null?void 0:S.abbreviatedRoundName,o[h].finishingPositionRange=(E=(T=s[h])==null?void 0:T[0])==null?void 0:E.finishingPositionRange,h===1||!o[h-1]){const y=m.sort(Ve),b=Ge(y,2);o[h].drawPositions=y,o[h].pairedDrawPositions=b}else{const y=o[h-1],b=y.drawPositions,N=y.matchUpsCount/o[h].matchUpsCount,A=Ge(b,N),C=d.map(v=>{const{roundPosition:P}=v,U=[...v.drawPositions||[],void 0,void 0].slice(0,2);if(!P)return U;const O=(U==null?void 0:U.filter(Boolean))||[];if(!(O!=null&&O.length))return[void 0,void 0];if(h<3&&(O==null?void 0:O.length)===2)return U==null?void 0:U.slice().sort(Ve);const D=qe(b,O).length!==(O==null?void 0:O.length);if(O!=null&&O.length&&D)return(O==null?void 0:O.length)===1?[O[0],void 0]:U==null?void 0:U.slice().sort(Ve);const M=(P-1)*2;return A.slice(M,M+2).map(k=>O==null?void 0:O.find(_=>k.includes(_)))});o[h].drawPositions=C==null?void 0:C.flat(),o[h].pairedDrawPositions=C}o[h+1]&&o[h+1].matchUpsCount===o[h].matchUpsCount&&(o[h+1].feedRound=!0,o[h+1].feedRoundIndex=a,o[h].preFeedRound=!0,a+=1),o[h]&&!o[h].feedRound&&(o[h].roundIndex=c,c+=1)});const l=!!Object.values(o).find(({matchUpsCount:h})=>!mr(h));return{hasNoRoundPositions:t.some(h=>!h.roundPosition),roundsNotPowerOf2:l,maxMatchUpsCount:i,roundMatchUps:s,roundNumbers:u,roundProfile:o}}function HI(t){var r;const e=t==null?void 0:t.matchUp;let n=e==null?void 0:e.matchUpType;if(!n&&((r=e.sides)!=null&&r.length)){const s=e.sides.find(({participant:c})=>c),i=s==null?void 0:s.participant,o=i==null?void 0:i.participantType;n=o===xt&&Oe||o===_t&&me||o===se&&se||void 0}return{matchUpType:n}}function Na({drawDefinition:t,attributes:e}){let{extension:n}=Hu({name:Gu,drawDefinition:t});const r=(n==null?void 0:n.value)||{};return e.forEach(s=>{Object.keys(s).forEach(i=>{r[i]?Object.assign(r[i],s[i]):r[i]=s[i]})}),n={name:Gu,value:r},Nf({drawDefinition:t,extension:n}),{entryProfile:r}}function Aa({drawDefinition:t}){const{extension:e}=Hu({name:Gu,drawDefinition:t});return{entryProfile:(e==null?void 0:e.value)||{}}}const It="MAIN",Pt="QUALIFYING",Re="CONSOLATION",je="VOLUNTARY_CONSOLATION",Ie="PLAY_OFF",Ff=[It,Pt,Re,Ie,je],ao={[Pt]:1,[It]:2,[Ie]:3,[Re]:3,[je]:4},qI="finishingPositions",YI="aggregateEventStructures",zI={[It]:1,[Ie]:2,[Re]:3,[Pt]:4,[je]:5},LP={[Ie]:1,[It]:2,[Re]:3,[Pt]:4,[je]:5},Lf="CLUSTER",RP="SEPARATE",Rf="WATERFALL",tl="ITEM",mn="CONTAINER",Cr="DRAW",KI="RANDOM",Ni="TOP_DOWN",uo="BOTTOM_UP",Ai="POSITION",vi="WINNER",lo="LOSER",fs="FIRST_MATCHUP",Xn="AD_HOC",ic="FEED_IN",oc="COMPASS",cc="OLYMPIC",BP="SINGLE_ELIMINATION",Ms="SINGLE_ELIMINATION",va="DOUBLE_ELIMINATION",ac="FIRST_MATCH_LOSER_CONSOLATION",Ca="FIRST_ROUND_LOSER_CONSOLATION",Ci="LUCKY_DRAW",el="CURTIS_CONSOLATION",xP="CURTIS_CONSOLATION",Bf="FEED_IN_CHAMPIONSHIP_TO_SF",Pa="FEED_IN_CHAMPIONSHIP_TO_SF",xf="FEED_IN_CHAMPIONSHIP_TO_QF",Ua="FEED_IN_CHAMPIONSHIP_TO_QF",$f="FEED_IN_CHAMPIONSHIP_TO_R16",Oa="FEED_IN_CHAMPIONSHIP_TO_R16",JI="MODIFIED_FEED_IN_CHAMPIONSHIP",Ma="MODIFIED_FEED_IN_CHAMPIONSHIP",Da="FEED_IN_CHAMPIONSHIP",Pr="ROUND_ROBIN",Ds="ROUND_ROBIN_WITH_PLAYOFF",QI="DECIDER",ZI="BACKDRAW",Vf={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"}},jf={0:{name:"EAST",abbreviation:"E"},"0-1":{name:"WEST",abbreviation:"W"},"0-2":{name:"NORTH",abbreviation:"N"},"0-1-1":{name:"SOUTH",abbreviation:"S"}},uc="WIN_RATIO",fo="ROUND_OUTCOME",XI=[oc,el,Ua,Oa,Pa,Da,xf,$f,Bf,ac,Ca,Ci,Ma,cc,Ie,Ds],$P={MAIN:It,QUALIFYING:Pt,CONSOLATION:Re,ITEM:tl,CONTAINER:mn,FIRST_MATCHUP:fs,WINNER:vi,LOSER:lo,AD_HOC:Xn,FEED_IN:ic,COMPASS:oc,PLAY_OFF:Ie,OLYMPIC:cc,KNOCKOUT:BP,SINGLE_ELIMINATION:Ms,DOUBLE_ELIMINATION:va,CURTIS:el,FICSF:Bf,FICQF:xf,FICR16:$f,MFIC:JI,VOLUNTARY_CONSOLATION:je,FIRST_MATCH_LOSER_CONSOLATION:ac,FIRST_ROUND_LOSER_CONSOLATION:Ca,MODIFIED_FEED_IN_CHAMPIONSHIP:Ma,FEED_IN_CHAMPIONSHIP_TO_R16:Oa,FEED_IN_CHAMPIONSHIP_TO_QF:Ua,FEED_IN_CHAMPIONSHIP_TO_SF:Pa,FEED_IN_CHAMPIONSHIP:Da,LUCKY_DRAW:Ci,ROUND_ROBIN_WITH_PLAYOFF:Ds,ROUND_ROBIN:Pr,DECIDER:QI,BACKDRAW:ZI,COMPASS_ATTRIBUTES:Vf,OLYMPIC_ATTRIBUTES:jf,DRAW:Cr,RANDOM:KI,TOP_DOWN:Ni,BOTTOM_UP:uo,WATERFALL:Rf,WIN_RATIO:uc,ROUND_OUTCOME:fo,MULTI_STRUCTURE_DRAWS:XI,generatedDrawTypes:[Xn,oc,el,va,Ua,Oa,Pa,Da,ic,ac,Ca,Ci,Ma,cc,Ie,Pr,Ds,Ms],stageOrder:ao,finishOrder:zI,AGGREGATE_EVENT_STRUCTURES:YI,FINISHING_POSITIONS:qI};function Pi(t,e,n){var f,p;const r=h=>{var d,m;return(m=(d=Ke({element:h,name:Hr}))==null?void 0:d.extension)==null?void 0:m.value},s=n==null?void 0:n.deprioritizeCompleted,i=(n==null?void 0:n.mode)===YI&&LP,o=(n==null?void 0:n.mode)===qI&&zI,c=o||i||ao,a=h=>(h==null?void 0:h.stage)===It&&(h==null?void 0:h.stageSequence)===1,u=h=>a(h)?-1:c[h==null?void 0:h.stage],l=h=>h==null?void 0:h.matchUps.every(({matchUpStatus:d})=>We.includes(d)?1:-1);return s&&l(t)-l(e)||i&&u(t)-u(e)||((t==null?void 0:t.stage)&&c[t.stage]||0)-((e==null?void 0:e.stage)&&c[e.stage]||0)||(r(t)||0)-(r(e)||0)||!o&&!i&&(((f=e==null?void 0:e.positionAssignments)==null?void 0:f.length)??1/0)-(((p=t==null?void 0:t.positionAssignments)==null?void 0:p.length)??1/0)||((t==null?void 0:t.stageSequence)??0)-((e==null?void 0:e.stageSequence)??0)||(nl(t)||0)-(nl(e)||0)}function nl(t){return((t==null?void 0:t.matchUps)||[]).reduce((e,n)=>{var s;const r=(((s=n.finishingPositionRange)==null?void 0:s.winner)||[]).reduce((i,o)=>i+o,0);return!e||r<e?r:e},void 0)}function Ot({drawDefinition:t,structureId:e}){if(!t)return{error:lt};if(!e)return{error:En};const{structures:n}=lr({drawDefinition:t}),r=n==null?void 0:n.map(o=>o.structures?[...o.structures].concat(o):o).flat(),s=r==null?void 0:r.find(o=>o.structureId===e);if(!s)return{error:Te};const i=s.structureType===tl?r==null?void 0:r.find(o=>{var c;return(c=o.structures)==null?void 0:c.some(a=>a.structureId===e)}):void 0;return{structure:s,containingStructure:i}}function lr({withStageGrouping:t,drawDefinition:e,stageSequences:n,stageSequence:r,roundTarget:s,sortConfig:i,stages:o,stage:c}){var d;const a=!e&&lt||!(e!=null&&e.structures)&&G1||void 0;if(a)return{error:a,structures:[],stageStructures:{}};const u=m=>{var I,S;const g=(S=(I=Ke({element:m,name:Hr}))==null?void 0:I.extension)==null?void 0:S.value;return!s||s===g},l=((d=e==null?void 0:e.structures)==null?void 0:d.filter(p).filter(h).filter(u).sort((m,g)=>Pi(m,g,i)))??[],f=t?Object.assign({},...Ff.map(m=>{const g=l==null?void 0:l.filter(I=>I.stage===m);return(g==null?void 0:g.length)&&{[m]:g}}).filter(Boolean)):{};return{structures:l,stageStructures:f};function p(m){return!c&&!Array.isArray(o)||c&&m.stage===c||Array.isArray(o)&&o.includes(m.stage)}function h(m){return!r&&!Array.isArray(n)||r&&m.stageSequence===r||Array.isArray(n)&&n.includes(m.stageSequence)}}const dr=un.Alternate,rl=un.Confirmed,Ur=un.DirectAcceptance,wa=un.FeedIn,sl=un.JuniorExempt,ka=un.LuckyLoser,il=un.OrganiserAcceptance,ol=un.Qualifier,VP=un.Registered,cl=un.SpecialExempt,Or=un.Ungrouped,po=un.Unpaired,lc=un.Wildcard,ti=un.Withdrawn,Gf=[rl,Ur,sl,il,cl],jP=[wa,ka,ol],ho=[rl,Ur,wa,sl,il,cl,lc],ps=[rl,Ur,wa,sl,ka,ol,il,cl,lc],GP=[dr,rl,Ur,wa,sl,ka,il,ol,VP,cl,Or,po,lc,ti],tS=ps;function _a({stage:t,drawDefinition:e}){const{entryProfile:n}=Aa({drawDefinition:e}),r=Object.keys(n).includes(t);if(!r&&Ff.includes(t)){const s=[{[t]:{drawSize:void 0,alternates:!0}}];return Na({drawDefinition:e,attributes:s}),!0}return r}function WP({stage:t,drawDefinition:e}){var r;const{entryProfile:n}=Aa({drawDefinition:e});return((r=n[t])==null?void 0:r.alternates)||0}function HP({stage:t,drawDefinition:e}){var r;const{entryProfile:n}=Aa({drawDefinition:e});return((r=n[t])==null?void 0:r.wildcardsCount)||0}function al({stage:t,drawDefinition:e,entryStatus:n}){return e.entries.reduce((r,s)=>s.entryStage===t&&s.entryStatus===n?r+1:r,0)}function mo({provisionalPositioning:t,placementGroup:e,drawDefinition:n,stageSequence:r,entryStatuses:s,structureId:i,roundTarget:o,stages:c,stage:a}){var l;const u=((l=n.entries)==null?void 0:l.reduce((f,p)=>{var T,E;const h=(E=(T=Ke({name:Hr,element:p}))==null?void 0:T.extension)==null?void 0:E.value,d=a&&p.entryStage===a||(c==null?void 0:c.length)&&p.entryStage&&c.includes(p.entryStage),m=!s||p.entryStatus&&s.includes(p.entryStatus),g=p.entryStageSequence??1;return d&&(!r||g===r)&&m&&(!o||!h||o===h)?f.concat(p):f},[]))??[];if(i&&a===Ie){const{playoffEntries:f,error:p}=qP({provisionalPositioning:t,drawDefinition:n,structureId:i});return p&&console.log("playoff entries error"),(f!=null&&f.length?f:u).filter(h=>!e||h.placementGroup===e)}return u}function qP({provisionalPositioning:t,drawDefinition:e,structureId:n}){const r=[],s=(e.links??[]).find(i=>i.linkType===Ai&&i.target.structureId===n);if(s){const{finishingPositions:i,structureId:o}=s.source,{structure:c}=Ot({drawDefinition:e,structureId:o});(c==null?void 0:c.structureType)===mn&&(c.structures??[]).forEach(u=>{const l=u.positionAssignments??[],{structureId:f}=u,p=f,h=Object.assign({},...l.map(I=>{var E;const{participantId:S}=I,T=(E=Ke({element:I,name:Ys}).extension)==null?void 0:E.value;return T&&S?{[S]:T}:void 0}).filter(Boolean)),m=Object.keys(h).reduce((I,S)=>{const T=h[S],E=T.groupOrder||t&&T.provisionalOrder;return I.includes(E)||I.push(E),I},[]).length===Object.keys(h).length,g=Object.keys(h).filter(I=>{const S=h[I],T=S.groupOrder||t&&S.provisionalOrder;return i==null?void 0:i.includes(T)});(!t||m)&&g.forEach(I=>{const S=h[I],{groupOrder:T,provisionalOrder:E,GEMscore:y}=S,b=T||t&&E,N=(i??[]).sort(Ve).indexOf(b)+1;r.push({entryStage:Ie,entryStatus:wa,placementGroup:N,groupingValue:p,participantId:I,GEMscore:y})})})}return{playoffEntries:r}}function eS({stage:t,drawDefinition:e}){return ho.reduce((n,r)=>(al({drawDefinition:e,entryStatus:r,stage:t})||0)+n,0)}function YP({stage:t,drawDefinition:e}){return al({entryStatus:lc,drawDefinition:e,stage:t})}function Mr({provisionalPositioning:t,drawDefinition:e,structureId:n,structure:r}){var p;let s,i=[];if(r||({structure:r,error:s}=Ot({drawDefinition:e,structureId:n})),s||!r)return{seedAssignments:[],error:Te};n||(n=r.structureId);const{stage:o,stageSequence:c}=r,u=o===Ie&&e&&mo({provisionalPositioning:t,drawDefinition:e,stageSequence:c,structureId:n,stage:o}),l=u?u.filter(h=>h.placementGroup===1).sort((h,d)=>h.GEMscore<d.GEMscore&&1||h.GEMscore>d.GEMscore&&-1||0).map((h,d)=>{const m=d+1;return{participantId:h.participantId,seedValue:m,seedNumber:m,seedProxy:!0}}):[];l.length?i=l:r.seedAssignments?i=r.seedAssignments:s=x1;const f=r.seedLimit||((p=r==null?void 0:r.positionAssignments)==null?void 0:p.length);return{seedAssignments:i,seedLimit:f,stage:o,stageSequence:c,error:s}}function Wf({drawDefinition:t}){if(typeof t!="object")return{error:Gi};const e={},{structures:n=[],links:r=[]}=t||{},s=n.reduce((o,c)=>{const{stage:a}=c;return o[a]?o[a].push(c):o[a]=[c],o},{});for(const o of Object.keys(s)){const c=s[o].find(({stageSequence:l})=>l===1);if(!c)continue;const{structureId:a}=c;i({aggregator:{},targetRound:0,exitProfiles:e,exitProfile:"0",structureId:a,stage:o})}return{exitProfiles:e};function i({exitProfiles:o,exitProfile:c,structureId:a,targetRound:u,aggregator:l,stage:f}){o[a]||(o[a]=[]),c==="0"&&[Re,Ie].includes(f)||o[a].push(c);const p=r.filter(h=>h.source.structureId===a&&h.source.roundNumber>=u);for(const h of p){const d=h.source.roundNumber,m=h.target.roundNumber,g=h.target.structureId,I=n.find(T=>T.structureId===g).stage,S=[I,g,m,d].join("|");if(l[S])return;l[S]=!0,i({exitProfile:`${c}-${d}`,structureId:g,exitProfiles:o,targetRound:m,aggregator:l,stage:I})}}}function ln({drawDefinition:t,structure:e}){const n={},r=[];return((t==null?void 0:t.structures)??[e]).filter(s=>s&&typeof s=="object").forEach(s=>{if(!s)return;const{structureId:i,matchUps:o,structures:c}=s,a=Array.isArray(c);if(a)a&&c.forEach(u=>{const{structureName:l}=u,f=u.matchUps;n[u.structureId]={matchUps:f,itemStructureIds:[],structureName:l},f&&(r.push(...f),f.forEach(p=>{p.tieMatchUps&&r.push(...p.tieMatchUps)})),n[i]||(n[i]={itemStructureIds:[],matchUps:[]}),n[i].itemStructureIds||(n[i].itemStructureIds=[]),n[i].itemStructureIds.push(u.structureId)});else{const u=o;n[i]={matchUps:u,itemStructureIds:[]},u==null||u.forEach(l=>{r.push(l),l.tieMatchUps&&r.push(...l.tieMatchUps)})}}),{mappedMatchUps:n,drawMatchUps:r}}function Ui({mappedMatchUps:t,matchUpsMap:e,structureId:n,inContext:r}){t=(e==null?void 0:e.mappedMatchUps)??t;const s=t[n],i=((s==null?void 0:s.itemStructureIds)||[]).map(o=>{const{matchUps:c,structureName:a}=t[o];return r?c.map(u=>Object.assign(pt(u,!0,!0),{containerStructureId:n,structureId:o,structureName:a})):c}).flat();return((s==null?void 0:s.matchUps)||[]).concat(...i)}function nS({groupedOrder:t,roundPositionsCount:e}){if(!t||(t==null?void 0:t.length)<=e)return t;const r=Ge(t,t.length/e).map(i=>i.reduce((o,c)=>o+c)),s=r.slice().sort(Ve);return r.map(i=>s.indexOf(i)+1)}function ul(t){if(!Array.isArray(t))return"";const e=t.filter(Me);return e.length?Vt([Math.min(...e),Math.max(...e)]).join("-"):""}function zP({drawDefinition:t,structureId:e,matchUpsMap:n}){if(!t)return{error:lt};if(!e)return{error:En};const{structure:r}=Ot({drawDefinition:t,structureId:e});if((r==null?void 0:r.stage)!==Re)return{error:xs,info:"Structure is not CONSOLATION stage"};const{links:s}=t,i=(s==null?void 0:s.filter(f=>f.target.structureId===e))||[],o=(i==null?void 0:i.reduce((f,p)=>{const{structureId:h}=p.source;return f.includes(h)?f:f.concat(h)},[]))||[],c=Object.assign({},...o.map(f=>{const p=Ui({structureId:f,matchUpsMap:n}),d=Cn({matchUps:p}).roundProfile;return{[f]:d}})),a=Ui({matchUpsMap:n,structureId:e}),{roundProfile:u}=Cn({matchUps:a}),l={};return i==null||i.forEach(f=>{var D;const{structureId:p,roundNumber:h}=f.source,{feedProfile:d,groupedOrder:m,positionInterleave:g,roundNumber:I}=f.target,S=c[p],T=(D=S[1])==null?void 0:D.drawPositions,E=S[h],y=E==null?void 0:E.matchUpsCount;if(!y)return;const b=y?T.length/y:0,N=T.length/b;let A=T.slice();const C=nS({roundPositionsCount:A.length,groupedOrder:m}),v=(C==null?void 0:C.length)||1;if(v<=N){const M=T.length/v,w=Ge(A,M);d===uo&&w.forEach(k=>k.reverse()),A=(C==null?void 0:C.length)&&(C==null?void 0:C.map(k=>w[k-1]).flat())||A}let P=Ge(A,b);if(!(C!=null&&C.length)&&d===uo&&P.reverse(),g){const M=ht(0,g.interleave).map(()=>{}),w=ht(0,g.offset).map(()=>{});P=P.map(_=>[_,...M]),P.unshift(w),P=P.flat(1);const k=P.length-g.offset;P=P.slice(0,k)}l[I]||(l[I]={});const U=u==null?void 0:u[I],O=U!=null&&U.feedRound?2:1;P.forEach((M,w)=>{const k=1+w*O;l[I][k]||(l[I][k]=ul(M))})}),{sourceDrawPositionRanges:l}}function rS({drawDefinition:t}){if(!t)return{error:lt};const e={};return{allPositionedParticipantIds:(t.structures||[]).map(r=>{const s=r.stage;e[s]||(e[s]=[]);const{positionAssignments:i}=ee({structure:r}),o=(i==null?void 0:i.map(kn("participantId")).filter(Boolean))??[];return e[s].push(...o),o}).flat(),stagePositionedParticipantIds:e}}function ee({drawDefinition:t,structureId:e,structure:n}){let r,s=[];if(!n){if(!t)return{positionAssignments:s,error:lt};if({structure:n,error:r}=Ot({drawDefinition:t,structureId:e}),r)return{positionAssignments:s,error:r}}return n.structures?s=[].concat(...n.structures.map(i=>ee({structure:i}).positionAssignments)):n.positionAssignments?s=n.positionAssignments:r=z1,{positionAssignments:s,error:r}}function ke({drawDefinition:t,structureId:e,structure:n}){var u;const r=((u=ee({drawDefinition:t,structureId:e,structure:n}))==null?void 0:u.positionAssignments)||[],s=r==null?void 0:r.filter(l=>l.participantId??l.bye??l.qualifier),i=r&&(r==null?void 0:r.length)===(s==null?void 0:s.length),o=r==null?void 0:r.filter(l=>!l.participantId&&!l.bye&&!l.qualifier),c=r==null?void 0:r.filter(l=>!l.participantId&&l.bye),a=r==null?void 0:r.filter(l=>!l.participantId&&l.qualifier);return{allPositionsAssigned:i,positionAssignments:r,unassignedPositions:o,assignedPositions:s,qualifierPositions:a,byePositions:c}}function KP({drawPositions:t,roundProfile:e,roundNumber:n}){const r=[void 0,void 0];if(U1(t))return{orderedDrawPositions:r,displayOrder:r};const s=e==null?void 0:e[n],i=s==null?void 0:s.pairedDrawPositions,o=(i==null?void 0:i.find(a=>tn(a||[],t.filter(Boolean))))||r,c=s==null?void 0:s.feedRound;if(P1(t)){const a=t.sort(Ve);return{orderedDrawPositions:a.length===2?a:o,displayOrder:c?a:o}}if(c){const u=[t.find(l=>!isNaN(vt(l))),void 0];return{orderedDrawPositions:u,displayOrder:u}}return{orderedDrawPositions:o,displayOrder:o}}function JP({drawDefinition:t,roundProfile:e,structureId:n,matchUpsMap:r}){var a;if(!t)return{error:lt};if(!n)return{error:En};if(!e){const u=Ui({matchUpsMap:r,structureId:n});if({roundProfile:e}=Cn({matchUps:u}),!e)return{error:Tt}}const i=(Math.min(...((a=e==null?void 0:e[1])==null?void 0:a.drawPositions)||[])||1)-1,o=Object.keys(e);return{drawPositionsRanges:Object.assign({},...(o||[]).map(u=>{var T,E;const l=(T=e==null?void 0:e[u])==null?void 0:T.matchUpsCount,f=((E=e==null?void 0:e[1])==null?void 0:E.drawPositions)||[],p=Ge(f,f.length/l),h=p.map(ul),d=p.map(y=>y.map(b=>b-i)).map(ul),m=o.map(y=>{var N;if(y>u)return;const b=((N=e==null?void 0:e[y])==null?void 0:N.drawPositions)??[];return Ge(b,b.length/l)}).filter(Boolean),g=ht(0,l).map(y=>m.map(b=>b[y]).flat().filter(Boolean).sort(Ve)).map(y=>Vt(y)),I=g.map(y=>C1(y).map(ul).join(", ")),S=Object.assign({},...ht(0,l).map(y=>({[y+1]:{firstRoundDrawPositionsRange:h[y],firstRoundOffsetDrawPositionsRange:d[y],possibleDrawPositions:g[y],drawPositionsRange:I[y]}})));return{[u]:S}}))}}function Hf({matchUp:t}){let e=[],n=[],r=[],s=[],i;if(t||(i=Rn),t&&!t.sides&&(i=qn),t&&!t.hasContext&&(i=Pu),!i){s=t.sides.map(a=>a.participantId);const o=t.sides.filter(a=>a.participantType===xt).map(a=>a.participantId).filter(Boolean);e=t.sides.map(a=>{var u;return(u=a.participant)==null?void 0:u.individualParticipants}).filter(Boolean).map(a=>a.map(u=>u==null?void 0:u.participantId).filter(Boolean)),r=[...o,...e.flat()].filter(Boolean),n=Vt(r.concat(s)).filter(Boolean)}return{nestedIndividualParticipantIds:e,allRelevantParticipantIds:n,individualParticipantIds:r,sideParticipantIds:s,error:i}}function Fa({matchUp:t}){if(!t)return{error:Rn};if(!t.hasContext)return{error:Pu};if(!t.sides||t.sides.filter(Boolean).length!==2)return{error:qn};const{nestedIndividualParticipantIds:e,allRelevantParticipantIds:n,sideParticipantIds:r}=Hf({matchUp:t}),i=(t.timeItems||[]).filter(u=>[Mf,Df].includes(u==null?void 0:u.itemType)).sort((u,l)=>new Date(u.createdAt).getTime()-new Date(l.createdAt).getTime()),c=i.map(u=>u.itemValue).filter(u=>i.filter(l=>(l==null?void 0:l.itemValue)===u).reverse()[0].itemType===Mf);return e==null||e.forEach((u,l)=>{const f=r[l],p=(u==null?void 0:u.length)&&u.every(h=>c.includes(h));f&&p&&!c.includes(f)&&c.push(f)}),r.forEach((u,l)=>{c.includes(u)&&((e==null?void 0:e[l])||[]).forEach(f=>{f&&!c.includes(f)&&c.push(f)})}),{allParticipantsCheckedIn:r.reduce((u,l)=>c.includes(l)&&u,!0),checkedInParticipantIds:c,allRelevantParticipantIds:n}}function go(t){const{matchUps:e,isCollectionMatchUp:n,excludeMatchUpStatuses:r,matchUpStatuses:s,hasWinningSide:i,matchUpFormats:o,roundPositions:c,matchUpFormat:a,collectionIds:u,isMatchUpTie:l,roundNumbers:f,matchUpIds:p,roundNames:h,stageSequences:d,scheduledDates:m,scheduledDate:g,participantIds:I,processContext:S,tournamentIds:T,matchUpTypes:E,structureIds:y,readyToScore:b,courtIds:N,eventIds:A,venueIds:C,drawIds:v,stages:P,filterMatchUpIds:U=!0,filterMatchUpTypes:O=!0}=t,D=Array.isArray(I)?I.filter(Boolean):[],M=Array.isArray(s)?s.filter(Boolean):[],w=Array.isArray(r)?r.filter(Boolean):[],k=Array.isArray(P)?P.filter(Boolean):[],_=Array.isArray(d)?d.filter(Boolean):[],F=Array.isArray(u)?u.filter(Boolean):[],L=Array.isArray(h)?h.filter(Boolean):[],W=Array.isArray(f)?f.filter(Boolean):[],j=Array.isArray(c)?c.filter(Boolean):[],H=Array.isArray(p)&&U?p.filter(Boolean):[],B=Array.isArray(E)&&O?E.filter(Boolean):[],R=Array.isArray(N)?N.filter(Boolean):[],x=Array.isArray(C)?C.filter(Boolean):[],q=Array.isArray(o)&&o.filter(Boolean)||typeof a=="string"&&[a]||[],V=Array.isArray(m)&&m.filter(Boolean)||typeof g=="string"&&g.length&&[g]||[],Y=Array.isArray(T)?T.filter(Boolean):[],z=Array.isArray(A)?A.filter(Boolean):[],J=Array.isArray(v)?v.filter(Boolean):[],Q=Array.isArray(y)?y.filter(Boolean):[];return e.filter(X=>{var Z;if(b&&X.matchUpType!==yr&&!X.readyToScore||X.winningSide&&i&&![1,2].includes(X.winningSide)||l!==void 0&&(l&&!X.tieMatchUps||!l&&X.tieMatchUps)||n!==void 0&&(n&&!X.collectionId||!n&&X.collectionId)||k.length&&!k.includes(X.stage)||_.length&&!_.includes(X.stageSequence)||F.length&&(!X.collectionId||!F.includes(X.collectionId))||L.length&&(!X.roundName||!L.includes(X.roundName))||W.length&&(!X.roundNumber||!W.includes(X.roundNumber))||j.length&&(!X.roundPosition||!j.includes(X.roundPosition))||M.length&&(!X.matchUpStatus||!M.includes(X.matchUpStatus))||w.length&&X.matchUpStatus&&w.includes(X.matchUpStatus)||H.length&&!H.includes(X.matchUpId)||B.length&&(!X.matchUpType||!B.includes(X.matchUpType))||q.length&&(!X.matchUpFormat||!q.includes(X.matchUpFormat)))return!1;if(V!=null&&V.length){const{scheduledTime:nt}=wf({matchUp:X}),{scheduledDate:rt}=bi({matchUp:X}),it=Bt(nt)||rt;if(!V.find(st=>as(st,it)))return!1}if(R.length){const{courtId:nt}=VI({matchUp:X}),{allocatedCourts:rt}=$I({matchUp:X}),K=rt==null?void 0:rt.map(({courtId:it})=>it);if(!R.filter(Boolean).includes(nt)||K!=null&&K.includes(nt))return!1}if(x.length){const{venueId:nt}=jI({matchUp:X});if(!x.filter(Boolean).includes(nt))return!1}if(S){if(Y.length&&!Y.includes(X.tournamentId)||z.length&&!z.includes(X.eventId)||J.length&&!J.includes(X.drawId)||Q.length&&!Q.includes(X.structureId))return!1;if(D.length){const nt=((Z=X.sides)==null?void 0:Z.map(({participantId:K})=>K).filter(Boolean))??[];if(!D.some(K=>nt.includes(K)))return!1}}return!0})}function qf({roundsNotPowerOf2:t,drawDefinition:e,structure:n,matchUps:r}){var i;if(!n)return!1;r=r??n.matchUps??[],t=t??Cn({matchUps:r}).roundsNotPowerOf2;const s=!!((i=n.positionAssignments)!=null&&i.find(({drawPosition:o})=>o))||!!(r!=null&&r.find(({drawPositions:o})=>o==null?void 0:o.length));return(!(e!=null&&e.drawType)||e.drawType!==Ci)&&!(n!=null&&n.structures)&&t&&s}function Qr({drawDefinition:t,structure:e}){if(!e)return!1;const n=e.matchUps||e.roundMatchUps&&Object.values(e.roundMatchUps).flat(),r=n==null?void 0:n.find(i=>i==null?void 0:i.roundPosition),s=n==null?void 0:n.find(i=>{var o;return(o=i==null?void 0:i.drawPositions)==null?void 0:o.length});return!(e!=null&&e.structures)&&(e==null?void 0:e.stage)!==je&&!(t!=null&&t.drawType&&t.drawType!==Xn)&&!r&&!s}const sS={[Lu]:{policyName:"Round Naming Default",namingConventions:{round:"Round"},abbreviatedRoundNamingMap:{1:"F",2:"SF",4:"QF"},roundNamingMap:{1:"Final",2:"Semifinal",4:"Quarterfinal"},affixes:{roundNumber:"R",preFeedRound:"Q"},stageConstants:{[It]:"",[Ie]:"P",[Pt]:"Q",[Re]:"C"}}};function QP({roundNamingPolicy:t,structure:e,matchUps:n}){const{roundProfile:r,roundMatchUps:s}=Cn({matchUps:n}),{structureAbbreviation:i,stage:o}=e,c=Qr({structure:e}),a=qf({structure:e}),u=e.structures,l={},f=sS[Lu],p=(t==null?void 0:t.roundNamingMap)||f.roundNamingMap||{},h=(t==null?void 0:t.abbreviatedRoundNamingMap)||f.abbreviatedRoundNamingMap||{},d=(t==null?void 0:t.affixes)||f.affixes,m=d.roundNumber||f.affixes.roundNumber,I=((t==null?void 0:t.namingConventions)||f.namingConventions).round,S=o&&o!==It&&o[0],T=t==null?void 0:t.stageConstants,E=o&&(T==null?void 0:T[o])||S,y=r?Object.keys(r):[];return u||c||a?Object.assign(l,...y.map(b=>{const N=`${I} ${b}`,A=`${m}${b}`;return{[b]:{roundName:N,abbreviatedRoundName:A}}})):Object.assign(l,...y.map(b=>{if(!(r!=null&&r[b]))return;const{matchUpsCount:N,preFeedRound:A}=r[b],C=N*2,v=p[N]||`${d.roundNumber}${C}`,P=A?`-${d.preFeedRound}`:"",U=`${v}${P}`,O=[E,i,U].filter(Boolean).join("-"),M=`${h[N]||`${d.roundNumber}${C}`}${P}`,w=[E,i,M].filter(Boolean).join("-");return{[b]:{abbreviatedRoundName:w,roundName:O}}})),{roundNamingProfile:l,roundProfile:r,roundMatchUps:s}}function ZP({drawPositionCollectionAssignment:t,positionAssignments:e,displaySideNumber:n,seedAssignments:r,drawPosition:s,isFeedRound:i,sideNumber:o}){var h,d,m,g;const c=e.find(I=>I.drawPosition&&I.drawPosition===s),a=t?(h=t[s])==null?void 0:h.participantId:c==null?void 0:c.participantId,u=c?XP({displaySideNumber:n,seedAssignments:r,participantId:a,assignment:c,sideNumber:o}):{};i&&(o===1?Object.assign(u,{participantFed:!0}):Object.assign(u,{participantAdvanced:!0}));const l=(d=t==null?void 0:t[s])==null?void 0:d.teamParticipant,f=(m=t==null?void 0:t[s])==null?void 0:m.participant,p=(g=t==null?void 0:t[s])==null?void 0:g.substitutions;return f&&Object.assign(u,{participant:f}),p&&Object.assign(u,{substitutions:p}),l&&Object.assign(u,{teamParticipant:l}),u}function XP({displaySideNumber:t,seedAssignments:e,participantId:n,assignment:r,sideNumber:s}){const i={drawPosition:r.drawPosition,displaySideNumber:t,sideNumber:s};if(n){const o=tU({seedAssignments:e,participantId:n});Object.assign(i,o,{participantId:n})}else r.bye&&Object.assign(i,{bye:!0});return r.qualifier&&Object.assign(i,{qualifier:!0}),i}function tU({seedAssignments:t,participantId:e}){return t==null?void 0:t.find(n=>!n.seedProxy&&n.participantId===e)}const Io="ANY",Se="MALE",hs="MIXED",So="OTHER",Ne="FEMALE",iS={ANY:Io,MALE:Se,FEMALE:Ne,MIXED:hs,OTHER:So};function Qt({scheduleVisibilityFilters:t,tournamentAppliedPolicies:e,provisionalPositioning:n,tournamentParticipants:r,afterRecoveryTimes:s,policyDefinitions:i,tournamentRecord:o,seedAssignments:c,contextFilters:a,contextContent:u,matchUpFilters:l,participantMap:f,scheduleTiming:p,contextProfile:h,drawDefinition:d,context:m={},exitProfiles:g,matchUpsMap:I,structure:S,inContext:T,event:E}){var dt,mt,Mt,Nt,St;let y={},b={};if(r=r??(o==null?void 0:o.participants),!S)return{collectionPositionMatchUps:y,error:Wi,roundMatchUps:b,matchUps:[]};const N=Array.isArray(l==null?void 0:l.eventIds)?l==null?void 0:l.eventIds.filter(Boolean):[],A=Array.isArray(l==null?void 0:l.structureIds)?l==null?void 0:l.structureIds.filter(Boolean):[],C=Array.isArray(l==null?void 0:l.drawIds)?l==null?void 0:l.drawIds.filter(Boolean):[],v=!(m!=null&&m.eventId)||!(N!=null&&N.length)&&!((dt=a==null?void 0:a.eventIds)!=null&&dt.filter(Boolean).length)||(N==null?void 0:N.includes(m.eventId))||((mt=a==null?void 0:a.eventIds)==null?void 0:mt.includes(m.eventId)),P=!(A!=null&&A.length)||A.includes(S.structureId),U=!d||!(C!=null&&C.length)||C.includes(d.drawId);if(!v||!P||!U)return{collectionPositionMatchUps:y,roundMatchUps:b,matchUps:[]};h&&!u&&(u=Cs({tournamentRecord:o,contextProfile:h,drawDefinition:d}));const{appliedPolicies:O}=ge({drawDefinition:d}),D={...e,...O,...i},M=(Mt=D==null?void 0:D.scoring)==null?void 0:Mt.structures,w=S.stage&&(M==null?void 0:M.stage)&&(M==null?void 0:M.stage[S.stage]),k=S.stageSequence&&(w==null?void 0:w.stageSequence)&&w.stageSequence[S.stageSequence],_=((Nt=D==null?void 0:D.scoring)==null?void 0:Nt.requireAllPositionsAssigned)||(w==null?void 0:w.requireAllPositionsAssigned)||(k==null?void 0:k.requireAllPositionsAssigned);I||(I=ln({drawDefinition:d,structure:S}));const{positionAssignments:F,allPositionsAssigned:L}=ke({structure:S}),W=!_||L,{seedAssignments:j}=Mr({provisionalPositioning:n,drawDefinition:d,structure:S});c=c??j;const{roundOffset:H,structureId:B,structureName:R,stage:x,stageSequence:q}=S,{drawId:V,drawName:Y,drawType:z}=d??{};g=g||d&&Wf({drawDefinition:d}).exitProfiles;const J=g==null?void 0:g[B],Q=(J==null?void 0:J.length)&&(J[0].split("-").map(ct=>parseInt(ct)).reduce((ct,Et)=>ct+Et)||0),X=!!S.structures;let Z=Ui({matchUpsMap:I,structureId:B,inContext:T});const nt=D==null?void 0:D[Lu],rt=QP({roundNamingPolicy:nt,structure:S,matchUps:Z}),{roundNamingProfile:K,roundProfile:it}=rt;if(b=(rt==null?void 0:rt.roundMatchUps)??[],l&&(Z=go({matchUps:Z,...l,filterMatchUpTypes:!1,filterMatchUpIds:!1})),T){const{sourceDrawPositionRanges:ct}=zP({drawDefinition:d,matchUpsMap:I,structureId:B}),Et=d?JP({drawDefinition:d,roundProfile:it,matchUpsMap:I,structureId:B}).drawPositionsRanges:void 0;Z=Z.map(Ft=>st({scheduleVisibilityFilters:t,sourceDrawPositionRanges:ct,drawPositionsRanges:Et,roundNamingProfile:K,initialRoundOfPlay:Q,appliedPolicies:D,isRoundRobin:X,roundProfile:it,matchUp:Ft,event:E})),(Z==null?void 0:Z.filter(Ft=>Array.isArray(Ft.tieMatchUps))).forEach(Ft=>{const yt=Ft.tieMatchUps;Z=Z.concat(...yt)}),a&&(Z=go({processContext:!0,...a,matchUps:Z}))}else(Z==null?void 0:Z.filter(Et=>Array.isArray(Et.tieMatchUps))).forEach(Et=>{const gt=Et.tieMatchUps;Z=Z.concat(...gt)});return l&&(Z=go({matchUps:Z,...l,filterMatchUpTypes:!1,filterMatchUpIds:!1})),(l!=null&&l.matchUpTypes||l!=null&&l.matchUpIds)&&(Z=go({matchUpTypes:l.matchUpTypes,matchUpIds:l.matchUpIds,matchUps:Z})),(l!=null&&l.matchUpTypes||l!=null&&l.matchUpIds||T)&&(b=Cn({matchUps:Z}).roundMatchUps??[]),(St=hn({drawDefinition:d,structure:S,event:E}))!=null&&St.tieFormat&&({collectionPositionMatchUps:y}=ZC({matchUps:Z})),{matchUps:Z,roundMatchUps:b,roundProfile:it,collectionPositionMatchUps:y};function st({scheduleVisibilityFilters:ct,sourceDrawPositionRanges:Et,drawPositionsRanges:gt,initialRoundOfPlay:Ft,additionalContext:yt,roundNamingProfile:wt,tieDrawPositions:Xt,appliedPolicies:$t,isCollectionBye:At,matchUpTieId:Dt,isRoundRobin:at,roundProfile:ot,sideLineUps:Lt,matchUp:ft,event:Ct}){var cA,aA,uA,lA,dA,fA,pA,hA,mA,gA,IA,SA,TA,yA,EA;yt=yt||{};const Ut=(cA=hn({drawDefinition:d,structure:S,matchUp:ft,event:Ct}))==null?void 0:cA.tieFormat,Kt=Ut==null?void 0:Ut.collectionDefinitions,ut=ft.collectionId&&(Kt==null?void 0:Kt.find(rn=>rn.collectionId===ft.collectionId)),Rt=ft.collectionId?ut==null?void 0:ut.matchUpFormat:ft.matchUpFormat||(S==null?void 0:S.matchUpFormat)||(d==null?void 0:d.matchUpFormat)||(Ct==null?void 0:Ct.matchUpFormat),ne=ft.matchUpType||(ut==null?void 0:ut.matchUpType)||(S==null?void 0:S.matchUpType)||(d==null?void 0:d.matchUpType)||(Ct==null?void 0:Ct.eventType)!==we&&(Ct==null?void 0:Ct.eventType),Ae=At?re:ft.matchUpStatus,{schedule:Ee,endDate:Un}=_f({scheduleVisibilityFilters:ct,afterRecoveryTimes:s,tournamentRecord:o,scheduleTiming:p,matchUpFormat:Rt,matchUpType:ne,matchUp:ft,event:Ct}),Xe=Xt??ft.drawPositions??[],{collectionPosition:Lr,collectionId:jn,roundPosition:ue}=ft,he=ft.roundNumber||yt.roundNumber,$i=jn?FP({tournamentParticipants:r,positionAssignments:F,collectionPosition:Lr,drawDefinition:d,participantMap:f,drawPositions:Xe,collectionId:jn,sideLineUps:Lt,matchUpType:ne}):void 0,sA=((aA=wt==null?void 0:wt[he])==null?void 0:aA.roundName)||yt.roundName,iA=((uA=wt==null?void 0:wt[he])==null?void 0:uA.abbreviatedRoundName)||yt.abbreviatedRoundName,G2=(lA=ot==null?void 0:ot[he])==null?void 0:lA.feedRound,W2=(dA=ot==null?void 0:ot[he])==null?void 0:dA.preFeedRound,H2=(fA=ot==null?void 0:ot[he])==null?void 0:fA.roundFactor,Sm=gt==null?void 0:gt[he],q2=ue?Sm==null?void 0:Sm[ue]:void 0,Tm=Et==null?void 0:Et[he],Y2=ut!=null&&ut.category?{...(m==null?void 0:m.category)||{},...ut.category}:m==null?void 0:m.category,z2=((pA=ft.processCodes)==null?void 0:pA.length)&&ft.processCodes||((hA=ut==null?void 0:ut.processCodes)==null?void 0:hA.length)&&(ut==null?void 0:ut.processCodes)||((mA=S==null?void 0:S.processCodes)==null?void 0:mA.length)&&(S==null?void 0:S.processCodes)||((gA=d==null?void 0:d.processCodes)==null?void 0:gA.length)&&(d==null?void 0:d.processCodes)||((IA=Ct==null?void 0:Ct.processCodes)==null?void 0:IA.length)&&(Ct==null?void 0:Ct.processCodes)||(o==null?void 0:o.processCodes),K2=(h==null?void 0:h.withCompetitiveness)&&dI({...u,matchUp:ft}),J2=ft.finishingPositionRange||yt.finishingPositionRange,Cd=rn=>bt(rn,void 0,!0),ve={...Cd(m),...Cd({matchUpFormat:ft.matchUpType===we?void 0:Rt,tieFormat:ft.matchUpType!==we?void 0:Ut,roundOfPlay:x!==Pt&&oe(Ft)&&Ft+(he||0),endDate:ft.endDate||Un,gender:ut==null?void 0:ut.gender,discipline:Ct==null?void 0:Ct.discipline,category:Y2,finishingPositionRange:J2,abbreviatedRoundName:iA,drawPositionsRange:q2,competitiveProfile:K2,structureName:R,stageSequence:q,drawPositions:Xe,matchUpStatus:Ae,processCodes:z2,isRoundRobin:at,matchUpTieId:Dt,preFeedRound:W2,matchUpType:ne,roundFactor:H2,roundOffset:H,structureId:B,roundNumber:he,feedRound:G2,roundName:sA,drawName:Y,drawType:z,schedule:Ee,drawId:V,stage:x}),...pt(Cd(ft),!0,!0)};if(Rt&&((SA=ft.score)!=null&&SA.scoreStringSide1)){const rn=yn(Rt),{bestOf:Ls,finalSetFormat:Sn,setFormat:le}=rn??{};(Sn!=null&&Sn.tiebreakSet||le!=null&&le.tiebreakSet||le!=null&&le.timed)&&(ve.score.sets=ve.score.sets.sort((pn,On)=>pn.setNumber-On.setNumber).map((pn,On)=>(On+1===Ls?(Sn!=null&&Sn.tiebreakSet||Sn!=null&&Sn.timed)&&(pn.tiebreakSet=!0):(le!=null&&le.tiebreakSet||le!=null&&le.timed)&&(pn.tiebreakSet=!0),pn)))}if(Array.isArray(Xe)){const{orderedDrawPositions:rn,displayOrder:Ls}=KP({drawPositions:Xe,roundProfile:ot,roundNumber:he}),Sn=(TA=ot==null?void 0:ot[he])==null?void 0:TA.feedRound,le=Ls[0]!==rn[0],On=rn.concat(void 0,void 0).slice(0,2).map((er,Rr)=>{var NA;const Tn=Rr+1,Rc=le?3-Tn:Tn,ym=ZP({drawPositionCollectionAssignment:$i,positionAssignments:F,displaySideNumber:Rc,seedAssignments:c,drawPosition:er,isFeedRound:Sn,sideNumber:Tn}),Pd=(NA=ft.sides)==null?void 0:NA.find(X2=>X2.sideNumber===Tn),bA=ue?(ue-1)*2+Rr+1:void 0,Z2=bA?Tm==null?void 0:Tm[bA]:void 0;return Cd({sourceDrawPositionRange:Z2,...Pd,...ym})});Object.assign(ve,pt({sides:On},!0,!0))}if(r&&ve.sides){const rn=i==null?void 0:i[oa],Ls=le=>{var On;const pn=(On=f==null?void 0:f[le])==null?void 0:On.participant;return pn&&Fu({template:rn==null?void 0:rn.participant,source:pn})};if(ve.sides.filter(Boolean).forEach(le=>{var pn,On,er;if(le.participantId){const Rr=pt(Ls(le.participantId)||r&&Ps({policyDefinitions:$t,participantId:le.participantId,tournamentParticipants:r,internalUse:!0,contextProfile:h}),void 0,!0);if(Rr){if(d!=null&&d.entries){const Tn=d.entries.find(Rc=>Rc.participantId===le.participantId);Tn!=null&&Tn.entryStatus&&(Rr.entryStatus=Tn.entryStatus),Tn!=null&&Tn.entryStage&&(Rr.entryStage=Tn.entryStage)}Object.assign(le,{participant:Rr})}}if((On=(pn=le==null?void 0:le.participant)==null?void 0:pn.individualParticipantIds)!=null&&On.length&&!((er=le.participant.individualParticipants)!=null&&er.length)){const Rr=le.participant.individualParticipantIds.map(Tn=>Ls(Tn)||r&&Ps({policyDefinitions:$t,tournamentParticipants:r,internalUse:!0,contextProfile:h,participantId:Tn}));Object.assign(le.participant,{individualParticipants:Rr})}}),!ve.matchUpType){const{matchUpType:le}=HI({matchUp:ve});le&&Object.assign(ve,{matchUpType:le})}if((h==null?void 0:h.inferGender)&&(!ve.gender||ve.gender===hs)&&((yA=ve.sides)==null?void 0:yA.length)===2&&ve.matchUpType!==we){const le=ve.sides.map(pn=>{var On,er,Rr,Tn;if(ve.matchUpType===Oe)return(er=(On=pn.participant)==null?void 0:On.person)==null?void 0:er.sex;if(((Tn=(Rr=pn.participant)==null?void 0:Rr.individualParticipants)==null?void 0:Tn.length)===2){const Rc=Vt(pn.participant.individualParticipants.map(ym=>{var Pd;return(Pd=ym.person)==null?void 0:Pd.sex})).filter(Boolean);if(Rc.length===1)return Rc[0]}});if(le.filter(Boolean).length===2&&Vt(le).length===1){const pn=le[0];ve.inferredGender=pn}}}if(ve.tieMatchUps){const rn=ve.matchUpStatus===re,Ls=(EA=ve.sides)==null?void 0:EA.map(({participant:Sn,drawPosition:le,sideNumber:pn,lineUp:On})=>{const er=(Sn==null?void 0:Sn.participantType)===we&&Sn;return{teamParticipant:er&&bt({participantRoleResponsibilities:er.participantRoleResponsibilities,participantOtherName:er.participanOthertName,participantName:er.participantName,participantId:er.participantId,teamId:er.teamId}),drawPosition:le,sideNumber:pn,lineUp:On}});ve.tieMatchUps=ve.tieMatchUps.map(Sn=>{const le=ve.matchUpId,On={finishingPositionRange:ve.finishingPositionRange,abbreviatedRoundName:iA,roundNumber:he,roundName:sA};return st({tieDrawPositions:Xe,scheduleVisibilityFilters:ct,sourceDrawPositionRanges:Et,sideLineUps:Ls,drawPositionsRanges:gt,initialRoundOfPlay:Ft,roundNamingProfile:wt,additionalContext:On,appliedPolicies:$t,isCollectionBye:rn,matchUpTieId:le,isRoundRobin:at,roundProfile:ot,matchUp:Sn,event:Ct})})}const oA=ve.sides&&ve.sides.filter(rn=>rn==null?void 0:rn.participantId).length===2,Q2=!ve.winningSide;if(Object.assign(ve,{readyToScore:W&&oA&&Q2,hasContext:!0}),oA){const{allParticipantsCheckedIn:rn,checkedInParticipantIds:Ls}=Fa({matchUp:ve});Object.assign(ve,{allParticipantsCheckedIn:rn,checkedInParticipantIds:Ls})}return Array.isArray(h==null?void 0:h.exclude)&&(h==null||h.exclude.forEach(rn=>delete ve[rn])),ve}}function eU(t){return Object.assign(t,{inContext:!0}),{matchUp:pt(ie(t).matchUp,!1,!0)}}function ie({tournamentParticipants:t,afterRecoveryTimes:e,contextContent:n,contextProfile:r,drawDefinition:s,matchUpsMap:i,matchUpId:o,inContext:c,context:a,event:u}){if(!s)return{error:lt};if(!o)return{error:$e};if(typeof o!="string")return{error:tt};const{structures:l=[]}=lr({drawDefinition:s});r&&!n&&(n=Cs({contextProfile:r,drawDefinition:s}));for(const f of l){const{matchUps:p}=Qt({tournamentParticipants:t,afterRecoveryTimes:e,contextContent:n,drawDefinition:s,contextProfile:r,matchUpsMap:i,inContext:c,structure:f,context:a,event:u}),{matchUp:h}=cI({matchUps:p,matchUpId:o});if(h)return{matchUp:h,structure:f}}return{error:Ye}}function oS({collectionGroups:t=[]}){const e=Object.assign({},...t.filter(r=>(r==null?void 0:r.groupValue)&&(r==null?void 0:r.groupNumber)).map(r=>({[r.groupNumber]:{...r,allGroupMatchUpsCompleted:!0,matchUpsCount:0,sideWins:[0,0],values:[0,0]}}))),n=Object.keys(e).map(r=>vt(r));return{groupValueGroups:e,groupValueNumbers:n}}function La(t){var E,y,b,N;const{sideAdjustments:e=[0,0],separator:n="-",drawDefinition:r,matchUpsMap:s,structure:i,matchUp:o,event:c}=t;if(!Array.isArray(e)||e.length!==2||isNaN(e.reduce((A,C)=>A+C)))return{error:tt};if(!o)return{error:Rn};const a=((E=hn({matchUp:o,drawDefinition:r,structure:i,event:c}))==null?void 0:E.tieFormat)||(t==null?void 0:t.tieFormat);if(!a)return{error:Nu};const u=vn({tieFormat:a});if(u.error)return u;const l=(a==null?void 0:a.collectionDefinitions)||[],f=(o==null?void 0:o.tieMatchUps)||[],p=[0,0],{groupValueGroups:h,groupValueNumbers:d}=oS(a);for(const A of l)qC({collectionDefinition:A,groupValueNumbers:d,groupValueGroups:h,sideTieValues:p,tieMatchUps:f});for(const A of d){const C=h[A],{allGroupMatchUpsCompleted:v,matchUpCount:P,winCriteria:U,groupValue:O,sideWins:D,values:M}=C;let w;if(U!=null&&U.aggregateValue)v&&M[0]!==M[1]&&(w=M[0]>M[1]?1:2);else if(U!=null&&U.valueGoal)w=M.reduce((k,_,F)=>_>=U.valueGoal?F+1:k,void 0);else{const k=Math.floor(P/2)+1;w=D.reduce((_,F,L)=>F>=k?L+1:_,void 0)}w&&(p[w-1]+=O)}const m=p.map((A,C)=>A+e[C]),g={side1Score:m[0],side2Score:m[1],winningSide:void 0},I=m.join(n),S=m.slice().reverse().join(n);let T;if(a!=null&&a.winCriteria){const{valueGoal:A,aggregateValue:C,tallyDirectives:v}=a.winCriteria;if(A){const P=m.map((U,O)=>({sideNumber:O+1,points:U})).find(({points:U})=>U>=A);T=P==null?void 0:P.sideNumber}else C&&f.every(U=>U.matchUpStatus&&We.includes(U.matchUpStatus)||U.winningSide)&&m[0]!==m[1]&&(T=m[0]>m[1]?1:2);if(!T&&v){const P=o.matchUpId,U=o.hasContext?o:((y=s==null?void 0:s.drawMatchUps)==null?void 0:y[P])||r&&((b=ie({inContext:!0,drawDefinition:r,matchUpId:P}))==null?void 0:b.matchUp);if(U){const{completedTieMatchUps:O,order:D}=hf({matchUps:[U]});if(O&&(D!=null&&D.length)){const M=D[0].participantId;T=(N=U.sides.find(({participantId:w})=>w===M))==null?void 0:N.sideNumber}}}}return T&&(g.winningSide=T),{scoreStringSide1:I,scoreStringSide2:S,winningSide:T,set:g}}function Dr(t){if(t)return pt(t,!1,!0)}function Be(t){var p,h;const e=t==null?void 0:t.matchUp,n=(t==null?void 0:t.score)||(e==null?void 0:e.score),r=(p=n==null?void 0:n.sets)==null?void 0:p[0],{side1Score:s,side2Score:i,side1TiebreakScore:o,side2TiebreakScore:c,side1PointScore:a,side2PointScore:u}=r||{},l=s||i||o||c||a||u;return!!(((h=n==null?void 0:n.sets)==null?void 0:h.length)>1||l)}function Ra({matchUpStatus:t}){return UC.includes(t)}function nU({matchUpStatus:t}){return xg.includes(t)}function Yf({matchUpStatus:t}){return OC.includes(t)}function zf({matchUpStatus:t,winningSide:e,tieMatchUps:n,sides:r,score:s}){var a;const i=r==null?void 0:r.find(({participantId:u})=>u),o=(a=n==null?void 0:n.filter(zf))==null?void 0:a.length;return Be({score:s})||o||e&&i||t&&nU({matchUpStatus:t})&&![te,ce,Gr].includes(t)}function Kf(t){var e;return typeof t!="object"?{error:Tt}:typeof t.element!="object"?{error:tt}:t.notes?typeof t.notes!="string"&&!((e=t.notes)!=null&&e.testing)?{error:tt}:(Object.assign(t.element,{notes:t.notes}),{...$}):{error:Tt}}function rU(t){return typeof t!="object"?{error:Tt}:typeof t.element!="object"?{error:tt}:(t.element.notes&&delete t.element.notes,{...$})}function ll(t,e){var i;if(!t)return{error:lt};let n=Date.now();t.updatedAt&&n===new Date(t.updatedAt).getTime()&&(n+=1);const r=new Date(n).toISOString(),s=e==null?void 0:e.filter(Boolean);return t.updatedAt=r,(i=t.structures)==null||i.filter(Boolean).forEach(o=>{(!(s!=null&&s.length)||s!=null&&s.includes(o.structureId))&&(o.updatedAt=r)}),{...$}}function Oi({drawDefinition:t,tournamentId:e,matchUps:n,eventId:r}){return t&&ll(t),Ht({payload:{matchUps:n,tournamentId:e,eventId:r},topic:Pf}),{...$}}function ei({drawDefinition:t,tournamentId:e,matchUpIds:n,eventId:r,action:s}){t&&ll(t),Ht({topic:CI,payload:{tournamentId:e,matchUpIds:n,eventId:r,action:s}});for(const i of n)Og({key:i});return{...$}}function qt({drawDefinition:t,tournamentId:e,structureId:n,context:r,eventId:s,matchUp:i}){return i?(t&&Zt({drawDefinition:t,structureIds:n?[n]:void 0,tournamentId:e,eventId:s}),Ht({topic:UI,payload:{matchUp:i,tournamentId:e,context:r},key:i.matchUpId}),{...$}):(console.log(Rn),{error:Rn})}function sU({tournamentId:t,inContextMatchUp:e}){return e?(Ht({topic:Uf,payload:{inContextMatchUp:e,tournamentId:t},key:e.matchUpId}),{...$}):{error:Rn}}function Ba({tournamentId:t,eventId:e,drawDefinition:n}){return n?(ll(n),Ht({payload:{drawDefinition:n,tournamentId:t,eventId:e},topic:yI,key:n.drawId}),{...$}):(console.log(lt),{error:lt})}function iU({tournamentId:t,eventId:e,drawId:n}){return Ht({payload:{drawId:n,tournamentId:t,eventId:e},topic:vI,key:n}),Og({key:n}),{...$}}function Zt({drawDefinition:t,tournamentId:e,structureIds:n,eventId:r}){return t?(ll(t,n),Ht({payload:{tournamentId:e,eventId:r,drawDefinition:t},topic:PI,key:t.drawId}),{...$}):{error:lt}}function cS({drawDefinition:t,tournamentId:e,structure:n,eventId:r}){if(!t)return{error:lt};if(!n)return{error:Wi};const s=n.seedAssignments,i=n.structureId,o=t.drawId;return Ht({payload:{tournamentId:e,eventId:r,drawId:o,structureId:i,seedAssignments:s},topic:MI,key:t.drawId}),Zt({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:r}),{...$}}function ni({drawDefinition:t,tournamentId:e,structure:n,event:r}){if(!t)return{error:lt};if(!n)return{error:Wi};const s=ee({structure:n}),i=n.structureId,o=t.drawId,c=r==null?void 0:r.eventId;return Ht({topic:OI,payload:{positionAssignments:s,tournamentId:e,structureId:i,eventId:c,drawId:o},key:i}),Zt({structureIds:[i],drawDefinition:t,tournamentId:e,eventId:c}),{...$}}const dl=t=>t==null?void 0:t.participantId;function oU({positionAssignments:t}){const e=(t||[]).filter(dl).map(i=>{const{extension:o}=Ke({element:i,name:rc}),c=vt(o==null?void 0:o.value),a=!isNaN(c)&&c;return a&&{participantId:i.participantId,subOrder:a}}).filter(Boolean),n=e.map(({subOrder:i})=>i),r=Mn(n);return{subOrderMap:Object.assign({},...e.filter(({subOrder:i})=>r[i]===1).map(({participantId:i,subOrder:o})=>({[i]:o})))}}function Jf({positionAssignments:t,tournamentRecord:e,drawDefinition:n,matchUpFormat:r,matchUps:s,event:i}){if(!cr(s))return{error:tt};if(!t)return{error:tt};const{policyDefinitions:o}=Zi({policyTypes:[tI],tournamentRecord:e,drawDefinition:n,event:i}),{subOrderMap:c}=oU({positionAssignments:t}),a=hf({policyDefinitions:o,matchUpFormat:r,subOrderMap:c,matchUps:s});if(a.error)return a;const{participantResults:u,bracketComplete:l,report:f}=a,p=Object.keys(u);return t.forEach(h=>{const{participantId:d}=h;if(p.includes(d)){const m={value:u[d],name:Ys};ae({element:h,extension:m}),u[d].ties||Ar({element:h,name:rc})}else Ar({element:h,name:Ys}),Ar({element:h,name:rc})}),Zt({drawDefinition:n}),{...$,participantResults:u,bracketComplete:l,report:f}}function Qf({participantsProfile:t,participants:e=[]}){const n=pt(e,t==null?void 0:t.convertExtensions,!0),r=n.filter(o=>o.participantType===se),s=n.filter(o=>o.participantType===Fn),i=n.filter(o=>o.participantType===_t);return n.forEach(o=>{if(o.participantType===xt){const{participantId:c}=o;o.groupParticipantIds=[],o.teamParticipantIds=[],o.pairParticipantIds=[],o.groups=[],o.teams=[],r.forEach(a=>{((a==null?void 0:a.individualParticipantIds)||[]).forEach(u=>{var l;u===c&&!((l=o.teamParticipantIds)!=null&&l.includes(a.participantId))&&(o.teamParticipantIds.push(a.participantId),o.teams.push({participantRoleResponsibilities:a.participantRoleResponsibilities,participantOtherName:a.participantOtherName,participantName:a.participantName,participantId:a.participantId,teamId:a.teamId}))})}),i.forEach(a=>{((a==null?void 0:a.individualParticipantIds)||[]).forEach(u=>{u===c&&!o.pairParticipantIds.includes(a.participantId)&&o.pairParticipantIds.push(a.participantId)})}),s.forEach(a=>{((a==null?void 0:a.individualParticipantIds)||[]).forEach(u=>{u===c&&!o.groupParticipantIds.includes(a.participantId)&&(o.groupParticipantIds.push(a.participantId),o.groups.push({participantRoleResponsibilities:a.participantRoleResponsibilities,participantOtherName:a.participantOtherName,participantName:a.participantName,participantId:a.participantId}))})})}}),n}const Zf=t=>e=>t[e],Xf=(t=[])=>t.map(Qe).filter(Boolean),xa=(t=[])=>t.map(fe).filter(Boolean),fe=(t={})=>Zf(t)("participantId"),cU=(t={})=>Zf(t)("drawPosition"),Qe=(t={})=>Zf(t)("matchUpId");function aU({structureMatchUps:t,matchUp:e}){const{roundNumber:n,roundPosition:r}=e,s=t.filter(o=>o.roundNumber===n&&!o.matchUpTieId),i=t.filter(o=>o.roundNumber===n+1&&!o.matchUpTieId);if(i.length){let o;return i.length===s.length?o=i.find(c=>c.roundPosition===r):i.length===s.length/2&&(o=i.find(c=>c.roundPosition===Math.ceil(r/2))),{matchUp:o}}return{message:"no progression found"}}function tp({sourceRoundMatchUpCount:t,inContextDrawMatchUps:e,sourceRoundPosition:n,drawDefinition:r,targetLink:s}){var v;if(!s)return{error:Km};const{target:{structureId:i,feedProfile:o,groupedOrder:c,roundNumber:a,positionInterleave:u}}=s,{structure:l}=Ot({drawDefinition:r,structureId:i}),{positionAssignments:f}=ee({structure:l}),h=(e==null?void 0:e.filter(P=>P.structureId===(l==null?void 0:l.structureId))).filter(P=>P.roundNumber===a&&!P.matchUpTieId),d=h.length,m=ht(1,d+1),g=d/t;let I=Math.ceil(g*n),S=1-n%2;if(u!=null&&u.interleave&&g!==.5){const P=u.offset+(n-1)*u.interleave,U=n+P;I=Math.ceil(U/2),S=1-U%2}let T=m,E=m[I-1];const y=nS({groupedOrder:c,roundPositionsCount:m.length}),b=(y==null?void 0:y.length)||1;if(b<=m.length){const P=d/b,U=Ge(m,P);o===uo&&U.forEach(O=>O.reverse()),T=(y==null?void 0:y.length)&&(y==null?void 0:y.map(O=>U[O-1]).flat())||T}o===Ni?E=T[I-1]:o===uo?((!(y!=null&&y.length)||b>m.length)&&(I=h.length+1-I),E=T[I-1]):o===KI&&ze()&&console.log(bg,{feedProfile:o});const N=E&&h.reduce((P,U)=>U.roundPosition===E?U:P,void 0);let A;N!=null&&N.feedRound?(S=0,A=Math.min(...(N.drawPositions||[]).filter(Boolean))):A=((v=N==null?void 0:N.drawPositions)==null?void 0:v.length)===2&&(N==null?void 0:N.drawPositions[S]);const C=f==null?void 0:f.find(({drawPosition:P})=>P===A);if(C){const{extension:P}=Ke({element:C,name:Vu});if(P!=null&&P.value)return{disabledDrawPosition:A}}return{matchUp:N,targetDrawPosition:A,matchUpDrawPositionIndex:S}}function uU({drawDefinition:t,roundNumber:e,structureId:n}){if(!t)return{error:lt};if(!n)return{error:En};const{links:r}=$a({drawDefinition:t,structureId:n}),s=r.source.reduce((o,c)=>!c.source.roundNumber||c.source.roundNumber===e?o.concat(c):o,[]),i=r.target.reduce((o,c)=>!c.target.roundNumber||c.target.roundNumber===e?o.concat(c):o,[]);return{links:{source:s,target:i}}}function ep({finishingPositions:t,linkCondition:e,linkType:n,source:r}){var i;const s=r.find(o=>{var u,l;const c=!((u=o.source)!=null&&u.finishingPositions)||!t||tn(t,(l=o.source)==null?void 0:l.finishingPositions);return e===o.linkCondition&&c&&o.linkType===n});return[vi,lo].includes(s==null?void 0:s.linkType)&&!((i=s==null?void 0:s.source)!=null&&i.roundNumber)?G({result:{error:tt},stack:"getTargetLink",context:s}):s}function $a({drawDefinition:t,structureId:e,roundNumber:n}){return t?e?{links:(t.links||[]).filter(Boolean).reduce((i,o)=>{var c,a;return((c=o.source)==null?void 0:c.structureId)===e&&(!n||o.source.roundNumber===n)&&(i.source=i.source.concat(o)),((a=o.target)==null?void 0:a.structureId)===e&&(!n||o.target.roundNumber===n)&&(i.target=i.target.concat(o)),i},{source:[],target:[]})}:{error:En}:{error:lt}}function gn({inContextDrawMatchUps:t=[],useTargetMatchUpIds:e,inContextMatchUp:n,drawDefinition:r,matchUpId:s}){let i=n;t.length&&!i&&(i=t.find(a=>a.matchUpId===s));const{structure:o}=Ot({structureId:i==null?void 0:i.structureId,drawDefinition:r});return(o==null?void 0:o.finishingPosition)===fo?lU({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:r,structure:o,matchUp:i}):dU({matchUp:i})}function lU({inContextDrawMatchUps:t,useTargetMatchUpIds:e,drawDefinition:n,structure:r,matchUp:s}){var U,O,D;const{winnerMatchUpId:i,loserMatchUpId:o}=s,{links:c}=uU({roundNumber:s.roundNumber,structureId:r.structureId,drawDefinition:n}),a=c==null?void 0:c.source,u=ep({source:a,linkType:vi}),l=ep({linkCondition:fs,linkType:lo,source:a});let f=ep({source:a,linkType:lo});const p=l&&f;f||(f=l);const h=(U=u==null?void 0:u.target)==null?void 0:U.feedProfile,d=(O=f==null?void 0:f.target)==null?void 0:O.feedProfile,m=(D=l==null?void 0:l.target)==null?void 0:D.feedProfile;let g,I,S,T,E,y,b,N,A,C;if(e&&(i||o)&&(b=i&&h!==Cr&&t.find(({matchUpId:M})=>M===i),T=o&&d!==Cr&&t.find(({matchUpId:M})=>M===o),b||T))return{matchUp:s,targetLinks:{loserTargetLink:f,winnerTargetLink:u},targetMatchUps:{loserMatchUp:T,winnerMatchUp:b}};const{roundPosition:v}=s;C=C||t.filter(M=>M.structureId===r.structureId);const P=C.reduce((M,w)=>w.roundNumber===s.roundNumber&&!w.matchUpTieId?M+1:M,0);return f&&!T&&d!==Cr&&({matchUpDrawPositionIndex:y,targetDrawPosition:E,matchUp:T}=tp({targetLink:f,sourceRoundMatchUpCount:P,inContextDrawMatchUps:t,sourceRoundPosition:v,drawDefinition:n})),p&&m!==Cr&&({matchUpDrawPositionIndex:S,targetDrawPosition:I,matchUp:g}=tp({targetLink:l,sourceRoundMatchUpCount:P,inContextDrawMatchUps:t,sourceRoundPosition:v,drawDefinition:n})),u&&!b&&h!==Cr&&({matchUpDrawPositionIndex:A,targetDrawPosition:N,matchUp:b}=tp({targetLink:u,sourceRoundMatchUpCount:P,inContextDrawMatchUps:t,sourceRoundPosition:v,drawDefinition:n})),b||(C=C||t.filter(M=>M.structureId===r.structureId),{matchUp:b}=aU({structureMatchUps:C,matchUp:s})),bt({matchUp:s,targetLinks:{loserTargetLink:f,winnerTargetLink:u,byeTargetLink:l},targetMatchUps:{winnerMatchUpDrawPositionIndex:A,loserMatchUpDrawPositionIndex:y,byeMatchUpDrawPositionIndex:S,winnerTargetDrawPosition:N,loserTargetDrawPosition:E,byeTargetDrawPosition:I,winnerMatchUp:b,loserMatchUp:T,byeMatchUp:g},targetMatchUpIds:!!(i||o)})}function dU({matchUp:t}){return{targetLinks:{loserTargetLink:void 0,winnerTargetLink:void 0},targetMatchUps:{loserMatchUp:void 0,winnerMatchUp:void 0},matchUp:t}}function fU({drawDefinition:t,inContextDrawMatchUps:e}){const n={};return e.forEach(r=>{var a,u,l,f,p;const{matchUpId:s,structureId:i,drawPositions:o=[]}=r,{structure:c}=Ot({drawDefinition:t,structureId:i});if((c==null?void 0:c.finishingPosition)===uc){const{roundNumber:h}=r,d=h&&vt(h)+1,m=c.matchUps||[],{roundMatchUps:g}=Cn({matchUps:m});if(d&&(g!=null&&g[d])){const I=o.sort().map((S,T)=>{const E=g[d].find(y=>{var b;return(b=y.drawPositions)==null?void 0:b.includes(S)});return{matchUpId:E==null?void 0:E.matchUpId,roundNumber:d,schedule:E==null?void 0:E.schedule,sideNumber:T+1,structureName:c.structureName}});Object.assign(r,{sidesTo:I})}}else{const h=gn({useTargetMatchUpIds:!0,inContextDrawMatchUps:e,inContextMatchUp:r,drawDefinition:t,matchUpId:s});let{winnerMatchUp:d}=h.targetMatchUps;const{loserMatchUp:m}=h.targetMatchUps;!r.winnerMatchUpId&&d&&(r.winnerMatchUpId=d.matchUpId),!r.loserMatchUpId&&m&&(r.loserMatchUpId=m.matchUpId);const g=np({upcomingMatchUp:d});let I=np({upcomingMatchUp:m});if(r.matchUpStatus!==re&&(m==null?void 0:m.matchUpStatus)===re){const{matchUp:T}=aS({matchUp:m,drawDefinition:t,inContextDrawMatchUps:e})||{};I=T&&np({upcomingMatchUp:T})||I}const S=(a=r.schedule)==null?void 0:a.timeAfterRecovery;if(S&&((u=g==null?void 0:g.schedule)!=null&&u.scheduledTime&&jt(g.schedule.scheduledTime)<jt(S)&&(n[g.matchUpId]=r.matchUpId,g.schedule.scheduleConflict=r.matchUpId),(l=I==null?void 0:I.schedule)!=null&&l.scheduledTime&&jt(I.schedule.scheduledTime)<jt(S)&&(n[I.matchUpId]=r.matchUpId,I.schedule.scheduleConflict=r.matchUpId)),Object.assign(r,{winnerTo:g,loserTo:I}),(f=r.drawPositions)!=null&&f.filter(Boolean).length){const T=(p=h.targetLinks)==null?void 0:p.loserTargetLink,E=(T==null?void 0:T.linkCondition)===fs,y=pU(r);if(y.length){const b=xa(d==null?void 0:d.sides),N=xa(m==null?void 0:m.sides),C=y.find(({participantId:U})=>b.includes(U))?[]:y,P=y.find(({participantId:U})=>N.includes(U))?[]:y;m&&E&&P.length<2&&P.push({bye:!0,tbd:!0}),C!=null&&C.length&&d&&(!h.targetMatchUpIds&&d&&(d=e.find(({matchUpId:U})=>U===d.matchUpId)),d.potentialParticipants||(d.potentialParticipants=[]),d.potentialParticipants.push(C)),P!=null&&P.length&&m&&(h.targetMatchUpIds||(d=e.find(({matchUpId:U})=>U===m.matchUpId)),m.potentialParticipants||(m.potentialParticipants=[]),m.potentialParticipants.push(P))}}}}),Object.keys(n).length&&e.forEach(r=>{Object.keys(n).includes(r.matchUpId)&&(r.schedule.scheduleConflict=n[r.matchUpId])}),{scheduleConflictMatchUpIds:n}}function pU(t){var e;return((e=t==null?void 0:t.sides)==null?void 0:e.map(({participant:n,participantId:r,qualifier:s})=>n||r&&{participantId:r}||s&&{qualifier:s}).filter(Boolean))||[]}function aS({matchUp:t,drawDefinition:e,inContextDrawMatchUps:n}){const{matchUpId:r,matchUpStatus:s,structureId:i}=t||{};if(!t||!i||(t==null?void 0:t.matchUpStatus)===Le)return{matchUp:t};if(s===re){let o;if(t.winnerMatchUpId)o=n.find(({matchUpId:c})=>c===t.winnerMatchUpId);else{const c=gn({inContextDrawMatchUps:n,drawDefinition:e,matchUpId:r});({winnerMatchUp:o}=(c==null?void 0:c.targetMatchUps)||{})}return aS({matchUp:o,drawDefinition:e,inContextDrawMatchUps:n})}return{matchUp:void 0}}function np(t){if(t!=null&&t.upcomingMatchUp)return(({matchUpId:e,structureId:n,schedule:r,roundNumber:s,roundPosition:i,structureName:o})=>({matchUpId:e,structureId:n,schedule:r,roundNumber:s,roundPosition:i,structureName:o}))(t.upcomingMatchUp)}function Va({requireParticipants:t=!0,scheduleVisibilityFilters:e,tournamentAppliedPolicies:n,tournamentParticipants:r,afterRecoveryTimes:s,policyDefinitions:i,tournamentRecord:o,matchUpFilters:c,contextFilters:a,contextContent:u,participantMap:l,scheduleTiming:f,contextProfile:p,drawDefinition:h,exitProfiles:d,matchUpsMap:m,structureId:g,inContext:I,structure:S,context:T,event:E}){!S&&g&&({structure:S}=Ot({drawDefinition:h,structureId:g}));const y=Qt({tournamentAppliedPolicies:n,scheduleVisibilityFilters:e,tournamentParticipants:r,afterRecoveryTimes:s,policyDefinitions:i,tournamentRecord:o,drawDefinition:h,matchUpFilters:c,contextFilters:a,contextProfile:p,contextContent:u,participantMap:l,scheduleTiming:f,exitProfiles:d,matchUpsMap:m,structure:S,inContext:I,context:T,event:E}),b=[],N=[],A=[],C=[],v=[];if(y.error)return y;const{matchUps:P}=y,{assignedPositions:U}=ke({structure:S}),O=U==null?void 0:U.filter(M=>M.participantId).map(M=>M.drawPosition);let D;return P.filter(M=>{var k;const w=((k=c==null?void 0:c.matchUpTypes)==null?void 0:k.length)===1&&c.matchUpTypes[0]===Jt;return!(M.matchUpType!==Jt&&w)}).forEach(M=>{var B,R,x,q;if(M.matchUpStatus===zn){b.push(M);return}M.matchUpType===Jt&&(D=!0);const w=M.collectionId,k=w&&((B=M.sides)==null?void 0:B.every(V=>V.participantId)),_=!w&&((R=M.drawPositions)==null?void 0:R.filter(Boolean).length)===2,F=!w&&((x=M.drawPositions)==null?void 0:x.every(V=>O==null?void 0:O.includes(V))),L=U==null?void 0:U.filter(V=>V.bye).map(V=>V.drawPosition),W=!w&&((q=M.drawPositions)==null?void 0:q.find(V=>L==null?void 0:L.includes(V))),H=MC.includes(M.matchUpStatus)&&(k||_&&(!t||F));return W?v.push(M):Qo({matchUp:M})?N.push(M):H?A.push(M):C.push(M)}),{includesTeamMatchUps:D,abandonedMatchUps:b,completedMatchUps:N,upcomingMatchUps:A,pendingMatchUps:C,byeMatchUps:v,structure:S}}function xe(t){const e="getAllDrawMatchUps";Object.assign(t,{requireParticipants:!1});const n=To(t);if(n.error)return G({result:n,stack:e});const{abandonedMatchUps:r,completedMatchUps:s,upcomingMatchUps:i,pendingMatchUps:o,byeMatchUps:c,matchUpsMap:a}=n;return{matchUps:(r??[]).concat(...s??[],...i??[],...o??[],...c??[]),matchUpsMap:a}}function To(t){if(!(t!=null&&t.drawDefinition))return{error:lt};let{tournamentParticipants:e,contextContent:n,matchUpsMap:r}=t;const{scheduleVisibilityFilters:s,tournamentAppliedPolicies:i,requireParticipants:o,participantsProfile:c,afterRecoveryTimes:a,policyDefinitions:u,tournamentRecord:l,contextFilters:f,contextProfile:p,drawDefinition:h,matchUpFilters:d,scheduleTiming:m,participantMap:g,nextMatchUps:I,inContext:S,context:T,event:E}=t;let y=[],b=[],N=[],A=[],C=[];p&&!n&&(n=Cs({policyDefinitions:u,tournamentRecord:l,contextProfile:p,event:E})),!(e!=null&&e.length)&&l&&(e=l==null?void 0:l.participants,(S||c!=null&&c.withGroupings)&&(e!=null&&e.length)&&(e=Qf({participants:e,participantsProfile:c})));const{structures:v}=lr({drawDefinition:h});if(!v)return{error:Te};r||(r=ln({drawDefinition:h}));const P=h&&Wf({drawDefinition:h}).exitProfiles;v.forEach(D=>{const{byeMatchUps:M=[],pendingMatchUps:w=[],upcomingMatchUps:k=[],completedMatchUps:_=[],abandonedMatchUps:F=[]}=Va({matchUpFilters:I?void 0:d,contextFilters:I?void 0:f,inContext:S||I||f,tournamentAppliedPolicies:i,scheduleVisibilityFilters:s,tournamentParticipants:e,requireParticipants:o,afterRecoveryTimes:a,policyDefinitions:u,tournamentRecord:l,participantMap:g,scheduleTiming:m,contextContent:n,contextProfile:p,drawDefinition:h,exitProfiles:P,matchUpsMap:r,structure:D,context:T,event:E});y=y.concat(...F),b=b.concat(..._),N=N.concat(...k),A=A.concat(...w),C=C.concat(...M)});const U=D=>(!d&&!I&&!f||(d&&(D=go({matchUps:D,...d})),f&&(D=go({matchUps:D,...f,processContext:!0}))),D),O={abandonedMatchUps:U(y),completedMatchUps:U(b),upcomingMatchUps:U(N),pendingMatchUps:U(A),byeMatchUps:U(C),matchUpsMap:r,...$};if(I){const D=typeof I=="object"||{abandoned:!0,completed:!0,upcoming:!0,pending:!0,bye:!0},{abandoned:M,completed:w,upcoming:k,pending:_,bye:F}=D,L=[].concat(...M&&y||[],...w&&b||[],...k&&N||[],..._&&A||[],...F&&C||[]);fU({inContextDrawMatchUps:L,drawDefinition:h})}return O}const fl={matchUpStatus:Le,matchUpStatusCodes:[],score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0},matchUpFormat:void 0,winningSide:void 0};function Zr({matchUpStatusCodes:t,removeWinningSide:e,tournamentRecord:n,drawDefinition:r,matchUpFormat:s,matchUpStatus:i,removeScore:o,winningSide:c,matchUpId:a,matchUp:u,event:l,notes:f,score:p}){var b,N,A,C,v,P,U,O;const h="modifyMatchUpScore";let d;const m=u.matchUpType===Jt;if(m&&r){if(a&&u.matchUpId!==a){const D=ie({drawDefinition:r,matchUpId:a,event:l});if(!D.matchUp)return{error:Ye};({matchUp:u,structure:d}=D)}}else u.matchUpId!==a&&console.log("!!!!!");i&&[ce,Fe].includes(i)||o?Object.assign(u,{...fl}):p&&(u.score=p);const g=i&&(u==null?void 0:u.matchUpStatus)===te&&i!==te;i&&(u.matchUpStatus=i),s&&(u.matchUpFormat=s),t&&(u.matchUpStatusCodes=t),c&&(u.winningSide=c),e&&(u.winningSide=void 0),!d&&r&&({structure:d}=ie({drawDefinition:r,matchUpId:a,event:l})),i&&!u.winningSide&&Be(u)&&!We.includes(i)&&![Jo,mi].includes(i)&&(u.matchUpStatus=pe.InProgress);let I;if(g&&((b=u==null?void 0:u.processCodes)!=null&&b.length)||i===te){const D=(N=ge({tournamentRecord:n,drawDefinition:r,structure:d,event:l}))==null?void 0:N.appliedPolicies;I=(C=(A=D==null?void 0:D[Xo])==null?void 0:A.processCodes)==null?void 0:C.incompleteAssignmentsOnDefault}if(!u.collectionId){const D=(d==null?void 0:d.structureType)===mn,M=Qr({drawDefinition:r,structure:d});if(qf({drawDefinition:r,structure:d})||M||D){const w=F=>{s=m?"SET1-S:T100":s??u.matchUpFormat??(F==null?void 0:F.matchUpFormat)??(r==null?void 0:r.matchUpFormat)??(l==null?void 0:l.matchUpFormat);const L=m?{matchUpTypes:[Jt]}:void 0,{matchUps:W}=Qt({afterRecoveryTimes:!1,inContext:!0,matchUpFilters:L,structure:F,event:l});return M&&(F.positionAssignments=Vt(W.flatMap(j=>(j.sides??[]).map(H=>H.participantId)).filter(Boolean)).map(j=>({participantId:j}))),Jf({positionAssignments:F.positionAssignments,tournamentRecord:n,drawDefinition:r,matchUpFormat:s,matchUps:W,event:l})},k=D&&d.structures.find(F=>F==null?void 0:F.matchUps.find(L=>L.matchUpId===a)),_=w(k||d);if(_.error)return G({result:_,stack:h})}}if(f){const D=Kf({element:u,notes:f});if(D.error)return G({result:D,stack:h})}const S=n==null?void 0:n.tournamentId,T=$r().topics.includes(Uf),E=(T||I)&&ln({drawDefinition:r}),y=E&&((v=xe({matchUpFilters:{matchUpIds:[a]},nextMatchUps:!0,tournamentRecord:n,inContext:!0,drawDefinition:r,matchUpsMap:E}).matchUps)==null?void 0:v[0]);if(T&&y&&sU({tournamentId:S,inContextMatchUp:y}),Array.isArray(I)&&y&&!((P=y.sides)!=null&&P.every(({participantId:D})=>D)))if(i===te)u.processCodes?u.processCodes.push(...I):u.processCodes=I;else for(const D of I||[]){const M=D&&((U=u==null?void 0:u.processCodes)==null?void 0:U.lastIndexOf(D));(O=u==null?void 0:u.processCodes)==null||O.splice(M,1)}return qt({eventId:l==null?void 0:l.eventId,context:h,drawDefinition:r,tournamentId:S,matchUp:u}),{...$}}function ms({tournamentRecord:t,exitWhenNoValues:e,drawDefinition:n,matchUpStatus:r,removeScore:s,matchUpsMap:i,matchUpId:o,event:c}){var C,v;const a=ie({drawDefinition:n,event:c,matchUpId:o});if(a.error)return a;if(!a.matchUp)return{error:Ye};const{matchUp:u,structure:l}=a;if(!u.tieMatchUps)return{error:qn};const{extension:f}=xn({name:ec,element:u});if(f!=null&&f.value)if(s)Ar({element:u,name:ec});else return{...$,score:u.score};const p=(C=hn({drawDefinition:n,structure:l,matchUp:u,event:c}))==null?void 0:C.tieFormat;u.tieFormat=Dr(p);const h=La({drawDefinition:n,matchUpsMap:i,structure:l,matchUp:u,event:c}),{winningSide:d,set:m,scoreStringSide1:g,scoreStringSide2:I}=h,S=(m==null?void 0:m.side1Score)||(m==null?void 0:m.side2Score);if(e&&!u.score&&!S)return{...$};const T={scoreStringSide1:g,scoreStringSide2:I,sets:m?[m]:[]},E=d&&[1,2].includes(d),y=E&&De||zf({matchUpStatus:r??u.matchUpStatus,tieMatchUps:u.tieMatchUps,winningSide:u.winningSide,score:T})&&Gr||Le,b=!!(u.winningSide&&!E),N=u.tieMatchUps.find(({score:P,winningSide:U,matchUpStatus:O})=>{var D;return((D=P==null?void 0:P.sets)==null?void 0:D.length)&&(P.sets[0].side1Score||P.sets[0].side2Score)||O&&We.includes(O)||U});let A;if(u.tieFormat&&!E&&!N){const P=(v=hn({drawDefinition:n,structure:l,event:c}))==null?void 0:v.tieFormat;P&&JSON.stringify(p)===JSON.stringify(P)&&(u.tieFormatId=void 0,u.tieFormat=void 0,A=!0)}return Zr({matchUpStatus:y,score:T,removeWinningSide:b,tournamentRecord:t,drawDefinition:n,removeScore:s,winningSide:d,matchUpId:o,matchUp:u,event:c}),{...$,score:T,removeWinningSide:b,tieFormatRemoved:A,winningSide:d}}function gs(t){const{winnerFirst:e=!0,addOutcomeString:n,reversed:r=!1,matchUpStatus:s,matchUpFormat:i,autoComplete:o,winningSide:c,sets:a}=t;if(!a)return{error:Tt,info:"missing sets"};const u=i&&yn(i),{bestOf:l,finalSetFormat:f,setFormat:p}=u||{},d=r||!(!e||!c||c===1),m=n?hU({matchUpStatus:s}):"",g=(a==null?void 0:a.sort(mU).map(I).filter(Boolean).join(" "))||"";if(!m)return g;if(c===2)return`${m} ${g}`;return`${g} ${m}`;function I(S){const E=l&&S.setNumber===l&&f?f:p,y=F=>Me(F==null?void 0:F.side1Score)||Me(F==null?void 0:F.side2Score),b=F=>Me(F==null?void 0:F.side1TiebreakScore)||Me(F==null?void 0:F.side2TiebreakScore),N=(E==null?void 0:E.tiebreakSet)||!y(S)&&b(S),{side1Score:A,side2Score:C,side1TiebreakScore:v,side2TiebreakScore:P}=S,U=v||(Me(v)||o?0:""),O=P||(Me(P)||o?0:"");if(N)return`[${(d?[O,U]:[U,O]).join("-")}]`;const D=Math.min(U,O),M=D?`(${D})`:"",w=A||(Me(A)||o?0:""),k=C||(Me(C)||o?0:"");let _=d?`${[k,w].join("-")}${M}`:`${[w,k].join("-")}${M}`;return["-"," "].includes(_)&&(_=""),_}}function hU({matchUpStatus:t}){const e={[In]:"RET",[ce]:"WO",[en]:"DF/DF",[Fe]:"WO/WO",[mi]:"SUS",[zn]:"ABN",[te]:"DEF",[ia]:"DR"};return t&&e[t]||""}function mU(t,e){return t.setNumber-e.setNumber}function gU({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:n,winningSide:r,score:s}){const i=(s==null?void 0:s.sets)||[],c=((i==null?void 0:i.filter(b=>b==null?void 0:b.winningSide))||[]).reduce((b,N)=>{const{winningSide:A}=N;if(!A)return b;const C=A-1;return b[C]++,b},[0,0]),a=r?r-1:void 0,u=a!==void 0?1-a:void 0,l=a!==void 0&&c[a],f=u!==void 0&&c[u],p=e?yn(e):void 0,h=Math.max(...c),d=Mn(c)[h],m=p==null?void 0:p.bestOf,g=m&&Math.ceil(m/2)||1,I=n||t,S=I&&[te,In,ce].includes(I),T=!p||!i.length||i.every((b,N)=>{const A=N+1,C=A===m,v=A===i.length,{side1Score:P,side2Score:U,side1TiebreakScore:O,side2TiebreakScore:D,winningSide:M}=b,w=Math.max(P||0,U||0),k=O||D,{finalSetFormat:_,setFormat:F}=p,L=C&&_||F;if(k){const{tiebreakTo:j,NoAD:H}=(L==null?void 0:L.tiebreakFormat)||{},B=Math.max(O||0,D||0);if(H&&B>j||B<j&&M&&(v&&!S||!v))return!1}return L.setTo?!(!L.noTiebreak&&w>L.setTo+1):!0}),E=(!e||h===g)&&d===1&&c.indexOf(h)+1||void 0;return{valid:T&&(r&&l>f&&r===E||!r&&!E||S)}}function rp({existingMatchUpStatus:t,matchUpFormat:e,matchUpStatus:n,winningSide:r,score:s}){if(typeof s!="object")return{error:tt};const{sets:i,scoreStringSide1:o,scoreStringSide2:c}=s,a="scoreString must be a string!";if(o!==void 0&&typeof o!="string")return{error:tt,info:a};if(c!==void 0&&typeof c!="string")return{error:tt,info:a};if(i!==void 0&&!Array.isArray(i))return{error:tt,info:sn("sets")};if(i!=null&&i.length){const u=i.map(f=>f==null?void 0:f.setNumber).filter(Boolean);if(u.length!==Vt(u).length)return{error:tt,info:"setNumbers not unique"};for(const f of i){const{side1Score:p,side2Score:h,side1TiebreakScore:d,side2TiebreakScore:m,side1PointScore:g,side2PointScore:I,winningSide:S,setNumber:T}=f;if(![[p,h],[d,m],[g,I]].filter(b=>b.some(N=>N!==void 0)).every(b=>b.every(N=>oe(N))))return{error:tt,info:"non-numeric values"};if(![T,S].filter(b=>b!==void 0).every(b=>oe(b)))return{error:tt,info:"non-numeric values"};if(S&&![1,2].includes(S))return{error:tt,info:"winningSide must be 1 or 2"}}const{valid:l}=gU({existingMatchUpStatus:t,matchUpStatus:n,matchUpFormat:e,winningSide:r,score:s});if(!l)return{error:sv,info:"score is invalid for matchUpFormat or winningSide does not match calculated winningSide"}}return{valid:!0}}function sp({analysis:t,set:e}){const n=ip({set:e}),{isDecidingSet:r,isTiebreakSet:s,matchUpScoringFormat:i}=t;return uS({matchUpScoringFormat:i,isDecidingSet:r,isTiebreakSet:s,set:e})&&n}function uS(t){let e=t.matchUpScoringFormat;const{ignoreTiebreak:n=!1,matchUpFormat:r,isTiebreakSet:s,isDecidingSet:i,set:o}=t;if(!o)return{error:Tt};e=e||r;const c=i&&e.finalSetFormat||(e==null?void 0:e.setFormat)||{},{side1Score:a,side2Score:u}=o,{NoAD:l,setTo:f,tiebreakAt:p,tiebreakFormat:h}=c,d=h==null?void 0:h.NoAd,m=ip({set:o}),g=Math.abs(a-u),I=a>=f||u>=f,S=s||a>=f&&u>=f||p&&p<f&&(a===p||u===p),T=n||S&&(m===1&&o.side1TiebreakScore>o.side2TiebreakScore||m===2&&o.side2TiebreakScore>o.side1TiebreakScore),y=g>=(l||S&&(p&&!s||s&&d)?1:2);return(I&&(y||S)||s)&&(!S||T)}function ip({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}}const yo=" ",op="DEF",IU="COMPLETED",lS="WO",SU="WO/WO",dS="ABN",fS="SUS",pS="RET",hS="INT",mS=[pS,op,lS,SU,dS,fS,hS],cp="DEFAULTED",gS="WALKOVER",IS="ABANDONED",SS="SUSPENDED",TS="RETIRED",yS="INTERRUPTED",TU=[TS,cp,gS],Eo="()",Mi="[]",yU=["up","left","shift+tab"],EU=["enter","down","tab","right"],pl="backspace",ES="r",bS="s",NS="a",AS="d",vS="w",CS="i",ap=[ES,AS,vS,NS,bS,CS],hl="space",up=["[","("],ml=[...yU,...EU,hl,"]"],PS="-",bU="/",bo=PS,Is=PS,US=[bU],NU=0,OS=["0","1","2","3","4","5","6","7","8","9"].concat(ap),AU=OS.map(t=>`shift+${t}`),vU=[bo,pl].concat(ml,US),CU=[OS,AU,vU].join(",");function PU({analysis:t,scoreString:e,sets:n,value:r}){let s;if(!(n!=null&&n.length))return{sets:[]};const i=n[n.length-1];r=vt(r);const{validSide2Score:o,requiresTiebreak:c}=UU({analysis:t,set:i,value:r});if(o){s=!0,e=(e||"")+r,i.side2Score=r;const a=sp({analysis:t,set:n[n.length-1]});if(i.winningSide=a||void 0,c){const u=Eo.split("")[0];e+=u}else t.isDecidingSet||(e+=yo)}return{sets:n,scoreString:e,updated:s}}function UU({analysis:t,set:e={},value:n}){const r=t.isDecidingSet&&t.matchUpScoringFormat.finalSetFormat||t.matchUpScoringFormat.setFormat,{tiebreakAt:s,setTo:i,NoAD:o}=r,{side1Score:c}=e;let a,u;return s&&s<i?c===s?a=n<=i:a=n<=s:c===i?o?a=n<i:a=n<=i+1:c===i-1?o?a=n<=i:a=n<=i+1:c===i+1?a=n===i||n===i-1:a=n<=i,a&&(s&&s<i?u=c===i&&n===s||c===s&&n===i:u=c>=i&&n>=i&&c!==n),{validSide2Score:a,requiresTiebreak:u}}function dc({scoreString:t,lowSide:e,outcome:n}){if({scoreString:t}=MS({scoreString:t}),e===2){const s=(t&&t[t.length-1])!==yo?yo:"";return t+s+n}else return n+yo+t}function MS({scoreString:t}){if(!t)return{scoreString:""};let e=!1;for(const n of mS){const r=t==null?void 0:t.indexOf(n);r===0?t=t.slice(n.length+1).trim()+yo:r>0&&(t=t.slice(0,r)),r>=0&&(e=!0)}return t!=null&&t.trim()||(t=""),{scoreString:t,removed:e}}function lp({analysis:t,scoreString:e,sets:n,lowSide:r}){var m,g,I;let s,i;if(!e)return{scoreString:e,sets:n};const{scoreString:o,removed:c}=MS({scoreString:e});if(e=o,c)return{scoreString:e,sets:n,outcomeRemoved:!0};let a=n[n.length-1]||{};const u=Object.values(a).filter(S=>S!==void 0).length;a.setNumber&&u===1&&(n=n.slice(0,n.length-1),a=n[n.length-1]||{});const{tiebreakSet:l}=t.setFormat,{tiebreakTo:f,NoAD:p}=l||{},{isTiebreakEntry:h}=fc({brackets:Mi,scoreString:e}),d=MU(e);if(d>=0){s=e.slice(0,d);const{isTiebreakEntry:S}=fc({brackets:Eo,scoreString:s}),{lastOpenBracketIndex:T,isTiebreakEntry:E}=fc({brackets:Mi,scoreString:s}),y=s&&s[s.length-1].trim(),b=s&&!isNaN(y);let N=t.isIncompleteSetScore;if(h&&E){const C=s.slice(T+1).split(Is),v=(C==null?void 0:C.length)>0&&C[0]!==void 0&&!isNaN(parseInt(C[0]))&&parseInt(C[0])||void 0,P=(C==null?void 0:C.length)>1&&C[1]!==void 0&&parseInt(C[1])||void 0,U=[v,P];if(P){const O=r===1?1:0;U[O]=((U==null?void 0:U[1-O])||0)+(p?1:2),(U[O]||0)<f&&(U[O]=f),s=e.slice(0,T+1),s+=U.join(Is)}else v!==void 0?(s=e.slice(0,T+1),s+=v):(s=e.slice(0,T),N=!0);a.side1TiebreakScore=U[0]||0,a.side2TiebreakScore=U[1]||0}if(s.length||(s=void 0),N){const A=(m=a.side1Score)==null?void 0:m.toString();if(A){const C=A==null?void 0:A.slice(0,A.length-1);a.side1Score=!isNaN(C)&&parseInt(C)||void 0,a.side1Score===void 0&&(a.side2Score=void 0)}t.isTimedSet?(i=a.side1Score?n:(n==null?void 0:n.slice(0,n.length-1))||[],i[n.length-1]=a):i=(n==null?void 0:n.slice(0,n.length-1))||[]}else if(b){const A=(g=a.side2Score)==null?void 0:g.toString(),C=(I=a.side1Score)==null?void 0:I.toString();if(!t.isTiebreakEntry&&!t.isMatchTiebreak)if(a.side2Score){const v=A==null?void 0:A.slice(0,A.length-1);a.side2Score=!isNaN(v)&&parseInt(v)||void 0}else{const v=C==null?void 0:C.slice(0,C.length-1);a.side1Score=!isNaN(v)&&parseInt(v)||void 0}t.isTimedSet?a.side1Score?(i=n||[],i[n.length-1]=a):i=(n==null?void 0:n.slice(0,n.length-1))||[]:(i=n||[],i[n.length-1]=a),i[i.length-1]&&Object.assign(i[i.length-1],{winningSide:void 0})}else S?(i=n||[],Object.assign(i[i.length-1]||{},{winningSide:void 0,side1TiebreakScore:void 0,side2TiebreakScore:void 0})):(h&&!E?i=(n==null?void 0:n.slice(0,n.length-1))||[]:(i=n,i[n.length-1]=a),h||(i[i.length-1].side2Score=0,i[i.length-1].winningSide=void 0));return{scoreString:s,sets:i}}return{scoreString:e,sets:n}}function fc({brackets:t=Eo,scoreString:e}){if(!e)return{};const[n,r]=t.split(""),s=e.split(""),i=Math.max(...Br(n,s)),o=Math.max(...Br(r,s));return{isTiebreakEntry:i>o,lastOpenBracketIndex:i}}function OU({scoreString:t}){if(!t)return!1;const e=t&&t[t.length-1].trim(),n=t&&!isNaN(e),[r,s]=Mi.split(""),i=t.split(""),o=Math.max(...Br(r,i)),c=Math.max(...Br(s,i)),a=Math.max(...Br(Is,i));return n&&o>c&&a>o}function MU(t){return t.split("").reduce((r,s,i)=>(s.match(/\d+/g)&&r.push(i),r),[]).pop()}function DS(t){const{lowValue:e=0,NoAD:n=!1,tiebreakTo:r}=t||{},s=n?1:2;return e+1>=r?e+s:parseInt(r)}function wS({matchUpFormat:t,matchUpStatus:e,winningSide:n,sets:r}){const s=yn(t),{bestOf:i}=s,o=Math.ceil(i/2),c=r==null?void 0:r.reduce((u,l)=>{const{winningSide:f}=l;return f&&u[f-1]++,u},[0,0]);let a=(c==null?void 0:c.indexOf(o))+1||void 0;return TU.includes(e)&&n&&(a=n),{matchUpWinningSide:a}}function kS({lowSide:t,value:e,sets:n,scoreString:r,winningSide:s,matchUpStatus:i}){let o;return e===ES?r?(o=!0,r=dc({scoreString:r,lowSide:t,outcome:pS}),s=t===2?1:2,i=TS):(o=!0,r=dc({scoreString:r,lowSide:t,outcome:op}),s=t===2?1:2,i=cp):e===AS?(o=!0,r=dc({scoreString:r,lowSide:t,outcome:op}),s=t===2?1:2,i=cp):e===vS?(o=!0,n=[],r=lS,s=t===2?1:2,i=gS):e===bS&&r?(o=!0,r=dc({scoreString:r,lowSide:t,outcome:fS}),i=SS,s=void 0):e===NS?(o=!0,r=dc({scoreString:r,lowSide:t,outcome:dS}),i=IS,s=void 0):e===CS&&r&&(o=!0,r=dc({scoreString:r,lowSide:t,outcome:hS}),i=yS,s=void 0),{updated:o,sets:n,scoreString:r,matchUpStatus:i,winningSide:s}}function DU(t){let{sets:e,info:n,scoreString:r,winningSide:s,matchUpStatus:i}=t;const{analysis:o,lowSide:c,value:a}=t;let u,l;!(e!=null&&e.length)&&a!==pl&&(e=[{setNumber:1}]);const f=e.length-1;if(ap.includes(a)){const p=e[e.length-1]||{},{side1Score:h,side2Score:d}=p;h&&!d?n="missing side2Score":o.finalSetIsComplete||s?n="final set is already complete":o.isIncompleteSetScore?n="incomplete set scoreString":o.isIncompleteSetScore||({sets:e,scoreString:r,winningSide:s,matchUpStatus:i,updated:u}=kS({lowSide:c,value:a,sets:e,scoreString:r,matchUpStatus:i,winningSide:s}))}else if(a===pl){if({scoreString:r,sets:e,outcomeRemoved:l}=lp({analysis:o,scoreString:r,sets:e}),(r==null?void 0:r.trim())===""&&(r=r.trim()),r||(e=[]),l){const p=e[e.length-1]||{},{side1Score:h,side2Score:d}=p;if(h&&d){const m=h>d&&1||d>h&&2||void 0;m&&(p.winningSide=m,e.push({setNumber:e.length+1}))}}i=void 0,s=void 0,u=!0}else if(o.hasOutcome)n="has outcome";else{if(s)return{sets:e,scoreString:r,winningSide:s,matchUpStatus:i,updated:!1,info:"matchUp is complete"};if(a===hl){const p=e[e.length-1]||{},{side1Score:h,side2Score:d}=p,m=h>d&&1||d>h&&2||void 0;m&&!s&&!o.isIncompleteSetScore&&(e[e.length-1].winningSide=m,e.push({setNumber:e.length+1}),r+=" ",u=!0)}else if(a===bo&&e[f].side1Score!==void 0&&e[f].side2Score===void 0&&r&&o.isNumericEnding)r+="-",e[f].side2Score=0,i=void 0,s=void 0,u=!0;else if(!isNaN(a)){let p;if(e[f].side2Score===void 0){const h=vt((e[f].side1Score||0).toString()+a).toString().slice(0,2);e[f].side1Score=vt(h),p=e[f].side1Score.toString(),u=!0}else{const h=vt((e[f].side2Score||0).toString()+a).toString().slice(0,2);e[f].side2Score=vt(h),p=[e[f].side1Score,e[f].side2Score].join("-"),u=!0}if(u){const h=(e.slice(0,f)||[]).filter(d=>d).map(d=>{const{side1Score:m,side2Score:g}=d;return[m,g].join("-")}).join(" ");h?r=h+" "+p:r=p}}}return{sets:e,scoreString:r,winningSide:s,matchUpStatus:i,info:n,updated:u}}function wU({analysis:t,auto:e,lowSide:n,scoreString:r="",sets:s,value:i}){var p;let o,c;const{tiebreakSet:{tiebreakTo:a,NoAD:u}}=t.setFormat,[l]=Mi.split("");if(t.isMatchTiebreakEntry||(r+=l),s[t.setNumber-1]){const{lastOpenBracketIndex:h}=fc({brackets:Mi,scoreString:r}),m=(r.slice((h??0)+1)+(e?"":i)).split(Is);if((((p=m[n-1])==null?void 0:p.length)||0)>=2)c="tiebreak digit limit";else if(e){n===1&&(m[0]=(m[0]||"")+i),n===2&&(m[1]=(m[1]||"")+i);const I=[m[0]||0,m[1]||0].map(E=>vt(E)),S=n===1?1:0;I[S]=I[1-S]+(u?1:2),I[S]<a&&(I[S]=a);const T=s[s.length-1];T.side1TiebreakScore=I[0],T.side2TiebreakScore=I[1],r=r.slice(0,(h??0)+1),r+=I.join(Is),o=!0}else{const I=[m[0]||0,m[1]||0].map(T=>vt(T)),S=s[s.length-1];S.side1TiebreakScore=I[0],S.side2TiebreakScore=I[1],r+=i,o=!0}}else{const h=DS({lowValue:vt(i||0),tiebreakTo:a,NoAD:u}),d=[vt(i),h];n===2&&d.reverse();const m={side1TiebreakScore:d[0],side2TiebreakScore:d[1],setNumber:(s==null?void 0:s.length)+1||1};s.push(m),r+=d.join(Is),o=!0}return{info:c,scoreString:r,sets:s,updated:o}}function kU({analysis:t,lowSide:e,scoreString:n,value:r}){const{setTo:s,tiebreakAt:i,NoAD:o}=(t==null?void 0:t.setFormat)||{},c=r===parseInt(i||s);if(i&&i<s&&r>i)return{scoreString:n};if(o&&r===s||r>s)return{scoreString:n};const a=m(),u=[r,a];e===2&&u.reverse();const f=Eo.split("")[0],p=u.join(bo)+(c?f:yo);n=(n||"")+p;const h={side1Score:u[0],side2Score:u[1]},d=sp({analysis:t,set:h});return h.winningSide=d||void 0,{scoreString:n,set:h};function m(){return c?r+1:r+1===s?r+(o?1:2):s}}function _U({matchUpFormat:t,scoreString:e,winningSide:n,value:r,sets:s}){var H,B,R;const o=(((H=s==null?void 0:s.filter(x=>x==null?void 0:x.winningSide))==null?void 0:H.length)||0)+(n?0:1),c=yn(t),a=o===(c==null?void 0:c.bestOf),u=a&&(c==null?void 0:c.finalSetFormat)||(c==null?void 0:c.setFormat)||{},l=(u==null?void 0:u.timed)||(c==null?void 0:c.timed),f=a&&s[(c==null?void 0:c.bestOf)-1],p=f==null?void 0:f.winningSide,{isTiebreakEntry:h}=fc({brackets:Eo,scoreString:e}),{isTiebreakEntry:d}=fc({brackets:Mi,scoreString:e}),m=h||d,g=!!u.tiebreakSet,I=(B=e==null?void 0:e[e.length-1])==null?void 0:B.trim(),S=e&&!isNaN(I),T=!m&&I===bo,E=h&&up.includes(I),y=d&&up.includes(I),b=d&&I===Is,N=e==null?void 0:e.split(""),[A]=Mi.split(""),C=N&&Math.max(...Br(A,N)),v=N&&Math.max(...Br(Is,N)),P=N&&v>C,U=(R=s[s.length-1])==null?void 0:R.winningSide,O=(s==null?void 0:s.length)&&!U,D=mS.find(x=>(e==null?void 0:e.indexOf(x))>=0),M=!isNaN(r),w=r===hl,k=ml.includes(r),_=e==null?void 0:e.split("").find(x=>up.includes(x)),F=k&&d&&!y&&(b||!OU({scoreString:e}));return{isTiebreakSetValue:g&&M,matchUpScoringFormat:c,setNumber:o,setFormat:u,matchTiebreakHasJoiner:P,isGameScoreEntry:O,isSpace:w,isCloser:k,isTiebreakCloser:k&&_&&m&&S,isDecidingSet:a,isTiebreakSet:g,isTimedSet:l,isNumericEnding:S,isNumericValue:M,hasOpener:_,hasOutcome:D,finalSet:f,finalSetIsComplete:p,lastSetIsComplete:U,isInvalidSetTiebreakValue:w&&m&&E,isInvalidMatchTiebreakValue:F,isTiebreakEntry:m,isSetTiebreakEntry:h,isMatchTiebreakEntry:d,isIncompleteSetScore:T,isIncompleteSetTiebreak:E,isIncompleteMatchTiebreak:y,isPartialMatchTiebreakValue:b}}function FU(t){let{lowSide:e=1,value:n}=t,{scoreString:r,sets:s,winningSide:i,matchUpStatus:o}=t;const{matchUpFormat:c,shiftFirst:a,auto:u=!0}=t;let l,f;const p=a&&e===2||!a&&e===1;if(!CU.includes(n))return{updated:!1,info:"invalid key"};a&&(e=3-e);const{matchUpWinningSide:h}=wS({sets:s,winningSide:i,matchUpStatus:o,matchUpFormat:c});i=h;const d=_U({value:n,winningSide:i,scoreString:r,sets:s,matchUpFormat:c});if(US.includes(n)&&(n=bo),d.hasOpener&&d.isTiebreakEntry&&!d.isTiebreakSet&&p&&vt(n)===0&&(d.isTiebreakCloser=!0),ml.includes(n)&&d.hasOpener&&(n=""),ml.includes(n)&&(n=hl),d.lastSetIsComplete){const m=(r==null?void 0:r.length)&&r[r.length-1];r&&m!==" "&&(r+=" ")}if(d.isTimedSet)({info:f,sets:s,scoreString:r,updated:l,matchUpStatus:o,winningSide:i}=DU({analysis:d,lowSide:e,scoreString:r,sets:s,matchUpStatus:o,winningSide:i,value:n}));else if(ap.includes(n))d.finalSetIsComplete||i?f="final set is already complete":!d.isTiebreakEntry&&!d.isIncompleteSetScore?{sets:s,scoreString:r,matchUpStatus:o,winningSide:i,updated:l}=kS({lowSide:e,sets:s,scoreString:r,matchUpStatus:o,winningSide:i,value:n}):d.isTiebreakEntry||d.isIncompleteSetScore?f="incomplete set scoreString or tiebreak entry":console.log("handle case",{value:n});else if(n===pl)l=!0,{scoreString:r,sets:s}=lp({analysis:d,scoreString:r,sets:s,lowSide:e}),r||(s=[]),o=void 0,i=void 0;else if(d.hasOutcome)f="has outcome";else if(n===bo&&!d.isMatchTiebreakEntry)(!d.isSetTiebreakEntry||d.isSetTiebreakEntry&&!d.isNumericEnding)&&(l=!0,{scoreString:r,sets:s}=lp({analysis:d,scoreString:r,sets:s,lowSide:e}),o=void 0);else if(n===Is&&d.isMatchTiebreakEntry&&!d.isSetTiebreakEntry)d.matchTiebreakHasJoiner?f="existing joiner":d.isNumericEnding&&(l=!0,r+=Is);else if([bo,Is].includes(n))f="invalid location for joiner";else{if(i)return{updated:!1,info:"matchUp is complete"};if(d.isIncompleteSetScore)d.isNumericValue&&({sets:s,scoreString:r,updated:l}=PU({analysis:d,scoreString:r,sets:s,value:n}));else if(d.isInvalidMatchTiebreakValue)f="invalid matchUp tiebreak character";else if(d.isInvalidSetTiebreakValue)f="invalid set tiebreak character";else if(d.isTiebreakCloser){const m=d.isSetTiebreakEntry?Eo:Mi,g=m.split("").reverse()[0],I=m.split("")[0],S=s[s.length-1],{tiebreakFormat:T}=d.setFormat,{tiebreakTo:E,NoAD:y}=T||{},b=ip({set:S});if(!d.isTiebreakSet){const A=parseInt(r.split(I).reverse()[0]),C=DS({lowValue:A,tiebreakTo:E,NoAD:y});b===1?(S.side1TiebreakScore=C,S.side2TiebreakScore=A):(S.side1TiebreakScore=A,S.side2TiebreakScore=C)}r=(r||"")+g,d.isDecidingSet||(r+=yo);const N=sp({analysis:d,set:S});S.winningSide=N||void 0,l=!0}else if(d.isTiebreakSetValue)({info:f,scoreString:r,sets:s,updated:l}=wU({analysis:d,auto:u,lowSide:e,scoreString:r,sets:s,value:n}));else if(d.isSetTiebreakEntry){const[m]=Eo.split(""),g=Math.max(...Br(m,r.split(""))),I=r.slice(g+1),S=I&&vt(I)===NU,T=vt(I?I+n:n),{tiebreakFormat:E}=d.setFormat,{tiebreakTo:y,NoAD:b}=E||{};!S&&I.length<2?b&&T>y-1?f="invalid low value for NoAD tiebreak":(l=!0,r=(r||"")+n):f=S?"tiebreak begins with zero":"tiebreak digit limit"}else if(d.isCloser)f=`invalid key: ${n}`;else if(d.isGameScoreEntry)f="game scoreString entry";else if(d.lastSetIsComplete||!s.length){l=!0;const{scoreString:m,set:g}=kU({analysis:d,lowSide:e,scoreString:r,value:vt(n)});g&&(g.setNumber=(s==null?void 0:s.length)+1||1),s=(s==null?void 0:s.concat(g).filter(Boolean))||[g],r=m||void 0}else console.log("error: unknown outcome")}if(l){s=s==null?void 0:s.filter(Boolean);const{matchUpWinningSide:m}=wS({sets:s,winningSide:i,matchUpStatus:o,matchUpFormat:c});return i=m,m&&(!o||[Le,us].includes(o))?(o=IU,s=s.filter(g=>{const{side1Score:I,side2Score:S,side1TiebreakScore:T,side2TiebreakScore:E}=g;return I||S||T||E})):r&&!i&&![SS,IS,yS].includes(o)&&(o=void 0),{updated:l,scoreString:r,sets:s,winningSide:i,matchUpStatus:o,info:f}}return{updated:l,scoreString:r,sets:s,winningSide:i,matchUpStatus:o,info:f}}function LU({matchUpScoringFormat:t,isDecidingSet:e,isTiebreakSet:n,setObject:r}){if(!r)return;const s=_S({set:r});return RU({matchUpScoringFormat:t,isDecidingSet:e,isTiebreakSet:n,set:r})&&s||void 0}function RU({ignoreTiebreak:t=!1,matchUpScoringFormat:e,matchUpFormat:n,isTiebreakSet:r,isDecidingSet:s,set:i}){if(!i)return{error:Tt,info:"missing set"};e=e||n&&yn(n);const o=s&&e.finalSetFormat||(e==null?void 0:e.setFormat)||{},{side1Score:c,side2Score:a}=i,{setTo:u,tiebreakAt:l,tiebreakFormat:f}=o,p=f==null?void 0:f.NoAd,h=_S({set:i}),d=Math.abs(c-a),m=c>=u||a>=u,g=r||c>=u&&a>=u||l&&l<u&&(c===l||a===l),I=t||g&&(h===1&&i.side1TiebreakScore>i.side2TiebreakScore||h===2&&i.side2TiebreakScore>i.side1TiebreakScore),T=d>=(g&&(l&&!r||r&&p)?1:2);return(m&&(T||g)||r)&&(!g||I)}function _S({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 gl(t){const{setObject:e,matchUpScoringFormat:n}=t;if(!e)return{error:Gd};const{setNumber:r}=e||{},{bestOf:s}=n||{},i=!!(r&&s&&r===s),o=i&&(n==null?void 0:n.finalSetFormat)||(n==null?void 0:n.setFormat),c=!!(o!=null&&o.tiebreakSet),a=!!(o!=null&&o.timed),u=!c&&!a,l=!!(r&&s&&r<=s),f=[e==null?void 0:e.side1Score,e==null?void 0:e.side2Score],p=[e==null?void 0:e.side1PointScore,e==null?void 0:e.side2PointScore],h=[e==null?void 0:e.side1TiebreakScore,e==null?void 0:e.side2TiebreakScore],d=f.filter(w=>w!==void 0).length,m=p.filter(w=>w!==void 0).length,g=h.filter(w=>w!==void 0).length,I=f==null?void 0:f.filter(w=>!isNaN(w)).length,S=h==null?void 0:h.filter(w=>!isNaN(w)).length,{tiebreakAt:T}=o||{},E=T&&f.filter(w=>w>=T).length===2,y=E&&(f[0]>f[1]&&1||f[1]>f[0]&&2||void 0),b=!!(S&&!I),N=!!(e!=null&&e.winningSide),{error:A,result:C}=BU({setObject:e,setFormat:o,sideGameScores:f,sideTiebreakScores:h}),{error:v,result:P}=xU({setObject:e,setFormat:o,sideTiebreakScores:h}),U=u&&!b&&C||c&&b&&P,O=l&&!(c&&!b)&&!(u&&b)&&(!N||U),D=LU({isDecidingSet:i,isTiebreakSet:b,matchUpScoringFormat:n,setObject:e}),M={expectTiebreakSet:c,expectTimedSet:a,hasTiebreakCondition:E,isCompletedSet:N,isDecidingSet:i,isTiebreakSet:b,isValidSet:O,isValidSetNumber:l,isValidSetOutcome:U,leadingSide:y,setFormat:o,sideGameScores:f,sideGameScoresCount:d,sidePointScores:p,sidePointScoresCount:m,sideTiebreakScores:h,sideTiebreakScoresCount:g,winningSide:D};return(e==null?void 0:e.winningSide)!==void 0&&(b?(M.isValidTiebreakSetOutcome=P,P||(M.tiebreakSetError=v)):(M.isValidStandardSetOutcome=C,C||(M.standardSetError=A))),M}function BU({setObject:t,setFormat:e,sideGameScores:n,sideTiebreakScores:r}){if(!t)return{result:!1,error:Gd};const s=!!(e!=null&&e.tiebreakSet),i=!!(e!=null&&e.timed);if(!e||s||i)return{result:!1,error:tt};if(!((n==null?void 0:n.filter(P=>!isNaN(P)).length)===2))return{result:!1,error:ig};const{setTo:c,tiebreakAt:a,tiebreakFormat:u,NoAD:l}=e||{};if(!!!(c&&(n!=null&&n.find(P=>P>=c))))return{result:!1,error:ig};const p=[1,2].includes(t==null?void 0:t.winningSide);if(!t||!p)return{result:!1,error:og};const h=(t==null?void 0:t.winningSide)-1,d=1-h,m=n[h],g=n[d],I=m-g;if(!(m>g))return{result:!1,error:{message:"winningSide game scoreString is not high"}};const T=a&&u,E=(r==null?void 0:r.filter(P=>!isNaN(P)).length)===2,y=r==null?void 0:r[h],b=r==null?void 0:r[d],N=a&&n.filter(P=>P>=a).length===2;if(T){const{NoAD:P,tiebreakTo:U}=u;if(N){if(I>1)return{result:!1,error:{message:"invalid winning game scoreString (5)"}};if(!E)return{result:!1,error:{message:"invalid tiebreak scores (1)"}};if(isNaN(U))return{result:!1,error:{message:"tiebreakTo error"}};if(!!!(U&&(r!=null&&r.find(L=>L>=U))))return{result:!1,error:{message:"invalid tiebreak scores (2)"}};const M=a<c?c:c+1;if(m>M)return{result:!1,error:{message:"invalid winning game scoreString (1)"}};if(!y||!b||y<b)return{result:!1,error:{message:"winningSide tiebreak value is not high"}};const w=P?1:2,k=y-b,_=b>=U-1;if(k&&_&&k<w)return{result:!1,error:{message:"invalid tiebreak scores (3)"}}}if(m>c&&!N)return{result:!1,error:{message:"invalid winning game scoreString (2)"}}}const A=l?1:2,C=g>=c-1;return I&&C&&!N&&I<A?{result:!1,error:{message:"invalid winning game scoreString (3)"}}:I>A&&m>c?{result:!1,error:{message:"invalid winning game scoreString (4)"}}:{result:!0}}function xU({setObject:t,setFormat:e,sideTiebreakScores:n}){if(!t)return{result:!1,error:Gd};const r=!!(e!=null&&e.tiebreakSet),s=!!(e!=null&&e.timed);if(!e||!r||s)return{result:!1,error:{message:"not tiebreak set"}};const i=[1,2].includes(t==null?void 0:t.winningSide);if(!t||!i)return{result:!1,error:og};const{tiebreakSet:o}=e||{},{NoAD:c,tiebreakTo:a}=o||{};if(!((n==null?void 0:n.filter(T=>!isNaN(T)).length)===2))return{result:!1,error:{message:"invalid tiebreak scores (1)"}};if(isNaN(a))return{result:!1,error:{message:"tiebreakTo error"}};if(!!!(n!=null&&n.find(T=>T>=a)))return{result:!1,error:{message:"invalid tiebreak scores (2)"}};const f=(t==null?void 0:t.winningSide)-1,p=1-f,h=n[f],d=n[p];if(!h||!d||h<d)return{result:!1,error:{message:"winningSide tiebreak value is not high"}};const m=c?1:2,g=h-d,I=d>=a-1;return g&&I&&g<m?{result:!1,error:{message:"invalid tiebreak scores (3)"}}:{result:!0}}function $U(t){if(!(t!=null&&t.score))return{error:Tt};const{sets:e}=t.score,n=e.map(i=>{const{side1TiebreakScore:o,side2TiebreakScore:c,winningSide:a,side1Score:u,side2Score:l,setNumber:f}=i;return bt({winningSide:a?3-a:void 0,side1TiebreakScore:c,side2TiebreakScore:o,side1Score:l,side2Score:u,setNumber:f})}),r=gs({sets:n}),s=gs({sets:n,reversed:!0});return{reversedScore:{sets:n,scoreStringSide1:r,scoreStringSide2:s},...$}}const FS=t=>{const{isSide1:e,lowValue:n,setTo:r,tiebreakAt:s,NoAD:i}=t;if(n===void 0)return!1;let o=vt(n);(o==null?void 0:o.toString().length)>2&&(o=parseInt(o.toString().slice(0,2))),s&&s<r&&o>s&&(o=s);let c;return i&&!s?c=o<r?r:r-1:c=o+1<r&&r||s&&s<r&&o===s&&r||!s&&o+2||r+1,[e?o:c,e?c:o]},dp=t=>{const{isSide1:e,lowValue:n,tiebreakTo:r,tiebreakNoAd:s}=t;if(n===void 0)return!1;let i=typeof n=="string"?parseInt(n):n;(i==null?void 0:i.toString().length)>2&&(i=parseInt(i.toString().slice(0,2))),s&&i>r-1&&(i=r-1);const o=VU({lowValue:i,NoAD:s,tiebreakTo:r});return[e?i:o,e?o:i]};function VU(t){const{lowValue:e,NoAD:n,tiebreakTo:r}=t,s=n?1:2;return e+1>=r?e+s:r}const LS={stringifyMatchUpFormat:wd,isValidMatchUpFormat:nr,parseMatchUpFormat:yn,generateTieMatchUpScore:La,getTiebreakComplement:dp,updateTieMatchUpScore:ms,generateScoreString:gs,checkSetIsComplete:uS,validateTieFormat:vn,getSetComplement:FS,scoreHasValue:Be,keyValueScore:FU,validateScore:rp,reverseScore:$U,analyzeSet:gl};function RS(t){return t&&typeof String.fromCodePoint<"u"?t.toUpperCase().replace(/./g,e=>String.fromCodePoint(e.charCodeAt(0)+127397)):t}function jU(t){const e=Object.assign({},...ri.filter(n=>n.ioc).map(n=>({[n.ioc]:n.iso})));return RS(e[t])}const ri=[{ioc:"",iso2:"",iso:"",label:"NONE",phone:""},{ioc:"AND",iso2:"AD",iso:"AND",label:"Andorra",phone:"376"},{ioc:"UAE",iso2:"AE",iso:"ARE",label:"United Arab Emirates",phone:"971"},{ioc:"AFG",iso2:"AF",iso:"AFG",label:"Afghanistan",phone:"93"},{ioc:"ANT",iso2:"AG",iso:"ATG",label:"Antigua and Barbuda",phone:"1-268"},{ioc:"AIA",iso2:"AI",iso:"AIA",label:"Anguilla",phone:"1-264"},{ioc:"ALB",iso2:"AL",iso:"ALB",label:"Albania",phone:"355"},{ioc:"ARM",iso2:"AM",iso:"ARM",label:"Armenia",phone:"374"},{ioc:"ANG",iso2:"AO",iso:"AGO",label:"Angola",phone:"244"},{ioc:"",iso2:"AQ",iso:"ATA",label:"Antarctica",phone:"672"},{ioc:"ARG",iso2:"AR",iso:"ARG",label:"Argentina",phone:"54"},{ioc:"ASA",iso2:"AS",iso:"ASM",label:"American Samoa",phone:"1-684"},{ioc:"AUT",iso2:"AT",iso:"AUT",label:"Austria",phone:"43"},{ioc:"AUS",iso2:"AU",iso:"AUS",label:"Australia",phone:"61",suggested:!0},{ioc:"ARU",iso2:"AW",iso:"ABW",label:"Aruba",phone:"297"},{ioc:"AZE",iso2:"AZ",iso:"AZE",label:"Azerbaijan",phone:"994"},{ioc:"BIH",iso2:"BA",iso:"BIH",label:"Bosnia and Herzegovina",phone:"387"},{ioc:"BAR",iso2:"BB",iso:"BRB",label:"Barbados",phone:"1-246"},{ioc:"BAN",iso2:"BD",iso:"BGD",label:"Bangladesh",phone:"880"},{ioc:"BEL",iso2:"BE",iso:"BEL",label:"Belgium",phone:"32"},{ioc:"BUR",iso2:"BF",iso:"BFA",label:"Burkina Faso",phone:"226"},{ioc:"BUL",iso2:"BG",iso:"BGR",label:"Bulgaria",phone:"359"},{ioc:"BRN",iso2:"BH",iso:"BHR",label:"Bahrain",phone:"973"},{ioc:"BDI",iso2:"BI",iso:"BDI",label:"Burundi",phone:"257"},{ioc:"BEN",iso2:"BJ",iso:"BEN",label:"Benin",phone:"229"},{ioc:"",iso2:"BL",iso:"BLM",label:"Saint Barthelemy",phone:"590"},{ioc:"BER",iso2:"BM",iso:"BMU",label:"Bermuda",phone:"1-441"},{ioc:"BRU",iso2:"BN",iso:"BRN",label:"Brunei Darussalam",phone:"673"},{ioc:"BOL",iso2:"BO",iso:"BOL",label:"Bolivia",phone:"591"},{ioc:"BRA",iso2:"BR",iso:"BRA",label:"Brazil",phone:"55"},{ioc:"BAH",iso2:"BS",iso:"BHS",label:"Bahamas",phone:"1-242"},{ioc:"BHU",iso2:"BT",iso:"BTN",label:"Bhutan",phone:"975"},{ioc:"",iso2:"BV",iso:"BVT",label:"Bouvet Island",phone:"47"},{ioc:"BOT",iso2:"BW",iso:"BWA",label:"Botswana",phone:"267"},{ioc:"BLR",iso2:"BY",iso:"BLR",label:"Belarus",phone:"375"},{ioc:"BIZ",iso2:"BZ",iso:"BLZ",label:"Belize",phone:"501"},{ioc:"CAN",iso2:"CA",iso:"CAN",label:"Canada",phone:"1",suggested:!0},{ioc:"",iso2:"CC",iso:"CCK",label:"Cocos (Keeling) Islands",phone:"61"},{ioc:"CGO",iso2:"CD",iso:"COG",label:"Congo, Republic of the",phone:"242"},{ioc:"CAF",iso2:"CF",iso:"CAF",label:"Central African Republic",phone:"236"},{ioc:"COD",iso2:"CG",iso:"CGD",label:"Congo, Democratic Republic of the",phone:"243"},{ioc:"SUI",iso2:"CH",iso:"CHE",label:"Switzerland",phone:"41"},{ioc:"CIV",iso2:"CI",iso:"CIV",label:"Cote d'Ivoire",phone:"225"},{ioc:"COK",iso2:"CK",iso:"COK",label:"Cook Islands",phone:"682"},{ioc:"CHI",iso2:"CL",iso:"CHL",label:"Chile",phone:"56"},{ioc:"CMR",iso2:"CM",iso:"CMR",label:"Cameroon",phone:"237"},{ioc:"CHN",iso2:"CN",iso:"CHN",label:"China",phone:"86"},{ioc:"COL",iso2:"CO",iso:"COL",label:"Colombia",phone:"57"},{ioc:"CRC",iso2:"CR",iso:"CRI",label:"Costa Rica",phone:"506"},{ioc:"CUB",iso2:"CU",iso:"CUB",label:"Cuba",phone:"53"},{ioc:"CPV",iso2:"CV",iso:"CPV",label:"Cape Verde",phone:"238"},{ioc:"CUW",iso2:"CW",iso:"CUW",label:"Curacao",phone:"599"},{ioc:"CXR",iso2:"CX",iso:"CXR",label:"Christmas Island",phone:"61"},{ioc:"CYP",iso2:"CY",iso:"CYP",label:"Cyprus",phone:"357"},{ioc:"CZE",iso2:"CZ",iso:"CZE",label:"Czech Republic",phone:"420"},{ioc:"GER",iso2:"DE",iso:"DEU",label:"Germany",phone:"49",suggested:!0},{ioc:"DJI",iso2:"DJ",iso:"DJI",label:"Djibouti",phone:"253"},{ioc:"DEN",iso2:"DK",iso:"DNK",label:"Denmark",phone:"45"},{ioc:"DMA",iso2:"DM",iso:"DMA",label:"Dominica",phone:"1-767"},{ioc:"DOM",iso2:"DO",iso:"DOM",label:"Dominican Republic",phone:"1-809"},{ioc:"ALG",iso2:"DZ",iso:"DZA",label:"Algeria",phone:"213"},{ioc:"ECU",iso2:"EC",iso:"ECU",label:"Ecuador",phone:"593"},{ioc:"EST",iso2:"EE",iso:"ESE",label:"Estonia",phone:"372"},{ioc:"EGY",iso2:"EG",iso:"EGY",label:"Egypt",phone:"20"},{ioc:"",iso2:"EH",iso:"ESH",label:"Western Sahara",phone:"212"},{ioc:"ERI",iso2:"ER",iso:"ERI",label:"Eritrea",phone:"291"},{ioc:"ESP",iso2:"ES",iso:"ESP",label:"Spain",phone:"34"},{ioc:"ETH",iso2:"ET",iso:"ETH",label:"Ethiopia",phone:"251"},{ioc:"FIN",iso2:"FI",iso:"FIN",label:"Finland",phone:"358"},{ioc:"FIJ",iso2:"FJ",iso:"FJI",label:"Fiji",phone:"679"},{ioc:"FLK",iso2:"FK",iso:"FLK",label:"Falkland Islands (Malvinas)",phone:"500"},{ioc:"FSM",iso2:"FM",iso:"FSM",label:"Micronesia, Federated States of",phone:"691"},{ioc:"FAR",iso2:"FO",iso:"FRO",label:"Faroe Islands",phone:"298"},{ioc:"FRA",iso2:"FR",iso:"FRA",label:"France",phone:"33",suggested:!0},{ioc:"GAB",iso2:"GA",iso:"GAB",label:"Gabon",phone:"241"},{ioc:"GBR",iso2:"GB",iso:"GBR",label:"United Kingdom",phone:"44"},{ioc:"GRN",iso2:"GD",iso:"GRD",label:"Grenada",phone:"1-473"},{ioc:"GEO",iso2:"GE",iso:"GEO",label:"Georgia",phone:"995"},{ioc:"FGU",iso2:"GF",iso:"GUF",label:"French Guiana",phone:"594"},{ioc:"",iso2:"GG",iso:"GGY",label:"Guernsey",phone:"44"},{ioc:"",iso2:"GH",iso:"GHA",label:"Ghana",phone:"233"},{ioc:"GIB",iso2:"GI",iso:"GIB",label:"Gibraltar",phone:"350"},{ioc:"GRL",iso2:"GL",iso:"GRL",label:"Greenland",phone:"299"},{ioc:"GAM",iso2:"GM",iso:"GMB",label:"Gambia",phone:"220"},{ioc:"GUI",iso2:"GN",iso:"GIN",label:"Guinea",phone:"224"},{ioc:"GUD",iso2:"GP",iso:"GLP",label:"Guadeloupe",phone:"590"},{ioc:"GEQ",iso2:"GQ",iso:"GNQ",label:"Equatorial Guinea",phone:"240"},{ioc:"GRE",iso2:"GR",iso:"GRC",label:"Greece",phone:"30"},{ioc:"",iso2:"GS",iso:"SGS",label:"South Georgia and the South Sandwich Islands",phone:"500"},{ioc:"GUA",iso2:"GT",iso:"GTM",label:"Guatemala",phone:"502"},{ioc:"GUM",iso2:"GU",iso:"GUM",label:"Guam",phone:"1-671"},{ioc:"GBS",iso2:"GW",iso:"GNB",label:"Guinea-Bissau",phone:"245"},{ioc:"GUY",iso2:"GY",iso:"GUY",label:"Guyana",phone:"592"},{ioc:"HKG",iso2:"HK",iso:"HKG",label:"Hong Kong",phone:"852"},{ioc:"",iso2:"HM",iso:"HMD",label:"Heard Island and McDonald Islands",phone:"672"},{ioc:"HON",iso2:"HN",iso:"HND",label:"Honduras",phone:"504"},{ioc:"CRO",iso2:"HR",iso:"HRV",label:"Croatia",phone:"385"},{ioc:"HAI",iso2:"HT",iso:"HTI",label:"Haiti",phone:"509"},{ioc:"HUN",iso2:"HU",iso:"HUN",label:"Hungary",phone:"36"},{ioc:"INA",iso2:"ID",iso:"IDN",label:"Indonesia",phone:"62"},{ioc:"IRL",iso2:"IE",iso:"IRL",label:"Ireland",phone:"353"},{ioc:"ISR",iso2:"IL",iso:"ISR",label:"Israel",phone:"972"},{ioc:"",iso2:"IM",iso:"IMN",label:"Isle of Man",phone:"44"},{ioc:"IND",iso2:"IN",iso:"IND",label:"India",phone:"91"},{ioc:"",iso2:"IO",iso:"IOT",label:"British Indian Ocean Territory",phone:"246"},{ioc:"IRQ",iso2:"IQ",iso:"IRQ",label:"Iraq",phone:"964"},{ioc:"IRI",iso2:"IR",iso:"IRN",label:"Iran, Islamic Republic of",phone:"98"},{ioc:"ISL",iso2:"IS",iso:"ISL",label:"Iceland",phone:"354"},{ioc:"ITA",iso2:"IT",iso:"ITA",label:"Italy",phone:"39"},{ioc:"",iso2:"JE",iso:"JEY",label:"Jersey",phone:"44"},{ioc:"JAM",iso2:"JM",iso:"JAM",label:"Jamaica",phone:"1-876"},{ioc:"JOR",iso2:"JO",iso:"JOR",label:"Jordan",phone:"962"},{ioc:"JPN",iso2:"JP",iso:"JPN",label:"Japan",phone:"81",suggested:!0},{ioc:"KEN",iso2:"KE",iso:"KEN",label:"Kenya",phone:"254"},{ioc:"KGZ",iso2:"KG",iso:"KGZ",label:"Kyrgyzstan",phone:"996"},{ioc:"CAM",iso2:"KH",iso:"KHM",label:"Cambodia",phone:"855"},{ioc:"KIR",iso2:"KI",iso:"KIR",label:"Kiribati",phone:"686"},{ioc:"COM",iso2:"KM",iso:"COM",label:"Comoros",phone:"269"},{ioc:"SKN",iso2:"KN",iso:"KNA",label:"Saint Kitts and Nevis",phone:"1-869"},{ioc:"KOR",iso2:"KP",iso:"KOR",label:"Korea, Democratic People's Republic of",phone:"850"},{ioc:"PRK",iso2:"KR",iso:"PRK",label:"Korea, Republic of",phone:"82"},{ioc:"KUW",iso2:"KW",iso:"KWT",label:"Kuwait",phone:"965"},{ioc:"CAY",iso2:"KY",iso:"CYM",label:"Cayman Islands",phone:"1-345"},{ioc:"KAZ",iso2:"KZ",iso:"KAZ",label:"Kazakhstan",phone:"7"},{ioc:"LAO",iso2:"LA",iso:"LAO",label:"Lao People's Democratic Republic",phone:"856"},{ioc:"LIB",iso2:"LB",iso:"LBN",label:"Lebanon",phone:"961"},{ioc:"LCA",iso2:"LC",iso:"LCA",label:"Saint Lucia",phone:"1-758"},{ioc:"LIE",iso2:"LI",iso:"LIE",label:"Liechtenstein",phone:"423"},{ioc:"SRI",iso2:"LK",iso:"LKA",label:"Sri Lanka",phone:"94"},{ioc:"LBR",iso2:"LR",iso:"LBR",label:"Liberia",phone:"231"},{ioc:"LES",iso2:"LS",iso:"LSO",label:"Lesotho",phone:"266"},{ioc:"LTU",iso2:"LT",iso:"LTU",label:"Lithuania",phone:"370"},{ioc:"LUX",iso2:"LU",iso:"LUX",label:"Luxembourg",phone:"352"},{ioc:"LAT",iso2:"LV",iso:"LVA",label:"Latvia",phone:"371"},{ioc:"LBA",iso2:"LY",iso:"LBY",label:"Libya",phone:"218"},{ioc:"MAR",iso2:"MA",iso:"MAR",label:"Morocco",phone:"212"},{ioc:"MON",iso2:"MC",iso:"MCO",label:"Monaco",phone:"377"},{ioc:"MDA",iso2:"MD",iso:"MDA",label:"Moldova, Republic of",phone:"373"},{ioc:"MNE",iso2:"ME",iso:"MNE",label:"Montenegro",phone:"382"},{ioc:"",iso2:"MF",iso:"MAF",label:"Saint Martin (French part)",phone:"590"},{ioc:"MAD",iso2:"MG",iso:"MDG",label:"Madagascar",phone:"261"},{ioc:"MSH",iso2:"MH",iso:"MHL",label:"Marshall Islands",phone:"692"},{ioc:"MKD",iso2:"MK",iso:"MKD",label:"Macedonia, the Former Yugoslav Republic of",phone:"389"},{ioc:"MLI",iso2:"ML",iso:"MLI",label:"Mali",phone:"223"},{ioc:"MYA",iso2:"MM",iso:"MMR",label:"Myanmar",phone:"95"},{ioc:"MGL",iso2:"MN",iso:"MNG",label:"Mongolia",phone:"976"},{ioc:"MAC",iso2:"MO",iso:"MAC",label:"Macao",phone:"853"},{ioc:"NMA",iso2:"MP",iso:"NMP",label:"Northern Mariana Islands",phone:"1-670"},{ioc:"MRT",iso2:"MQ",iso:"MTQ",label:"Martinique",phone:"596"},{ioc:"MTN",iso2:"MR",iso:"MRT",label:"Mauritania",phone:"222"},{ioc:"MNT",iso2:"MS",iso:"MSR",label:"Montserrat",phone:"1-664"},{ioc:"MLT",iso2:"MT",iso:"MLT",label:"Malta",phone:"356"},{ioc:"MRI",iso2:"MU",iso:"MUS",label:"Mauritius",phone:"230"},{ioc:"MDV",iso2:"MV",iso:"MDV",label:"Maldives",phone:"960"},{ioc:"MAW",iso2:"MW",iso:"MWI",label:"Malawi",phone:"265"},{ioc:"MEX",iso2:"MX",iso:"MEX",label:"Mexico",phone:"52"},{ioc:"MAS",iso2:"MY",iso:"MYS",label:"Malaysia",phone:"60"},{ioc:"MOZ",iso2:"MZ",iso:"MOZ",label:"Mozambique",phone:"258"},{ioc:"NAM",iso2:"NA",iso:"NAM",label:"Namibia",phone:"264"},{ioc:"NCL",iso2:"NC",iso:"NCL",label:"New Caledonia",phone:"687"},{ioc:"NIG",iso2:"NE",iso:"NER",label:"Niger",phone:"227"},{ioc:"NFI",iso2:"NF",iso:"NFK",label:"Norfolk Island",phone:"672"},{ioc:"NGR",iso2:"NG",iso:"NGA",label:"Nigeria",phone:"234"},{ioc:"NCA",iso2:"NI",iso:"NIC",label:"Nicaragua",phone:"505"},{ioc:"NED",iso2:"NL",iso:"NLD",label:"Netherlands",phone:"31"},{ioc:"NOR",iso2:"NO",iso:"NOR",label:"Norway",phone:"47"},{ioc:"NEP",iso2:"NP",iso:"NPL",label:"Nepal",phone:"977"},{ioc:"NRU",iso2:"NR",iso:"NRU",label:"Nauru",phone:"674"},{ioc:"NIU",iso2:"NU",iso:"NIU",label:"Niue",phone:"683"},{ioc:"NZL",iso2:"NZ",iso:"NZL",label:"New Zealand",phone:"64"},{ioc:"OMA",iso2:"OM",iso:"OMN",label:"Oman",phone:"968"},{ioc:"PAN",iso2:"PA",iso:"PAN",label:"Panama",phone:"507"},{ioc:"PER",iso2:"PE",iso:"PER",label:"Peru",phone:"51"},{ioc:"FPO",iso2:"PF",iso:"PYF",label:"French Polynesia",phone:"689"},{ioc:"PNG",iso2:"PG",iso:"PNG",label:"Papua New Guinea",phone:"675"},{ioc:"PHI",iso2:"PH",iso:"PHL",label:"Philippines",phone:"63"},{ioc:"PAK",iso2:"PK",iso:"PAK",label:"Pakistan",phone:"92"},{ioc:"POL",iso2:"PL",iso:"POL",label:"Poland",phone:"48"},{ioc:"SPM",iso2:"PM",iso:"SPM",label:"Saint Pierre and Miquelon",phone:"508"},{ioc:"",iso2:"PN",iso:"PCN",label:"Pitcairn",phone:"870"},{ioc:"PUR",iso2:"PR",iso:"PRI",label:"Puerto Rico",phone:"1"},{ioc:"PLE",iso2:"PS",iso:"PSE",label:"Palestine, State of",phone:"970"},{ioc:"POR",iso2:"PT",iso:"PRT",label:"Portugal",phone:"351"},{ioc:"PLW",iso2:"PW",iso:"PLW",label:"Palau",phone:"680"},{ioc:"PAR",iso2:"PY",iso:"PRY",label:"Paraguay",phone:"595"},{ioc:"QAT",iso2:"QA",iso:"QAT",label:"Qatar",phone:"974"},{ioc:"REU",iso2:"RE",iso:"REU",label:"Reunion",phone:"262"},{ioc:"ROU",iso2:"RO",iso:"ROU",label:"Romania",phone:"40"},{ioc:"SRB",iso2:"RS",iso:"SRB",label:"Serbia",phone:"381"},{ioc:"RUS",iso2:"RU",iso:"RUS",label:"Russia",phone:"7"},{ioc:"RWA",iso2:"RW",iso:"RWA",label:"Rwanda",phone:"250"},{ioc:"KSA",iso2:"SA",iso:"SAU",label:"Saudi Arabia",phone:"966"},{ioc:"SOL",iso2:"SB",iso:"SLB",label:"Solomon Islands",phone:"677"},{ioc:"SEY",iso2:"SC",iso:"SYC",label:"Seychelles",phone:"248"},{ioc:"SUD",iso2:"SD",iso:"SDN",label:"Sudan",phone:"249"},{ioc:"SWE",iso2:"SE",iso:"SWE",label:"Sweden",phone:"46"},{ioc:"SIN",iso2:"SG",iso:"SGP",label:"Singapore",phone:"65"},{ioc:"HEL",iso2:"SH",iso:"SHN",label:"Saint Helena",phone:"290"},{ioc:"SLO",iso2:"SI",iso:"SVN",label:"Slovenia",phone:"386"},{ioc:"",iso2:"SJ",iso:"SJM",label:"Svalbard and Jan Mayen",phone:"47"},{ioc:"SVK",iso2:"SK",iso:"SVK",label:"Slovakia",phone:"421"},{ioc:"SLE",iso2:"SL",iso:"SLE",label:"Sierra Leone",phone:"232"},{ioc:"SMR",iso2:"SM",iso:"SMR",label:"San Marino",phone:"378"},{ioc:"SEN",iso2:"SN",iso:"SEN",label:"Senegal",phone:"221"},{ioc:"SOM",iso2:"SO",iso:"SOM",label:"Somalia",phone:"252"},{ioc:"SUR",iso2:"SR",iso:"SUR",label:"Suriname",phone:"597"},{ioc:"",iso2:"SS",iso:"SSD",label:"South Sudan",phone:"211"},{ioc:"STP",iso2:"ST",iso:"STP",label:"Sao Tome and Principe",phone:"239"},{ioc:"ESA",iso2:"SV",iso:"SLV",label:"El Salvador",phone:"503"},{ioc:"",iso2:"SX",iso:"SMX",label:"Sint Maarten",phone:"1-721"},{ioc:"SYR",iso2:"SY",iso:"SYR",label:"Syria",phone:"963"},{ioc:"",iso2:"SZ",iso:"SWZ",label:"Swaziland",phone:"268"},{ioc:"TKS",iso2:"TC",iso:"TCA",label:"Turks and Caicos Islands",phone:"1-649"},{ioc:"CHA",iso2:"TD",iso:"TCD",label:"Chad",phone:"235"},{ioc:"",iso2:"TF",iso:"ATF",label:"French Southern Territories",phone:"262"},{ioc:"TOG",iso2:"TG",iso:"TGO",label:"Togo",phone:"228"},{ioc:"THA",iso2:"TH",iso:"THA",label:"Thailand",phone:"66"},{ioc:"TJK",iso2:"TJ",iso:"TJK",label:"Tajikistan",phone:"992"},{ioc:"",iso2:"TK",iso:"TKL",label:"Tokelau",phone:"690"},{ioc:"TLS",iso2:"TL",iso:"TLS",label:"Timor-Leste",phone:"670"},{ioc:"TKM",iso2:"TM",iso:"TKM",label:"Turkmenistan",phone:"993"},{ioc:"TUN",iso2:"TN",iso:"TUN",label:"Tunisia",phone:"216"},{ioc:"TGA",iso2:"TO",iso:"TON",label:"Tonga",phone:"676"},{ioc:"TUR",iso2:"TR",iso:"TUR",label:"Turkey",phone:"90"},{ioc:"TTO",iso2:"TT",iso:"TTO",label:"Trinidad and Tobago",phone:"1-868"},{ioc:"TUV",iso2:"TV",iso:"TUV",label:"Tuvalu",phone:"688"},{ioc:"TPE",iso2:"TW",iso:"TWN",label:"Taiwan",phone:"886"},{ioc:"TAN",iso2:"TZ",iso:"TZA",label:"United Republic of Tanzania",phone:"255"},{ioc:"UKR",iso2:"UA",iso:"UKR",label:"Ukraine",phone:"380"},{ioc:"UGA",iso2:"UG",iso:"UGA",label:"Uganda",phone:"256"},{ioc:"USA",iso2:"US",label:"United States",phone:"1",suggested:!0,iso:"USA"},{ioc:"URU",iso2:"UY",iso:"URY",label:"Uruguay",phone:"598"},{ioc:"UZB",iso2:"UZ",iso:"UZB",label:"Uzbekistan",phone:"998"},{ioc:"",iso2:"VA",iso:"VAT",label:"Holy See (Vatican City State)",phone:"379"},{ioc:"VIN",iso2:"VC",iso:"VCT",label:"Saint Vincent and the Grenadines",phone:"1-784"},{ioc:"VEN",iso2:"VE",iso:"VEN",label:"Venezuela",phone:"58"},{ioc:"IVB",iso2:"VG",iso:"VGB",label:"British Virgin Islands",phone:"1-284"},{ioc:"ISV",iso2:"VI",iso:"VIR",label:"US Virgin Islands",phone:"1-340"},{ioc:"VIE",iso2:"VN",iso:"VNM",label:"Vietnam",phone:"84"},{ioc:"VAN",iso2:"VU",iso:"VUT",label:"Vanuatu",phone:"678"},{ioc:"WAF",iso2:"WF",iso:"WLF",label:"Wallis and Futuna",phone:"681"},{ioc:"SAM",iso2:"WS",iso:"WSM",label:"Samoa",phone:"685"},{ioc:"KOS",iso2:"XK",iso:"KOS",label:"Kosovo",phone:"383"},{ioc:"YEM",iso2:"YE",iso:"YEM",label:"Yemen",phone:"967"},{ioc:"MAY",iso2:"YT",iso:"MYT",label:"Mayotte",phone:"262"},{ioc:"RSA",iso2:"ZA",iso:"ZAF",label:"South Africa",phone:"27"},{ioc:"ZAM",iso2:"ZM",iso:"ZMB",label:"Zambia",phone:"260"},{ioc:"ZIM",iso2:"ZW",iso:"ZWE",label:"Zimbabwe",phone:"263"}],No="ELO",GU="NTRP",WU="UTR",BS="WTN",wr={[No]:{defaultInitialization:1500,decimalsCount:0,range:[0,3e3],ascending:!0},[GU]:{accessors:["ntrpRating","dntrpRatingHundredths"],attributes:{ustaRatingType:""},accessor:"dntrpRatingHundredths",defaultInitialization:3,decimalsCount:1,ascending:!0,range:[1,7]},[WU]:{defaultInitialization:6,accessors:["utrRating"],accessor:"utrRating",decimalsCount:2,ascending:!0,range:[1,16]},[BS]:{attributes:{confidence:{generator:!0,range:[60,100]}},accessors:["wtnRating","confidence"],defaultInitialization:23,accessor:"wtnRating",ascending:!1,decimalsCount:2,range:[40,1]}};var HU=[{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}],qU="COLLEGE_D3",YU={valueGoal:5},zU={collectionDefinitions:HU,tieFormatName:qU,winCriteria:YU},KU=[{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}],JU="COLLEGE_DEFAULT",QU={valueGoal:5},ZU={collectionDefinitions:KU,tieFormatName:JU,winCriteria:QU},XU=[{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}],t0="COLLEGE_JUCO",e0={valueGoal:5},n0={collectionDefinitions:XU,tieFormatName:t0,winCriteria:e0},r0=[{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}],s0="DOMINANT_DUO",i0={valueGoal:2},xS={collectionDefinitions:r0,tieFormatName:s0,winCriteria:i0},o0=[{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}],c0="DOMINANT_DUO_MIXED",a0={valueGoal:2},$S={collectionDefinitions:o0,tieFormatName:c0,winCriteria:a0},u0=[{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}],l0=[{groupNumber:1,groupName:"Day 1"},{groupNumber:2,groupName:"Day 2"},{groupNumber:3,groupName:"Day 3"}],d0="LAVER_CUP",f0={valueGoal:13},VS={collectionDefinitions:u0,collectionGroups:l0,tieFormatName:d0,winCriteria:f0},p0=[{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}],h0="Doubles Shuffle",m0=!0,g0={aggregateValue:!0},jS={collectionDefinitions:p0,tieFormatName:h0,unrestrictedSelections:m0,winCriteria:g0},I0=[{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}],S0=[{groupNumber:1,groupName:"Doubles",groupValue:1,winCriteria:{valueGoal:2}}],T0="USTA_BREWER_CUP",y0={valueGoal:4},GS={collectionDefinitions:I0,collectionGroups:S0,tieFormatName:T0,winCriteria:y0},E0={valueGoal:23},b0="USTA_OZAKI_CUP",N0=[{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}],WS={winCriteria:E0,tieFormatName:b0,collectionDefinitions:N0},A0=[{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}],v0="USTA_COLLEGE",C0={valueGoal:4},HS={collectionDefinitions:A0,tieFormatName:v0,winCriteria:C0},P0=[{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"}],U0="USTA_GOLD_TEAM_CHALLENGE",O0={valueGoal:9},qS={collectionDefinitions:P0,tieFormatName:U0,winCriteria:O0},M0=[{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}],D0="USTA_INTERSECTIONAL",w0={valueGoal:8},YS={collectionDefinitions:M0,tieFormatName:D0,winCriteria:w0},k0=[{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}],_0="USTA_LEVEL_1",F0={valueGoal:10},zS={collectionDefinitions:k0,tieFormatName:_0,winCriteria:F0},L0=[{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"]}],R0="USTA_SECTION_BATTLE",B0={valueGoal:9},KS={collectionDefinitions:L0,tieFormatName:R0,winCriteria:B0},x0=[{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}],$0="USTA_SOUTHERN_LEVEL_5",V0={valueGoal:8},JS={collectionDefinitions:x0,tieFormatName:$0,winCriteria:V0},j0=[{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}],G0="USTA_TOC",W0={aggregateValue:!0},QS={collectionDefinitions:j0,tieFormatName:G0,winCriteria:W0},H0=[{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}],q0="USTA_WTT_ITT",Y0={aggregateValue:!0},ZS={collectionDefinitions:H0,tieFormatName:q0,winCriteria:Y0},z0=[{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}],K0="USTA_ZONAL",J0={valueGoal:10},XS={collectionDefinitions:z0,tieFormatName:K0,winCriteria:J0};const tT={COLLEGE_D3:zU,COLLEGE_DEFAULT:ZU,COLLEGE_JUCO:n0,DOMINANT_DUO:xS,DOMINANT_DUO_MIXED:$S,LAVER_CUP:VS,TEAM_DOUBLES_3_AGGREGATION:jS,USTA_BREWER_CUP:GS,USTA_OZAKI_CUP:WS,USTA_COLLEGE:HS,USTA_GOLD_TEAM_CHALLENGE:qS,USTA_INTERSECTIONAL:YS,USTA_LEVEL_1:zS,USTA_SECTION_BATTLE:KS,USTA_SOUTHERN_LEVEL_5:JS,USTA_TOC:QS,USTA_WTT_ITT:ZS,USTA_ZONAL:XS},Q0={[WC]:{roundsToSeparate:void 0,policyName:"Nationality Code",policyAttributes:[{key:"person.nationalityCode"},{key:"individualParticipants.person.nationalityCode"}]}},Z0="qualifierDrawPositionAssignment",X0="withdrawParticipantAtDrawPosition",tO="alternateDrawPositionAssignment",eO="luckyLoserDrawPositionAssignment",eT="removeDrawPositionAssignment",nO="swapDrawPositionAssignments",rO="modifyPairAssignment",sO="modifyParticipantOtherName",nT="assignDrawPosition",iO="removeSeededParticipant",oO="assignDrawPositionBye",cO="modifySeedAssignment",rT="addPenalty",sT="MODIFY_PAIR",fp="QUALIFIER",iT="ALTERNATE",oT="WITHDRAW",pc="ASSIGN",cT="REMOVE",aT="LUCKY",Il="REMOVE_SEED",uT="SWAP",Sl="NICKNAME",hc="SEED_VALUE",mc="PENALTY",pp="BYE",lT={[vs]:{policyName:"positionActionsDefault",enabledStructures:[{stages:[Pt,It],stageSequences:[1],enabledActions:[],disabledActions:[]},{stages:[],stageSequences:[],enabledActions:[Sl,mc,fp,hc],disabledActions:[]}],disbledStructures:[],otherFlightEntries:!1,activePositionOverrides:[]}},aO={[vs]:{policyName:"positionActionsDisabled",enabledStructures:!1}},uO={[vs]:{policyName:"positionActionsNoMovement",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[hc,Sl,mc],disabledActions:[]}]}},lO={[vs]:{policyName:"positionActionsUnrestricted",enabledStructures:[],otherFlightEntries:!0,disableRoundRestrictions:!0,activePositionOverrides:[hc,Il]}},dO={[oa]:{policyName:"Participant Privacy Policy",participant:{contacts:!1,individualParticipants:{onlineResources:!1,participantName:!0,participantOtherName:!0,participantId:!0,participantRole:!0,participantStatus:!0,penalties:!1,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,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}}}},hp="ADULT",mp="JUNIOR",Tl="WHEELCHAIR",fO={[ff]:{defaultTimes:{averageTimes:[{categoryNames:[],minutes:{default:90}}],recoveryTimes:[{minutes:{[me]:30,default:60}}]},defaultDailyLimits:{[Oe]:2,[me]:2,total:3},matchUpAverageTimes:[{matchUpFormatCodes:[Kn],averageTimes:[{categoryNames:[],minutes:{default:90}},{categoryTypes:[Tl],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:[hp,Tl],minutes:{default:60,[me]:30}},{categoryTypes:[mp],minutes:{default:60,[me]: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:[hp,Tl],minutes:{default:30}},{categoryTypes:[mp],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:[hp,mp],minutes:{default:30}},{categoryTypes:[Tl],minutes:{default:15}}]},{matchUpFormatCodes:["SET1-S:TB10"],recoveryTimes:[{categoryNames:[],minutes:{default:15}}]}],matchUpDailyLimits:[]}},pO={[Xo]:{requireAllPositionsAssigned:!1,stage:{[It]:{stageSequence:{1:{requireAllPositionsAssigned:!0}}}},defaultMatchUpFormat:Kn,matchUpFormats:[{description:"Best of 3 tiebreak sets",matchUpFormat:Kn,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"}]}},hO={[Xo]:{defaultMatchUpFormat:Kn,requireAllPositionsAssigned:!1,processCodes:{incompleteAssignmentsOnDefault:["RANKING.IGNORE"]},stage:{[It]:{stageSequence:{1:{requireAllPositionsAssigned:!0}}}}}},mO={[tc]:{seedingProfile:{positioning:Lf},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}]}},gp={[tc]:{validSeedPositions:{ignore:!0},duplicateSeedNumbers:!0,drawSizeProgression:!0,seedingProfile:{positioning:RP},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}]}},gO={ratingsParameters:wr,matchUpFormats:kC,countryToFlag:RS,tieFormats:tT,countries:ri,policies:{POLICY_AVOIDANCE_COUNTRY:Q0,POLICY_POSITION_ACTIONS_DEFAULT:lT,POLICY_POSITION_ACTIONS_DISABLED:aO,POLICY_POSITION_ACTIONS_NO_MOVEMENT:uO,POLICY_POSITION_ACTIONS_UNRESTRICTED:lO,POLICY_PRIVACY_DEFAULT:dO,POLICY_ROUND_NAMING_DEFAULT:sS,POLICY_SCHEDULING_USTA:fO,POLICY_SCORING_DEFAULT:hO,POLICY_SCORING_USTA:pO,POLICY_SEEDING_ITF:mO,POLICY_SEEDING_USTA:gp},flagIOC:jU};function gc({collectionDefinitions:t=[],collectionGroups:e=[]}){let n=0;const{groupValueNumbers:r}=oS({collectionGroups:e});let s;for(const o of t||[]){const{collectionValueProfiles:c,collectionGroupNumber:a,collectionValue:u,matchUpCount:l,matchUpValue:f,scoreValue:p,setValue:h}=o,d=a&&r.includes(a);if(h||p)s=!0;else{if(d)continue;if(u)n+=u;else if(c!=null&&c.length)for(const m of c)n+=m.matchUpValue;else f?n+=(l||0)*f:n+=l||0}}for(const o of e)n+=o.groupValue||0;return s||!n?{aggregateValue:!0}:{valueGoal:Math.floor(n/2)+1}}function yl({participant:t,withISO2:e,withIOC:n}){const{person:r,individualParticipants:s}=t,i=[r,s==null?void 0:s.map(({person:c})=>c)].flat().filter(Boolean);function o(c){const{nationalityCode:a}=c||{};if(a){const u=ri.find(({iso:l})=>l===a);n&&(u!=null&&u.ioc)&&!c.iocNationalityCode&&(c.iocNationalityCode=u.ioc),e&&(u!=null&&u.iso2)&&!c.iso2NationalityCode&&(c.iso2NationalityCode=u.iso2),u!=null&&u.label&&!c.countryName&&(c.countryName=u.label)}}i.forEach(o)}function kr({returnPreviousValues:t,itemSubTypes:e,itemType:n,element:r}){if(!r)return{error:Tt,info:Ef};if(e&&!Array.isArray(e))return{error:tt,context:{itemSubTypes:e}};if(!Array.isArray(r.timeItems))return{error:Tg};const s=r.timeItems.filter(o=>(o==null?void 0:o.itemType)===n).filter(o=>!(e!=null&&e.length)||e.some(c=>{var a;return(a=o==null?void 0:o.itemSubTypes)==null?void 0:a.includes(c)})).sort((o,c)=>{const a=new Date(o.createdAt||void 0).getTime(),u=new Date(c.createdAt||void 0).getTime();return a-u}),i=s.pop();if(i){const o={timeItem:i,...$};return t&&Object.assign(o,{previousItems:s}),o}else return{info:an}}function IO({returnPreviousValues:t,drawDefinition:e,itemSubTypes:n,itemType:r}){if(!e)return{error:Hn};if(!e.timeItems)return{info:an};const{timeItem:s,previousItems:i,info:o}=kr({element:e,returnPreviousValues:t,itemSubTypes:n,itemType:r});return s&&{timeItem:s,previousItems:i}||{info:o}}function ws({returnPreviousValues:t,itemSubTypes:e,itemType:n,event:r}){if(!r)return{error:Wt};if(!r.timeItems)return{info:an};const{timeItem:s,previousItems:i,info:o}=kr({returnPreviousValues:t,element:r,itemSubTypes:e,itemType:n});return s&&{timeItem:s,previousItems:i}||{info:o}}function El({returnPreviousValues:t,tournamentRecord:e,itemSubTypes:n,itemType:r}){if(!e)return{error:et};if(!e.timeItems)return{info:an};const{timeItem:s,previousItems:i,info:o}=kr({element:e,returnPreviousValues:t,itemSubTypes:n,itemType:r});return s&&{timeItem:s,previousItems:i}||{info:o}}function SO({returnPreviousValues:t,tournamentRecord:e,participantId:n,itemSubTypes:r,itemType:s}){if(!e)return{error:et};if(!n)return{error:Ce};const i=zs({tournamentRecord:e,participantId:n});if(i.error)return i;const{participant:o}=i;if(!(o!=null&&o.timeItems))return{info:an};const{timeItem:c,previousItems:a,info:u}=kr({element:i.participant,returnPreviousValues:t,itemSubTypes:r,itemType:s});return c&&{timeItem:c,previousItems:a}||{info:u}}const TO={[Fn]:"groupParticipantIds",[_t]:"pairParticipantIds",[se]:"teamParticipantIds"},yO={[Fn]:"groups",[se]:"teams"};function dT({withIndividualParticipants:t,convertExtensions:e,policyDefinitions:n,tournamentRecord:r,withSignInStatus:s,withScaleValues:i,internalUse:o,withISO2:c,withIOC:a}){const u=n==null?void 0:n[oa],l=u==null?void 0:u.participant,f={};for(const p of r.participants||[]){const h=p==null?void 0:p.participantId;h&&AO({participantMap:f,participantId:h})}for(const p of r.participants||[]){const h=pt(p,e,o),d=l?Fu({template:u.participant,source:h}):h,{participantId:m,individualParticipantIds:g,participantType:I}=d;if(Object.assign(f[m].participant,d),g&&NO({individualParticipantIds:g,filteredParticipant:d,participantMap:f,participantType:I,participantId:m}),s&&(f[m].participant.signedIn=EO(h)),i){const{ratings:S,rankings:T,seedings:E}=sc({participant:h});f[m].participant.seedings=E,f[m].participant.rankings=T,f[m].participant.ratings=S}(a||c)&&yl({participant:f[m].participant,withISO2:c,withIOC:a})}return t&&bO({participantMap:f}),{participantMap:f}}function EO(t){const{timeItem:e}=kr({itemType:Ta,element:t});return(e==null?void 0:e.itemValue)===ya}function bO({participantMap:t}){var n;const e=Object.values(t);for(const r of e){const s=r.participant;if((n=s.individualParticipantIds)!=null&&n.length){s.individualParticipants=[];for(const i of s.individualParticipantIds)s.individualParticipants.push(t[i].participant)}}}function NO({individualParticipantIds:t,filteredParticipant:e,participantMap:n,participantType:r,participantId:s}){for(const i of t){const o=n[i].participant;if(o[TO[r]].push(s),[se,Fn].includes(r)){const{participantRoleResponsibilities:c,participantOtherName:a,participantName:u,participantId:l,teamId:f}=e,p=yO[r];o[p].push({participantRoleResponsibilities:c,participantOtherName:a,participantName:u,participantId:l,teamId:f})}if(r===_t){const c=t.find(a=>a!==i);n[i].pairIdMap[s]=c,n[i].pairIdMap[c]=s}}}function AO({participantMap:t,participantId:e}){if(t[e])return;const n={walkoverWins:0,defaultWins:0,walkovers:0,defaults:0,losses:0,wins:0};t[e]={structureParticipation:{},potentialMatchUps:{},scheduleConflicts:[],scheduleItems:[],participant:{groupParticipantIds:[],pairParticipantIds:[],teamParticipantIds:[],groups:[],teams:[]},statistics:{},opponents:{},pairIdMap:{},matchUps:{},events:{},draws:{},counters:{[Oe]:{...n},[me]:{...n},[se]:{...n},...n}}}function Ao({participantsProfile:t,useParticipantMap:e,policyDefinitions:n,tournamentRecord:r,contextProfile:s,inContext:i}){var c;if(e)return{participantMap:(c=dT({...t,...s,policyDefinitions:n,tournamentRecord:r}))==null?void 0:c.participantMap};let o=pt(r.participants,!1,!0)||[];if((t!=null&&t.withIOC||t!=null&&t.withISO2)&&o.forEach(a=>yl({participant:a,...t})),(i||t!=null&&t.withGroupings)&&(o!=null&&o.length)&&(o=Qf({participantsProfile:t,participants:o})),t!=null&&t.withScaleValues&&(o!=null&&o.length))for(const a of o){const{ratings:u,rankings:l}=sc({participant:a});a.rankings=l,a.ratings=u}return{participants:o}}function He(t){if(!(t!=null&&t.tournamentRecord))return{error:et};let{participantMap:e,participants:n}=t;const{scheduleVisibilityFilters:r,participantsProfile:s,afterRecoveryTimes:i,useParticipantMap:o,policyDefinitions:c,tournamentRecord:a,inContext:u=!0,contextProfile:l,matchUpFilters:f,contextFilters:p,nextMatchUps:h,context:d}=t,m=t.tournamentId??a.tournamentId,g=(a==null?void 0:a.events)??[];n||({participants:n,participantMap:e}=Ao({participantsProfile:s,policyDefinitions:c,useParticipantMap:o,tournamentRecord:a,contextProfile:l,inContext:u}));const{appliedPolicies:I}=ge({tournamentRecord:a}),S={...d,tournamentId:m,indoorOutDoor:a.indoorOutdoor,surfaceCategory:a.surfaceCategory,endDate:a.endDate},T=Cs({policyDefinitions:c,tournamentRecord:a,contextProfile:l});return{matchUps:g.flatMap(y=>{var b;return S.eventDrawsCount=((b=y.drawDefinitions)==null?void 0:b.length)??0,si({context:S,scheduleVisibilityFilters:r,tournamentAppliedPolicies:I,participantsProfile:s,afterRecoveryTimes:i,policyDefinitions:c,tournamentRecord:a,contextContent:T,contextFilters:p,contextProfile:l,matchUpFilters:f,participantMap:e,nextMatchUps:h,participants:n,inContext:u,event:y}).matchUps??[]}).concat(...a.matchUps??[])}}function tr(t){let{participants:e,participantMap:n,contextContent:r}=t;const{scheduleVisibilityFilters:s,tournamentAppliedPolicies:i,participantsProfile:o,afterRecoveryTimes:c,policyDefinitions:a,useParticipantMap:u,tournamentRecord:l,contextFilters:f,contextProfile:p,drawDefinition:h,matchUpFilters:d,nextMatchUps:m,inContext:g,context:I,event:S}=t,{eventId:T,eventName:E,eventType:y,category:b,gender:N,matchUpFormat:A}=S??{},C={...I,eventId:T,eventType:y,eventName:E,category:b,gender:N,matchUpFormat:A,indoorOutDoor:(S==null?void 0:S.indoorOutdoor)??(l==null?void 0:l.indoorOutdoor),surfaceCategory:(S==null?void 0:S.surfaceCategory)??(l==null?void 0:l.surfaceCategory),endDate:S==null?void 0:S.endDate};return!(e!=null&&e.length)&&!n&&l&&({participants:e=[],participantMap:n}=Ao({participantsProfile:o,useParticipantMap:u,policyDefinitions:a,tournamentRecord:l,contextProfile:p,inContext:g})),p&&!r&&(r=Cs({policyDefinitions:a,tournamentRecord:l,contextProfile:p,drawDefinition:h,event:S})),xe({context:C,tournamentAppliedPolicies:i,scheduleVisibilityFilters:s,tournamentParticipants:e,participantsProfile:o,afterRecoveryTimes:c,policyDefinitions:a,tournamentRecord:l,drawDefinition:h,contextContent:r,contextFilters:f,contextProfile:p,matchUpFilters:d,participantMap:n,nextMatchUps:m,inContext:g,event:S})}function si(t){let{participants:e=[],contextContent:n,participantMap:r}=t;const{scheduleVisibilityFilters:s,tournamentAppliedPolicies:i,participantsProfile:o,afterRecoveryTimes:c,policyDefinitions:a,useParticipantMap:u,tournamentRecord:l,contextFilters:f,contextProfile:p,matchUpFilters:h,nextMatchUps:d,inContext:m,context:g,event:I}=t;if(!I)return{error:Wt};const{eventId:S,eventName:T,endDate:E,category:y,gender:b,matchUpFormat:N}=I,A=[],C={...g,...bt({indoorOutDoor:I.indoorOutdoor??(l==null?void 0:l.indoorOutdoor),surfaceCategory:I.surfaceCategory??(l==null?void 0:l.surfaceCategory),endDate:I.endDate??(l==null?void 0:l.endDate),tournamentId:l==null?void 0:l.tournamentId,matchUpFormat:N,eventName:T,category:y,gender:b,eventId:S})};if(E&&(C.endDate=E),p&&!n&&(n=Cs({policyDefinitions:a,tournamentRecord:l,contextProfile:p,event:I})),!(e!=null&&e.length)&&!r&&l){const O=Ao({participantsProfile:o,useParticipantMap:u,policyDefinitions:a,tournamentRecord:l,contextProfile:p,inContext:m});r=O.participantMap,e=O.participants??[]}const v=I.drawDefinitions??[],P=pa({tournamentRecord:l,event:I}).scheduleTiming;return{matchUps:v.flatMap(O=>{const{matchUps:D,matchUpsMap:M}=xe({tournamentParticipants:e,tournamentAppliedPolicies:i,scheduleVisibilityFilters:s,context:C,participantsProfile:o,afterRecoveryTimes:c,policyDefinitions:a,tournamentRecord:l,contextFilters:f,contextProfile:p,drawDefinition:O,contextContent:n,matchUpFilters:h,participantMap:r,scheduleTiming:P,nextMatchUps:d,inContext:m,event:I});return M!=null&&M.drawMatchUps&&A.push(...M.drawMatchUps),D??[]}),eventMatchUps:A}}function fT(t){if(!(t!=null&&t.tournamentRecord))return{error:et};let e=t.contextContent;const{scheduleVisibilityFilters:n,participantsProfile:r,afterRecoveryTimes:s,policyDefinitions:i,useParticipantMap:o,tournamentRecord:c,inContext:a=!0,contextFilters:u,contextProfile:l,matchUpFilters:f,nextMatchUps:p,context:h}=t,d=t.tournamentId??c.tournamentId,m=(c==null?void 0:c.events)??[],{participants:g,participantMap:I}=Ao({participantsProfile:r,policyDefinitions:i,useParticipantMap:o,tournamentRecord:c,contextProfile:l,inContext:a});l&&!e&&(e=Cs({policyDefinitions:i,tournamentRecord:c,contextProfile:l}));const{appliedPolicies:S}=ge({tournamentRecord:c}),T=(u==null?void 0:u.eventIds)??[];return m.filter(y=>!T.includes(y.eventId)).map(y=>{var A,C;const b=be({event:y}).flightProfile,N={eventDrawsCount:((A=b==null?void 0:b.flights)==null?void 0:A.length)||((C=y.drawDefinitions)==null?void 0:C.length)||0,...h};return pT({context:N,tournamentAppliedPolicies:S,scheduleVisibilityFilters:n,participantsProfile:r,afterRecoveryTimes:s,policyDefinitions:i,tournamentRecord:c,contextFilters:u,contextProfile:l,contextContent:e,matchUpFilters:f,participantMap:I,participants:g,tournamentId:d,nextMatchUps:p,inContext:a,event:y})}).reduce((y,b)=>{const N=b&&Object.keys(b).filter(A=>!["success","matchUpsMap"].includes(A));return N==null||N.forEach(A=>{y[A]||(y[A]=[]),y[A]=y[A].concat(b[A]),y.matchUpsCount+=b[A].length}),y},{matchUpsCount:0})}function pT(t){let{participants:e,contextContent:n,participantMap:r}=t;const{tournamentAppliedPolicies:s,scheduleVisibilityFilters:i,participantsProfile:o,afterRecoveryTimes:c,policyDefinitions:a,useParticipantMap:u,tournamentRecord:l,contextFilters:f,contextProfile:p,matchUpFilters:h,nextMatchUps:d,tournamentId:m,inContext:g,context:I,event:S}=t;if(!S)return{error:Wt};const{eventId:T,eventName:E,endDate:y}=S,b={...I,...bt({eventId:T,eventName:E,endDate:y??(l==null?void 0:l.endDate),tournamentId:m??(l==null?void 0:l.tournamentId),indoorOutDoor:S.indoorOutdoor??(l==null?void 0:l.indoorOutdoor),surfaceCategory:S.surfaceCategory??(l==null?void 0:l.surfaceCategory)})};return!e&&l&&({participants:e,participantMap:r}=Ao({participantsProfile:o,policyDefinitions:a,useParticipantMap:u,tournamentRecord:l,contextProfile:p,inContext:g})),p&&!n&&(n=Cs({policyDefinitions:a,tournamentRecord:l,contextProfile:p,event:S})),(S.drawDefinitions??[]).reduce((A,C)=>{const v=To({context:b,tournamentAppliedPolicies:s,scheduleVisibilityFilters:i,tournamentParticipants:e,participantsProfile:o,afterRecoveryTimes:c,policyDefinitions:a,tournamentRecord:l,drawDefinition:C,contextContent:n,contextFilters:f,contextProfile:p,matchUpFilters:h,participantMap:r,nextMatchUps:d,inContext:g,event:S}),P=Object.keys(v);return P==null||P.forEach(U=>{A[U]||(A[U]=[]),A[U]=A[U].concat(v[U])}),A},{})}function vO({participants:t,tournamentAppliedPolicies:e,scheduleVisibilityFilters:n,participantsProfile:r,afterRecoveryTimes:s,policyDefinitions:i,useParticipantMap:o,tournamentRecord:c,contextFilters:a,contextProfile:u,contextContent:l,drawDefinition:f,matchUpFilters:p,participantMap:h,nextMatchUps:d,tournamentId:m,inContext:g,context:I,event:S}){const{eventId:T,eventName:E,endDate:y}=S??{},b={...I,...bt({eventId:T,eventName:E,endDate:y??(S==null?void 0:S.endDate)??(c==null?void 0:c.endDate),tournamentId:m??(c==null?void 0:c.tournamentId),indoorOutDoor:(S==null?void 0:S.indoorOutdoor)??(c==null?void 0:c.indoorOutdoor),surfaceCategory:(S==null?void 0:S.surfaceCategory)??(c==null?void 0:c.surfaceCategory)})};return!(t!=null&&t.length)&&c&&({participants:t,participantMap:h}=Ao({participantsProfile:r,policyDefinitions:i,useParticipantMap:o,tournamentRecord:c,contextProfile:u,inContext:g})),S&&u&&!l&&(l=Cs({policyDefinitions:i,tournamentRecord:c,contextProfile:u,drawDefinition:f,event:S})),To({context:b,tournamentAppliedPolicies:e,scheduleVisibilityFilters:n,tournamentParticipants:t,participantsProfile:r,afterRecoveryTimes:s,policyDefinitions:i,tournamentRecord:c,participantMap:h,drawDefinition:f,matchUpFilters:p,contextFilters:a,contextProfile:u,contextContent:l,nextMatchUps:d,inContext:g,event:S})}function ja({finishingPositionOffset:t=0,finishingPositionLimit:e,positionsFed:n,roundsCount:r,roundLimit:s,matchUps:i,lucky:o,fmlc:c}){var g;if(!cr(i))return[];const{roundProfile:a,roundNumbers:u=[]}=Cn({interpolate:!0,matchUps:i});r=r||Math.max(...u,0);const l=s?r-s:0,f=l&&((g=a==null?void 0:a[r-l])==null?void 0:g.matchUpsCount),p=a&&Object.values(a).map(kn("matchUpsCount")),h=(I,S)=>{let T=Math.min(...I);f&&S&&T===1&&(T=f);let E=Math.max(...I);return e&&E>e&&(E=e),[T,E]},d=a&&Object.assign({},...u.map(I=>{const S=(r||0)+1-I-l,T=a[I].matchUpsCount,E={finishingPositionRange:{},finishingRound:S},y=p==null?void 0:p.slice(I-1).reduce((O,D)=>O+(D||0),0),b=c&&I!==1,N=1+t+(b&&n||0),A=1,C=ht(N,o?N+T*2:y+N+A),v=y+A-T,P=h(C.slice(v)),U=h(C.slice(0,v),!0);return E.finishingPositionRange={loser:P,winner:U},{[I]:E}})),m=ze({finishingRound:!0});return i.filter(Boolean).forEach(I=>{const S=I.roundNumber&&d[I.roundNumber];m&&!S&&console.log({roundFinishingData:d,matchUp:I}),I.finishingRound=S==null?void 0:S.finishingRound,I.finishingPositionRange=S==null?void 0:S.finishingPositionRange}),i}function Ic({inContextDrawMatchUps:t,drawDefinition:e,matchUpsMap:n}){var i;if(!e)return{error:lt};const r={loserMatchUpIds:{},winnerMatchUpIds:{}};if(t||({matchUps:t,matchUpsMap:n}=xe({inContext:!0,drawDefinition:e,matchUpsMap:n})),!(n==null?void 0:n.drawMatchUps.some(o=>o.finishingPositionRange))&&((i=e==null?void 0:e.structures)==null?void 0:i.length)===1&&!(e!=null&&e.structures[0].structures)){const o=(n==null?void 0:n.drawMatchUps)||[];ja({matchUps:o})}return(t||[]).filter(({collectionId:o})=>!o).forEach(o=>{const{matchUpId:c,structureId:a}=o,u=gn({inContextDrawMatchUps:t,drawDefinition:e,matchUpId:c}),{winnerMatchUp:l,loserMatchUp:f}=u.targetMatchUps,p=l==null?void 0:l.matchUpId,h=f==null?void 0:f.matchUpId,m=Ui({matchUpsMap:n,structureId:a}).find(g=>g.matchUpId===c);if(m&&(p&&(r.winnerMatchUpIds[m.matchUpId]=p,Object.assign(m,{winnerMatchUpId:p}),Object.assign(o,{winnerMatchUpId:p})),h&&(r.loserMatchUpIds[m.matchUpId]=h,o.loserMatchUpId=h,m.loserMatchUpId=h,o.finishingPositionRange))){const g=f.finishingPositionRange&&[...o.finishingPositionRange.loser,...f.finishingPositionRange.loser],I=g&&[Math.min(...g),Math.max(...g)];o.finishingPositionRange.loser=I,m.finishingPositionRange.loser=I}}),{inContextDrawMatchUps:t,goesToMap:r}}function bl(t){var o;const{sides:e,matchUpType:n}=t||{},r=(o=t.potentialParticipants)!=null&&o.length?t.potentialParticipants.flat().map(c=>n===me?(c==null?void 0:c.individualParticipantIds)||[]:c.participantId).flat():[],s=(e||[]).map(c=>{var a;return n===me&&(((a=c==null?void 0:c.participant)==null?void 0:a.individualParticipantIds)||[])||(c==null?void 0:c.participantId)&&[c.participantId]||[]}).flat();return{individualParticipantIds:s.concat(r).flat(),enteredIndividualParticipantIds:s,potentialIndividualParticipantIds:r}}function ks({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:n,tournamentRecords:r,policyDefinitions:s,matchUpFilters:i,contextFilters:o,nextMatchUps:c,inContext:a}){return typeof r!="object"||!Object.keys(r).length?{error:Gt}:{matchUps:Object.keys(r).map(f=>{const p=r[f];return He({scheduleVisibilityFilters:t,afterRecoveryTimes:e,participantsProfile:n,policyDefinitions:s,tournamentRecord:p,matchUpFilters:i,contextFilters:o,nextMatchUps:c,inContext:a}).matchUps??[]}).flat()}}function Ip({scheduleVisibilityFilters:t,participantsProfile:e,tournamentRecords:n,policyDefinitions:r,matchUpFilters:s,contextFilters:i,nextMatchUps:o,inContext:c}){return typeof n!="object"||!Object.keys(n).length?{error:Gt}:Object.keys(n).map(l=>{const f=n[l];return fT({scheduleVisibilityFilters:t,participantsProfile:e,policyDefinitions:r,tournamentRecord:f,matchUpFilters:s,contextFilters:i,nextMatchUps:o,inContext:c})}).reduce((l,f)=>(Object.keys(f).forEach(h=>{l[h]||(l[h]=[]),l[h]=l[h].concat(f[h])}),l),{})}function vo(t,e){return CO(t,e)||((t==null?void 0:t.stageSequence)||0)-((e==null?void 0:e.stageSequence)||0)||(t==null?void 0:t.roundNumber)&&e.roundNumber&&(t==null?void 0:t.roundNumber)-(e==null?void 0:e.roundNumber)||((t==null?void 0:t.roundPosition)||0)-((e==null?void 0:e.roundPosition)||0)}function CO(t,e){return(ao[t==null?void 0:t.stage]||0)-(ao[e==null?void 0:e.stage]||0)}function fr(t){var T;let e=t.tournamentRecords??{};const n=t.matchUps??[];let r=t.drawIds??[];const{includeParticipantDependencies:s,tournamentRecord:i,drawDefinition:o}=t;if(!Array.isArray(n))return{error:$s};if(!Array.isArray(r))return{error:Hn};const c=(T=t.matchUpIds)!=null&&T.length?t.matchUpIds:n.map(E=>E.matchUpId);if(!Array.isArray(c))return{error:qc};const a={},u={},l={},f={};i&&!Object.keys(e).length&&(e={[i.tournamentId]:i});const p=Object.values(e),d=p.reduce((E,y)=>E.concat(y.events||[]).map(b=>(b.drawDefinitions||[]).map(N=>N.links||[])).flat(1/0),[]).filter(({linkType:E})=>E===Ai);let m=n;if(d.length){m=ks({nextMatchUps:!0,tournamentRecords:e}).matchUps;const E=d.reduce((y,b)=>{var C,v;const N=(C=b.source)==null?void 0:C.structureId,A=(v=b.target)==null?void 0:v.structureId;return N&&A&&(l[A]=N),N&&!y.includes(N)&&y.push(N),y},[]);for(const y of E)a[y]=[];for(const y of m||[]){const b=y.containerStructureId||y.structureId;E.includes(b)&&a[b].push(y.matchUpId)}}const g=E=>{u[E]||(u[E]={dependentMatchUpIds:[],participantIds:[],matchUpIds:[],sources:[]},f[E]=[])},I=(E,y)=>{u[E].matchUpIds.forEach(N=>{u[y].matchUpIds.push(N)}),u[y].matchUpIds.push(E),u[E].dependentMatchUpIds.push(y),s&&u[E].participantIds.forEach(N=>u[y].participantIds.push(N))},S=E=>{const y=Object.keys(a).length;for(const b of E||[]){const{matchUpId:N,winnerMatchUpId:A,loserMatchUpId:C}=b;if(!c.length||c.includes(N)){if(g(N),s){const{individualParticipantIds:U}=bl(b);u[N].participantIds=U}A&&(g(A),I(N,A),f[A].push(N)),C&&(g(C),I(N,C),f[C].push(N)),u[N].sources.push(f[N]);const v=f[N].map(U=>u[U].sources[0]).flat(),P=f[N].map(U=>u[U].sources[1]).flat();if(u[N].sources.push(v,P),y){const U=b.containerStructureId||b.structureId,O=l[U];if(a[O])for(const D of a[O])g(D),I(D,N),f[D].push(N)}}}};if(o)Ic({drawDefinition:o}),m!=null&&m.length||(m=tr({drawDefinition:o}).matchUps),S(m);else{if(m!=null&&m.length||(m=ks({nextMatchUps:!0,tournamentRecords:e}).matchUps),!r.length){const E=p!=null&&p.length?p.map(({events:y=[]})=>y.map(({drawDefinitions:b=[]})=>b.map(({drawId:N})=>N))).flat(1/0):[];E&&(r=E)}for(const E of r){const y=m==null?void 0:m.filter(N=>N.drawId===E).sort(vo);if(!(y==null?void 0:y.find(({roundPosition:N})=>!N))){const N=y==null?void 0:y.find(({tournamentId:C})=>C),{drawDefinition:A}=Je({tournamentRecord:e[N==null?void 0:N.tournamentId],drawId:E});A&&Ic({drawDefinition:A})}S(y)}}return{positionDependencies:a,matchUpDependencies:u,sourceMatchUpIds:f,matchUps:m,...$}}function hT({tournamentRecords:t,matchUps:e}){if(!cr(e))return{error:$s};if(e.some(({matchUpId:d,hasContext:m})=>d&&!m))return{info:"matchUps must have { inContext: true, nextMatchUps: true }",error:Pu};const n=Math.max(...e.map(({schedule:d})=>(d==null?void 0:d.courtOrder)||1).map(d=>vt(d))),r=ht(1,n+1).map(d=>e.filter(m=>{var g;return vt((g=m.schedule)==null?void 0:g.courtOrder)===d})),s={},i={},o={};r.flat().filter(Boolean).sort(vo).forEach(({schedule:d})=>delete d[Tf]);const a=Vt(e.map(({drawId:d})=>d)),u=fr({includeParticipantDependencies:!0,tournamentRecords:t,drawIds:a}).matchUpDependencies,l=r.map((d,m)=>d.reduce((g,I)=>{if(!I.matchUpId)return g;const{matchUpId:S,winnerMatchUpId:T,loserMatchUpId:E,schedule:y,sides:b,potentialParticipants:N}=I,A=y==null?void 0:y.courtId;s[S]=m,i[A]=[],g.matchUpIds.push(S),o[S]=I;const C=u[S].matchUpIds;C.length&&g.sourceMatchUpIds.push(...C);const v=(b==null?void 0:b.map(U=>{var O;return[(O=U.participant)==null?void 0:O.individualParticipantIds,U.participantId]}).flat().filter(Boolean))||[],P=(N==null?void 0:N.flat().map(({individualParticipantIds:U,participantId:O})=>[U,O]).flat().filter(Boolean))||[];return g.participantIds.push(...P,...v),T&&g.targetMatchUpIds.push(T),E&&g.targetMatchUpIds.push(E),g},{sourceMatchUpIds:[],targetMatchUpIds:[],participantIds:[],matchUpIds:[]})),f=(d,m)=>u[d].sources.reduce((g,I,S)=>I.includes(m)&&S+1||g,0),p=l.map(()=>[]),h=(d,m,g,I)=>{if(!o[d].schedule[Tf]){o[d].schedule[Tf]=m,o[d].schedule[cP]=I,p[s[d]].push({matchUpId:d,issueType:g,issueIds:I,issue:m});const S=o[d].schedule.courtId;i[S]||(i[S]=[]),i[S].push({matchUpId:d,issue:m,issueType:g,issueIds:I})}};return l.forEach((d,m)=>{const g=m?l[m-1]:void 0,I=l.slice(m+1),S={},T=Mn(d.participantIds),E=Object.keys(T).filter(N=>T[N]>1),y=d.matchUpIds.filter(N=>u[N].participantIds.some(A=>E.includes(A)));y.forEach(N=>{S[N]||(S[N]={}),S[N][no]||(S[N][no]=y.filter(A=>A!==N))});const b=g&&d.participantIds.filter(N=>g.participantIds.includes(N));b&&b.forEach(N=>{const A=d.matchUpIds.concat(g.matchUpIds).filter(C=>u[C].participantIds.includes(N));A.forEach(C=>{S[C]||(S[C]={}),S[C][ro]||(S[C][ro]=A.filter(v=>v!==C))})}),d.matchUpIds.forEach(N=>{var v,P,U,O;const A=u[N].matchUpIds;for(const D of I){const M=D.matchUpIds.filter(w=>A.includes(w));M!=null&&M.length&&(M.forEach(w=>h(w,mI,Si,[N])),h(N,mI,Si,M))}if((v=S[N])!=null&&v[no]&&h(N,no,hI,S[N][no]),d.sourceMatchUpIds.includes(N)){const D=d.matchUpIds.filter(M=>u[M].matchUpIds.includes(N));h(N,no,Si,D),d.matchUpIds.filter(M=>u[M].matchUpIds.includes(N)).forEach(M=>h(M,no,Si,[N]))}const C=(P=g==null?void 0:g.matchUpIds)==null?void 0:P.filter(D=>f(N,D)>1);if(C!=null&&C.length&&(h(N,gI,Si,C),C.forEach(D=>h(D,gI,Si,[N]))),(U=S[N])!=null&&U[ro]&&h(N,ro,hI,S[N][ro]),(O=g==null?void 0:g.targetMatchUpIds)!=null&&O.includes(N)){const D=o[N].schedule.courtId,M=A.filter(k=>g.matchUpIds.includes(k));M.some(k=>o[k].schedule.courtId===D)||(M.forEach(k=>h(k,ro,Si,[N])),h(N,ro,Si,M))}})}),{courtIssues:i,rowIssues:p}}function Nl(t){var s;if(!t)return{};const e=[],n=t.tieFormatName,r=(s=t.collectionDefinitions)==null?void 0:s.map(i=>{const{matchUpType:o,matchUpFormat:c,matchUpCount:a,category:u,gender:l}=i;e.includes(c)||e.push(c);const f=u==null?void 0:u.ageCategoryCode;return[a,o===Tr?"D":"S",f,c,l].join(";")}).join("|");return{tieFormatName:t&&n||"UNNAMED",matchUpFormats:e,tieFormatDesc:r}}function Sc({considerations:t={},descendant:e,ancestor:n}){var I,S;const r={},s={},{matchUpFormats:i,tieFormatDesc:o}=Nl(e),{matchUpFormats:c,tieFormatDesc:a}=Nl(n),u=Vt((i??[]).filter(T=>!(c??[]).includes(T)).concat((c??[]).filter(T=>!(i??[]).includes(T)))),l=!!(t!=null&&t.collectionName&&e.collectionDefinitions.map(({collectionName:T})=>T).join("|")!==n.collectionDefinitions.map(({collectionName:T})=>T).join("|")),f=!!(t!=null&&t.collectionOrder&&e.collectionDefinitions.map(({collectionOrder:T})=>T).join("|")!==n.collectionDefinitions.map(({collectionOrder:T})=>T).join("|")),p=l||f||a!==o,h=Object.assign({},...((e==null?void 0:e.collectionDefinitions)||[]).map(T=>({[T.collectionId]:T}))),d=Object.assign({},...((n==null?void 0:n.collectionDefinitions)||[]).map(T=>({[T.collectionId]:T})));r.collectionIds=Vm(Object.keys(h),Object.keys(d)),s.collectionIds=Vm(Object.keys(d),Object.keys(h)),r.collectionsValue=mT(h,r),s.collectionsValue=mT(d,s),r.groupsCount=((I=n==null?void 0:n.collectionGroups)==null?void 0:I.length)??(0-(((S=e==null?void 0:e.collectionGroups)==null?void 0:S.length)??0)||0),s.groupsCount=r.groupsCount?-1*r.groupsCount:0;const m=r.collectionsValue.totalValue-s.collectionsValue.totalValue,g=r.collectionsValue.totalMatchUps-s.collectionsValue.totalMatchUps;return{matchUpFormatDifferences:u,matchUpCountDifference:g,descendantDifferences:r,ancestorDifferences:s,orderDifference:f,valueDifference:m,nameDifference:l,descendantDesc:o,ancestorDesc:a,...$,different:p}}function mT(t,e){let n=0;return{totalValue:e.collectionIds.reduce((s,i)=>{const o=t[i],{collectionValueProfiles:c,collectionValue:a,matchUpCount:u,matchUpValue:l}=o;return n+=u,c?s+c.reduce((f,p)=>f+p.value,0):l&&u?s+l*u:s+a},0),totalMatchUps:n}}function PO({tournamentRecord:t}){if(!t)return{error:et};if(typeof t!="object"||!t.tournamentId)return{error:tt};const{matchUps:e}=He({tournamentRecord:t,inContext:!1});if(e!=null&&e.length){const n=UO({tournamentRecord:t});MO(e,n)}return{...$}}function UO({tournamentRecord:t}){const e={};for(const n of t.events||[]){n.matchUpFormat&&(e[n.eventId]=n.matchUpFormat);for(const r of n.drawDefinitions||[]){r.matchUpFormat&&(e[r.drawId]=r.matchUpFormat);for(const s of r.structures||[]){s.matchUpFormat&&(e[s.structureId]=s.matchUpFormat);for(const i of s.structures||[])i.matchUpFormat&&(e[i.structureId]=i.matchUpFormat)}}}return e}const OO=["collectionId","collectionPosition","drawPositions","extensions","finishingPositionRange","finishingRound","isMock","matchUpId","matchUpStatus","matchUpStatusCodes","orderOfFinish","processCodes","roundNumber","tieFormat","tieMatchUps","roundPosition","score","sides","winnerMatchUpId","loserMatchUpId","matchUpDuration","winningSide"];function MO(t,e={}){for(const n of t){const{structureId:r,drawId:s,eventId:i}=n,o=e[r]||e[s]||e[i],c=n.matchUpFormat===o?void 0:n.matchUpFormat;for(const a of Object.keys(n))OO.includes(a)||delete n[a];n.sides&&n.drawPositions&&!n.tieMatchUps&&delete n.sides,c&&(n.matchUpFormat=c)}}function Ga({court:t,date:e}){const n=e&&t.dateAvailability.find(s=>as(s.date,e)),r=t.dateAvailability.find(s=>!s.date);return n||r}function Tc({includeBookingTypes:t=[],courtDate:e}){const n=[];let r=Pe(e.startTime);(e.bookings||[]).filter(i=>!i.bookingType||!t.includes(i.bookingType)).sort((i,o)=>ku(i.startTime).localeCompare(ku(o.startTime))).forEach(i=>{const o={startTime:de(r.toISOString()),endTime:i.startTime};Pe(i.startTime)>r&&n.push(o),Pe(i.endTime)>r&&(r=Pe(i.endTime))});const s={startTime:de(r.toISOString()),endTime:e.endTime};return Pe(e.endTime)>r&&n.push(s),n}function DO({averageMatchUpMinutes:t,includeBookingTypes:e,periodStartTime:n,periodEndTime:r}){const s=o=>!!Tc({includeBookingTypes:e,courtDate:o}).filter(i).length;function i(o){const c=Pe(o.startTime),a=Pe(o.endTime);return c>n||a<r?!1:ea(n,a)>=t}return{enoughTime:s}}function gT(t){const{averageMatchUpMinutes:e,includeBookingTypes:n,periodStart:r,date:s}=t,i=t.courts,o=Pe(r),c=nf(o,e),{enoughTime:a}=DO({averageMatchUpMinutes:e,includeBookingTypes:n,periodStartTime:o,periodEndTime:c});return{availableToScheduleCount:((i==null?void 0:i.filter(l=>{if(!Array.isArray(l.dateAvailability))return!1;const f=Ga({date:s,court:l});return!!(f&&a(f))}))||[]).length}}function Sp(t){const{remainingScheduleTimes:e=[],clearScheduleDates:n,periodLength:r=30,scheduleDate:s,courts:i=[]}=t;let{bookings:o=[]}=t;if(!Array.isArray(i)||!i.length)return{error:tt,courts:i};if(!Array.isArray(o))return{error:Wd};if(!Yn(s))return{error:bn};n&&(Array.isArray(n)?n.includes(s)&&(o=[]):o=[]);const{courtBookings:c,unassignedBookings:a}=o.reduce((h,d)=>{const{courtId:m}=d;return m?h.courtBookings[m]?h.courtBookings[m].push(d):h.courtBookings[m]=[d]:h.unassignedBookings.push(d),h},{courtBookings:{},unassignedBookings:[]}),u=i.map((h,d)=>{const{courtId:m,courtName:g}=h,I=c[m]||[],S=Ga({date:s,court:h})||{},{bookings:T=[],startTime:E,endTime:y,date:b}=S,A=[e[d]&&{startTime:E,endTime:e[d]},...pt(T,!1,!0),...I].filter(Boolean);return{courtId:m,courtName:g,dateAvailability:{bookings:A,startTime:E,endTime:y,date:b}}});a.sort((h,d)=>jt(h.startTime)-jt(d.startTime));const l=()=>u.map(h=>{const d=h.dateAvailability,m=Tc({courtDate:d});return{courtName:h.courtName,courtId:h.courtId,timeSlots:m}}).flat(),f=[];for(const h of a){const{startTime:d,endTime:m,averageMinutes:g,recoveryMinutes:I,matchUpId:S}=h,T=jt(d),E=jt(m),b=l().reduce((N,{courtId:A,courtName:C,timeSlots:v})=>{let P;return v.find(({startTime:O,endTime:D})=>{P=jt(O)-T;const M=T>=jt(O);return E<=jt(D)&&N.startDifference!==0&&((P===0||P+r>=0)&&(N.startDifference===void 0||P<N.startDifference)||M)})?{courtName:C,courtId:A,startDifference:P}:N},{});if(b.courtId){const N={averageMinutes:g,recoveryMinutes:I,matchUpId:S,startTime:d,endTime:m};f.push(N);const A=u.find(({courtId:C})=>C===b.courtId);A==null||A.dateAvailability.bookings.push(N)}else console.log({unassignedBooking:h})}return{virtualCourts:u.map(({courtId:h,courtName:d,dateAvailability:m})=>({dateAvailability:[m],courtName:d,courtId:h})),assignedBookings:f}}function Al({averageMatchUpMinutes:t,periodLength:e=30,recoveryMinutes:n}){const r=(t||90)+(n||0);return e>r?r:e||30}function yc({scheduleDate:t,startTime:e,endTime:n,courts:r}){const s=e&&"startTime"||n&&"endTime"||void 0;return r.reduce((i,o)=>{const c=Ga({date:t,court:o}),a=s&&((c==null?void 0:c[s])||o[s]);return a&&(!i||e&&jt(a)<jt(i)||n&&jt(a)>jt(i))?a:i},void 0)}function wO({averageMinutes:t,startTime:e,endTime:n,courts:r,date:s}){e=e||yc({courts:r,scheduleDate:s,startTime:!0}),n=n||yc({courts:r,scheduleDate:s,endTime:!0});let i;if(e&&n){const o=Pe(e),c=Pe(n);for(const a of r||[]){if(!Array.isArray(a.dateAvailability))continue;const u=Ga({court:a,date:s});Tc({courtDate:u}).forEach(f=>{const p=Pe(f.startTime),h=Pe(f.endTime);if(p>c||p<o||h<o)return!1;if(ea(p,h)>=t){const g=de(p.toISOString());(!i||g<i)&&(i=g)}})}}return{firstTimeSlotStartTime:i}}function IT(t){const{startTime:e="8:00",endTime:n="20:30",count:r=10,date:s}=t||{};return ht(0,r).map(()=>({dateAvailability:[{date:s,startTime:e,endTime:n}]}))}function Tp(t){let{date:e=tf(),startTime:n="08:00",endTime:r="19:00",periodLength:s,courts:i}=t;const{calculateStartTimeFromCourts:o=!0,remainingScheduleTimes:c,averageMatchUpMinutes:a,clearScheduleDates:u,courtsCount:l,bookings:f}=t;s=s||Al({averageMatchUpMinutes:a}),e=Bt(e),n=de(n),r=de(r);let p=0,h=0,d=0,m=0,g=0;!i&&l&&(i=IT({startTime:n,endTime:r,count:l,date:e}));const{virtualCourts:I}=Sp({remainingScheduleTimes:c,clearScheduleDates:u,scheduleDate:e,periodLength:s,bookings:f,courts:i}),{firstTimeSlotStartTime:S}=wO({averageMinutes:a,courts:I,startTime:n,endTime:r,date:e});o&&S&&(n=S||n);const T=jt(n),y=jt(r)-T,b=Math.floor(y/s),A=ht(0,b+1).map(v=>{const P=T+v*s,U=dC(P),{availableToScheduleCount:O}=gT({courts:I||[],averageMatchUpMinutes:a,periodStart:U,date:e}),D=O>h?O-h:0;g+=v?O:0;const M=v?g/v:O,k=s*M/a,_=v?k*(v-1)+M:M,F=O?h&&_-p||D:0;p=_,h=O,d+=F;const L=vt(d)-m;return m+=L,{periodStart:U,add:L,availableToScheduleCount:O,newCourts:D,totalMatchUps:m}});return{scheduleTimes:A.reduce((v,P)=>{const O=ht(0,P.add).map(()=>({scheduleTime:P.periodStart}));return v.concat(...O)},[]).flat(),timingProfile:A,totalMatchUps:m}}const kO={getCourtsAvailableAtPeriodStart:gT,generateTimeSlots:Tc,getScheduleTimes:Tp,courtGenerator:IT},_O=(t,e)=>t.filter(Boolean).every(n=>typeof n===e),FO=t=>t.filter(Boolean).every(Me);function ST({consideredDate:t,category:e}={consideredDate:""}){const n={error:tt,ageMin:8,ageMax:99};if(typeof e!="object"||!Yn(t))return n;const r=parseInt(t.split("-")[0]),s=[];let{ageCategoryCode:i,ageMaxDate:o,ageMinDate:c,ageMax:a,ageMin:u}=e;const l=e.categoryName;let f;if(!_O([i,o,c,l],"string")||!FO([a,u]))return n;i=i??l;const p=/^([UO]?)(\d{1,2})([UO]?)$/,h=/^C(\d{1,2})-(\d{1,2})$/,d=i==null?void 0:i.includes("-"),m=d&&(i==null?void 0:i.match(h)),g=i==null?void 0:i.match(p),I=A=>A.match(/^\d{2}-\d{2}$/),S=(A,C,v)=>Yn(C)&&C||C&&I(C)&&`${A}-${C}`||`${A}-${v}`,T=A=>{const C=r-A;return c=S(C,c,"01-01"),a&&a!==A-1&&s.push(`Invalid ageMax: ${a}`),a||(a=A-1),{ageMinDate:c,ageMax:a}},E=A=>{const C=r-A-1;return c=S(C,c,"01-01"),a&&a!==A&&s.push(`Invalid ageMax: ${a}`),a||(a=A),{ageMinDate:c,ageMax:a}},y=A=>{const C=r-A-2;return o=S(C,o,"12-31"),u&&u!==A+1&&s.push(`Invalid ageMin: ${u}`),u||(u=A+1),{ageMaxDate:o,ageMin:u}},b=A=>{const C=r-A-1;return o=S(C,o,"12-31"),u&&u!==A&&s.push(`Invalid ageMin: ${u}`),u||(u=A),{ageMaxDate:o,ageMin:u}},N=A=>{const[C,v,P]=(A.match(p)||[]).slice(1),U=parseInt(v);C==="U"&&({ageMinDate:c,ageMax:a}=T(U)),P==="U"&&({ageMinDate:c,ageMax:a}=E(U)),C==="O"&&({ageMaxDate:o,ageMin:u}=y(U)),P==="O"&&({ageMaxDate:o,ageMin:u}=b(U))};if(m){const[A,C]=((i==null?void 0:i.match(h))??[]).slice(1).map(v=>parseInt(v));A<=C?(u=u??A,a=a??C,f=!0):s.push(`Invalid combined age range ${i}`)}else d?i==null||i.split("-").forEach(N):g&&N(i);return s.length?{error:s,ageMin:8,ageMax:99}:bt({combinedAge:f,ageMaxDate:o,ageMinDate:c,ageMax:a,ageMin:u})}function vl({tiebreakTo:t=7,scoreString:e}){return e.split(" ").filter(Boolean).map((r,s)=>n({set:r,setNumber:s+1}));function n({set:r,setNumber:s}){const i=(r==null?void 0:r.startsWith("["))&&r.split("[")[1].split("]")[0].split("-").map(g=>parseInt(g)),o=r.includes("(")&&r.split("(")[0]||r.includes("[")&&r.split("[")[0]||r,c=!i&&o.split("-").map(g=>parseInt(g)),a=i?i[0]>i[1]&&1||i[0]<i[1]&&2||void 0:c[0]>c[1]&&1||c[0]<c[1]&&2||void 0,u=r.includes("(")?r.split("(")[1].split(")")[0]:void 0,f=u&&dp({lowValue:u,isSide1:a===2,tiebreakTo:t})||[],[p,h]=c||[],[d,m]=i||f||[];return{side1Score:p,side2Score:h,side1TiebreakScore:d,side2TiebreakScore:m,winningSide:a,setNumber:s}}}function yp({drawPositions:t}){const e=s=>t.filter(i=>i!==s).map(i=>[s,i]),n=[].concat(...t.map(e)),r=Vt(n.map(Cl)).map(s=>s.split("|").map(i=>+i));return{groupMatchUps:n,uniqueMatchUpGroupings:r}}function Cl(t){return t.sort(Ve).join("|")}function TT({groupSize:t,drawPositionOffset:e}){const n=f=>[...Array(f)].map((p,h)=>h),r=n(2*Math.round(t/2)+1).slice(1),s=n(r.length-1).map(()=>[]);let i=r.slice(0,r.length/2),o=r.slice(r.length/2);r.slice(1).forEach((f,p)=>{i.forEach((g,I)=>{s[p].push([i[I],o[I]])});const h=i.shift(),d=i.pop(),m=o.shift();i=[h,m,...i].filter(Boolean),o=[...o,d].filter(Boolean)});const c=i.shift(),a=i.pop(),u=o.shift();i=[c,u,...i].filter(Boolean),o=[...o,a].filter(Boolean);const l=f=>f[0].reduce((p,h)=>p+h);return s.reverse().sort((f,p)=>l(f)-l(p)).map(f=>f.filter(p=>p.every(h=>h<=t)).map(p=>{const h=p.map(d=>d+e);return Cl(h)}))}function LO({rounds:t,hash:e}){return t.reduce((n,r,s)=>r.includes(e)?s+1:n,void 0)}const RO={getRoundRobinGroupMatchUps:yp,determineRoundNumber:LO,drawPositionsHash:Cl,groupRounds:TT},Pl="\\d+-\\d+",Wa="\\d+-\\d+\\(\\d+\\)",Ep="\\[\\d+-\\d+\\]",BO="\\d+-\\d+\\(\\d+-\\d+\\)",xO=new RegExp(`(${Pl}),`,"g"),$O=new RegExp(`(${Wa}),`,"g"),VO=[Pl,Wa,Ep,BO],jO=["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"].map(t=>{const n=t.split("").map(r=>VO[r]).join(" ");return new RegExp(`^${n}$`)});function yT(t){return!t||jO.some(e=>e.test(t))}function GO(t){const e="[];",n="()",r=e+n,s=[e[0],n[0]],i=Object.assign({},...r.split("").map(a=>({[a]:0})));let o="";const c=t.split("").map(a=>{const u=r.includes(a)&&a,l=s.includes(u);if(l&&u)return i[u]+=1,o=u,a;if(!l&&u&&o&&u!==o){i[o]-=1;const f=e.includes(o)&&e||n.includes(o)&&n||"",p=f.split("").find(h=>h!==o);if(f.includes(u))i[o]||(o="");else return i[u]||(o=""),p}return a}).join("");return t!==c?c:t}function Ul(t){return/^\(\d+\)$/.test(t)||/^\(\d+$/.test(t)}function WO(t){return/^\(\d+-\d+\)$/.test(t)||/^\[\d+-\d+\]$/.test(t)}function Ec(t){const n=(r=>r==null?void 0:r.split("-").join("").split("/").join(""))(t);if(/^\d+$/.test(n)&&n.length===2){const r=n.split("");return Math.abs(r.reduce((i,o)=>+i-+o))===1}return!1}function Ol(t,e){const n=[t.slice(e,e+2),e?t.slice(0,1):t.slice(2)].map(i=>parseInt(i.join(""))),r=e?n.reverse():n;if(Math.abs(r.reduce((i,o)=>+i-+o))>=2)return r.join("-")}function ET(t){return t.length===2?t.split("").join("-"):([", ",",","/"," "].forEach(e=>t=t.split(e).join("-")),t=t.replace(/-{2,}/,"-"),t)}function HO(t){return t.startsWith("(")&&t.endsWith(")")}function qO({score:t,applied:e}){t=GO(t);const n=/\)(\d+)/g;if(n.test(t))for(const b of t.match(n)){const N=b.replace(")",") ");t=t.replace(b,N)}t=t.replace(/\)\//g,") / "),t=t.replace(/\/\)/g,")");const r=/\(([\d- ]+)\)/g,s=/\(([\d- ]+)\)/,i=t.match(r);for(const b of i||[]){const[N]=b.match(s).slice(1),A=N.replace(/ /g,"");t=t.replace(b,`(${A})`)}let o=/\(\(\d-\d\)\)/g;if(o.test(t)){const b=t.match(o);b.length&&b.forEach(N=>{const A=N.match(/\((\(\d-\d\))\)/).slice(1)[0];t=t.replace(N,A)})}if(o=/\(\((\d)\)\)/g,o.test(t)){const b=t.match(o);b.length&&b.forEach(N=>{const A=N.match(/\((\(\d\))\)/).slice(1)[0];t=t.replace(N,A)})}/(^|\s)6-,/.test(t)&&(t=t.replace(/(^|\s)6-,/g,"6-0,"));const c=new RegExp(/[-,]{2,}/g);t=t.replace(c,"-"),["- "," -"].forEach(b=>{const N=new RegExp(`(\\d+)${b}(\\d+)`,"g"),A=t.match(N);A&&A.forEach(C=>t=t.replace(C,C.split(b).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," "));const a=/\(\d+, \)/g;a.test(t)&&t.match(a).forEach(N=>{const[A]=N.match(/\((\d+), \)/).slice(1);A.length===2?t=t.replace(N,`(${A})`):A.length===1&&A==="6"&&(t=t.replace(N,"(6-0)"))});const u=/\((\d+)\/\)/g;u.test(t)&&t.match(u).forEach(N=>{const[A]=N.match(/\((\d+)\/\)/).slice(1);A.length===2?t=t.replace(N,`(${A})`):A.length===1&&A==="6"?t=t.replace(N,"(6-0)"):t=t.replace(N,`(${A})`)});const l=/\d\/\d\/,/g;l.test(t)&&t.match(l).forEach(N=>{const[A]=N.match(/(\d\/\d)\/,/).slice(1);t=t.replace(N,`${A},`),e.push("slashComma")});const f=/\(\/(\d+)\)/g;f.test(t)&&t.match(f).forEach(N=>{const[A]=N.match(/\(\/(\d+)\)/).slice(1);A.length===2?t=t.replace(N,`(${A})`):A.length===1&&parseInt(A)<6?t=t.replace(N,`(6-${A})`):t=t.replace(N,`(${A})`)});let p,h,d,m,g;const I=()=>{g=Mn(t.split("")),h=g["("]===(g[")"]||0)+1,p=(g["("]||0)+1===g[")"],d=g["["]===g["]"]+1,m=h&&!d};I();const S=/(\d+-\d+\(\d+)0,/;if(S.test(t)){const[b]=t.match(S).slice(1);t=t.replace(S,b+")")}if(g["("]===g[")"]&&g["("]>1){const b=t.split(")(").join(") (").split(" ");b.every(HO)?t=b.map(N=>{const A=N.slice(1,N.length-1);return A.length>2?A:N}).join(" "):t=b.join(" ")}I();const T=/[A-Za-z]+/.test(t),E=/\d+/.test(t);if(!T&&!E)return{score:""};if(/^\[.+\]$/.test(t)&&"()/,- ".split("").some(b=>g[b])&&(t=t.slice(1,t.length-1)),/^\(.+\)$/.test(t)&&g["("]===1&&g[")"]===1&&"[]/,".split("").some(b=>g[b]>1)&&(t=t.slice(1,t.length-1)),t.startsWith("(")&&t.endsWith("))")&&(t=t.slice(1,t.length-1)),g["("]>(g[")"]||0)&&t[t.length-1]==="("&&(t=t.slice(0,t.length-1)+")",I()),g["("]===1&&!g[")"]&&t[0]==="("&&(t=t+")",I()),g["("]>(g[")"]||0)&&t.slice(0,2)==="(("&&(t=t.slice(1)),p){if(/^9\d/.test(t))t="("+t.slice(1);else if(t[0]!=="(")t="("+t;else{const b=[];let N=0;for(const A of t.split("").reverse())A===")"&&(N?b.push("("):N+=1),A==="("&&(N-=1),b.push(A);b.reverse(),t=b.join("")}I()}if(g[")"]>(g["("]||0)&&t[0]===")"&&(t="("+t.slice(1),I()),m&&(t.endsWith(9)||/\d+0$/.test(t))&&(t=t.slice(0,t.length-1)+")",I()),m&&(!t.endsWith(")")||t.startsWith("(("))&&(t=t+")",I()),m){let b="",N=0;for(const A of t.split(""))A==="("&&(N?b+=")":N+=1),A===")"&&(N-=1),b+=A;t=b}I(),d&&!h&&(t=t+"]"),t.includes("([")&&t.includes("])")&&(t=t.split("([").join("[").split("])").join("]"),I()),/\(\d+0$/.test(t)&&(t=t.slice(0,t.length-1)+")"),I(),g[")"]===1&&!g["("]&&t.endsWith(")")&&(t=t.slice(0,t.length-1)),t.startsWith("(")&&t.endsWith(")")&&g["("]===1&&g[")"]===1&&(t=t.slice(1,t.length-1),I());const y=b=>{const N=b.indexOf("("),A=b.indexOf(")");return N>=0&&A>=0&&N<A};if(/^\([\d ]+.*[\d ]+\)$/.test(t)&&g["("]===g[")"]){const b=t.slice(1,t.length-1);y(b)&&(t=b,I())}return{score:t,applied:e}}function Ml(t){if(!/^[\d-]+(\(\d\))*$/.test(t))return t;const e=Br("-",t.split(""));if(!e.length)return t;const n=t.split("-"),r=!(n.length%2),s=!!(e.length%2);return r&&s&&e.length>n.length/2&&e.filter((o,c)=>c%2).forEach(o=>{t=t.substring(0,o)+" "+t.substring(o+1)}),t}function YO({score:t,applied:e}){return t.includes("( ")&&(e.push("removeParenSpacingAfterOpen"),t=t.split("( ").map(n=>n.trim()).join("(")),t.includes(" )")&&(e.push("removeParenSpacingBeforeClose"),t=t.split(" )").map(n=>n.trim()).join(")")),[xO,$O].forEach(n=>{const r=t.match(n);r!=null&&r.length&&(r.forEach(s=>{t=t.replace(s,s.slice(0,s.length-1)+" ")}),e.push("setsEndComma"))}),t=t.split(" ").filter(Boolean).map(Ml).join(" "),{score:t,applied:e}}function zO({score:t}){if(typeof t!="string")return{score:t};const e=p=>p==null?void 0:p.split("-").join("").split("/").join(""),n=p=>p.split("[").join("(").split("]").join(")");t=t.split(", ").join(" ");let r=t.split(" ");t=r.map(p=>{const h=/^-(\d+)$/;if(h.test(p)){const[d]=p.match(h).slice(1);if(d.length===2)return d.split("").join("-")}return p}).join(" "),r=t.split(" ");const s=r.filter(Ul);let i=0,o="";for(const p of s){const h=Br(p,r).filter(I=>!i||I>i)[0],d=r.slice(i,h-1),m=r[h-1],g=e(m);if(/^\d+$/.test(g)&&g.length===2){const I=g.split(""),S=Math.abs(I.reduce((T,E)=>+T-+E));if(S===1){const T=[d.join(" "),[m,p].join("")].join(" ");o+=T,i=h+1}else if(S===0){const T=Math.max(...I);if([4,5,6,7,8,9].includes(T)){const E=[6,4].includes(T)?T+1:T-1,y=[T,E].sort().reverse().join("-"),b=[d.join(" "),[y,p].join("")].join(" ");o+=b,i=h+1}}}}if(s.length&&o.length){const p=r.slice(i).join(" ");return o=[o,p].join(" "),{score:o.trim()}}if(r.length===2&&["(","["].some(p=>r[1].includes(p))){const h=e(r[0]).split("");if(Math.abs(h.reduce((m,g)=>+m-+g,0))===1)return r[1]=n(r[1]),{score:r.join("")}}const c=r.map(p=>WO(p)&&"bracket"||Ec(p)&&"set");if(c.includes("set")&&c.includes("bracket")){let p,h="";return r.forEach((d,m)=>{c[m]==="bracket"&&p==="set"?(d=n(d),h+=d):h+=` ${d}`,p=c[m]}),{score:h.trim()}}r=t.split(" ");let a,u=r.map(p=>{const h=new RegExp(/^(\d+)-(\d+)$/);if(h.test(p)){const[d,m]=p.match(h).slice(1),g=Math.abs([d,m].reduce((S,T)=>+S-+T)),I=Math.max(d,m);if(g===1)return a="tiebreakSet",a;if(g>=2&&I>=7&&a==="tiebreakSet")return a="tiebreak",a}});const l=Br("tiebreak",u);if(l.length){let p="";r.forEach((h,d)=>{l.includes(d)?p+=`(${h}) `:l.includes(d+1)?p+=`${h}`:p+=`${h} `}),t=p.trim()}const f=/(\d+-\d+)\((\d+)-(\d+)\)$/;if(f.test(t)){const[p,h,d]=t.match(f).slice(1),g=Math.max(h,d)>=10;!Ec(p)&&g&&(t=t.replace(f,`${p} [${h}-${d}]`))}return u=[],t=t.split(" ").map(p=>{const h=/^\((.*)\)$/,d=h.test(p),m=new RegExp(Ep).test(p)&&"super"||new RegExp(Wa).test(p)&&"tiebreak"||new RegExp(Pl).test(p)&&"standard"||"unknown";return u.push(m),m==="standard"&&d?p.match(h)[1]:p}).join(" "),{score:t}}function KO({score:t,applied:e}){for(const v of[".",","," ","/"]){const P=new RegExp(`^(\\d+)\\${v}(\\d+)$`);if(P.test(t)){const U=t.match(P).slice(1).map(D=>parseInt(D)),O=Math.abs(U[0]-U[1]);O<=10&&O>=2&&(t=t.split(v).join("-"),e.push("variedJoinerPattern"))}}t.includes(";")&&(t=t.split(";").join(" "),e.push("semicolon set separation"));const n=/(^|\s)(\d)\/(\d)(\d)\/(\d)(\(|$)/;if(n.test(t)){const[v,P,U,O,D,M]=t.match(n).slice(1);t=t.replace(n,`${v}${P}-${U} ${O}-${D}${M}`),e.push("smashSlashPattern")}/.*\s6[/-]+$/.test(t)&&(t+="0",e.push("incompleteFinalSetPattern"));const s=/\(6,\)/g;s.test(t)&&(t=t.replace(s,"(6, 0)"),e.push("missingZeroPattern1"));const i=/^\d{3,}\(/,o=/\(\d+\)\d+/;[i,o].forEach(()=>{t=t.split(" ").map(P=>(i.test(P)&&(P=P.replace("("," (")),o.test(P)&&(P=P.replace(")",") ")),P)).join(" "),e.push("spaceConsiderationPatterns")});const a=Ml(t);a!==t&&(t=a,e.push("deDashMash"));const u=/^(\d)[-/,]+(\d{2})[-/,]+(\d)$/;if(u.test(t)){const[v,P,U]=t.match(u).slice(1),[O,D]=P.split("");t=`${v}-${O} ${D}-${U}`,e.push("smashSetPattern")}const l=/^(\d+)[ -](\d+)$/,f=/^([\d -]+)\/([\d -]+)$/;if(f.test(t)){const[v,P]=t.match(f).slice(1),U=v.trim(),O=P.trim();if(l.test(U)&&l.test(O)){const D=U.match(l).slice(1,3).join("-"),M=O.match(l).slice(1,3).join("-");t=`${D} ${M}`,e.push("slashSeparationPattern")}}const p=/^([\d -]+),([\d -]+)$/;if(p.test(t)){const[v,P]=t.match(p).slice(1),U=v.trim(),O=P.trim();if(l.test(U)&&l.test(O)){const D=U.match(l).slice(1,3).join("-"),M=O.match(l).slice(1,3).join("-");t=`${D} ${M}`,e.push("commaSeparationPattern")}}const h=/^\d \d,/;if(h.test(t)){const v=t.match(h)[0],P=v.slice(0,v.length-1).split(" ").join("-");t=t.replace(v,P),e.push("singleSetCommaSeparationPattern")}let d=0;const m=/(\d+)-(\d{2})-(\d+)/;for(;m.test(t)&&d<3;){const[v,P,U]=t.match(m).slice(1),O=P.split(""),D=`${v}-${O[0]} ${O[1]}-${U}`;t=t.replace(m,D),e.push("noSetSeparationPattern"),d+=1}const g=/(^|\s)7-6\s(\d+)\s/g,I=t.match(g);if(I!=null&&I.length){const v=/(^|\s)7-6\s(\d+)\s/;I.forEach(P=>{const U=P.match(v).slice(2)[0];t=t.replace(P,`7-6(${U}) `),e.push("floatingTiebreakPattern1")})}let S=t.match(/\d \d /);S==null||S.forEach(v=>{const P=v.slice(0,v.length-1).split(" ").join("-");t=t.replace(v,P),e.push("spaceSeparatedSetPattern1")}),S=t.match(/ \d \d$/),S==null||S.forEach(v=>{const P=" "+v.slice(1).split(" ").join("-");t=t.replace(v,P),e.push("spaceSeparatedSetPattern2")});const T=/^\d, *\d\/\d, *\d/;if(T.test(t)){const v=t.match(T)[0],P=v.split("/").map(U=>`(${U})`).join(" ")+" ";t=t.replace(v,P),e.push("slashCommaSetPattern")}const E=/\(6-\)/g;E.test(t)&&(t=t.replace(E,"(6-0)"),e.push("missingZeroPattern2"));const y=new RegExp("(?<!-)(\\d+)\\/(\\d+)(?!-)","g");if(y.test(t)){const v=t.match(y),P=new RegExp("(?<!-)(\\d+)\\/(\\d+)(?!-)");let U=t;v.forEach(O=>{const[D,M]=O.match(P).slice(1),w=`${D}-${M}`;U=U.replace(O,w)}),t=U,e.push("slashSetPattern")}const b=/(.*)\s(1\d)\s(\d+)$/;if(b.test(t)){const[v,P,U]=t.match(b).slice(1);v.replace(/\D/g,"").length>=4&&(t=v+` ${P}${U}`,e.push("spaceSeparatedSuperPattern"))}const N=/(^|\s)(\d+-\d+)\s(\d+)(\s|$)/g;for(const v of t.match(N)||[]){const[P,U,O,D]=v.match(/(^|\s)(\d+-\d+)\s(\d+)(\s|$)/).slice(1),[M,w]=U.split("-").map(_=>parseInt(_));Math.abs(M-w)===1&&(t=t.replace(v,`${P}${U}(${O})${D}`),e.push("spaceSeparatedSetPattern"))}const A=/\d-\d \(\d{1,2}\)(\s|$|,)/g;for(const v of t.match(A)||[]){const P=/(\d-\d) \((\d{1,2})\)(\s|$|,)/,[U,O,D]=v.match(P).slice(1),[M,w]=U.split("-").map(_=>parseInt(_));Math.abs(M-w)===1&&(t=t.replace(v,`${U}(${O})${D}`),e.push("floatingTiebreakPattern2"))}const C=/(^|\s)(\d \d)\(/g;for(const v of t.match(C)||[]){const P=/(^|\s)(\d \d)\(/,[U,O]=v.match(P).slice(1);t=t.replace(v,`${U}${O.split(" ").join("-")}(`),e.push("spacedTiebreakPattern")}return{score:t,applied:e}}function JO({score:t,matchUpStatus:e}){var c;let n=t==null?void 0:t.split(" ");t=n.map(a=>{if(a.endsWith("]")){const u=a.split("[");if(Ec(u[0]))return u[0]+`(${u[1].slice(0,u[1].length-1)})`}return a}).join(" ");const r=new RegExp(/(\([\d ]+\))/g);if(r.test(t))for(const a of t.match(r)){let l=(c=a.replace(" ","-").match(/\((.*)\)/))==null?void 0:c[1];if(Me(l)&&(l==null?void 0:l[0])>2){if([2,4].includes(l.length))l=l.split("").join("-");else if(l.length===3){const f=l.indexOf("1");l=Ol(l.split(""),f)}}t=t.replace(a,`(${l})`)}n=t==null?void 0:t.split(" ");let s=new RegExp(/^(\d[-/]+\d)\((\d+)[-/]+(\d+)\)$/);const i=n.length-1;t=n.map((a,u)=>{const l=[void 0,"","COMPLETED"].includes(e)||u!==i;if(s.test(a)&&l){const[f,p,h]=Array.from(a.match(s)).slice(1),d=Math.min(p,h);return`${f}(${d})`}return a}).join(" "),n=t==null?void 0:t.split(" "),s=new RegExp(/^(\d{2})\((\d+)\)$/),t=n.map(a=>{if(s.test(a)){const[u,l]=Array.from(a.match(s)).slice(1),f=u.split("");return`${f[0]}-${f[1]}(${l})`}return a}).join(" "),n=t==null?void 0:t.split(" "),s=new RegExp(/^\((\d[-/]+\d)\)(\d+)$/),t=n.map(a=>{if(s.test(a)){const[u,l]=Array.from(a.match(s)).slice(1);return Ec(u)?`${u}(${l})`:u}return a}).join(" "),n=t==null?void 0:t.split(" "),s=new RegExp(/^1-0\((\d+)\)$/),t=n.map(a=>{if(s.test(a)){const[u]=a.match(s).slice(1);return`[${u<9?10:parseInt(u)+2}-${u}]`}return a}).join(" ");const o=/\((\d)+0 /;if(o.test(t)){const a=t.match(o)[1];t=t.replace(o,`(${a}) `)}return{score:t}}function QO({score:t,attributes:e,identifier:n}){var f;if(typeof t!="string")return{score:t,identifier:n};const r=new RegExp(/\([\d,/ ]+\)/g),s=t.match(r);for(const p of s||[]){const h=p.match(/^\((.*)\)$/),d=(f=h==null?void 0:h.slice(1))==null?void 0:f[0],g=t.split(p)[0].split(")").reverse()[0].replace(/\D/g,"");if((d==null?void 0:d.length)===2&&(g==null?void 0:g.length)>=2){const T=g.slice(g.length-2).split("").map(y=>parseInt(y));if(Math.abs(T[0]-T[1])===1)continue}const I=ET(d),S=Ml(I);t=t.replace(p,`(${S})`).trim()}const i=new RegExp(/\[[\d,/ ]+\]/g),o=t.match(i);o==null||o.forEach(p=>{const h=ET(p.match(/^\[(.*)\]$/)[1]);t=t.replace(p,`(${h}) `).trim()});const c=[")","]"],a=[")(","), (",") (",")[",") [","](","] ("];if(t.startsWith("(")&&c.some(p=>t.endsWith(p))&&a.some(p=>t.includes(p))){let p="";const h=t.split(/[)\]]/).filter(Boolean).map(S=>(S.startsWith(",")&&(S=S.slice(1)),S.trim())),d=h.every(S=>S.includes(",")||Ul(S)),m=h.every(S=>S.includes("/")||Ul(S)),g=h.every(S=>S.includes("-")||Ul(S)),I=d&&","||g&&"-"||m&&"/";if(I){let S;h.forEach(T=>{if(T.startsWith("("))if(S==="set"&&(p+=" "),T.includes(I))p+=T.slice(1).split(I).map(E=>E.trim()).join("-"),S="set";else{const E=T.slice(1);p+=`(${E}) `,S="tiebreak"}else if(T.startsWith("[")){const E=T.slice(1).split(I).map(b=>parseInt(b.trim())),y=Math.min(...E);S==="set"?p+=`(${y}) `:p+=`[${E.join("-")}] `,S="tiebreak"}}),t=p.trim()}}const u=Mn(t.split(""));u["("]===1&&u[")"]===1&&t.startsWith("(")&&t.endsWith(")")&&(t=t.slice(1,t.length-1),u["-"]===1&&Ec(t)&&Me(e==null?void 0:e.removed)&&(t=t+`(${e.removed})`,e.removed=void 0));const l=/\(\)/g;return l.test(t)&&(t=t.replace(l,"").trim()),{score:t}}function bT({score:t}){const e=t.split(""),n=[];let r;const s=()=>r=[void 0,void 0,void 0],i=()=>{let c=`${r[0]}-${r[1]}`;return r[2]&&(c+=` (${r[2]})`),s(),r.push(r),c};s();const o=()=>r[0]!==void 0&&r[1]!==void 0&&Math.abs(parseInt(r[0])-parseInt(r[1]));for(;e.length;){const c=e.shift(),a=Me(c)&&parseInt(c),u=r[0]!==void 0&&r[1]!==void 0;if(Me(a)){if(r[0]===void 0){r[0]=a;continue}if(r[1]===void 0&&(r[1]=a,o()||0>1)){n.push(i()),r=[void 0,void 0];continue}if(u&&e.length===1&&Me(e[0])){const l=e.pop();r[0]=r[0].toString()+r[1].toString(),r[1]=l,n.push(i()),r=[void 0,void 0]}u&&o()}}return{sets:n}}function bp(t){const e=t.indexOf("1"),n=t.split(""),r=n.every(s=>!isNaN(s));if(r&&t.length===3&&e===0){const s=Ol(n,e);if(s)return s}if(r&&t.length===7&&e>3){const s=n.slice(4),i=Ol(s,e-4);if(i)return`${n[0]}-${n[1]} ${n[2]}-${n[3]} ${i}`}}function NT(t){let{score:e}=t;const{applied:n,matchUpStatus:r}=t,s=e==null?void 0:e.toString().split(""),i=s==null?void 0:s.every(c=>Me(c)),o=c=>Math.abs(c[0]-c[1]);if(typeof e=="number"||i){e=e.toString().toLowerCase(),i&&(e=s.join(""));const c=i?s.map(a=>parseInt(a)):e.split("").map(a=>parseInt(a));if(bT({score:e}),c.length,e.length===3&&o(c.slice(0,2))===1){const[a,u,l]=c;e=`${a}-${u}(${l})`,n.push("numericTiebreakPattern1")}else if(e.length===3&&c[0]===1){const[a,u,l]=c;e=`[${a}${u}-${l}]`,n.push("numericTiebreakPattern2")}else if(e.length===4&&o(c.slice(0,2))===1&&"987654".split("").includes(c[0].toString())){const[a,u,l,f]=c,p=Math.min(l,f);e=`${a}-${u}(${p})`,n.push("numericTiebreakPattern3")}else if(e.length===4&&c[0]===1&&c[2]===1){const[a,u,l,f]=c;e=`[${a}${u}-${l}${f}]`,n.push("bigSuper")}else if(e.length===4){const[a,u,l,f]=c;e=`${a}${u} ${l}${f}`,n.push("split4")}else if(e.length===5&&o(c.slice(0,2))===1){const[a,u,l,f,p]=c;e=`${a}-${u}(${l}) ${f}-${p}`,n.push("numericTiebreakPattern4")}else if(e.length===5&&o(c.slice(3))===1){const[a,u,l,f,p]=c;e=`${a}-${u} ${l}-${f}(${p})`,n.push("numericTiebreakPattern5")}else if(c.length===7)if(o(c.slice(0,2))>1&&o(c.slice(2,4))>1&&c[4]===1){const[a,u,l,f,p,h,d]=c;e=`${a}-${u} ${l}-${f} [${p}${h}-${d}]`,n.push("numericTiebreakPattern6")}else if(o(c.slice(0,2))===1&&o(c.slice(3,5))>1&&o(c.slice(5,7))>1){const[a,u,l,f,p,h,d]=c;e=`${a}-${u}(${l}) ${f}-${p} ${h}-${d}`,n.push("numericTiebreakPattern7")}else if(o(c.slice(0,2))>1&&o(c.slice(2,4))===1&&o(c.slice(5,7))>1){const[a,u,l,f,p,h,d]=c;e=`${a}-${u} ${l}-${f}(${p}) ${h}-${d}`,n.push("numericTiebreakPattern8")}else if(o(c.slice(0,2))>1&&o(c.slice(2,4))>1&&o(c.slice(4,6))===1){const[a,u,l,f,p,h,d]=c;e=`${a}-${u} ${l}-${f} ${p}-${h}(${d})`,n.push("numericTiebreakPattern9")}else e=e.slice(0,2)+" "+e.slice(2,4)+" "+e.slice(4),n.push("numericMatchTiebreakPattern");else if(e.length%2){const a=bp(e);a&&e!==a&&n.push("parsedSuperPattern"),e=a||e}else{const a=Ge(e.split(""),2).map(g=>g.join("")),u=a.map(g=>{const[I,S]=g.split("").map(y=>parseInt(y)),T=Math.abs(I-S),E=I>S?1:2;return T>1&&E||E*-1}),l=u.reduce((g,I)=>g>0&&I>0,1),f=Mn(u),p=u.map(g=>Math.abs(g)),h=Mn(p),d=u[0]<0,m=!d&&u[1]<0;if(u[0]>0&&u[1]>0&&u[0]!==u[1])e=[a.slice(0,2).join(" "),a.slice(2).join("-")].join(" "),n.push("numeric3rdSetTiebreakPattern");else if(l)e=a.join(" "),n.push("chunkSplit");else if(c.length==6){if(f[1]==2||f[2]===2)if(!Object.values(h).includes(3))e=a.join(" "),n.push("chunkSplit");else{const[g,I,S,T,E,y]=c,b=u.reduce((N,A,C)=>A<0?C:N,void 0);if(b===0){const N=Math.min(S,T);e=`${g}-${I}(${N}) ${E}-${y}`,n.push("chunkSplitTiebreak1")}else if(b===1){const N=Math.min(E,y);e=`${g}-${I} ${S}-${T}(${N})`,n.push("chunkSplitTiebreak2")}else e=`${g}-${I} ${S}-${T}`,n.push("chunkSplitTrimExtraneous")}}else if(c.length===8){const[g,I,S,T,E,y,b,N]=c;d||m?c[5]===1&&(d?e=`${g}-${I}(${S}) ${T}-${E} [${y}${b}-${N}]`:e=`${g}-${I} ${S}-${T}(${E}) [${y}${b}-${N}]`):(u[0],u[1])}}}return{score:e,applied:n,matchUpStatus:r}}function AT(t){const e=[0,0],n=[],r=t.split(" "),s=/(\d+)-(\d+)/;r.forEach(a=>{if(s.test(a)){const u=a.match(s).slice(1).map(f=>parseInt(f)),l=u[0]>u[1]&&1||u[1]>u[0]&&2;l&&(e[l-1]+=1,n.push(l))}});const i=e[0]>e[1]&&1||e[1]>e[0]&&2,o=e[0]>0&&e[0]===e[1],c=e.reduce((a,u)=>a+u,0);return{setsWon:e,setsTied:o,setWinners:n,totalSets:c,winningSide:i}}function ZO({score:t,matchUpStatus:e,attributes:n}){const r=[];let s;const i=t.split(" "),o=i.length;t=i.map((l,f)=>{if(new RegExp(Wa).test(l)){const h=l.slice(3),d=l.slice(0,3),m=d.split("-");if(!Ec(d)&&!e){const g=Math.max(...m),I=d.indexOf(g),S=[g,g-1];return(I?S.reverse().join("-"):S.join("-"))+h}}else if(l.length===2&&Me(l))return l.split("").join("-");l=Ml(l);const p=new RegExp(`^${Ep}$`).test(l)&&"super"||new RegExp(`^${Wa}$`).test(l)&&"tiebreak"||new RegExp(`^${Pl}$`).test(l)&&"standard"||"unknown";if(r.push(p),o>1&&p==="standard"&&f<2){const[h,d]=l.split("-"),m=Math.abs(parseInt(h)-parseInt(d)),g=Math.max(h,d),I=Math.min(h,d),S=[parseInt(h),parseInt(d)].indexOf(I);if(g>9&&m>2){const T=g.toString().split(""),E=T.find(y=>parseInt(y)>I||f&&parseInt(y)<=s)||T[0];E&&(l=S?[E,I].join("-"):[I,E].join("-"))}g>(s||0)&&(s=g)}if(p==="standard"){const[h,d]=l.split("-");if(!Math.abs(parseInt(h)-parseInt(d))&&e!=="RETIRED")return""}return l}).filter(Boolean).join(" ");const{setsWon:c,setWinners:a,totalSets:u}=AT(t);if(u===1&&(n==null?void 0:n.removed)==="6"&&(t+=" 6-0"),t.split(" ").length>2&&Math.max(...c)>=2&&a[0]===a[1]&&(t=t.split(" ").slice(0,2).join(" ")),Math.max(...c)>2){const l=[0,0];t=t.split(" ").map((f,p)=>(l[a[p]]+=1,Math.max(...l)>2?void 0:f)).filter(Boolean).join(" ")}return{score:t,profile:r}}function XO({score:t}){const{setsTied:e,winningSide:n}=AT(t),r=/\s\((\d+)\)$/;if(!n&&e&&r.test(t)){const c=t.match(r).slice(1)[0],a=c<=8?10:c+2;t=t.replace(r,` [${a}-${c}]`)}const s=t.split(" "),i=s[s.length-1];if(!i.includes("-")||i.indexOf("(")>0)return{score:t};let o=i.split("(").join("").split(")").join("").split("-");if(!o.every(c=>Me(c)))return{score:t};if(o[0]==="76"){const c=o[1].length===2?Math.min(...o[1].split("").map(a=>parseInt(a))):o[1];t=[...s.slice(0,s.length-1),`7-6(${c})`].join(" ")}else{o=o.map(u=>parseInt(u));const c=Math.max(...o);let a=Math.abs(o[0]-o[1]);if(c>=10){if(a>2&&o.every(u=>+u>=10)){const u=o.map(l=>l===c?l-10:10).sort();a=Math.abs(u[0]-u[1]),a>2&&(o=u)}t=[...s.slice(0,s.length-1),`[${o.join("-")}]`].join(" ")}else s.length===3&&c>=7&&a>2&&(t=[...s.slice(0,s.length-1),`[${o.join("-")}]`].join(" "))}return{score:t}}function tM({score:t}){return t=(t==null?void 0:t.toString().toLowerCase())||"",{score:t}}function eM({score:t,applied:e}){return typeof t!="string"?{score:t}:(t.toLowerCase().includes("o")&&(t=t.toLowerCase().split(" ").map(n=>n.split("o").join("0")).join(" "),e.push("replaceOh")),{score:t,applied:e})}function nM({score:t,applied:e}){return typeof t!="string"?{score:t}:(t=t.toLowerCase().split(" ").map(n=>{if(/^\d+$/.test(n)&&n.length>2){const r=n.indexOf("1");if(n.length%2){if(n.length===3&&r===0){const s=Ol(n.split(""),r);return e.push("getSuper"),s}}else{const{score:s,applied:i}=NT({score:n,applied:[]});s!==n&&(n=s,e.push(...i))}}return n}).join(" "),{score:t,applied:e})}function rM({score:t,applied:e}){return typeof t!="string"?{score:t}:[3,4].includes(t.length)&&bp(t)?{score:bp(t)}:(t=t.toLowerCase().split(" ").map(n=>{if(/^\d+$/.test(n)&&n.length===1){e.push("removeErroneous1");return}return n}).filter(Boolean).join(" "),{score:t,applied:e})}function sM({score:t,applied:e}){return["walkover","wo","w/o","w-o"].includes(t==null?void 0:t.toString().toLowerCase())?(e.push("handleWalkover"),{matchUpStatus:"walkover",score:"",applied:e}):{score:t}}function iM({score:t,profile:e,applied:n}){var c;t=t==null?void 0:t.toString().toLowerCase();const r=/^(.*\d+.*)(ret|con)+[A-Za-z ]*$/;if(r.test(t)){const[a]=t.match(r).slice(1);return n.push("handleRetired"),{score:a.trim(),matchUpStatus:"retired",applied:n}}const s=(c=e==null?void 0:e.matchUpStatuses)==null?void 0:c.retired,o=["rtd",...Array.isArray(s)?s:[s].filter(Boolean)].find(a=>t==null?void 0:t.endsWith(a));return o?(n.push("handleRetired"),{matchUpStatus:"retired",score:t==null?void 0:t.replace(o,"").trim(),applied:n}):{score:t}}function oM({score:t,attributes:e}){(t.endsWith(" am")||t.endsWith(" pm"))&&(t=""),t=t.replace(/[A-Za-z]+/g,"").trim(),[".",","].some(s=>t.endsWith(s))&&(t=t.slice(0,t.length-1));const n="()/-".split("").some(s=>t.includes(s));/ \d$/.test(t)&&n&&(e={removed:t.slice(t.length-2).trim()},t=t.slice(0,t.length-2));const r=/(.*)[A-Za-z]+$/;return r.test(t)&&(t=t.match(r).slice(1)[0].trim()),{score:t,attributes:e}}function cM({score:t}){return new RegExp(/-\d+\/\d+-/).test(t)&&(t=t.split("/").join(" ")),{score:t}}function aM({score:t}){const e=new RegExp(/^\d+\/\d+/),n=t.split(" ");n.some(s=>e.test(s))&&(t=n.map(s=>e.test(s)?s.replace("/","-"):s).join(" "));const r=/^(\d+), *(\d+)$/;if(r.test(t)){const[s,i]=t.match(r).slice(1);t=[s,i].join("-")}return{score:t}}function uM({score:t}){const e=new RegExp(/\(\d+\/\d+\)/g),n=t.match(e);for(const r of n||[]){const s=r.replace("/","-");t=t.replace(r,s)}return{score:t}}function lM({score:t}){if(t.includes(",")){const e=t.split(",").map(s=>s.trim()),n=s=>/\d \d/.test(s);e.every(n)&&(t=e.map(s=>{const i=/\d+ \d+/g;for(const o of s.match(i)){const[c,a]=o.match(/(\d+) (\d+)/).slice(1);s=s.replace(o,`${c}-${a}`)}return s}).join(" "))}if(t.includes(" ")){const e=t.replace(/[ ,]/g,"");e.split("").every(r=>Me(r))&&e.length===4&&(t=e)}return{score:t}}function dM({score:t}){const e=new RegExp(/^\[\d+\](.*)$/);e.test(t)&&(t=t.match(e).slice(1)[0].trim());const n=/\(,/g;return n.test(t)&&(t=t.replace(n,"(")),{score:t}}const fM={handleTiebreakSlashSeparation:uM,handleSetSlashSeparation:cM,punctuationAdjustments:qO,handleGameSeparation:aM,joinFloatingTiebreak:zO,handleBracketSpacing:YO,handleSpaceSeparator:lM,separateScoreBlocks:nM,matchKnownPatterns:KO,removeDanglingBits:oM,removeErroneous:rM,handleWalkover:sM,properTiebreak:JO,handleNumeric:NT,handleRetired:iM,containedSets:QO,sensibleSets:ZO,stringScore:tM,superSquare:XO,setBuilder:bT,excisions:dM,replaceOh:eM};let Np={};const pM=["handleNumeric","handleWalkover","handleRetired","replaceOh","stringScore","punctuationAdjustments","excisions","handleSpaceSeparator","matchKnownPatterns","removeDanglingBits","handleBracketSpacing","matchKnownPatterns","containedSets","separateScoreBlocks","handleGameSeparation","removeErroneous","joinFloatingTiebreak","handleSetSlashSeparation","handleTiebreakSlashSeparation","properTiebreak","sensibleSets","superSquare"],hM=["handleNumeric","separateScoreBlocks","sensibleSets","superSquare"];function mM(t){const{score:e,sheetName:n,identifier:r,fileName:s,stepLog:i,fullLog:o,profile:c}=t,a=[];let u,l=[],f,p,h=e;const d=g=>{g.forEach(I=>{p=fM[I]({profile:c,identifier:r,matchUpStatus:u,attributes:f,applied:l,score:h});const S=p.score!==h;S&&a.push({method:I,score:p.score}),i&&(o||S||p.matchUpStatus!==u)&&console.log(u?{score:p.score,matchUpStatus:u}:{score:p.score},I),p.matchUpStatus&&(u=p.matchUpStatus),p.attributes&&(f=p.attributes),p.applied&&(l=p.applied),h=p.score})};d(pM);let m=yT(h);return m||(h=e.toString().replace(/\D/g,""),f!=null&&f.removed&&(f.removed=void 0),d(hM),m=yT(h),m||(h="")),l.forEach(g=>{Np[g]||(Np[g]=0),Np[g]+=1}),{matchUpStatus:u==null?void 0:u.toUpperCase(),modifications:a,attributes:f,isValid:m,score:h}}const{FACTORY:vT}=rI;function Dl({tournamentRecord:t,value:e}){const{extension:n}=xn({element:t,name:vT}),r={name:vT,value:{...n==null?void 0:n.value,...e}};ae({element:t,extension:r})}function Di(t){const{mutationStatus:e,tournamentId:n,directives:r,timeStamp:s}=t||{},{topics:i}=$r();for(const o of[...i].sort(gM)){const c=sC({topic:o});c&&Mg({topic:o,notices:c})}e&&s&&i.includes(DI)&&Mg({notices:[{tournamentId:n,directives:r,timeStamp:s}],topic:DI})}const CT={[kI]:5,[wI]:5,[_I]:5,[MI]:5,[OI]:5,[PI]:5,[IP]:5,[SP]:5,[UI]:1,[Uf]:1,[nn]:5,[so]:5,[CI]:4,[NI]:4,[AI]:4,[vI]:4,[Pf]:3,[yI]:2};function gM(t,e){return(CT[e]||0)-(CT[t]||0)}function Co({tournamentRecords:t,convertExtensions:e,ignoreDisabled:n,venueIds:r=[],dates:s}){if(typeof t!="object"||!Object.keys(t).length)return{error:Gt};const i=[],o=[],c=[],a=[];return Object.keys(t).forEach(l=>{const f=t[l];for(const p of f.venues||[])if(f.venues,!(r.length&&!r.includes(p.venueId))){if(n){const{extension:h}=xn({name:Er,element:p});if(h!=null&&h.value)continue}i.includes(p.venueId)||(a.push(pt(p,e,!0)),i.push(p.venueId));for(const h of p.courts||[])if(!o.includes(h.courtId)){if(n&&s){const{extension:m}=xn({name:Er,element:h});if(SI({extension:m,dates:s}))continue}const{inContextCourt:d}=TI({convertExtensions:e,ignoreDisabled:n,venue:p,court:h});c.push(d),o.push(h.courtId)}}}),{courts:c,venues:a}}function Ap({tournamentRecords:t,requireCourts:e,dates:n}){return typeof t!="object"||!Object.keys(t).length?{error:Gt}:Object.keys(t).reduce((s,i)=>{const o=t[i],{venues:c}=Of({tournamentRecord:o,dates:n});return c==null||c.forEach(a=>{const{venueId:u,courts:l}=a;(!e||(l==null?void 0:l.length))&&!s.venueIds.includes(u)&&(s.venues.push(a),s.venueIds.push(u))}),s},{venues:[],venueIds:[]})}function Ha({duplicateValues:t=!0,creationTime:e=!0,removePriorValues:n,timeItem:r,element:s}){if(!r)return{error:Sg};if(!s)return{error:Tt,info:Ef};const i=r&&Object.keys(r),o=["itemType","itemValue"];if(!(o.filter(u=>i.includes(u)).length===o.length))return{error:Ig};if(!s.timeItems)s.timeItems=[];else{const{itemType:u,itemSubTypes:l,itemValue:f}=r,{timeItem:p}=kr({itemSubTypes:l,itemType:u,element:s});if(JSON.stringify(p==null?void 0:p.itemValue)===JSON.stringify(f)&&!t)return{...$}}if(r.itemSubTypes&&!r.itemSubTypes.length&&delete r.itemSubTypes,e){const u=new Date().toISOString();Object.assign(r,{createdAt:u})}return n&&(s.timeItems=s.timeItems.filter(({itemType:u})=>r.itemType!==u)),n&&!r.itemValue||s.timeItems.push(r),{...$}}function PT({creationTime:t=!0,removePriorValues:e,tournamentRecord:n,duplicateValues:r,participantId:s,timeItem:i}){if(!n)return{error:et};if(!s)return{error:Ce};const o=zs({tournamentRecord:n,participantId:s});return o.error?o:Ha({element:o.participant,removePriorValues:e,duplicateValues:r,creationTime:t,timeItem:i})}function _s(t){const{removePriorValues:e,tournamentRecord:n,duplicateValues:r,creationTime:s,timeItem:i}=t;return n?Ha({element:n,removePriorValues:e,duplicateValues:r,creationTime:s,timeItem:i}):{error:et}}function ii(t){const{removePriorValues:e,duplicateValues:n,creationTime:r,timeItem:s,event:i}=t;return i?Ha({removePriorValues:e,duplicateValues:n,element:i,creationTime:r,timeItem:s}):{error:wn}}function Ln({removePriorValues:t,tournamentRecord:e,duplicateValues:n,drawDefinition:r,disableNotice:s,matchUpId:i,timeItem:o,event:c}){const{matchUp:a}=ie({drawDefinition:r,event:c,matchUpId:i});if(!a)return{error:Ye};const u=Ha({removePriorValues:t,element:a,duplicateValues:n,timeItem:o});return s||qt({tournamentId:e==null?void 0:e.tournamentId,eventId:c==null?void 0:c.eventId,context:"addTimeItem",drawDefinition:r,matchUp:a}),u}function IM({tournamentRecord:t,drawDefinition:e,matchUpId:n,event:r}){const{matchUp:s}=ie({drawDefinition:e,event:r,matchUpId:n});return s?(s.timeItems=[],qt({tournamentId:t==null?void 0:t.tournamentId,context:"resetTimeItems",eventId:r==null?void 0:r.eventId,drawDefinition:e,matchUp:s}),{...$}):{error:Ye}}function wl({removePriorValues:t,tournamentRecords:e,tournamentRecord:n,drawDefinition:r,disableNotice:s,courtDayDate:i,matchUpId:o,courtIds:c}){var p,h;if(!n&&!e)return{error:et};if(!o)return{error:$e};const a=ie({drawDefinition:r,matchUpId:o});if(a.error)return a;if(((p=a==null?void 0:a.matchUp)==null?void 0:p.matchUpType)!==yr)return{error:qn};if(!(c===void 0||Array.isArray(c)&&c.length&&c.every(d=>typeof d=="string")))return{error:tt,context:{courtIds:c}};let l;if(c){const d=e?n:n&&{[n.tournamentId]:n},m=Co({tournamentRecords:d});if(m.error)return m;const g=(h=m.courts)==null?void 0:h.filter(I=>c.includes(I.courtId));if((g==null?void 0:g.length)!==c.length)return{error:tt,context:{courtIds:c}};l=g==null?void 0:g.map(I=>({venueId:I.venueId,courtId:I.courtId}))}return Ln({duplicateValues:!1,removePriorValues:t,tournamentRecord:n,drawDefinition:r,disableNotice:s,matchUpId:o,timeItem:{itemType:Qs,itemDate:i,itemValue:l}})}function bc({removePriorValues:t,tournamentRecords:e,tournamentRecord:n,drawDefinition:r,disableNotice:s,matchUpId:i,venueId:o}){if(!n)return{error:et};if(!i)return{error:$e};if(o){const a=Js({tournamentRecords:e,tournamentRecord:n,venueId:o});if(a.error)return a}return Ln({duplicateValues:!1,removePriorValues:t,tournamentRecord:n,drawDefinition:r,disableNotice:s,matchUpId:i,timeItem:{itemType:ga,itemValue:o}})}function Po({removePriorValues:t,tournamentRecords:e,tournamentRecord:n,drawDefinition:r,disableNotice:s,courtDayDate:i,matchUpId:o,courtId:c}){var u;if(!n&&!e)return{error:et};if(!o)return{error:$e};if(c){const l=io({tournamentRecords:e,tournamentRecord:n,courtId:c});if(l.error)return l;const f=(u=l.venue)==null?void 0:u.venueId;bc({tournamentRecords:e,tournamentRecord:n,drawDefinition:r,disableNotice:s,matchUpId:o,venueId:f})}return Ln({duplicateValues:!1,removePriorValues:t,tournamentRecord:n,drawDefinition:r,disableNotice:s,matchUpId:o,timeItem:{itemType:oo,itemDate:i,itemValue:c}})}function SM({matchUps:t,matchUpId:e}){if(!cr(t))return{error:tt};const n=t.find(c=>c.matchUpId===e),{drawId:r,eventId:s,structureId:i,tournamentId:o}=n||{};return{matchUpId:e,drawId:r,eventId:s,structureId:i,tournamentId:o}}function wi(t){let e=t.matchUp;const{removePriorValues:n,tournamentRecord:r,drawDefinition:s,disableNotice:i,scheduledTime:o,matchUpId:c}=t;if(!c)return{error:$e};if(!Ko(o))return{error:sr};if(!e){const d=ie({drawDefinition:s,matchUpId:c});if(d.error)return d;e=d.matchUp}const a=Bt(o),u="addMatchUpScheduledTime";if(a){const d=bi({matchUp:e}).scheduledDate;if(d&&d!==a)return G({info:`date in time: ${a} does not corresponde to scheduledDate: ${d}`,result:{error:sr},stack:u})}const l=kf({matchUp:e}).timeModifiers||[];if(l!=null&&l.length){const d=vp({disableNotice:!0,removePriorValues:n,tournamentRecord:r,timeModifiers:[],drawDefinition:s,matchUpId:c,matchUp:e});if(d!=null&&d.error)return d}const p=qi(o,!0,!0);return Ln({duplicateValues:!1,removePriorValues:n,tournamentRecord:r,drawDefinition:s,disableNotice:i,matchUpId:c,timeItem:{itemType:Sa,itemValue:p}})}function vp({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,timeModifiers:s,matchUpId:i,matchUp:o}){if(!i)return{error:$e};if(s!==void 0&&!Array.isArray(s))return{error:tt,info:sn("timeModifiers")};if(!o){const p=ie({drawDefinition:n,matchUpId:i});if(p.error)return p;o=p.matchUp}let c=kf({matchUp:o}).timeModifiers||[];const a=s.filter(p=>!c.includes(p));if(s.length&&!a.length)return{...$};if(a.some(p=>BI.includes(p))){c=c.filter(h=>!BI.includes(h));const p=wi({disableNotice:!0,removePriorValues:t,scheduledTime:"",tournamentRecord:e,drawDefinition:n,matchUpId:i});if(p.error)return p}const l=s!=null&&s.length?[...a,...c]:void 0;return Ln({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:i,timeItem:{itemType:RI,itemValue:l}})}function Xr(t,e){const n=wg.test(t)?t:de(t),r=Bt(t)||Bt(e)||Sr(new Date);return new Date(`${r}T${n}`).getTime()}function kl({errorOnAnachronism:t=!1,checkChronology:e=!0,matchUpDependencies:n,inContextMatchUps:r,removePriorValues:s,tournamentRecords:i,tournamentRecord:o,drawDefinition:c,disableNotice:a,drawMatchUps:u,matchUpId:l,schedule:f,event:p}){var U;if(!f)return{error:Tt,info:"Missing schedule"};if(!c)return{error:lt};if(!l)return{error:$e};const h="drawEngine.addMatchUpScheduleItems";let d,m;if(u)d=u.find(O=>O.matchUpId===l);else{const O=ie({drawDefinition:c,event:p,matchUpId:l});if(O.error)return O;d=O.matchUp}const{endTime:g,courtId:I,courtIds:S,courtOrder:T,resumeTime:E,scheduledDate:y,scheduledTime:b,startTime:N,stopTime:A,timeModifiers:C,venueId:v}=f;e&&(!n||!r)&&({matchUpDependencies:n,matchUps:r}=fr({drawDefinition:c}));const P=(U=n==null?void 0:n[l])==null?void 0:U.matchUpIds;if(f.scheduledDate&&e&&P){const O=r==null?void 0:r.filter(D=>{var M,w;return(((M=D.schedule)==null?void 0:M.scheduledDate)||Bt((w=D.schedule)==null?void 0:w.scheduledTime))&&P.includes(D.matchUpId)}).map(({schedule:D})=>{const M=Du(D);return new Date(M).getTime()});if(O!=null&&O.length){const D=Du(f),M=new Date(D).getTime();if(Math.max(...O)>=M){if(t)return G({result:{error:Gm},stack:h});m=Gm}}}if(y!==void 0){const O=Cp({disableNotice:!0,removePriorValues:s,tournamentRecord:o,drawDefinition:c,scheduledDate:y,matchUpId:l});if(O!=null&&O.error)return G({result:O,stack:h,context:{scheduledDate:y}})}if(b!==void 0){const O=wi({disableNotice:!0,removePriorValues:s,tournamentRecord:o,drawDefinition:c,scheduledTime:b,matchUpId:l,matchUp:d});if(O!=null&&O.error)return G({result:O,stack:h,context:{scheduledTime:b}})}if(N!==void 0){const O=Up({disableNotice:!0,removePriorValues:s,tournamentRecord:o,drawDefinition:c,matchUpId:l,startTime:N,event:p});if(O!=null&&O.error)return G({result:O,stack:h,context:{startTime:N}})}if(A!==void 0){const O=Mp({disableNotice:!0,removePriorValues:s,tournamentRecord:o,drawDefinition:c,matchUpId:l,stopTime:A,event:p});if(O!=null&&O.error)return G({result:O,stack:h,context:{stopTime:A}})}if(E!==void 0){const O=Dp({disableNotice:!0,removePriorValues:s,tournamentRecord:o,drawDefinition:c,resumeTime:E,matchUpId:l,event:p});if(O!=null&&O.error)return G({result:O,stack:h,context:{resumeTime:E}})}if(g!==void 0){const O=Op({disableNotice:!0,removePriorValues:s,tournamentRecord:o,drawDefinition:c,matchUpId:l,endTime:g,event:p});if(O!=null&&O.error)return G({result:O,stack:h,context:{endTime:g}})}if(S!==void 0){const O=wl({disableNotice:!0,removePriorValues:s,tournamentRecord:o,drawDefinition:c,matchUpId:l,courtIds:S});if(O!=null&&O.error)return G({result:O,stack:h,context:{courtIds:S}})}if(I!==void 0&&y!==void 0){const O=Po({courtDayDate:y,disableNotice:!0,removePriorValues:s,tournamentRecords:i,tournamentRecord:o,drawDefinition:c,matchUpId:l,courtId:I});if(O!=null&&O.error)return G({result:O,stack:h,context:{courtId:I}})}if(v!==void 0){const O=bc({disableNotice:!0,removePriorValues:s,tournamentRecords:i,tournamentRecord:o,drawDefinition:c,matchUpId:l,venueId:v});if(O!=null&&O.error)return G({result:O,stack:h,context:{venueId:v}})}if(T!==void 0&&oe(T)){const O=Pp({disableNotice:!0,removePriorValues:s,tournamentRecord:o,drawDefinition:c,courtOrder:T,matchUpId:l});if(O!=null&&O.error)return G({result:O,stack:h,context:{courtOrder:T}})}if(C!==void 0){const O=vp({disableNotice:!0,removePriorValues:s,tournamentRecord:o,drawDefinition:c,timeModifiers:C,matchUpId:l,matchUp:d});if(O!=null&&O.error)return G({result:O,stack:h,context:{timeModifiers:C}})}return a||qt({tournamentId:o==null?void 0:o.tournamentId,eventId:p==null?void 0:p.eventId,context:h,drawDefinition:c,matchUp:d}),m?{...$,warnings:[m]}:{...$}}function Cp({scheduledDate:t,removePriorValues:e,tournamentRecord:n,drawDefinition:r,disableNotice:s,matchUpId:i}){if(!i)return{error:$e};const o=t&&Vr.test(t);if(t&&!o)return{error:bn};const a={itemValue:Bt(t),itemType:Ia};return Ln({duplicateValues:!1,removePriorValues:e,tournamentRecord:n,drawDefinition:r,disableNotice:s,matchUpId:i,timeItem:a})}function Pp({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,courtOrder:s,matchUpId:i}){if(!i)return{error:$e};if(s&&!oe(s))return{error:tt,info:"courtOrder must be numeric"};const o=s&&vt(s);return Ln({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:i,timeItem:{itemType:LI,itemValue:o}})}function UT({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,participantId:s,officialType:i,matchUpId:o}){if(!o)return{error:$e};const c={itemType:"SCHEDULE.ASSIGNMENT.OFFICIAL",itemValue:s};return i&&(c.itemSubTypes=[i]),Ln({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:o,timeItem:c})}function Up({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:s,startTime:i,event:o}){if(!s)return{error:$e};if(!Ko(i))return{error:sr};const{matchUp:c}=ie({drawDefinition:n,event:o,matchUpId:s}),{scheduledDate:a}=bi({matchUp:c}),l=((c==null?void 0:c.timeItems)??[]).filter(f=>[Zs,Os,Xs].includes(f==null?void 0:f.itemType)).map(f=>Xr(f.itemValue,a)).reduce((f,p)=>!f||p<f?p:f,void 0);if(!l||Xr(i,a)<l){c!=null&&c.timeItems&&(c.timeItems=c.timeItems.filter(h=>h.itemType!==zr));const f=qi(i,!0,!0);return Ln({duplicateValues:!1,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:s,timeItem:{itemType:zr,itemValue:f}})}else return{error:Av}}function Op({validateTimeSeries:t=!0,removePriorValues:e,tournamentRecord:n,drawDefinition:r,disableNotice:s,matchUpId:i,endTime:o,event:c}){if(!i)return{error:$e};if(!Ko(o))return{error:sr};const{matchUp:a}=ie({drawDefinition:r,event:c,matchUpId:i}),{scheduledDate:u}=bi({matchUp:a}),f=((a==null?void 0:a.timeItems)??[]).filter(p=>[zr,Os,Zs].includes(p==null?void 0:p.itemType)).map(p=>Xr(p.itemValue,u)).reduce((p,h)=>!p||h>p?h:p,void 0);if(!t||!f||Xr(o,u)>f){a!=null&&a.timeItems&&(a.timeItems=a.timeItems.filter(d=>d.itemType!==Xs));const p=qi(o,!0,!0);return Ln({duplicateValues:!1,removePriorValues:e,tournamentRecord:n,drawDefinition:r,disableNotice:s,matchUpId:i,timeItem:{itemType:Xs,itemValue:p}})}else return{error:mg}}function Mp({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:s,stopTime:i,event:o}){if(!s)return{error:$e};if(!Ko(i))return{error:sr};const{matchUp:c}=ie({drawDefinition:n,event:o,matchUpId:s}),{scheduledDate:a}=bi({matchUp:c}),u=(c==null?void 0:c.timeItems)??[];if(u.reduce((m,g)=>g.itemType===Xs||m,void 0))return{error:gg};const f=u.filter(m=>[zr,Os,Zs].includes(m==null?void 0:m.itemType)).sort((m,g)=>Xr(m.itemValue,a)-Xr(g.itemValue,a)),p=f[f.length-1],h=p&&p.itemType===Zs,d=f.filter(m=>!h||m.createdAt!==p.createdAt).map(m=>Xr(m.itemValue,a)).reduce((m,g)=>!m||g>m?g:m,void 0);if(Xr(i,a)>d){if(c!=null&&c.timeItems&&h){const I=p.createdAt;c.timeItems=c.timeItems.filter(S=>S.createdAt!==I)}const g={itemValue:qi(i,!0,!0),itemType:Zs};return Ln({duplicateValues:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:s,timeItem:g})}else return{error:Nv}}function Dp({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,resumeTime:s,matchUpId:i,event:o}){if(!i)return{error:$e};if(!Ko(s))return{error:sr};const{matchUp:c}=ie({drawDefinition:n,event:o,matchUpId:i}),{scheduledDate:a}=bi({matchUp:c}),u=(c==null?void 0:c.timeItems)??[];if(u.reduce((m,g)=>g.itemType===Xs||m,void 0))return{error:gg};const f=u.filter(m=>[zr,Os,Zs].includes(m==null?void 0:m.itemType)).sort((m,g)=>Xr(m.itemValue,a)-Xr(g.itemValue,a)),p=f[f.length-1],h=p&&p.itemType===Os,d=f.filter(m=>!h||m.createdAt!==p.createdAt).map(m=>Xr(m.itemValue,a)).reduce((m,g)=>!m||g>m?g:m,void 0);if(Xr(s,a)>d){if(c!=null&&c.timeItems&&h){const I=p.createdAt;c.timeItems=c.timeItems.filter(S=>S.createdAt!==I)}const g={itemValue:qi(s,!0,!0),itemType:Os};return Ln({duplicateValues:!0,removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,matchUpId:i,timeItem:g})}else return{error:vv}}function OT({errorOnAnachronism:t=!1,checkChronology:e=!0,matchUpDependencies:n,tournamentRecords:r,tournamentRecord:s,matchUpDetails:i,matchUpIds:o,schedule:c}){var h,d,m;if(!s)return{error:et};if(!i&&(!o||!Array.isArray(o)))return{error:qc};if(!i&&(!c||typeof c!="object"))return{error:Cv};let a;const u=[];let l=0;if(e&&!n){const g=fr({tournamentRecords:r});n=g.matchUpDependencies,a=g.matchUps}a||(a=((h=He({tournamentRecord:s}))==null?void 0:h.matchUps)||[]);const f=a.reduce((g,I)=>{const{matchUpId:S,drawId:T}=I;return g[T]?g[T].push(S):g[T]=[S],g},{}),p=i==null?void 0:i.map(g=>g.matchUpId);for(const g of Object.keys(f)){const{drawDefinition:I}=Ks({tournamentRecord:s,drawId:g}),S=f[g].filter(E=>(o==null?void 0:o.includes(E))||(p==null?void 0:p.includes(E))),T=tr({inContext:!1,drawDefinition:I}).matchUps;for(const E of S){const y=((d=i==null?void 0:i.find(N=>N.matchUpId===E))==null?void 0:d.schedule)||c,b=kl({schedule:y,matchUpDependencies:n,errorOnAnachronism:t,inContextMatchUps:a,tournamentRecords:r,tournamentRecord:s,checkChronology:e,drawDefinition:I,drawMatchUps:T,matchUpId:E});if((m=b==null?void 0:b.warnings)!=null&&m.length&&u.push(...b.warnings),b!=null&&b.success&&(l+=1),b.error)return b}}return u.length?{...$,scheduled:l,warnings:u}:{...$,scheduled:l}}function MT({errorOnAnachronism:t,matchUpContextIds:e,tournamentRecords:n,checkChronology:r,matchUpDetails:s,schedule:i}){var u;if(!n)return{error:Gt};if(!Array.isArray(e)&&!Array.isArray(s))return{error:tt};if((!s||e)&&!i)return{error:Tt,info:"schedule is required"};const o=[];let c=0;const{matchUpDependencies:a}=fr({tournamentRecords:n});for(const l of Object.values(n)){const{tournamentId:f}=l,p=e==null?void 0:e.filter(d=>d.tournamentId===f).map(Qe),h=s==null?void 0:s.filter(d=>(d==null?void 0:d.tournamentId)===f);if(p!=null&&p.length||h!=null&&h.length){const d=OT({matchUpDetails:h,matchUpDependencies:a,errorOnAnachronism:t,tournamentRecords:n,tournamentRecord:l,checkChronology:r,matchUpIds:p,schedule:i});if((u=d.warnings)!=null&&u.length&&o.push(...d.warnings),d.scheduled&&(c+=d.scheduled),d.error)return d}}return o.length?{...$,scheduled:c,warnings:o}:{...$,scheduled:c}}function _l({tournamentRecords:t}){return t?Object.keys(t).reduce((n,r)=>{n.tournamentIdMap[r]=[];const i=t[r].events||[],o=i.map(({eventId:a})=>a),c=i.map(a=>(a.drawDefinitions||[]).map(({drawId:u})=>u)).flat();return n.tournamentIdMap[r].push(...o,...c),n.eventIds.push(...o),n.drawIds.push(...c),n},{eventIds:[],drawIds:[],tournamentIdMap:{}}):{error:Gt}}function Fl({tournamentRecords:t,eventId:e,drawId:n}){const{tournamentIdMap:r}=_l({tournamentRecords:t});return(r?Object.keys(r):[]).find(i=>e&&(r==null?void 0:r[i].includes(e))||n&&(r==null?void 0:r[i].includes(n)))}function TM({drawDefinition:t,matchUpStatus:e,matchUpsMap:n,winningSide:r,dualMatchUp:s,tieFormat:i,structure:o,matchUp:c,event:a,score:u}){var p;const l=pt(s,void 0,!0);for(const h of(l==null?void 0:l.tieMatchUps)||[])h.matchUpId===c.matchUpId&&(h.winningSide=r,h.score=u,!Be({score:u})&&!e?Object.assign(h,{...fl}):e&&(h.matchUpStatus=e));i=i||((p=hn({matchUp:c,structure:o,drawDefinition:t,event:a}))==null?void 0:p.tieFormat);const{winningSide:f}=La({matchUp:l,drawDefinition:t,matchUpsMap:n,structure:o,tieFormat:i,event:a});return{projectedWinningSide:f}}function yM(t){var l;const{matchUpFormat:e,score:n}=t,r=(l=n==null?void 0:n.sets)==null?void 0:l.length,s=e&&yn(e),{setFormat:i,finalSetFormat:o,bestOf:c}=s||{},u=c&&r===c&&o||i;return(u==null?void 0:u.timed)||!1}function Uo({drawPosition:t,matchUps:e=[]}){return{initialRoundNumber:e.filter(({drawPositions:r})=>t&&(r==null?void 0:r.includes(t))).map(({roundNumber:r})=>r).sort(Ve)[0]}}function DT({structureId:t,matchUpsMap:e,matchUp:n}){const r=n==null?void 0:n.roundPosition,s=r%2?1:-1,i=r+s;return{pairedPreviousMatchUp:Ui({matchUpsMap:e,structureId:t}).find(({roundNumber:a,roundPosition:u})=>a===(n==null?void 0:n.roundNumber)&&u===i)}}function wT({inContextDrawMatchUps:t,sourceMatchUpStatus:e,sourceMatchUpId:n,matchUpsMap:r,matchUp:s}){const i=t.find(c=>c.matchUpId===n),{pairedPreviousMatchUp:o}=DT({structureId:i==null?void 0:i.structureId,matchUp:i,matchUpsMap:r});if(i&&o){const c=o==null?void 0:o.matchUpId,a=t.find(l=>l.matchUpId===c),u=(i==null?void 0:i.structureId)===(a==null?void 0:a.structureId)?(i==null?void 0:i.roundPosition)<(a==null?void 0:a.roundPosition)&&1||2:i.structureId===(a==null?void 0:a.structureId)&&2||1;s.matchUpStatusCodes=(s.matchUpStatusCodes??[]).map(l=>l.sideNumber===u?{...l,previousMatchUpStatus:e}:l)}}function EM({inContextDrawMatchUps:t,sourceMatchUpStatus:e,targetDrawPosition:n,tournamentRecord:r,sourceMatchUpId:s,drawDefinition:i,structureId:o,dualMatchUp:c,roundNumber:a,matchUpsMap:u,event:l}){const{structure:f}=Ot({drawDefinition:i,structureId:o});if((f==null?void 0:f.structureType)===mn)return{...$};u=u||ln({drawDefinition:i});const h=((u==null?void 0:u.mappedMatchUps)||{})[o].matchUps,{initialRoundNumber:d}=Uo({drawPosition:n,matchUps:h}),m=h==null?void 0:h.filter(I=>{var S;return I.roundNumber>=a&&I.roundNumber!==d&&((S=I.drawPositions)==null?void 0:S.includes(n))}),{positionAssignments:g}=ee({drawDefinition:i,structureId:o});for(const I of m||[])bM({inContextDrawMatchUps:t,sourceMatchUpStatus:e,positionAssignments:g,targetDrawPosition:n,tournamentRecord:r,sourceMatchUpId:s,drawDefinition:i,dualMatchUp:c,matchUpsMap:u,matchUp:I,event:l});return{...$}}function bM({inContextDrawMatchUps:t,positionAssignments:e,sourceMatchUpStatus:n,targetDrawPosition:r,tournamentRecord:s,sourceMatchUpId:i,drawDefinition:o,dualMatchUp:c,matchUpsMap:a,matchUp:u,event:l}){var d,m,g;const f="removeSubsequentDrawPosition";if(c){const S=(m=(d=t.find(({matchUpId:E})=>u.matchUpId===E).sides)==null?void 0:d.find(E=>E.drawPosition===r))==null?void 0:m.sideNumber,T=(g=u.sides)==null?void 0:g.find(E=>E.sideNumber===S);T&&delete T.lineUp}u.drawPositions=(u.drawPositions||[]).map(I=>I===r?void 0:I).filter(Boolean);const h=e.filter(({drawPosition:I})=>{var S;return(S=u.drawPositions)==null?void 0:S.includes(I)}).filter(I=>I.bye).length;return u.matchUpStatus=h&&re||[te,ce].includes(u.matchUpStatus)&&u.matchUpStatus||Le,[ce,te].includes(u.matchUpStatus)&&(u.winningSide=void 0),u.matchUpStatusCodes&&wT({inContextDrawMatchUps:t,sourceMatchUpStatus:n,sourceMatchUpId:i,matchUpsMap:a,matchUp:u}),qt({tournamentId:s==null?void 0:s.tournamentId,eventId:l==null?void 0:l.eventId,context:`${f}-${r}`,drawDefinition:o,matchUp:u}),{...$}}function kT({positionAssignments:t,tournamentRecord:e,drawDefinition:n,matchUpsMap:r,structure:s,event:i}){const{matchUps:o}=Qt({drawDefinition:n,matchUpsMap:r,structure:s,event:i});o.forEach(c=>{const u=t.filter(({drawPosition:l})=>{var f;return(f=c.drawPositions)==null?void 0:f.includes(l)}).filter(l=>l.bye).length;c.winningSide||(Object.assign(c,{matchUpStatus:u?re:Le}),qt({tournamentId:e==null?void 0:e.tournamentId,context:"modifyRoundRobinMatchUpsStatus",eventId:i==null?void 0:i.eventId,drawDefinition:n,matchUp:c}))})}function Nc({tournamentRecord:t,drawDefinition:e,event:n}){const r=(t==null?void 0:t.events)||n&&[n],s=(r==null?void 0:r.map(a=>a==null?void 0:a.drawDefinitions).flat().filter(Boolean))||e&&[e]||[],i={},o={},c=s.map(a=>{var u;return(u=a==null?void 0:a.structures)==null?void 0:u.filter(l=>l==null?void 0:l.structures)}).flat().filter(Boolean);for(const a of c){const{structures:u,structureId:l}=a||{};u&&l&&(i[l]=u==null?void 0:u.map(f=>f.structureId))&&u.forEach(f=>o[f.structureId]=a==null?void 0:a.structureId)}return{containedStructures:i,containerStructures:o}}function qa(t){var N;const{drawDefinition:e,findContainer:n,structureId:r,event:s}=t;let i=t.structure;const o={isCollectionMatchUp:!1},{containedStructures:c}=Nc({drawDefinition:e}),a=r?c[r]||[]:[];if(!i){const A=Ot({drawDefinition:e,structureId:r});if(A.error)return A;i=n&&A.containingStructure||A.structure}if(Qr({drawDefinition:e,structure:i}))return{structure:i,isAdHoc:!0,error:Wo};const{matchUps:u}=xe({inContext:!0,matchUpFilters:o,drawDefinition:e,event:s}),l=u==null?void 0:u.filter(A=>A.structureId===r||a.includes(A.structureId)),{matchUpDependencies:f}=fr({drawIds:[e.drawId],matchUps:u,drawDefinition:e}),p=[],h=[],d={},m=[];for(const A of u||[]){if(A.structureId===r||a.includes(A.structureId)){h.push(...A.drawPositions||[]);const C=A.roundNumber;for(const v of(A.drawPositions||[]).filter(Boolean))(!d[v]||C&&d[v]>C)&&(d[v]=C)}zf(A)&&(m.push(A),p.push(A.matchUpId,...((N=f==null?void 0:f[A==null?void 0:A.matchUpId])==null?void 0:N.matchUpIds)||[]))}const g=Vt(h.filter(Boolean)).sort(Ve),I=Vt(p),S=Vt(l==null?void 0:l.map(({matchUpId:A,drawPositions:C})=>I.includes(A)?C:[]).flat().filter(Boolean)).sort(Ve),{positionAssignments:T}=ee({drawDefinition:e,structure:i}),E=T==null?void 0:T.filter(A=>A.bye).map(A=>A.drawPosition),y=T==null?void 0:T.filter(A=>A.qualifier).map(A=>A.drawPosition),b=(g==null?void 0:g.filter(A=>!S.includes(A)))||[];return{allDrawPositions:g,inContextStructureMatchUps:l,drawPositionInitialRounds:d,activeDependentMatchUpIds:I,qualifyingDrawPositions:y,inactiveDrawPositions:b,positionAssignments:T,activeDrawPositions:S,byeDrawPositions:E,activeMatchUps:m,structure:i}}function ts(t,e){e||ze()}function Ac(t){let{inContextDrawMatchUps:e,participantId:n,drawPosition:r}=t;const{tournamentRecord:s,drawDefinition:i,structureId:o,matchUpsMap:c,event:a}=t,{structure:u}=Ot({drawDefinition:i,structureId:o}),f=(ke({drawDefinition:i,structure:u}).positionAssignments||[]).find(m=>n&&m.participantId===n||r&&m.drawPosition===r);if(f&&n&&!r&&(r=f==null?void 0:f.drawPosition),!r)return{error:Wc};n||(n=f==null?void 0:f.participantId);const{activeDrawPositions:p}=qa({drawDefinition:i,structureId:o});return p.includes(r)?{error:Rd}:(e||({matchUps:e}=xe({inContext:!0,drawDefinition:i,matchUpsMap:c})),wp({inContextDrawMatchUps:e,tournamentRecord:s,drawDefinition:i,structureId:o,drawPosition:r,matchUpsMap:c,event:a}).drawPositionCleared?(ni({tournamentId:s==null?void 0:s.tournamentId,drawDefinition:i,structure:u,event:a}),{...$,participantId:n}):{error:k1})}function wp({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,matchUpsMap:s,structureId:i,event:o}){const{structure:c}=Ot({drawDefinition:n,structureId:i});if(!c)return{error:Te};const a=ke({drawDefinition:n,structure:c}).positionAssignments||[],u=a.some(T=>{if(T.drawPosition===r)return delete T.participantId,delete T.qualifier,delete T.bye,!0});if(c.structureType===mn)return kT({positionAssignments:a,tournamentRecord:e,drawDefinition:n,matchUpsMap:s,structure:c}),{drawPositionCleared:u,...$};const l={isCollectionMatchUp:!1},{matchUps:f}=Qt({drawDefinition:n,matchUpFilters:l,matchUpsMap:s,structure:c,event:o}),{roundProfile:p,roundMatchUps:h}=Cn({matchUps:f}),d=p&&Object.keys(p),m=d==null?void 0:d.map(T=>vt(T));let g=r;const I=m==null?void 0:m.map(T=>{var D,M,w;const E=p==null?void 0:p[T],y=(D=E==null?void 0:E.pairedDrawPositions)==null?void 0:D.find(k=>k.includes(g)),b=y==null?void 0:y.find(k=>k!==g),N=a.find(k=>k.drawPosition===b),A=p==null?void 0:p[T+1],C=N==null?void 0:N.bye,v=(M=A==null?void 0:A.pairedDrawPositions)==null?void 0:M.find(k=>k.includes(b)),P=C&&v&&A&&((w=A.drawPositions)==null?void 0:w.includes(b)),O=y&&{pairedDrawPositionByeAdvancedPair:!P&&v,pairedDrawPosition:b,targetDrawPosition:g,relevantPair:y,roundNumber:T};return P&&(g=b),O}).filter(T=>T==null?void 0:T.targetDrawPosition),S=I==null?void 0:I.reduce((T,E)=>{const{roundNumber:y,relevantPair:b,targetDrawPosition:N,pairedDrawPosition:A,pairedDrawPositionByeAdvancedPair:C}=E,v={roundNumber:y,targetDrawPosition:N,relevantPair:b},P=C&&{roundNumber:y+1,targetDrawPosition:A,relevantPair:C,subsequentRoundRemoval:!0},U=[v,P].filter(Boolean);return T.concat(...U)},[]);return S==null||S.forEach(({roundNumber:T,targetDrawPosition:E,relevantPair:y})=>{const b=h==null?void 0:h[T].find(N=>tn(N.drawPositions.filter(Boolean),y.filter(Boolean)));b&&(NM({inContextDrawMatchUps:t,targetDrawPosition:E,tournamentRecord:e,drawDefinition:n,structureId:i,roundNumber:T,matchUpsMap:s}),_T({inContextDrawMatchUps:t,positionAssignments:a,tournamentRecord:e,drawDefinition:n,targetMatchUp:b,drawPosition:r,matchUpsMap:s,structure:c,event:o}))}),{tasks:S,drawPositionCleared:u,positionAssignments:a}}function NM({inContextDrawMatchUps:t,targetDrawPosition:e,tournamentRecord:n,drawDefinition:r,matchUpsMap:s,roundNumber:i,structureId:o}){const{structure:c}=Ot({drawDefinition:r,structureId:o});if(!c)return{error:Te};if(c.structureType===mn)return;s=s||ln({drawDefinition:r});const u=((s==null?void 0:s.mappedMatchUps)||{})[o].matchUps,{initialRoundNumber:l}=Uo({drawPosition:e,matchUps:u}),f=u==null?void 0:u.filter(h=>{var d;return h.roundNumber>=i&&h.roundNumber!==l&&((d=h.drawPositions)==null?void 0:d.includes(e))}),p=ee({drawDefinition:r,structureId:o}).positionAssignments||[];return f==null||f.forEach(h=>_T({drawPosition:e,targetMatchUp:h,inContextDrawMatchUps:t,positionAssignments:p,tournamentRecord:n,drawDefinition:r,matchUpsMap:s,structure:c})),{...$}}function _T({inContextDrawMatchUps:t,positionAssignments:e,tournamentRecord:n,drawDefinition:r,targetMatchUp:s,drawPosition:i,matchUpsMap:o,structure:c,event:a}){var v,P,U,O,D;const u="removeDrawPosition",l=(v=s.drawPositions)==null?void 0:v.slice(),f=s.matchUpStatus,p=s.winningSide;o=o||ln({drawDefinition:r});const d=o.mappedMatchUps[c.structureId].matchUps,{initialRoundNumber:m}=Uo({drawPosition:i,matchUps:d});if(s.roundNumber&&m&&s.roundNumber>m){const M=(s.drawPositions||[]).map(w=>w===i?void 0:w);s.drawPositions=M}if(s.matchUpType===Jt){const M=t==null?void 0:t.find(_=>_.matchUpId===s.matchUpId),k=((M==null?void 0:M.sides)||[]).reduce((_,F,L)=>F.drawPosition===i?L:_,void 0);k!==void 0&&((U=(P=s.sides)==null?void 0:P[k])!=null&&U.lineUp)&&((O=s.sides)==null||delete O[k].lineUp,qt({tournamentId:n==null?void 0:n.tournamentId,context:`${u}-TEAM`,eventId:a==null?void 0:a.eventId,matchUp:s,drawDefinition:r}))}const g=gn({matchUpId:s.matchUpId,inContextDrawMatchUps:t,drawDefinition:r}),{targetLinks:{winnerTargetLink:I},targetMatchUps:{loserMatchUp:S,winnerMatchUp:T,loserMatchUpDrawPositionIndex:E}}=g,b=e.filter(({drawPosition:M})=>{var w;return(w=s.drawPositions)==null?void 0:w.includes(M)}).filter(M=>M.bye).length,N=b&&re||s.matchUpStatus&&[te,ce].includes(s.matchUpStatus)&&s.matcHUpStatus||((D=s.drawPositions)==null?void 0:D.length)===2&&Le||void 0;s.matchUpStatus=N,s.matchUpStatus&&[ce,te].includes(s.matchUpStatus)&&(s.winningSide=void 0);const A=l==null?void 0:l.find(M=>{var w;return!((w=s.drawPositions)!=null&&w.includes(M))});if((l==null?void 0:l.includes(i))&&f===s.matchUpStatus&&p===s.winningSide||(A&&ts(),qt({tournamentId:n==null?void 0:n.tournamentId,eventId:a==null?void 0:a.eventId,matchUp:s,context:`${u}-${i}`,drawDefinition:r})),S&&S.structureId!==g.matchUp.structureId&&!b){const{drawPositions:M,roundNumber:w}=S;if(w===1){const k=M[E];wp({structureId:S.structureId,drawPosition:k,inContextDrawMatchUps:t,tournamentRecord:n,drawDefinition:r,matchUpsMap:o})}else{const k=Math.min(...M.filter(Boolean)),_=AM({loserMatchUpDrawPosition:k,inContextDrawMatchUps:t,tournamentRecord:n,drawDefinition:r,loserMatchUp:S,matchUpsMap:o,event:a});if(_.error)return G({result:_,stack:u});const L=((o==null?void 0:o.mappedMatchUps)||{})[S.structureId].matchUps,{initialRoundNumber:W}=Uo({drawPosition:k,matchUps:L});W===1&&(ts(),wp({structureId:S.structureId,drawPosition:k,inContextDrawMatchUps:t,tournamentRecord:n,drawDefinition:r,matchUpsMap:o}))}}return T&&T.structureId!==g.matchUp.structureId&&I.target.feedProfile,{...$}}function AM({loserMatchUpDrawPosition:t,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:r,loserMatchUp:s,matchUpsMap:i,event:o}){const{structure:c}=Ot({structureId:s.structureId,drawDefinition:r}),{positionAssignments:a}=ee({structure:c}),u=a==null?void 0:a.find(l=>l.drawPosition===t);if(u!=null&&u.bye){const l=Ac({drawPosition:t,structureId:s.structureId,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:r,matchUpsMap:i,event:o});if(l.error)return l}return{...$}}function vM({matchUpStatuses:t=[re,ce,te],drawPositionMatchUps:e,loserDrawPosition:n,sourceMatchUps:r}){var l;const s=e==null?void 0:e.reduce((f,p)=>!f||p.roundNumber>f.roundNumber?p:f,void 0),i=(l=s==null?void 0:s.drawPositions)==null?void 0:l.find(f=>f!==n),o=r.filter(f=>{var p;return(p=f==null?void 0:f.drawPositions)==null?void 0:p.includes(i)}).map(f=>f.matchUpStatus),c=r.filter(f=>{var p;return(p=f==null?void 0:f.drawPositions)==null?void 0:p.includes(n)}).map(f=>f.matchUpStatus),a=tn(o||[],t),u=tn(c||[],t);return{sourceMatchUp:s,winnerHadMatchUpStatus:a,winnerMatchUpStatuses:o,loserHadMatchUpStatus:u,loserMatchUpStatuses:c}}function vc(t){const{dualWinningSideChange:e,inContextDrawMatchUps:n,tournamentRecord:r,drawDefinition:s,matchUpStatus:i,matchUpsMap:o,dualMatchUp:c,targetData:a,matchUpId:u,structure:l,event:f}=t,p=!!t.matchUp.collectionId,h=Qr({drawDefinition:s,structure:l}),{drawPositions:d,winningSide:m}=a.matchUp||{};if(!h&&!d)return{error:Ld};const{targetLinks:{loserTargetLink:g,winnerTargetLink:I,byeTargetLink:S},targetMatchUps:{loserMatchUp:T,winnerMatchUp:E,byeMatchUp:y}}=a,b=Zr({...t,matchUpStatus:i||Le,removeWinningSide:!0});if(b.error)return b;let N;if(p){const{matchUpTieId:_,matchUpsMap:F}=t;if(N=ms({matchUpId:_,tournamentRecord:r,drawDefinition:s,matchUpsMap:F,event:f}),!e&&!N.removeWinningSide)return{...$}}if(h)return{...$};const{matchUps:A}=Qt({afterRecoveryTimes:!1,inContext:!0,drawDefinition:s,matchUpsMap:o,structure:l}),{positionAssignments:C}=ke({structure:l}),v=m-1,P=1-v,U=d[v],O=d[P],{winnerParticipantId:D,loserParticipantId:M}=(C==null?void 0:C.reduce((_,F)=>(F.drawPosition===O&&(_.loserParticipantId=F.participantId),F.drawPosition===U&&(_.winnerParticipantId=F.participantId),_),{winnerParticipantId:void 0,loserParticipantId:void 0}))||{},w=A.filter(_=>{var F;return(F=_.drawPositions)==null?void 0:F.includes(O)});if(E&&FT({sourceMatchUpStatus:i,sourceMatchUpId:u,inContextDrawMatchUps:n,winningDrawPosition:U,winnerParticipantId:D,tournamentRecord:r,winnerTargetLink:I,drawDefinition:s,winnerMatchUp:E,dualMatchUp:c,matchUpsMap:o}),T){const{winnerHadMatchUpStatus:_}=vM({drawPositionMatchUps:w,loserDrawPosition:O,sourceMatchUps:A}),L=g.linkCondition===fs;if(_&&L){const j=Math.min(...T.drawPositions);kp({targetLink:g,inContextDrawMatchUps:n,drawDefinition:s,drawPosition:j,matchUpsMap:o,event:f})}const W=CM({sourceMatchUpStatus:i,sourceMatchUpId:u,loserParticipantId:M,tournamentRecord:r,loserTargetLink:g,drawDefinition:s,loserMatchUp:T,dualMatchUp:c,matchUpsMap:o,event:f});if(W.error)return W}if(y){const _=Math.min(...y.drawPositions);kp({sourceMatchUpId:u,targetLink:S,inContextDrawMatchUps:n,drawDefinition:s,drawPosition:_,matchUpsMap:o,event:f})}return{...$,...N&&{tieMatchUpResult:N}}}function FT({inContextDrawMatchUps:t,winningDrawPosition:e,sourceMatchUpStatus:n,winnerParticipantId:r,tournamentRecord:s,winnerTargetLink:i,sourceMatchUpId:o,drawDefinition:c,winnerMatchUp:a,matchUpsMap:u,dualMatchUp:l,event:f}){var m;const{structureId:p,roundNumber:h}=a,d="removeDirectedWinner";if(i){const g=i.target.structureId,{structure:I}=Ot({drawDefinition:c,structureId:g});if(!I)return{error:Te};const{positionAssignments:S}=ke({structure:I});I.seedAssignments=(I.seedAssignments||[]).filter(v=>v.participantId!==r);const T=S==null?void 0:S.find(v=>v.participantId===r),E=T==null?void 0:T.drawPosition,{matchUps:y}=Qt({drawDefinition:c,structure:I,event:f}),b=y.map(v=>v.drawPositions).flat(1/0).filter(Boolean),N=Mn(b);if((E?N[E]:void 0)===1)S==null||S.forEach(v=>{v.participantId===r&&delete v.participantId});else{const v=y.filter(({drawPositions:P})=>P.includes(E));console.log("not removing from position assignments since instances > 1",{drawPositionMatchUps:v,winnerTargetLink:i})}const C=(m=u==null?void 0:u.drawMatchUps)==null?void 0:m.find(({matchUpId:v})=>v===a.matchUpId);C&&qt({tournamentId:s==null?void 0:s.tournamentId,eventId:f==null?void 0:f.eventId,matchUp:C,context:d,drawDefinition:c})}return h&&EM({targetDrawPosition:e,inContextDrawMatchUps:t,sourceMatchUpStatus:n,tournamentRecord:s,sourceMatchUpId:o,drawDefinition:c,dualMatchUp:l,matchUpsMap:u,roundNumber:h,structureId:p}),{...$}}function CM({sourceMatchUpStatus:t,loserParticipantId:e,tournamentRecord:n,loserTargetLink:r,sourceMatchUpId:s,drawDefinition:i,loserMatchUp:o,matchUpsMap:c,dualMatchUp:a,event:u}){var m,g,I;const l="removeDirectedLoser",f=r.target.structureId,{structure:p}=Ot({drawDefinition:i,structureId:f});if(!p)return{error:Te};const{positionAssignments:h}=ke({structure:p}),d=(m=h==null?void 0:h.find(S=>S.participantId===e))==null?void 0:m.drawPosition;if(h==null||h.forEach(S=>{S.participantId===e&&delete S.participantId}),p.seedAssignments=(p.seedAssignments||[]).filter(S=>S.participantId!==e),a){const S=o==null?void 0:o.sides.reduce((y,b,N)=>b.drawPosition===d?N:y,void 0),T=(g=c==null?void 0:c.drawMatchUps)==null?void 0:g.find(({matchUpId:y})=>y===o.matchUpId),E=(I=T==null?void 0:T.sides)==null?void 0:I[S];E&&(delete E.lineUp,qt({tournamentId:n==null?void 0:n.tournamentId,eventId:u==null?void 0:u.eventId,matchUp:T,context:l,drawDefinition:i}))}return{...$}}function kp({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,matchUpsMap:s,targetLink:i,event:o}){const c=i.target.structureId;return Ac({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,matchUpsMap:s,drawPosition:r,structureId:c,event:o}),{...$}}function LT(t){let{sourceMatchUp:e}=t;const{targetMatchUp:n,structure:r,matchUpsMap:s,drawPosition:i}=t,o=n.roundNumber>1&&n.roundNumber-1,c=Ui({structureId:r.structureId,matchUpsMap:s});!e&&i&&(e=c.find(({drawPositions:d,roundNumber:m})=>m===o&&(d==null?void 0:d.includes(i))));const a=e==null?void 0:e.roundPosition,u=a%2?1:-1,l=a+u,f=o&&c.find(({roundNumber:d,roundPosition:m})=>d===o&&m===l),p=f==null?void 0:f.matchUpStatus,h=[Fe,en].includes(p);return{pairedPreviousMatchUp:f,pairedPreviousMatchUpIsDoubleExit:h}}function Ll({drawDefinition:t,positionAction:e}){var i;const{extension:n}=xn({name:xu,element:t}),r=Array.isArray(n==null?void 0:n.value)?(n==null?void 0:n.value)||[]:[];if(!(r!=null&&r.length)){const o=t.structures.find(c=>c.stage===It);if(o){const c=(i=ee({structure:o}).positionAssignments)==null?void 0:i.map(({drawPosition:a,participantId:u,bye:l,qualifier:f})=>({drawPosition:a,participantId:u,qualifier:f,bye:l}));r.push({name:"initialMainAssignments",initialAssignments:c})}}const s={name:xu,value:r.concat(e)};ae({element:t,extension:s})}function Vn({provisionalPositioning:t,isPositionAction:e,tournamentRecord:n,drawDefinition:r,drawPosition:s,matchUpsMap:i,structureId:o,structure:c,event:a}){var P;if(!r)return{error:lt};if(c||({structure:c}=Ot({drawDefinition:r,structureId:o})),!c)return{error:Te};o||({structureId:o}=c);const u="assignDrawPositionBye";ts(),i||(i=ln({drawDefinition:r}));const{positionAssignments:l}=ee({structure:c}),{activeDrawPositions:f}=qa({drawDefinition:r,structureId:o}),p=l==null?void 0:l.find(U=>U.drawPosition===s);if(p!=null&&p.bye)return{...$};if(f==null?void 0:f.includes(s))return{error:Rd};const d=l==null?void 0:l.find(U=>U.drawPosition===s);if(!d)return{error:Wo};const{filled:m,containsBye:g,assignedParticipantId:I}=PM(d);if(g)return{...$};if(m&&!g)return G({result:{error:Gc},stack:u});const S=xe({inContext:!0,drawDefinition:r,matchUpsMap:i}).matchUps||[],T={isCollectionMatchUp:!1},{matchUps:E}=Qt({provisionalPositioning:t,drawDefinition:r,matchUpFilters:T,matchUpsMap:i,structure:c});if(l==null||l.forEach(U=>{U.drawPosition===s&&(U.bye=!0)}),c.structureType===mn)return UM({tournamentRecord:n,drawDefinition:r,drawPosition:s,matchUps:E}),ni({tournamentId:n==null?void 0:n.tournamentId,drawDefinition:r,structure:c,event:a}),RT({assignedParticipantId:I,isPositionAction:e,drawDefinition:r,drawPosition:s,structureId:o,stack:u});const{roundProfile:y,roundMatchUps:b}=Cn({matchUps:E}),N=y&&Object.keys(y).map(U=>parseInt(U)).reverse(),A=N==null?void 0:N.find(U=>{var O;return(O=y==null?void 0:y[U].drawPositions)==null?void 0:O.includes(s)}),C=A&&(b==null?void 0:b[A].find(({drawPositions:U})=>U==null?void 0:U.includes(s)));BT({tournamentRecord:n,drawDefinition:r,matchUp:C,event:a});const v=(P=C.drawPositions)==null?void 0:P.find(U=>U!==s);if(v){const U=_p({sourceDrawPositions:C.drawPositions,matchUpId:C.matchUpId,inContextDrawMatchUps:S,drawPositionToAdvance:v,tournamentRecord:n,drawDefinition:r,matchUpsMap:i});if(U.error)return U}return ni({tournamentId:n==null?void 0:n.tournamentId,drawDefinition:r,structure:c,event:a}),RT({assignedParticipantId:I,isPositionAction:e,drawDefinition:r,drawPosition:s,structureId:o,stack:u})}function RT({assignedParticipantId:t,isPositionAction:e,drawDefinition:n,drawPosition:r,structureId:s,stack:i}){return e&&Ll({drawDefinition:n,positionAction:{removedParticipantId:t,drawPosition:r,structureId:s,name:i}}),G({result:{...$},stack:i})}function PM(t){const e=t.bye,n=t.qualifier,r=t.participantId;return{containsBye:e,containsQualifier:n,assignedParticipantId:r,filled:e||n||r}}function BT({tournamentRecord:t,drawDefinition:e,eventId:n,matchUp:r,event:s}){Object.assign(r,{matchUpStatus:re,score:void 0,winningSide:void 0}),qt({tournamentId:t==null?void 0:t.tournamentId,eventId:n??(s==null?void 0:s.eventId),context:"setMatchUpStatusBye",drawDefinition:e,matchUp:r})}function UM({tournamentRecord:t,drawDefinition:e,drawPosition:n,matchUps:r,event:s}){r.forEach(i=>{var o;(o=i.drawPositions)!=null&&o.includes(n)&&BT({eventId:s==null?void 0:s.eventId,tournamentRecord:t,drawDefinition:e,matchUp:i})})}function _p({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:n,tournamentRecord:r,drawDefinition:s,matchUpsMap:i,matchUpId:o,event:c}){var E;ts();const a=i.drawMatchUps.find(y=>y.matchUpId===o),u=e.find(y=>y.matchUpId===o),l=u==null?void 0:u.structureId,{structure:f}=Ot({drawDefinition:s,structureId:l}),{positionAssignments:p}=ee({structure:f}),h=p==null?void 0:p.filter(y=>y.bye).map(y=>y.drawPosition),d=(E=a==null?void 0:a.drawPositions)==null?void 0:E.find(y=>y!==t),m=d&&(h==null?void 0:h.includes(d)),{targetLinks:{loserTargetLink:g},targetMatchUps:{loserMatchUp:I,winnerMatchUp:S,loserTargetDrawPosition:T}}=gn({inContextDrawMatchUps:e,drawDefinition:s,matchUpId:o});if(S&&S.structureId===(f==null?void 0:f.structureId)&&OM({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:n,tournamentRecord:r,drawDefinition:s,winnerMatchUp:S,matchUpsMap:i,event:c}),I&&m&&I.structureId!==(f==null?void 0:f.structureId)){const{roundNumber:y}=I;if(y===1){const b=Vn({structureId:g.target.structureId,drawPosition:T,tournamentRecord:r,drawDefinition:s,event:c});if(b.error)return b}else xT({loserTargetDrawPosition:T,tournamentRecord:r,loserTargetLink:g,drawDefinition:s,loserMatchUp:I,matchUpsMap:i,event:c})}return{...$}}function OM({drawPositionToAdvance:t,inContextDrawMatchUps:e,sourceDrawPositions:n,tournamentRecord:r,drawDefinition:s,winnerMatchUp:i,matchUpsMap:o,event:c}){var k,_,F;const a="advanceWinner",u=o.drawMatchUps.find(L=>L.matchUpId===i.matchUpId),l=e.find(L=>L.matchUpId===i.matchUpId),f=l==null?void 0:l.structureId,{structure:p}=Ot({drawDefinition:s,structureId:f}),{positionAssignments:h}=ee({structure:p}),d=h==null?void 0:h.find(({drawPosition:L})=>L===t),m=d==null?void 0:d.bye,g=(k=u.drawPositions)==null?void 0:k.filter(Boolean),I=h==null?void 0:h.filter(L=>g==null?void 0:g.includes(L.drawPosition)),S=h==null?void 0:h.find(({drawPosition:L})=>L===t),T=n==null?void 0:n.find(L=>L!==t),E=T&&(I==null?void 0:I.find(({drawPosition:L})=>L===T)),y=E==null?void 0:E.bye,b=m&&y;if(b&&console.log({isByeAdvancedBye:b}),(g==null?void 0:g.length)>1&&m&&!y)return G({result:{error:Gc},stack:a});const N=g==null?void 0:g.find(L=>L!==t);let A=b;const C=[...(u.drawPositions||[]).filter(Boolean),void 0,void 0].slice(0,2),v=C.map(L=>!L&&!A||L===t?(A=!0,t):L).sort(Ve);if(!A)return console.log("@@@@@@@",{advancingAssignmentIsBye:S,drawPositionToAdvance:t,existingAssignments:I}),G({result:{error:Gc},stack:a});const P=(_=h==null?void 0:h.find(({drawPosition:L})=>L===N))==null?void 0:_.bye,U=(F=h==null?void 0:h.find(({drawPosition:L})=>L===t))==null?void 0:F.bye;Object.assign(u,{matchUpStatus:U||P?re:Le,score:void 0,winningSide:void 0,drawPositions:v}),u.drawPositions.find(L=>!C.includes(L)),ts(),qt({tournamentId:r==null?void 0:r.tournamentId,matchUp:u,eventId:c==null?void 0:c.eventId,context:a,drawDefinition:s});const{targetLinks:{loserTargetLink:D},targetMatchUps:{loserMatchUp:M,loserTargetDrawPosition:w}}=gn({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:s});if(P||U){const L=P?t:N;if(L)_p({drawPositionToAdvance:L,matchUpId:i.matchUpId,inContextDrawMatchUps:e,tournamentRecord:r,drawDefinition:s,matchUpsMap:o});else if(U&&D&&M)if(M.feedRound)xT({loserTargetDrawPosition:w,tournamentRecord:r,loserTargetLink:D,drawDefinition:s,loserMatchUp:M,matchUpsMap:o});else{const j=1-i.roundPosition%2,H=M.drawPositions[j],B=Vn({structureId:D.target.structureId,drawPosition:H,tournamentRecord:r,drawDefinition:s,event:c});if(B.error)return B}}}function xT({loserTargetDrawPosition:t,tournamentRecord:e,loserTargetLink:n,drawDefinition:r,loserMatchUp:s,matchUpsMap:i,event:o}){const{roundNumber:c}=s;ts();const u=((i==null?void 0:i.mappedMatchUps)||{})[s.structureId].matchUps,{initialRoundNumber:l}=Uo({drawPosition:t,matchUps:u});if(l===c){const f=Vn({structureId:n.target.structureId,drawPosition:t,tournamentRecord:e,drawDefinition:r,event:o});if(f.error)return f}}function Fp({inContextTargetMatchUp:t,drawPositionSideIndex:e,teamParticipantId:n,tournamentRecord:r,drawDefinition:s,matchUp:i,event:o}){var p,h,d,m;const c=(h=(p=t==null?void 0:t.sides)==null?void 0:p[e])==null?void 0:h.sideNumber,a=c&&((d=i.sides)==null?void 0:d.find(g=>g.sideNumber===c)),{extension:u}=Ke({element:s,name:Wr}),f=((u==null?void 0:u.value)||{})[n];if(a)(m=i==null?void 0:i.sides)==null||m.forEach(g=>{g.sideNumber===c&&(g.lineUp=f)});else{i.sides=[1,2].map(I=>{var T;return{...((T=i.sides)==null?void 0:T.find(E=>E.sideNumber===I))||{},sideNumber:I}});const g=i.sides.find(I=>I.sideNumber===c);g&&(g.lineUp=f)}qt({tournamentId:r==null?void 0:r.tournamentId,context:"updateSidLineUps",eventId:o==null?void 0:o.eventId,drawDefinition:s,matchUp:i})}function MM({drawPosition:t,drawPositions:e}){let n=!1,r=!!(e!=null&&e.includes(t));return{updatedDrawPositions:r?e||[]:[...e,void 0,void 0].slice(0,2).map(o=>!o&&!r?(r=!0,n=!0,t):o).sort(Ve).filter(Boolean),positionAdded:n,positionAssigned:r}}function Rl({inContextDrawMatchUps:t,drawPosition:e,matchUpId:n}){const r=t.filter(({winnerMatchUpId:o,loserMatchUpId:c})=>c===n||o===n).sort((o,c)=>o.roundPosition-c.roundPosition);return t.find(o=>o.matchUpId===n).feedRound?1:r.reduce((o,c,a)=>{var u;return(u=c.drawPositions)!=null&&u.includes(e)?a+1:o},void 0)}function Cc({inContextDrawMatchUps:t,sourceMatchUpStatus:e,tournamentRecord:n,sourceMatchUpId:r,drawDefinition:s,matchUpStatus:i,drawPosition:o,matchUpsMap:c,matchUpId:a,event:u}){var O,D,M;const l="assignMatchUpDrawPosition";c||(c=ln({drawDefinition:s})),t||(t=xe({inContext:!0,drawDefinition:s,matchUpsMap:c}).matchUps??[]);const f=t.find(w=>w.matchUpId===a),p=f==null?void 0:f.structureId,h=(O=s==null?void 0:s.structures)==null?void 0:O.find(w=>w.structureId===p);if(!h)return{error:Te};const d=(D=c==null?void 0:c.drawMatchUps)==null?void 0:D.find(w=>w.matchUpId===a),m=(d==null?void 0:d.drawPositions)??[],{positionAdded:g,positionAssigned:I,updatedDrawPositions:S}=MM({drawPosition:o,drawPositions:m}),{positionAssignments:T}=ee({drawDefinition:s,structure:h}),E=T==null?void 0:T.filter(w=>S.includes(w.drawPosition)),y=E==null?void 0:E.find(({bye:w})=>w),b=(d==null?void 0:d.matchUpStatus)&&[ce,te].includes(d.matchUpStatus)&&S.filter(Boolean).length<2;if(i=y&&re||i||b&&d.matchUpStatus||(d==null?void 0:d.matchUpStatus)&&[Fe,en].includes(d.matchUpStatus)&&d.matchUpStatus||Le,d&&g){t=xe({inContext:!0,drawDefinition:s,matchUpsMap:c}).matchUps??[];const w=b&&Rl({inContextDrawMatchUps:t,drawPosition:o,matchUpId:a})||void 0;d!=null&&d.matchUpStatusCodes&&wT({inContextDrawMatchUps:t,sourceMatchUpStatus:e,sourceMatchUpId:r,matchUpsMap:c,matchUp:d}),Object.assign(d,{drawPositions:S,winningSide:w,matchUpStatus:i}),qt({tournamentId:n==null?void 0:n.tournamentId,eventId:f==null?void 0:f.eventId,context:l,drawDefinition:s,matchUp:d})}const N=gn({inContextDrawMatchUps:t,inContextMatchUp:f,drawDefinition:s,matchUpId:a}),{targetMatchUps:{winnerMatchUp:A,loserMatchUp:C,loserTargetDrawPosition:v},targetLinks:{loserTargetLink:P}}=N,U=Ui({structureId:h.structureId,matchUpsMap:c});if(I&&y){if(A)if([re,Fe,en].includes(i)){const w=Cc({matchUpId:A.matchUpId,inContextDrawMatchUps:t,tournamentRecord:n,drawDefinition:s,drawPosition:o,matchUpsMap:c});if(w.error)return w}else{const{structureId:w}=A;w!==h.structureId&&console.log("winnerMatchUp in different structure... participant is in different targetDrawPosition")}}else if(A&&f&&!f.feedRound){const{pairedPreviousMatchUpIsDoubleExit:w}=LT({targetMatchUp:d,drawPosition:o,matchUpsMap:c,structure:h});if(w){const k=Cc({matchUpId:A.matchUpId,inContextDrawMatchUps:t,tournamentRecord:n,drawDefinition:s,drawPosition:o,matchUpsMap:c});if(k.error)return k}}if((d==null?void 0:d.matchUpType)===Jt){const w=t==null?void 0:t.find(({matchUpId:L})=>L===d.matchUpId),_=((w==null?void 0:w.sides)??[]).reduce((L,W,j)=>W.drawPosition===o?j:L,void 0),F=(M=T==null?void 0:T.find(L=>L.drawPosition===o))==null?void 0:M.participantId;F&&_!==void 0&&Fp({inContextTargetMatchUp:w,drawPositionSideIndex:_,teamParticipantId:F,tournamentRecord:n,drawDefinition:s,matchUp:d})}if((P==null?void 0:P.linkCondition)===fs&&S.filter(Boolean).length===2&&!y&&U.filter(({drawPositions:_,roundNumber:F})=>F===1&&tn(_,S)).every(({matchUpStatus:_})=>[De,In].includes(_))&&C){const{structureId:_}=C,F=Vn({drawPosition:v,tournamentRecord:n,drawDefinition:s,structureId:_,matchUpsMap:c,event:u});if(F.error)return F}return I?{...$}:G({result:{error:Gc},context:{drawPosition:o},stack:l})}function Ya(t){var m;const{tournamentRecord:e,appliedPolicies:n,drawDefinition:r,matchUpsMap:s,targetData:i,structure:o,event:c}=t,a="doubleExitAdvancement";if(o.structureType===mn)return G({result:{...$},stack:a});const{matchUp:u,targetMatchUps:l,targetLinks:f}=i,{loserMatchUp:p,winnerMatchUp:h,loserTargetDrawPosition:d}=l;if(p&&p.matchUpStatus!==pe.Bye){const{loserTargetLink:g}=f;if((m=n==null?void 0:n.progression)!=null&&m.doubleExitPropagateBye){const I=VT({loserTargetDrawPosition:d,tournamentRecord:e,loserTargetLink:g,drawDefinition:r,loserMatchUp:p,matchUpsMap:s,event:c});if(I.error)return G({result:I,stack:a})}else{const{feedRound:I,drawPositions:S,matchUpId:T}=p,E=I?2:2-S.indexOf(d),y=$T({...t,targetMatchUp:p,walkoverWinningSide:E,tournamentRecord:e,sourceMatchUp:u,matchUpId:T});if(y.error)return G({result:y,stack:a})}}if(h){const g=$T({...t,matchUpId:h.matchUpId,targetMatchUp:h,tournamentRecord:e,sourceMatchUp:u});if(g.error)return G({result:g,stack:a})}return G({result:{...$},stack:a})}function $T(t){var R,x,q;const{inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:r,sourceMatchUp:s,targetMatchUp:i,matchUpsMap:o}=t,c=r.structures.find(({structureId:V})=>V===i.structureId),a=t.matchUpStatus===pe.DoubleDefault?pe.DoubleDefault:pe.DoubleWalkover,u=t.matchUpStatus===pe.DoubleDefault?pe.Defaulted:pe.Walkover,l="conditionallyAdvanceDrawPosition",f=o.drawMatchUps.find(V=>V.matchUpId===i.matchUpId);if(!f)return{error:Rn};const p=(s==null?void 0:s.drawPositions)||[];let h=(R=f.drawPositions)==null?void 0:R.filter(Boolean);const d=(s==null?void 0:s.structureId)===i.structureId;if(d&&tn(p,h)&&(h=h.filter(V=>!p.includes(V))),d&&h.length>1)return G({result:{error:Gc},stack:l});const{pairedPreviousMatchUpIsDoubleExit:m,pairedPreviousMatchUp:g}=LT(t),I=gn({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:r}),{targetMatchUps:S,targetLinks:T}=I,{loserTargetDrawPosition:E,winnerMatchUp:y,loserMatchUp:b}=S;if(b){const{loserTargetLink:V}=T,Y=VT({loserTargetDrawPosition:E,loserMatchUp:b,tournamentRecord:n,loserTargetLink:V,drawDefinition:r,matchUpsMap:o});if(Y.error)return G({result:Y,stack:l})}const N=((x=f.drawPositions)==null?void 0:x.filter(Boolean))||[],A=N.length===1,C=t.walkoverWinningSide||A&&Rl({drawPosition:N[0],matchUpId:i.matchUpId,inContextDrawMatchUps:e})||void 0,v=[pe.Walkover,pe.Defaulted].includes(f.matchUpStatus)&&!N.length,P=f.finishingRound===1,U=v&&!P?a:u,O=e.find(V=>V.matchUpId===g.matchUpId);let D=[],M;s&&((s==null?void 0:s.structureId)===(O==null?void 0:O.structureId)?s.roundPosition<(g==null?void 0:g.roundPosition)?M=1:M=2:i.feedRound?s.structureId===i.structureId?M=2:M=1:C&&(M=3-C));const w=t.matchUpStatus,k=g==null?void 0:g.matchUpStatus;M===1?D=[{matchUpStatus:Bl(w),previousMatchUpStatus:w,sideNumber:1},{matchUpStatus:Bl(k),previousMatchUpStatus:k,sideNumber:2}]:M===2&&(D=[{matchUpStatus:Bl(k),previousMatchUpStatus:k,sideNumber:1},{matchUpStatus:Bl(w),previousMatchUpStatus:w,sideNumber:2}]),D.length&&(D=D.map(V=>bt(V)));const _=Zr({...t,matchUp:f,winningSide:C,matchUpStatusCodes:D,matchUpStatus:U});if(_.error)return G({result:_,stack:l});if(v)return Ya({...t,matchUpStatus:U,targetData:I});if(!y)return G({result:{...$},stack:l});const F=h.length===2?h[C-1]:h[0],{positionAssignments:L}=ee({structure:c}),W=L==null?void 0:L.find(V=>V.drawPosition===F),j=o.drawMatchUps.find(V=>V.matchUpId===y.matchUpId),H=(q=j==null?void 0:j.drawPositions)==null?void 0:q.filter(Boolean),B=H.length===1;if(F){if(W!=null&&W.bye){const V=gn({matchUpId:j.matchUpId,inContextDrawMatchUps:e,drawDefinition:r});if(B){const Y=H.filter(Boolean)[0],z=Rl({drawPosition:Y,matchUpId:j.matchUpId,inContextDrawMatchUps:e}),J=Zr({matchUpId:j.matchUpId,matchUp:j,matchUpStatus:u,matchUpStatusCodes:[],removeScore:!0,drawDefinition:r,winningSide:z});return J.error?G({result:J,stack:l}):_p({drawPositionToAdvance:Y,matchUpId:j.matchUpId,inContextDrawMatchUps:e,drawDefinition:r,matchUpsMap:o})}else if([pe.Walkover,pe.Defaulted].includes(y.matchUpStatus)){const Y=Ya({...t,matchUpId:j.matchUpId,matchUpStatus:U,targetData:V});if(Y.error)return G({result:Y,stack:l})}return G({result:{...$},stack:l})}return Cc({matchUpId:y.matchUpId,drawPosition:F,inContextDrawMatchUps:e,drawDefinition:r})}else if(m){if(!j)return{error:Rn};if(B){const z=H[0],J=Rl({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawPosition:z});console.log("existing drawPosition is winningSide",{walkoverWinningSide:J})}const V=[pe.Walkover,pe.Defaulted].includes(j.matchUpStatus)?u:a,Y=Zr({matchUpId:j.matchUpId,matchUp:j,matchUpStatusCodes:[],removeScore:!0,drawDefinition:r,matchUpStatus:V});if(Y.error)return G({result:Y,stack:l});if(V===a){const z=Ya({...t,matchUpId:i.matchUpId,matchUpStatus:V,targetData:I});if(z.error)return z}}return G({result:{...$},stack:l})}function VT(t){var u;const{loserTargetDrawPosition:e,tournamentRecord:n,loserTargetLink:r,drawDefinition:s,matchUpsMap:i,event:o}=t,c=(u=r==null?void 0:r.target)==null?void 0:u.structureId,{structure:a}=Ot({drawDefinition:s,structureId:c});return a?Vn({drawPosition:e,tournamentRecord:n,drawDefinition:s,structureId:c,matchUpsMap:i,event:o}):{error:Wi}}function Bl(t){return t===pe.DoubleWalkover?pe.Walkover:t===pe.DoubleDefault?pe.Defaulted:t}function DM({tournamentRecord:t,drawDefinition:e,structure:n,matchUp:r}){var a;const s="attemptToSetMatchUpStatusBYE";if(r!=null&&r.winningSide)return G({result:{error:Hc},context:{matchUpStatus:re},stack:s});const{positionAssignments:i}=ke({structure:n}),o=i==null?void 0:i.filter(u=>u.bye).map(u=>u.drawPosition);return((a=r.drawPositions)==null?void 0:a.some(u=>o==null?void 0:o.includes(u)))?(r.matchUpStatus=re,r.matchUpStatusCodes=[],qt({tournamentId:t==null?void 0:t.tournamentId,context:s,drawDefinition:e,matchUp:r}),{...$}):G({result:{error:K1},info:"matchUp does not include BYE",stack:s})}function wM(t){const{tournamentRecord:e,drawDefinition:n,matchUpStatus:r,structure:s,matchUp:i}=t,o=!!(i.tieMatchUps&&!i.rondPosition&&t.inContextDrawMatchUps.find(I=>I.matchUpId===i.matchUpId).containerStructureId),c="attemptToSetMatchUpStatus",a=r===re,u=i.winningSide,l=[Fe,en].includes(r),f=Ra({matchUpStatus:r}),p=Yf({matchUpStatus:r}),h=!f&&!p,d=t.matchUpTieId||u&&f&&!l,m=u&&l,g=()=>Zr({...t,removeScore:[Gs,ce].includes(r),matchUpStatus:r||Le});return h&&{error:Zm}||d&&Lp(t)||m&&kM(t)||u&&vc(t)||p&&g()||a&&DM({tournamentRecord:e,drawDefinition:n,structure:s,matchUp:i})||!f&&{error:Zm}||l&&_M(t)||o&&Lp(t)||G({result:{error:Hc},stack:c})}function kM(t){const e=vc(t);return e.error?e:Ya(t)}function _M(t){const e=Lp({...t,removeScore:!0});return e.error?e:Ya(t)}function Lp(t){var i;const e="scoreModification";if(t.isCollectionMatchUp&&((i=t.dualMatchUp)==null?void 0:i.winningSide)&&!t.projectedWinningSide){const o=vc(t);if(o.error)return G({result:o,stack:e})}const r=!!t.matchUp.collectionId,s=Zr(t);if(r){const{matchUpTieId:o,drawDefinition:c,matchUpsMap:a}=t,u=ms({tournamentRecord:t.tournamentRecord,matchUpId:o,event:t.event,drawDefinition:c,matchUpsMap:a});if(u.error)return G({result:u,stack:e});Object.assign(s,{tieMatchUpResult:u})}return G({result:s,stack:e})}function FM({drawDefinition:t,structure:e,matchUp:n}){var f,p;const{drawPositions:r}=n,{positionAssignments:s}=ee({drawDefinition:t,structure:e}),i=s==null?void 0:s.filter(({drawPosition:h})=>r==null?void 0:r.includes(h)),o=i==null?void 0:i.map(h=>{var m;const{extension:d}=Ke({element:h,name:Ys});return(m=d==null?void 0:d.value)==null?void 0:m.groupOrder}),{containerStructures:c}=Nc({drawDefinition:t}),a=c[e.structureId],u=(p=(f=$a({drawDefinition:t,structureId:a}))==null?void 0:f.links)==null?void 0:p.source;return{structureIds:u==null?void 0:u.filter(h=>{var d;return tn(o,((d=h.source)==null?void 0:d.finishingPositions)||[])}).map(h=>h.source.structureId)}}function jT({drawDefinition:t,structureId:e}){if(!t)return{error:lt};const{structure:n}=Ot({drawDefinition:t,structureId:e}),r=((t==null?void 0:t.links)||[]).filter(i=>{var o;return((o=i.source)==null?void 0:o.structureId)===e}).map(i=>{var o;return(o=i.target)==null?void 0:o.structureId});return{playoffStructures:((t==null?void 0:t.structures)||[]).filter(i=>r.includes(i.structureId)),structure:n}}function GT({withStageGrouping:t,stageSequences:e,stageSequence:n,roundTarget:r,stages:s,event:i,stage:o}){if(!i)return{error:Wt};const c={},a=[];for(const u of i.drawDefinitions||[]){const{structures:l,stageStructures:f}=lr({withStageGrouping:t,stageSequences:e,drawDefinition:u,stageSequence:n,roundTarget:r,stages:s,stage:o});if(a.push(...l),f)for(const p of Object.keys(f))c[p]||(c[p]=[]),c[p].push(...f[p])}return{structures:a,stageStructures:c}}function LM({withStageGrouping:t,tournamentRecord:e,stageSequences:n,stageSequence:r,roundTarget:s,stages:i,stage:o}){if(!e)return{error:et};const c={},a=[];for(const u of e.events||[]){const{structures:l,stageStructures:f}=GT({withStageGrouping:t,stageSequences:n,stageSequence:r,roundTarget:s,stages:i,event:u,stage:o});if(l&&a.push(...l),f)for(const p of Object.keys(f))c[p]||(c[p]=[]),c[p].push(...f[p])}return{structures:a,stageStructures:c}}function RM(t){const e=[];if(!(t!=null&&t.drawDefinition))return{error:lt};const n=ki(t),r=WT(t);return{actions:e,state:{isComplete:n,hasPlayoffPositionsFilled:r}}}function ki(t){if(!(t!=null&&t.drawDefinition))return!1;const e=Va(t),n=e==null?void 0:e.includesTeamMatchUps;let{completedMatchUps:r,pendingMatchUps:s,upcomingMatchUps:i}=e||{};return n&&(r=r==null?void 0:r.filter(({matchUpType:c})=>c===Jt),s=s==null?void 0:s.filter(({matchUpType:c})=>c===Jt),i=i==null?void 0:i.filter(({matchUpType:c})=>c===Jt)),!!((r==null?void 0:r.length)&&!(s!=null&&s.length)&&!(i!=null&&i.length))}function WT(t){var a,u;const{drawDefinition:e,structureId:n}=t;if(!e)return{error:lt};const{playoffStructures:r}=jT({drawDefinition:e,structureId:n});if(!(r!=null&&r.length))return!1;const s=((u=(a=e==null?void 0:e.entries)==null?void 0:a.filter(l=>ps.includes(l==null?void 0:l.entryStatus)))==null?void 0:u.length)||0;let i=0;return(r||[]).reduce((l,f)=>{const p=ee({structure:f}).positionAssignments??[];return(p==null?void 0:p.filter(d=>(d.participantId&&i++,(d==null?void 0:d.bye)||(d==null?void 0:d.participantId))).length)&&l},!!r.length)||i===s}function HT({drawDefinition:t,structure:e,matchUp:n}){const r=[];if(e.finishingPosition===uc&&ki({drawDefinition:t,structure:e})){const{structureIds:i}=FM({drawDefinition:t,structure:e,matchUp:n});i!=null&&i.length&&r.push(...i)}return{connectedStructureIds:r}}function Rp(t){const{dualWinningSideChange:e,matchUpStatusCodes:n,tournamentRecord:r,drawDefinition:s,matchUpFormat:i,matchUpStatus:o,winningSide:c,matchUpId:a,structure:u,matchUp:l,event:f,score:p}=t,h=Ra({matchUpStatus:o})||[Gs,zn].includes(o)&&e,d="attemptToModifyScore",m=!!l.collectionId,g=Qr({drawDefinition:s,structure:u});if(!(m||g||BM({structure:u,matchUp:l})))return{error:Jm};const S=[ce].includes(o),T=Zr({matchUpStatusCodes:h&&n||[],matchUpStatus:h&&o||De,tournamentRecord:r,drawDefinition:s,matchUpFormat:i,removeScore:S,winningSide:c,matchUpId:a,matchUp:l,event:f,score:p});return G({result:T,stack:d})}function BM({structure:t,matchUp:e}){const{drawPositions:n}=e,{positionAssignments:r}=ke({structure:t}),s=r==null?void 0:r.filter(i=>(n==null?void 0:n.includes(i.drawPosition))&&i.participantId);return(s==null?void 0:s.length)===2}function Bp({lineUp:t}){if(!Array.isArray(t))return;const e={};return Vt(t.flatMap(({collectionAssignments:r})=>r.map(({collectionId:s,collectionPosition:i})=>[s,i].join("|")))).forEach(r=>{const[s,i]=r.split("|"),o=parseInt(i),{assignedParticipantIds:c}=Xu({collectionPosition:o,collectionId:s,lineUp:t});c.forEach(a=>{e[a]||(e[a]=[]),e[a].push({collectionId:s,collectionPosition:o})})}),Object.keys(e).map(r=>({participantId:r,collectionAssignments:e[r]}))}function Pc(t){if(!t)return 1/0;if(oe(t))return vt(t);const e=t.split("-")[0];return oe(e)?vt(e):1/0}const Ze=({finishingPosition:t=fo,qualifyingRoundNumber:e,structureAbbreviation:n,seedAssignments:r=[],stageSequence:s=1,structureOrder:i,seedingProfile:o,matchUpFormat:c,structureType:a,structureName:u,matchUpType:l,matchUps:f=[],structureId:p,roundOffset:h,roundLimit:d,stageOrder:m,structures:g,stage:I})=>{const S={structureId:p??Yt(),structureAbbreviation:n,finishingPosition:t,seedAssignments:r,matchUpFormat:c,stageSequence:s,structureName:u};i&&(S.structureOrder=i),a&&(S.structureType=a),o&&(typeof o=="string"?S.seedingProfile=o:typeof o=="object"&&typeof o.positioning=="string"&&(S.seedingProfile=o.positioning)),l&&(S.matchUpType=l),h&&(S.roundOffset=h),m&&(S.stageOrder=m),d&&(S.roundLimit=d),I&&(S.stage=I),e&&(S.qualifyingRoundNumber=e);const T=f.flatMap(({drawPositions:E})=>E).filter(Boolean);return g?S.structures=g:(S.matchUps=f,S.positionAssignments=Vt(T).sort((E,y)=>E-y).map(E=>({drawPosition:E}))),S};function za({structureName:t=It,stageSequence:e=1,structureOptions:n,appliedPolicies:r,seedingProfile:s,stage:i=It,matchUpType:o,roundTarget:c,structureId:a,drawSize:u,idPrefix:l,isMock:f,uuids:p}){const{groupCount:h,groupSize:d}=xM({structureOptions:n,appliedPolicies:r,drawSize:u}),m=uc;let g;const I=ht(1,h+1).map(T=>{const E=$M({groupSize:d,structureOrder:T,matchUpType:o,drawSize:u,idPrefix:l,isMock:f});return g=Math.max(...E.map(({roundNumber:y})=>y)),Ze({structureName:`Group ${T}`,structureId:p==null?void 0:p.pop(),structureType:tl,finishingPosition:m,structureOrder:T,matchUps:E})}),S=Ze({structureId:a||(p==null?void 0:p.pop()),structureType:mn,finishingPosition:m,seedingProfile:s,structureName:t,stageSequence:e,structures:I,stage:i});return c&&ae({extension:{name:Hr,value:c},element:S}),{structures:[S],maxRoundNumber:g,groupCount:h,links:[],groupSize:d,...$}}function xM({appliedPolicies:t,structureOptions:e,drawSize:n}){let r=e==null?void 0:e.groupSize;const s=(e==null?void 0:e.groupSizeLimit)||8,{validGroupSizes:i}=xp({groupSizeLimit:s,drawSize:n}),o=i&&Math.max(...i);r&&(i==null?void 0:i.includes(r))||(r&&r>4||!(i!=null&&i.includes(4))?r=o:r=4);const a=Math.ceil(n/r);return{groupSize:r,groupCount:a}}function xp({drawSize:t,groupSizeLimit:e=10}){const n=ht(3,e+1).filter(r=>{const s=Math.ceil(t/r),i=s*r-t,o=Math.ceil(t/s),c=Math.ceil(i/s);return(!i||i<r)&&o===r&&o>=3&&c<2});return{...$,validGroupSizes:n}}function $M({structureOrder:t,matchUpType:e,groupSize:n,drawSize:r,idPrefix:s,isMock:i,uuids:o}){const c=(t-1)*n,a=ht(1+c,n+1+c),{uniqueMatchUpGroupings:u}=yp({drawPositions:a}),l=TT({groupSize:n,drawPositionOffset:c});return u.map(h).sort((d,m)=>(d.roundNumber||1/0)-(m.roundNumber||1/0));function p(d){return l.reduce((m,g,I)=>g.includes(d)?I+1:m,void 0)}function h(d){const m=Cl(d),g=p(m),I=[1,r],S=VM({structureOrder:t,drawPositions:d,roundNumber:g,idPrefix:s,uuids:o}),T={matchUpStatus:g?pe.ToBePlayed:pe.Bye,matchUpType:e,finishingPositionRange:{winner:I,loser:I},drawPositions:d,roundNumber:g,matchUpId:S};return i&&(T.isMock=!0),T}}function VM({structureOrder:t,drawPositions:e,roundNumber:n,idPrefix:r,uuids:s}){return r?`${r}-${t}-${n}-DP-${e.join("-")}`:(s==null?void 0:s.pop())||Yt()}function xl(t){const{roundRobinGroupsCount:e,participantsCount:n,cluster:r}=t;if(!oe(n))return{seedBlocks:void 0,...G({result:{error:tt},context:{participantsCount:n},stack:"getSeedBlocks"})};const s=Vo(n);if(e){const h=Math.min(e,s),d=[];let m=1;for(ht(0,h).forEach(()=>{d.push([m]),m++});m<s;){const g=ht(m,m+h);m+=h,d.push(g)}return{...$,seedBlocks:d}}const i=ht(1,s+1),o=[];let c=s/2;for(;c>1;){const h=Ge(i,c),d=h.length;h.forEach((m,g)=>{let I;const S=g<d/2,T=g%2===0,E=m[0],y=m[m.length-1];r&&d>4?d===8?I=S?y:E:I=T?E:y:I=S?E:y,tn(m,o)||o.push(I)}),c=c/2}const a=i.filter(h=>!o.includes(h));for(;a.length;)a.length%2===0?o.push(a.pop()):o.push(a.shift());const u=ht(0,20).map(h=>Math.pow(2,h));u.unshift(1);const l=u.indexOf(s);let f=0;const p=[];return ht(0,l).forEach(h=>{p.push(o.slice(f,f+u[h])),f+=u[h]}),{...$,seedBlocks:p}}function $l({roundRobinGroupsCount:t,drawSize:e}){const n="getSeedGroups";if(!oe(e))return{seedGroups:void 0,...G({result:{error:tt},context:{drawSize:e},stack:n})};if(t){if(!oe(t))return{seedGroups:void 0,...G({result:{error:tt},context:{roundRobinGroupsCount:t},stack:n})};let r=1;const s=Math.floor(e/t);return{seedGroups:ht(0,s).map(()=>{const o=ht(r,r+t);return r+=t,o})}}else{const{seedBlocks:r}=xl({participantsCount:e,roundRobinGroupsCount:t});let s=0;return{seedGroups:(r||[]).map(o=>(o||[]).map(()=>(s+=1,s)))}}}function jM({roundRobinGroupsCount:t,participantsCount:e}){if(t){const{validGroupSizes:s}=xp({drawSize:e}),i=s==null?void 0:s.map(c=>Math.ceil(e/c));if(!(i!=null&&i.includes(t)))return G({result:{error:tt},context:{roundRobinGroupsCount:t}})}const{seedGroups:n}=$l({drawSize:e,roundRobinGroupsCount:t}),r=(n==null?void 0:n.map(s=>Math.min(...s)))||[];return{...$,seedingThresholds:r}}function Oo({provisionalPositioning:t,appliedPolicies:e,drawDefinition:n,allPositions:r,structure:s}){var k;let i=[];if(!s)return{error:Wi};const{matchUps:o,roundMatchUps:c}=Qt({matchUpFilters:{roundNumbers:[1]},provisionalPositioning:t,structure:s}),{seedAssignments:a}=Mr({provisionalPositioning:t,drawDefinition:n,structure:s}),{positionAssignments:u}=ke({structure:s}),l=u==null?void 0:u.length,f=(a==null?void 0:a.length)??0;let p=[];const d=Object.keys(c).map(_=>parseInt(_)).sort((_,F)=>_-F).map(_=>{const F=c[_].map(W=>W.drawPositions).flat(1/0).filter(Boolean),L=F.filter(W=>!p.includes(W));return p=p.concat(...F),L}).filter(_=>_.length).reverse(),m=d.pop(),g=m&&Math.min(...m)-1||0,I=(k=e==null?void 0:e.seeding)==null?void 0:k.seedingProfile,S=(m==null?void 0:m.length)||0,T=d.filter(_=>_.filter(F=>F<=f).length),{stage:E,structureType:y,roundLimit:b}=s,N=y===mn,A=!N&&(d==null?void 0:d.length),C=!N&&E===Pt&&b,v=T.flat(1/0),P=A?v==null?void 0:v.length:0,U=r?l:f,O=qf({drawDefinition:n,structure:s,matchUps:o}),D=O?0:!A&&U||U&&v.length<U&&U-v.length||0;if(C){const _=s!=null&&s.matchUps?s.matchUps.filter(({roundNumber:L})=>L===s.roundLimit).length:0,F=m.length/_;if(!A){const L=Ka(I),W=Ge(m,F);let j=1;const H=ht(0,W[0].length).map(()=>{const B=ht(j,j+W.length);return j+=W.length,B});({validSeedBlocks:i}=qT({drawPositionBlocks:W,positioning:L,seedGroups:H}))}}else N?{validSeedBlocks:i}=GM({seedingProfile:I,structure:s}):A?i=T.map(_=>({seedNumbers:_,drawPositions:_})):O&&Ge(m,2).map((F,L)=>({drawPositions:[F[0]],seedNumbers:[L+1]})).forEach(F=>i.push(F));if(!N&&!O&&!C){const{blocks:_}=WM({drawPositionOffset:g,seedNumberOffset:P,seedCountGoal:D,seedingProfile:I,baseDrawSize:S});_.forEach(F=>i.push(F))}const w=i.flatMap(_=>_.drawPositions).reduce((_,F)=>(m==null?void 0:m.includes(F))&&_,!0);return!O&&!A&&!N&&!w?{error:V1,validSeedBlocks:[],isContainer:N,isFeedIn:A}:{isLuckyStructure:O,validSeedBlocks:i,isContainer:N,isFeedIn:A}}function GM({seedingProfile:t,structure:e}){var u;const n=e.structures||[],r=n.length,s=(u=ee({structure:e}))==null?void 0:u.positionAssignments,i=Ka(t),o=(s==null?void 0:s.length)??0,{seedGroups:c}=$l({roundRobinGroupsCount:r,drawSize:o}),a=n.map(l=>{var f;return(f=ee({structure:l}).positionAssignments)==null?void 0:f.map(p=>p.drawPosition)});return qT({drawPositionBlocks:a,positioning:i,seedGroups:c})}function qT({positioning:t,seedGroups:e,drawPositionBlocks:n}){const r=[],s=(c,a)=>c-a,i=(c,a)=>a-c,o=[];return e.forEach((c,a)=>{a&&t!==Rf&&on(c),c.forEach((u,l)=>{const f=a%2?n.length-l-1:l,p=n[f].sort(a%2?i:s).find(h=>!o.includes(h));o.push(p),r.push({seedNumbers:[u],drawPositions:[p]})})}),{validSeedBlocks:r}}function WM(t){const{drawPositionOffset:e=0,roundRobinGroupsCount:n,seedNumberOffset:r=0,seedingProfile:s,seedCountGoal:i,baseDrawSize:o}=t;let c=1;const a=[],{seedBlocks:u}=xl({cluster:Ka(s)===Lf,participantsCount:o,roundRobinGroupsCount:n});c=0;for(const f of u){if(c+1>i)break;const p=f.map(d=>d+e),h=l(c+1,f.length).map(d=>+d+r);c+=f.length,a.push({drawPositions:p,seedNumbers:h})}return{blocks:a};function l(f,p){return Array.from(new Array(p),(h,d)=>d+f)}}function Vl({appliedPolicies:t,drawDefinition:e,seedBlockInfo:n,drawPosition:r,structureId:s,seedNumber:i}){var u,l,f,p,h;const{structure:o}=Ot({drawDefinition:e,structureId:s});t||(t=ge({drawDefinition:e}).appliedPolicies);let c=n==null?void 0:n.validSeedBlocks;if(!c&&o&&(c=(u=Oo({appliedPolicies:t,drawDefinition:e,structure:o}))==null?void 0:u.validSeedBlocks),(f=(l=t==null?void 0:t.seeding)==null?void 0:l.validSeedPositions)!=null&&f.ignore)return!0;if((h=(p=t==null?void 0:t.seeding)==null?void 0:p.validSeedPositions)!=null&&h.strict){const d=c.find(g=>g.seedNumbers.includes(i));return((d==null?void 0:d.drawPositions)||[]).includes(r)}return[].concat(...c.map(d=>d.drawPositions)).includes(r)}function jl(t){var _,F;const{provisionalPositioning:e,drawDefinition:n,seedBlockInfo:r,structureId:s,randomize:i}=t,{structure:o}=Ot({drawDefinition:n,structureId:s}),{seedAssignments:c}=Mr({provisionalPositioning:e,drawDefinition:n,structure:o}),{positionAssignments:a}=ke({structure:o}),u=a==null?void 0:a.filter(L=>L.participantId??L.bye??L.qualifier),l=u==null?void 0:u.map(L=>L.drawPosition).filter(Boolean),{appliedPolicies:f}=ge({drawDefinition:n}),d=((r==null?void 0:r.validSeedBlocks)||o&&((_=Oo({provisionalPositioning:e,appliedPolicies:f,drawDefinition:n,structure:o}))==null?void 0:_.validSeedBlocks)||[]).filter(L=>L.drawPositions.filter(j=>!(l!=null&&l.includes(j))).length)[0],m=c==null?void 0:c.map(L=>L.participantId).filter(Boolean),g=a==null?void 0:a.map(L=>L.participantId).filter(Boolean),I=m==null?void 0:m.filter(L=>g==null?void 0:g.includes(L)),S=m==null?void 0:m.filter(L=>!(g!=null&&g.includes(L))),T=c==null?void 0:c.filter(L=>S==null?void 0:S.includes(L.participantId)),E=c==null?void 0:c.filter(L=>!L.participantId),b=(T!=null&&T.length&&T.length>0?T.length:(E==null?void 0:E.length)??0)&&(d==null?void 0:d.drawPositions.filter(L=>!(l!=null&&l.includes(L))))||[],N=i?on(b):b,A=[],C=N.map(()=>{const L=k(T,A),W=L==null?void 0:L.participantId;return W&&A.push(W),W}).filter(Boolean),v=c==null?void 0:c.filter(L=>I==null?void 0:I.includes(L.participantId)).map(L=>L.seedNumber),U=((d==null?void 0:d.seedNumbers)||[]).filter(L=>!(v!=null&&v.includes(L))),O=c==null?void 0:c.filter(L=>U.includes(L.seedNumber)).map(L=>L.participantId),D=(F=f==null?void 0:f.seeding)==null?void 0:F.duplicateSeedNumbers;return{nextSeedBlock:d,unplacedSeedParticipantIds:(D!==void 0?D:!0)?C:O,unplacedSeedNumbers:U,unfilledPositions:N,unplacedSeedAssignments:T};function k(L,W){const j=L.filter(x=>!W.includes(x.participantId)),H=Math.min(...j.map(x=>Pc(x.seedValue))),B=j.filter(x=>Pc(x.seedValue)===H);return on(B).pop()}}function Ka(t){if(typeof t=="string")return t;if(typeof t=="object")return t.positioning}function Mo({participantId:t,drawDefinition:e,entryStatus:n,entryStage:r}){var i;if(!e)return{error:lt};const s=(i=e.entries)==null?void 0:i.find(o=>o.participantId===t&&(!n||n===o.entryStatus)&&(!r||r===o.entryStage));return t&&s}function Do({provisionalPositioning:t,tournamentRecord:e,drawDefinition:n,seedingProfile:r,participantId:s,seedBlockInfo:i,structureId:o,seedNumber:c,seedValue:a,eventId:u,event:l}){var b,N;const f="assignSeed",{structure:p}=Ot({drawDefinition:n,structureId:o}),{positionAssignments:h}=ke({structure:p}),d=Mr({provisionalPositioning:t,drawDefinition:n,structure:p}).seedAssignments,m=d.map(A=>A.seedNumber),g=Mo({drawDefinition:n,participantId:s});if(s&&!g)return G({result:{error:bs},context:{participantId:s},stack:f});const I=l?(N=(b=be({event:l}).flightProfile)==null?void 0:b.flights)==null?void 0:N.length:0,S=I&&I>1,T=h==null?void 0:h.find(A=>A.participantId===s),E=T==null?void 0:T.drawPosition;if(E&&!Vl({drawPosition:E,drawDefinition:n,seedBlockInfo:i,structureId:o,seedNumber:c}))return G({result:{error:qm},context:{assignedDrawPosition:E},info:"invalid seed position",stack:f});m.includes(c)||d.push({seedNumber:c,seedValue:a});let y;return d.forEach(A=>{A.participantId===s&&A.seedNumber!==c&&(A.participantId=void 0),A.seedNumber===c&&(A.participantId=s,!(r!=null&&r.groupSeedingThreshold)&&!S&&(A.seedValue=a||c),y=!0)}),y?(cS({tournamentId:e==null?void 0:e.tournamentId,drawDefinition:n,structure:p,eventId:u}),{...$}):G({result:{error:$1},stack:f})}function YT({inContextDrawMatchUps:t,drawDefinition:e,assignments:n,matchUpsMap:r,structure:s}){var f,p,h;const i=(f=Nc({drawDefinition:e}))==null?void 0:f.containedStructures,o=((p=i==null?void 0:i[s.structureId])==null?void 0:p.map(({structureId:d})=>d))||[];o.push(s==null?void 0:s.structureId);const c=(n==null?void 0:n.map(({drawPosition:d})=>d))||[],a=(t==null?void 0:t.filter(d=>o.includes(d.structureId)&&qe(d.drawPositions||[],c).length))||[],u=a.map(({matchUpId:d})=>d),l=((h=r==null?void 0:r.drawMatchUps)==null?void 0:h.filter(d=>u.includes(d.matchUpId)))||[];return{drawPositions:c,matchUps:l,targetMatchUps:a}}function zT({lineUp:t,tieFormat:e}){const n=[];if(!Array.isArray(t))return n.push(sn("lineUp")),{valid:!1,errors:n,error:tt};const r=t.every(o=>{if(typeof o!="object")return n.push("lineUp entries must be objects"),!1;const{participantId:c,collectionAssignments:a}=o;return c?typeof c!="string"?(n.push("participantIds must be strings"),!1):Array.isArray(a)?a.every(u=>{if(typeof u!="object")return n.push("collectionAssignments must be objects"),!1;const{collectionPosition:l}=u;return typeof l!="number"?(n.push("collectionPosition must be a number"),!1):!0}):(n.push(sn("collectionAssignments")),!1):(n.push("Missing participantId"),!1)}),s=Vt(t.map(fe)).length===t.length;return s||n.push("Duplicated participantId(s)"),{valid:r&&s,errors:n,error:n.length?tt:void 0}}function Uc({drawDefinition:t,participantId:e,tieFormat:n,lineUp:r}){if(typeof t!="object")return{error:lt};if(typeof e!="string")return{error:Ce};const s=zT({lineUp:r,tieFormat:n});if(!s.valid)return s;const{extension:i}=xn({element:t,name:Wr}),o=(i==null?void 0:i.value)||{};return o[e]=Bp({lineUp:r}),ae({element:t,extension:{name:Wr,value:o}}),Ba({drawDefinition:t}),{...$}}function $p({inContextDrawMatchUps:t,inheritance:e=!0,tournamentRecord:n,drawDefinition:r,matchUpsMap:s,assignments:i,structure:o,event:c}){if(!r)return{error:lt};const{drawPositions:a,matchUps:u,targetMatchUps:l}=YT({inContextDrawMatchUps:t,matchUpsMap:s,assignments:i,structure:o});for(const f of l)f.matchUpType===yr&&(f.sides||[]).forEach((p,h)=>{var d;if(p!=null&&p.drawPosition&&(a!=null&&a.includes(p.drawPosition))){const m=u.find(({matchUpId:g})=>g===f.matchUpId);if((d=m==null?void 0:m.sides)!=null&&d[h]){if(delete m.sides[h].lineUp,e===!1){const g=f.tieFormat,I=p.participantId;g&&I&&Uc({drawDefinition:r,participantId:I,lineUp:[],tieFormat:g})}qt({tournamentId:n==null?void 0:n.tournamentId,context:"resetLineUps",eventId:c==null?void 0:c.eventId,drawDefinition:r,matchUp:m})}}});return{...$}}function _r({provisionalPositioning:t,inContextDrawMatchUps:e,isQualifierPosition:n,sourceMatchUpStatus:r,tournamentRecord:s,drawDefinition:i,seedingProfile:o,participantId:c,seedBlockInfo:a,drawPosition:u,matchUpsMap:l,structureId:f,event:p}){var P;const h="assignDrawPosition";if(!c&&!n)return G({result:{error:Ce},stack:h});l=l||ln({drawDefinition:i}),e||({matchUps:e}=xe({inContext:!0,drawDefinition:i,matchUpsMap:l}));const d=Ot({drawDefinition:i,structureId:f});if(d.error)return G({result:d,stack:h});const{structure:m}=d;if(!m)return{error:Te};if(Qr({drawDefinition:i,structure:m}))return G({result:{error:qn},stack:h});const{seedAssignments:g}=Mr({provisionalPositioning:t,drawDefinition:i,structure:m}),I=g==null?void 0:g.find(U=>U.participantId===c),S=I==null?void 0:I.seedNumber,{appliedPolicies:T}=ge({tournamentRecord:s,drawDefinition:i,structure:m,event:p});if(S&&!Vl({seedNumber:S,appliedPolicies:T,drawDefinition:i,seedBlockInfo:a,drawPosition:u,structureId:f}))return G({result:{error:qm},context:{drawPosition:u},stack:h});const y=ke({structure:m}).positionAssignments||[],b=y==null?void 0:y.find(U=>U.drawPosition===u);if(!b)return G({result:{error:Wo},context:{drawPosition:u},stack:h});if(y==null?void 0:y.map(fe).includes(c))return G({result:{error:Yo},context:{drawPosition:u},stack:h});const{containsParticipant:A,containsBye:C}=v(b);if(C){const U=Ac({inContextDrawMatchUps:e,tournamentRecord:s,drawDefinition:i,drawPosition:u,structureId:f,matchUpsMap:l,event:p});if(U.error)return G({result:U,stack:h})}if(A&&b.participantId!==c){const{activeDrawPositions:U}=qa({drawDefinition:i,structureId:f});if(U.includes(u))return G({result:{error:Rd},stack:h});$p({assignments:[b],inContextDrawMatchUps:e,tournamentRecord:s,drawDefinition:i,matchUpsMap:l,structure:m})}if(b.participantId=c,n&&(b.qualifier=!0),((m==null?void 0:m.stageSequence)||0)>1||m.stage&&[Re,Ie].includes(m.stage)){const U=m.stage===Pt?Pt:It,O=(P=i.structures)==null?void 0:P.find(w=>(w==null?void 0:w.stage)===U&&(w==null?void 0:w.stageSequence)===1),M=((O==null?void 0:O.seedAssignments)||[]).find(w=>w.participantId===c);if(M!=null&&M.participantId){const{participantId:w,seedNumber:k,seedValue:_}=M;Do({eventId:p==null?void 0:p.eventId,provisionalPositioning:t,tournamentRecord:s,drawDefinition:i,seedingProfile:o,participantId:w,seedNumber:k,seedValue:_,structureId:f,event:p})}}if(m.structureType!==mn)HM({provisionalPositioning:t,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:s,drawDefinition:i,drawPosition:u,matchUpsMap:l,structure:m,event:p});else{kT({positionAssignments:y,tournamentRecord:s,drawDefinition:i,matchUpsMap:l,structure:m});const{drawPositions:U,matchUps:O,targetMatchUps:D}=YT({assignments:[b],inContextDrawMatchUps:e,drawDefinition:i,matchUpsMap:l,structure:m});if(U&&(O==null?void 0:O.length)===1&&O[0].matchUpType===Jt){const w=((D==null?void 0:D[0].sides)||[]).reduce((k,_,F)=>U!=null&&U.includes(_.drawPosition)?F:k,void 0);Fp({inContextTargetMatchUp:D[0],teamParticipantId:c,matchUp:O[0],drawPositionSideIndex:w,tournamentRecord:s,drawDefinition:i})}}return ni({tournamentId:s==null?void 0:s.tournamentId,drawDefinition:i,structure:m,event:p}),{positionAssignments:y,...$};function v(U){const O=U.bye,D=U.qualifier,M=U.participantId;return{containsBye:O,containsQualifier:D,containsParticipant:M,filled:O||D||M}}}function HM({provisionalPositioning:t,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:r,drawDefinition:s,drawPosition:i,matchUpsMap:o,structure:c,event:a}){const u={isCollectionMatchUp:!1},{matchUps:l}=Qt({provisionalPositioning:t,matchUpFilters:u,drawDefinition:s,matchUpsMap:o,structure:c,event:a}),{roundMatchUps:f}=Cn({matchUps:l}),{initialRoundNumber:p}=Uo({drawPosition:i,matchUps:l}),h=p&&(f==null?void 0:f[p].find(d=>{var m;return(m=d.drawPositions)==null?void 0:m.includes(i)}));if(h){const d=Cc({matchUpId:h.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:n,tournamentRecord:r,drawDefinition:s,drawPosition:i,matchUpsMap:o});if(d.error)return G({stack:"assignDrawPositionToMatchUps",context:{drawPosition:i},result:d})}return{...$}}function qM({winnerMatchUpDrawPositionIndex:t,inContextDrawMatchUps:e,projectedWinningSide:n,sourceMatchUpStatus:r,winningDrawPosition:s,tournamentRecord:i,winnerTargetLink:o,sourceMatchUpId:c,drawDefinition:a,winnerMatchUp:u,dualMatchUp:l,matchUpsMap:f,event:p}){var d,m,g;const h="directWinner";if(o){const I=u.drawPositions||[],S=I[t],T=o.source.structureId,E=Ot({structureId:T,drawDefinition:a});if(E.error)return E;const{structure:y}=E,{positionAssignments:b}=ke({structureId:T,drawDefinition:a}),N=b==null?void 0:b.find(M=>M.drawPosition===s),A=N==null?void 0:N.participantId,C=o.target.structureId,{positionAssignments:v}=ke({structureId:C,drawDefinition:a}),P=v==null?void 0:v.find(M=>M.participantId===A),U=P==null?void 0:P.drawPosition,O=v==null?void 0:v.filter(M=>{const w=I.includes(M.drawPosition),k=!M.participantId&&!M.bye&&!M.qualifier;return w&&k}).map(M=>M.drawPosition),D=O==null?void 0:O.includes(S);if(A&&o.target.roundNumber===1&&D)_r({drawPosition:S,participantId:A,structureId:C,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:i,drawDefinition:a,matchUpsMap:f,event:p});else if(A&&(O!=null&&O.length)){const M=O.pop();M&&_r({participantId:A,structureId:C,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:i,drawDefinition:a,drawPosition:M,matchUpsMap:f,event:p})}else if(U){const M=Cc({drawPosition:U,matchUpId:u.matchUpId,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:i,sourceMatchUpId:c,drawDefinition:a,matchUpsMap:f});if(M.error)return G({result:M,stack:h})}else if((y==null?void 0:y.stage)!==Pt){const M="winner target position unavaiallble";return console.log(M),{error:M}}if(y!=null&&y.seedAssignments&&y.structureId!==C){const M=y.seedAssignments.find(({participantId:k})=>k===A),w=M==null?void 0:M.participantId;M&&w&&Do({eventId:u==null?void 0:u.eventId,structureId:C,...M,tournamentRecord:i,drawDefinition:a,participantId:w})}}else{const I=Cc({matchUpId:u.matchUpId,drawPosition:s,inContextDrawMatchUps:e,sourceMatchUpStatus:r,tournamentRecord:i,sourceMatchUpId:c,drawDefinition:a,matchUpsMap:f});if(I.error)return I}if(l&&n){const I=(d=l.sides)==null?void 0:d.find(S=>S.sideNumber===n);if(I!=null&&I.lineUp){const S=l.roundPosition,T=u.roundPosition,E=S===T&&S!==1||Math.floor(S/2)===T?2:1,y=(m=f==null?void 0:f.drawMatchUps)==null?void 0:m.find(({matchUpId:A})=>A===u.matchUpId),b=[1,2].map(A=>{var v;return{...((v=y.sides)==null?void 0:v.find(P=>P.sideNumber===A))||{},sideNumber:A}});y.sides=b;const N=y.sides.find(A=>A.sideNumber===E);if(N){const A=(g=I.lineUp)==null?void 0:g.filter(C=>C==null?void 0:C.participantId);N.lineUp=Bp({lineUp:A}),qt({tournamentId:i==null?void 0:i.tournamentId,eventId:u==null?void 0:u.eventId,matchUp:y,context:h,drawDefinition:a})}}}return{...$}}function YM(t){var H,B;const{loserMatchUpDrawPositionIndex:e,inContextDrawMatchUps:n,projectedWinningSide:r,sourceMatchUpStatus:s,loserDrawPosition:i,tournamentRecord:o,loserTargetLink:c,drawDefinition:a,loserMatchUp:u,dualMatchUp:l,matchUpsMap:f,event:p}=t,h="directLoser",d=c.linkCondition,m=u.drawPositions||[],g=d===fs&&u.roundNumber===2&&Math.min(...m.filter(Boolean)),I=g||m[e],S=g||m[1-e],T=c.source.structureId,{structure:E}=Ot({structureId:T,drawDefinition:a}),{matchUps:y}=Qt({afterRecoveryTimes:!1,inContext:!0,drawDefinition:a,structure:E,event:p}),N=y.filter(R=>{var x;return(x=R.drawPositions)==null?void 0:x.includes(i)}).filter(R=>{const x=R.sides.find(V=>V.drawPosition===i),q=R.matchUpStatus===ce||R.matchUpStatus===te&&!Be(R);return(x==null?void 0:x.sideNumber)===R.winningSide&&!q}),A=d===fs&&N.length===0,{positionAssignments:C}=ke({structureId:T,drawDefinition:a}),v=C==null?void 0:C.find(R=>R.drawPosition===i),P=v==null?void 0:v.participantId,U=c.target.structureId,{positionAssignments:O}=ke({structureId:U,drawDefinition:a}),D=O==null?void 0:O.filter(({drawPosition:R})=>m.includes(R));if(D==null?void 0:D.some(R=>R.participantId===P))return{...$};const w=D==null?void 0:D.filter(R=>{const x=m.includes(R.drawPosition),q=!R.participantId&&!R.bye&&!R.qualifier;return x&&q}).map(R=>R.drawPosition),k=w==null?void 0:w.includes(I),_=c.target.roundNumber>1&&(w==null?void 0:w.length),F=c.target.roundNumber===1&&k;if(g){const R=L();if(R.error)return G({result:R,stack:h})}else if(F){const R=j();if(R.error)return G({result:R,stack:h})}else if(P&&_){const R=w.sort(Ve)[0],x=_r({participantId:P,structureId:U,drawPosition:R,inContextDrawMatchUps:n,sourceMatchUpStatus:s,tournamentRecord:o,drawDefinition:a,matchUpsMap:f,event:p});if(x.error)return G({result:x,stack:h})}else return G({result:{error:Wo},context:{loserDrawPosition:i,loserTargetLink:c},stack:h});if(E!=null&&E.seedAssignments&&E.structureId!==U){const R=E.seedAssignments.find(({participantId:q})=>q===P),x=R==null?void 0:R.participantId;R&&x&&Do({eventId:u==null?void 0:u.eventId,structureId:U,...R,tournamentRecord:o,drawDefinition:a,participantId:x})}if(l&&r){const R=(H=l.sides)==null?void 0:H.find(x=>x.sideNumber===3-r);if(R!=null&&R.lineUp){const{roundNumber:x,eventId:q}=u,{roundPosition:V}=l,Y=x===1?2-V%2:1,z=(B=f==null?void 0:f.drawMatchUps)==null?void 0:B.find(({matchUpId:X})=>X===u.matchUpId),J=[1,2].map(X=>{var nt;return{...((nt=z.sides)==null?void 0:nt.find(rt=>rt.sideNumber===X))||{},sideNumber:X}});z.sides=J;const Q=z.sides.find(X=>X.sideNumber===Y);Q&&(Q.lineUp=Bp({lineUp:R.lineUp}),qt({tournamentId:o==null?void 0:o.tournamentId,matchUp:z,context:h,drawDefinition:a,eventId:q}))}}return{...$};function L(){const R="loserLinkFedFMLC";return G(A?{result:j(),stack:R}:{result:W(),stack:R})}function W(){const R=Vn({drawPosition:S,structureId:U,tournamentRecord:o,drawDefinition:a,event:p});return G({result:R,stack:"assignLoserPositionBye"})}function j(){const R=P?_r({drawPosition:I,participantId:P,structureId:U,inContextDrawMatchUps:n,sourceMatchUpStatus:s,tournamentRecord:o,drawDefinition:a,matchUpsMap:f,event:p}):{error:Ce};return G({result:R,stack:"assignLoserDrawPosition"})}}function KT(t){const e=Rp(t);if(e.error)return e;const n=Ra({matchUpStatus:t.matchUpStatus}),{dualWinningSideChange:r,projectedWinningSide:s,inContextDrawMatchUps:i,tournamentRecord:o,drawDefinition:c,matchUpStatus:a,dualMatchUp:u,matchUpsMap:l,winningSide:f,targetData:p,matchUpId:h,structure:d,matchUp:m,event:g}=t,I="directParticipants",S=!!m.collectionId,T=Qr({drawDefinition:c,structure:d});let E=m.drawPositions,y;if(S){const{matchUpTieId:b,matchUpsMap:N}=t,A=ms({matchUpId:b,tournamentRecord:o,drawDefinition:c,matchUpsMap:N,event:g});y=A&&{tieMatchUpResult:A};const C=i.find(({matchUpId:v})=>v===b);if(E=C==null?void 0:C.drawPositions,!r)return G({result:{...$,...y},stack:I})}if(T)return G({result:{...$,...y},stack:I});if(E){const b=s?s-1:f-1,N=1-b,A=E[b],C=E[N],{targetLinks:{loserTargetLink:v,winnerTargetLink:P,byeTargetLink:U},targetMatchUps:{winnerMatchUpDrawPositionIndex:O,loserMatchUpDrawPositionIndex:D,winnerMatchUp:M,loserMatchUp:w,byeMatchUp:k}}=p;if(M){const _=qM({sourceMatchUpStatus:n&&a||De,winnerMatchUpDrawPositionIndex:O,sourceMatchUpId:h,inContextDrawMatchUps:i,projectedWinningSide:s,winningDrawPosition:A,tournamentRecord:o,winnerTargetLink:P,drawDefinition:c,winnerMatchUp:M,dualMatchUp:u,matchUpsMap:l,event:g});if(_.error)return G({result:_,stack:I})}if(w){const _=YM({sourceMatchUpStatus:n&&a||De,loserMatchUpDrawPositionIndex:D,sourceMatchUpId:h,inContextDrawMatchUps:i,projectedWinningSide:s,loserDrawPosition:C,tournamentRecord:o,loserTargetLink:v,drawDefinition:c,loserMatchUp:w,winningSide:f,matchUpsMap:l,dualMatchUp:u,event:g});if(_.error)return G({result:_,stack:I})}if(k){const _=k.drawPositions||[],F=Math.min(..._.filter(Boolean)),L=U.target.structureId,W=Vn({drawPosition:F,structureId:L,tournamentRecord:o,drawDefinition:c,event:g});if(W.error)return G({result:W,stack:I})}}else return G({result:{error:Ld},stack:I});return G({result:{...$,...y},stack:I})}function _i(t){var m,g;const{inContextDrawMatchUps:e,targetData:n,drawDefinition:r,relevantLink:s}=t;if((s==null?void 0:s.linkCondition)===fs&&((m=n==null?void 0:n.matchUp)==null?void 0:m.matchUpStatus)===re)return!1;const{targetMatchUps:{loserMatchUp:o,winnerMatchUp:c},targetLinks:a}=n,u=[te,ce].includes(o==null?void 0:o.matchUpStatus),l=((g=c==null?void 0:c.drawPositions)==null?void 0:g.filter(Boolean).length)||0;if(o!=null&&o.winningSide&&!u||c!=null&&c.winningSide&&l===2&&(!c.feedRound||![ce,te].includes(c==null?void 0:c.matchUpStatus)))return!0;const f=o&&gn({matchUpId:o.matchUpId,inContextDrawMatchUps:e,drawDefinition:r}),p=c&&gn({matchUpId:c.matchUpId,inContextDrawMatchUps:e,drawDefinition:r}),h=f&&_i({relevantLink:a==null?void 0:a.loserTargetLink,targetData:f,inContextDrawMatchUps:e,drawDefinition:r});return!!(p&&_i({targetData:p,inContextDrawMatchUps:e,drawDefinition:r})||h)}function zM(t){var c,a,u;let e;const{inContextDrawMatchUps:n,inContextMatchUp:r,drawDefinition:s,winningSide:i}=t,o=(c=t.targetData.targetLinks)==null?void 0:c.winnerTargetLink;if(o.target.feedProfile===Cr){const l=r.sides.find(({sideNumber:p})=>p!==i).participantId,f=n.find(p=>p.structureId===o.target.structureId&&p.roundNumber===o.target.roundNumber&&p.sides.some(({participantId:h})=>h===l));if((f==null?void 0:f.matchUpStatus)===Le){const p=gn({matchUpId:f.matchUpId,inContextDrawMatchUps:n,drawDefinition:s});if(!_i({inContextDrawMatchUps:n,drawDefinition:s,targetData:p})){const{structure:d}=Ot({structureId:f.structureId,drawDefinition:s}),m=ee({structure:d}).positionAssignments;for(const g of m||[])if(g.participantId===l){const I=r.sides.find(({sideNumber:S})=>S===i).participantId;if(g.participantId=I,d!=null&&d.positionAssignments)d.positionAssignments=m;else if(d!=null&&d.structures){const S=Object.assign({},...(m||[]).map(T=>({[T.drawPosition]:T.participantId})));for(const T of d.structures)(a=T.positionAssignments)==null||a.forEach(E=>E.participantId=S[E.drawPosition])}ni({tournamentId:(u=t.tournamentRecord)==null?void 0:u.tournamentId,event:t.event,drawDefinition:s,structure:d}),e=!0}}}}return{...$,qualifierReplaced:e}}function KM(t){var c,a,u,l,f;let e;const{inContextDrawMatchUps:n,inContextMatchUp:r,drawDefinition:s,winningSide:i}=t,o=(c=t.targetData.targetLinks)==null?void 0:c.winnerTargetLink;if(o.target.feedProfile===Cr){const p=(a=r.sides.find(({sideNumber:m})=>m===i))==null?void 0:a.participantId,h=n.filter(m=>m.structureId===o.target.structureId&&m.roundNumber===o.target.roundNumber&&m.sides.some(({participantId:g,qualifier:I})=>I&&!g)),d=Dn(h);if((d==null?void 0:d.matchUpStatus)===Le){const m=gn({matchUpId:d.matchUpId,inContextDrawMatchUps:n,drawDefinition:s});if(!_i({inContextDrawMatchUps:n,drawDefinition:s,targetData:m})){const I=(u=d.sides.find(E=>E.qualifier&&!E.participantId))==null?void 0:u.drawPosition,{structure:S}=Ot({structureId:d.structureId,drawDefinition:s});if(!S)return{error:Te};const T=ee({structure:S}).positionAssignments;for(const E of T||[])if(E.drawPosition===I&&!E.participantId){if(E.participantId=p,S.positionAssignments)S.positionAssignments=T;else if(S.structures){const y=Object.assign({},...(T||[]).map(b=>({[b.drawPosition]:b.participantId})));for(const b of S.structures)(l=b.positionAssignments)==null||l.forEach(N=>N.participantId=y[N.drawPosition])}ni({tournamentId:(f=t.tournamentRecord)==null?void 0:f.tournamentId,event:t.event,drawDefinition:s,structure:S}),e=!0}}}}return{...$,qualifierPlaced:e}}function JM(t){var h,d;const e="attemptToSetWinningSide";let n;const{appliedPolicies:r,disableAutoCalc:s,drawDefinition:i,dualMatchUp:o,winningSide:c,structure:a,matchUp:u}=t;if(o!=null&&o._disableAutoCalc&&s!==!1)return Rp(t);if(u.winningSide&&u.winningSide!==c){const{connectedStructureIds:m}=HT({drawDefinition:i,structure:a,matchUp:u});m.length&&(console.log({connectedStructureIds:m}),n=!0);const g=vc(t);if(g.error)return g}const l=KT(t);if(l.error)return G({result:l,stack:e});let f,p;return t.qualifierChanging&&((h=r==null?void 0:r[Ru])!=null&&h.autoReplaceQualifiers)&&(f=zM(t).qualifierReplaced),t.qualifierAdvancing&&((d=r==null?void 0:r[Ru])!=null&&d.autoPlaceQualifiers)&&(p=KM(t).qualifierPlaced),G({result:bt({...$,...l,connectedStructures:n,qualifierReplaced:f,qualifierPlaced:p}),stack:e})}function JT(t){var h;const{inContextDrawMatchUps:e,appliedPolicies:n,drawDefinition:r,matchUpsMap:s,targetData:i,matchUp:o}=t;let{iteration:c=0}=t;c+=1;const a="removeDoubleExit";ts();const{targetLinks:{loserTargetLink:u},targetMatchUps:{loserMatchUp:l,winnerMatchUp:f,loserTargetDrawPosition:p}}=i;if(f&&f.matchUpStatus!==re&&(ts(),QT({...t,targetMatchUp:f,sourceMatchUp:o,iteration:c})),l&&l.matchUpStatus!==re){const d=e.find(({matchUpId:g})=>g===l.matchUpId),{structure:m}=Ot({drawDefinition:r,structureId:d.structureId});if(ts(),(h=n==null?void 0:n.progression)!=null&&h.doubleExitPropagateBye)kp({drawPosition:p,targetLink:u,inContextDrawMatchUps:e,drawDefinition:r,matchUpsMap:s});else{const g=QT({...t,structure:m,targetMatchUp:l,iteration:c});if(g.error)return G({result:g,stack:a})}}return G({result:{...$},stack:a})}function QT(t){var E,y,b,N,A;const{inContextDrawMatchUps:e,appliedPolicies:n,drawDefinition:r,sourceMatchUp:s,targetMatchUp:i,matchUpsMap:o,structure:c,iteration:a}=t,u="conditionallyRemoveDrawPosition";ts();const l=gn({matchUpId:i.matchUpId,inContextDrawMatchUps:e,drawDefinition:r}),{targetMatchUps:{winnerMatchUp:f}}=l,p=o==null?void 0:o.drawMatchUps.find(C=>C.matchUpId===i.matchUpId);let h=[],d,m,g;if(i.feedRound){const C=(E=f==null?void 0:f.drawPositions)==null?void 0:E.filter(Boolean);g=C==null?void 0:C.find(v=>i.drawPositions.includes(v))}else if(!s)g=(y=qe((i==null?void 0:i.drawPositions)||[],(f==null?void 0:f.drawPositions)||[]))==null?void 0:y[0];else if(m=(b=DT({structureId:c.structureId,matchUp:s,matchUpsMap:o}))==null?void 0:b.pairedPreviousMatchUp,d=[Fe,en].includes(m==null?void 0:m.matchUpStatus),h=((N=m==null?void 0:m.drawPositions)==null?void 0:N.filter(Boolean))||[],[...We,re].includes(m==null?void 0:m.matchUpStatus)||(m==null?void 0:m.winningSide)){const v=s.drawPositions||[];let P=(A=i.drawPositions)==null?void 0:A.filter(Boolean);tn(v,P)&&(P=P==null?void 0:P.filter(O=>!v.includes(O))),g=v.concat(h).find(O=>P==null?void 0:P.includes(O))}f&&g&&(ts(),FT({winningDrawPosition:g,winnerMatchUp:f,inContextDrawMatchUps:e,drawDefinition:r,matchUpsMap:o}));let I=JT({targetData:l,matchUp:i,inContextDrawMatchUps:e,appliedPolicies:n,drawDefinition:r,matchUpsMap:o,structure:c,iteration:a});if(I.error)return G({result:I,stack:u});const S=QM({pairedPreviousDoubleExit:d,noContextTargetMatchUp:p});return I=Zr({...t,matchUpStatus:S,removeScore:!d,score:{scoreStringSide1:"",scoreStringSide2:"",sets:void 0},removeWinningSide:!0,matchUp:p,matchUpId:i.matchUpId,matchUpStatusCodes:[]}),I.error?G({result:I,stack:u}):{...$}}function QM({pairedPreviousDoubleExit:t,noContextTargetMatchUp:e}){return e.matchUpStatus===re?re:t?[en,te].includes(e==null?void 0:e.matchUpStatus)?te:ce:Le}function ZM(t){var o,c,a,u,l;let e;const{inContextDrawMatchUps:n,inContextMatchUp:r,drawDefinition:s}=t,i=(o=t.targetData.targetLinks)==null?void 0:o.winnerTargetLink;if(i.target.feedProfile===Cr){const f=(a=(c=r.sides)==null?void 0:c.find(({sideNumber:h})=>h===r.winningSide))==null?void 0:a.participantId,p=n.find(h=>{var d;return h.structureId===i.target.structureId&&h.roundNumber===i.target.roundNumber&&((d=h.sides)==null?void 0:d.some(({participantId:m})=>m===f))});if((p==null?void 0:p.matchUpStatus)===Le){const h=gn({matchUpId:p.matchUpId,inContextDrawMatchUps:n,drawDefinition:s});if(!_i({inContextDrawMatchUps:n,drawDefinition:s,targetData:h})){const{structure:m}=Ot({structureId:p.structureId,drawDefinition:s}),g=ee({structure:m}).positionAssignments;for(const I of g||[])if(I.participantId===f){if(I.participantId=void 0,m!=null&&m.positionAssignments)m.positionAssignments=g;else if(m!=null&&m.structures){const S=Object.assign({},...(g||[]).map(T=>({[T.drawPosition]:T.participantId})));for(const T of(m==null?void 0:m.structures)||[])(u=T.positionAssignments)==null||u.forEach(E=>E.participantId=S[E.drawPosition])}ni({tournamentId:(l=t.tournamentRecord)==null?void 0:l.tournamentId,event:t.event,drawDefinition:s,structure:m}),e=!0}}}}return{qualifierRemoved:e}}function XM(t){var g;const{matchUp:e,matchUpStatus:n,score:r,winningSide:s}=t,i="noDownStreamDependencies";if([Fe,en].includes(e==null?void 0:e.matchUpStatus)&&![Fe,en].includes(n)){const I=JT(t);if(I.error)return G({result:I,stack:i})}const c=n===Fe,a=Be({score:r})&&!c&&(t.isCollectionMatchUp&&!t.projectedWinningSide||!s),u=((g=t==null?void 0:t.inContextMatchUp)==null?void 0:g.collectionId)&&yM(t.inContextMatchUp),l=t.removeScore||!u&&![us,zn].includes(n||us),f=t.isCollectionMatchUp&&t.dualMatchUp.winningSide&&!t.projectedWinningSide||e.winningSide&&!s&&!Be({score:r}),p=n&&n!==Le,h=I=>{var C,v;let S;const{structure:T,drawDefinition:E,dualMatchUp:y,disableAutoCalc:b}=t;if(y!=null&&y._disableAutoCalc&&b!==!1)return Rp(t);const{connectedStructureIds:N}=HT({drawDefinition:E,structure:T,matchUp:e});N.length&&(console.log({connectedStructureIds:N}),S=!0),Object.assign(t,{removeScore:I});const A=vc(t);if(A.error)return A;if(t.removingQualifier&&((v=(C=t.appliedPolicies)==null?void 0:C[Ru])!=null&&v.autoRemoveQualifiers)){const P=ZM(t);return{...$,connectedStructures:S,...P}}return{...$,connectedStructures:S}};if(f&&s&&t.isCollectionMatchUp)return ZT(t);const d=[Gs,zn].includes(n)&&t.dualWinningSideChange,m=(s||d)&&JM(t)||a&&h(l)||p&&wM(t)||f&&h(l)||e&&ZT({...t,removeScore:!0})||{...$};return G({result:m,stack:i})}function ZT(t){var s;const e="scoreModification";if(t.isCollectionMatchUp&&((s=t.dualMatchUp)==null?void 0:s.winningSide)&&!t.projectedWinningSide){const i=vc(t);if(i.error)return i}const r=Zr({...t});if(t.isCollectionMatchUp){const{matchUpTieId:i,drawDefinition:o,event:c,matchUpsMap:a}=t,{removeWinningSide:u}=ms({tournamentRecord:t.tournamentRecord,matchUpId:i,drawDefinition:o,matchUpsMap:a,event:c});u&&console.log("REMOVE WINNING SIDE")}return G({result:r,stack:e})}function tD(t){var b;const{tournamentRecord:e,inContextMatchUp:n,structure:r,drawDefinition:s}=t,i=n.roundNumber,o=n.sides.find(N=>N.sideNumber===n.winningSide),c=n.sides.find(N=>N.sideNumber!==n.winningSide),{drawPosition:a,participantId:u}=o,{drawPosition:l,participantId:f}=c,p="swapWinnerLoser",{matchUps:h}=Qt(t),d=h.filter(({drawPositions:N,roundNumber:A})=>(N==null?void 0:N.includes(a))&&A>i);ze({changeWinner:!0})&&console.log({existingWinnerSubsequentMatchUps:d}),d.forEach(N=>{var A,C;N.drawPositions=((A=N.drawPositions)==null?void 0:A.map(v=>v===a?l:v))||[],qt({tournamentId:e==null?void 0:e.tournamentId,eventId:(C=t.event)==null?void 0:C.eventId,context:p,drawDefinition:s,matchUp:N})});const{stage:m,stageSequence:g}=r,I=s.structures.filter(({stage:N,stageSequence:A})=>N===m&&A>g).map(({structureId:N})=>N),{targetLinks:{loserTargetLink:S,winnerTargetLink:T}}=t.targetData,E=[S==null?void 0:S.target.structureId,(b=T==null?void 0:T.target)==null?void 0:b.structureId].filter(Boolean);return s.structures.filter(({stage:N,structureId:A})=>N!==m&&E.includes(A)).forEach(({stage:N,stageSequence:A,structureId:C})=>{I.includes(C)||I.push(C),s.structures.filter(({stage:v,stageSequence:P})=>v===N&&P>A).forEach(({structureId:v})=>{I.includes(v)||I.push(v)})}),s.structures.filter(({structureId:N})=>I.includes(N)).forEach(N=>{const{positionAssignments:A}=ee({structure:N}),C=A==null?void 0:A.find(({participantId:P})=>P===u),v=A==null?void 0:A.find(({participantId:P})=>P===f);C&&(C.participantId=f),v&&(v.participantId=u)}),Zr(t)}function Ja(t){var W,j,H,B;const e="setMatchUpStatus";t.matchUpStatus&&[ce,Fe].includes(t.matchUpStatus)&&(t.score=void 0);const{allowChangePropagation:n,disableScoreValidation:r,tournamentRecords:s,tournamentRecord:i,disableAutoCalc:o,enableAutoCalc:c,drawDefinition:a,matchUpStatus:u,winningSide:l,matchUpId:f,event:p,score:h}=t;if(!a)return{error:lt};if(u&&[Gs,us,zn,Le].includes(u)&&l)return{error:tt,winningSide:l,matchUpStatus:u};if(![void 0,...PC].includes(u))return G({result:{error:Hc},info:"matchUpStatus does not exist",stack:"setMatchUpStatus"});const d=ln({drawDefinition:a}),{matchUps:m}=xe({nextMatchUps:!0,inContext:!0,drawDefinition:a,matchUpsMap:d,event:p}),g=d.drawMatchUps.find(R=>R.matchUpId===f),I=m==null?void 0:m.find(R=>R.matchUpId===f);if(!g||!m)return{error:Ye};if((g.winningSide||l)&&u===re)return{context:"Cannot have Bye with winningSide",error:$d,matchUpStatus:u};const S=I==null?void 0:I.structureId,{structure:T}=Ot({drawDefinition:a,structureId:S}),E=(W=I==null?void 0:I.drawPositions)==null?void 0:W.filter(Boolean);let y;if(g.matchUpType===Jt){if(o)ae({extension:{name:ec,value:!0},element:g});else if(c){const R=g.winningSide;Ar({name:ec,element:g});const{winningSide:x,scoreStringSide1:q,scoreStringSide2:V,set:Y}=La({drawDefinition:a,matchUpsMap:d,structure:T,matchUp:g,event:p}),z={scoreStringSide1:q,scoreStringSide2:V,sets:Y?[Y]:[]};y=x!==R,Object.assign(t,{winningSide:x,dualWinningSideChange:y,projectedWinningSide:x,score:z})}}if(g.matchUpType===Jt&&u&&[Jo].includes(u))return{error:tt,info:"Not supported for matchUpType: TEAM"};const b=I==null?void 0:I.matchUpTieId,N=gn({matchUpId:b||f,inContextDrawMatchUps:m,drawDefinition:a});if(h&&g.matchUpType!==Jt&&!r){const R=g.matchUpFormat||(T==null?void 0:T.matchUpFormat)||(a==null?void 0:a.matchUpFormat)||(p==null?void 0:p.matchUpFormat),x=rp({existingMatchUpStatus:g.matchUpStatus,matchUpFormat:R,matchUpStatus:u,winningSide:l,score:h});if(x.error)return x}const A=g!=null&&g.sides?[]:ee({drawDefinition:a,structureId:S}).positionAssignments,C=((j=g.sides)==null?void 0:j.map(R=>R.participantId).filter(Boolean).length)===2||(E==null?void 0:E.length)===2&&(A==null?void 0:A.filter(R=>E.includes(R.drawPosition)).every(R=>R.participantId));if(u&&CC.includes(u)&&!C)return G({result:{error:Hc},info:"present in participantRequiredMatchUpStatuses",context:{matchUpStatus:u,bothSideParticipants:C}});const v=((H=ge({policyTypes:[Ru],tournamentRecord:i,drawDefinition:a,event:p}))==null?void 0:H.appliedPolicies)??{};typeof t.policyDefinitions=="object"&&Object.assign(v,t.policyDefinitions);const P=(I==null?void 0:I.stage)===Pt&&I.finishingRound===1,U=P&&l,O=P&&g.winningSide&&!l&&(!t.matchUpStatus||t.matchUpStatus&&Yf({matchUpStatus:t.matchUpStatus}))&&(!t.outcome||!Be({outcome:t.outcome})),D=U&&l!==g.winningSide&&g.winningSide;if(Object.assign(t,{inContextDrawMatchUps:m,qualifierAdvancing:U,qualifierChanging:D,removingQualifier:O,inContextMatchUp:I,appliedPolicies:v,matchUpTieId:b,matchUpsMap:d,targetData:N,structure:T,matchUp:g}),b){const{matchUp:R}=ie({matchUpId:b,inContext:!0,drawDefinition:a,matchUpsMap:d,event:p});if(R){const x=(B=hn({matchUp:R,drawDefinition:a,structure:T,event:p}))==null?void 0:B.tieFormat,{projectedWinningSide:q}=TM({drawDefinition:a,matchUpStatus:u,dualMatchUp:R,matchUpsMap:d,winningSide:l,tieFormat:x,structure:T,matchUp:g,event:p,score:h}),V=R.winningSide;y=q!==V,Object.assign(t,{isCollectionMatchUp:!0,dualWinningSideChange:y,projectedWinningSide:q,matchUpTieId:b,dualMatchUp:R,tieFormat:x})}}const M=_i(t),w=Ra({matchUpStatus:u});if(!b){if(M&&!l&&(u&&Yf({matchUpStatus:u})||u&&[Fe,en].includes(u)))return{error:$d,activeDownstream:M,winningSide:l};if(l&&l===g.winningSide&&u&&!w)return{context:"winningSide must include directing matchUpStatus",error:$d,directingMatchUpStatus:w,matchUpStatus:u}}const{schedule:k}=t;if(k){const R=kl({disableNotice:!0,tournamentRecords:s,tournamentRecord:i,drawDefinition:a,matchUpId:f,schedule:k});if(R.error)return R}const _=g.matchUpType!==Jt&&!y&&l&&g.winningSide&&g.winningSide!==l;if(n&&_&&g.roundPosition)return tD(t);const F=l&&!b||t.projectedWinningSide;ts();const L=!M&&XM(t)||F&&eD(t)||w&&XT(t)||{error:wv};return G({result:L,stack:e})}function eD(t){const{matchUp:e,winningSide:n,matchUpTieId:r,dualWinningSideChange:s}=t;return n===e.winningSide||r&&!s?XT(t):G({result:{error:ag},stack:"winningSideWithDownstreamDependencies",context:{winningSide:n,matchUp:e}})}function XT(t){const{tournamentRecord:e,matchUp:n,event:r}=t,s=t.isCollectionMatchUp&&n.winningSide&&!t.winningSide&&!Be({score:t.score}),i=t.isCollectionMatchUp?t.matchUpStatus||s&&Le||De:t.matchUpStatus||De,o=t.removeScore||[Gs,ce].includes(i)&&![us,zn].includes(i),c=Zr({...t,matchUpStatus:i,removeWinningSide:s,removeScore:o});if(c.error)return c;if(t.isCollectionMatchUp){const{matchUpTieId:a,drawDefinition:u,matchUpsMap:l}=t,f=ms({matchUpId:a,tournamentRecord:e,drawDefinition:u,matchUpsMap:l,event:r});if(f.error)return f;Object.assign(c,{tieMatchUpResult:f})}return c}function Gl(t){let e=t.structureIds;const{tournamentRecord:n,drawDefinition:r,matchUpFormat:s,structureId:i,matchUpId:o,event:c}=t;if(!r)return{error:lt};if(!s)return{error:Vd};if(!nr(s))return{error:bu};const a="setMatchUpFormat";if(o){const u=ie({drawDefinition:r,matchUpId:o,event:c});if(u.error)return u;if(!u.matchUp)return{error:Ye};const l=u.matchUp;if((l==null?void 0:l.matchUpType)===we)return{error:qn,info:"Cannot set matchUpFormat when { matchUpType: TEAM }"};l.matchUpFormat=s,qt({tournamentId:n==null?void 0:n.tournamentId,eventId:c==null?void 0:c.eventId,context:a,drawDefinition:r,matchUp:l})}else if(Array.isArray(e)){if((c==null?void 0:c.eventType)===we)return{error:ui};for(const u of e){const l=Ot({drawDefinition:r,structureId:u});if(l.error)return l;if(l.structure)l.structure.matchUpFormat=s;else return{error:Te}}}else if(i){if((c==null?void 0:c.eventType)===we)return{error:ui};const u=Ot({drawDefinition:r,structureId:i});if(u.error)return u;if(u.structure)u.structure.matchUpFormat=s;else return{error:Te}}else r&&(r.matchUpFormat=s);return e=e||(i?[i]:void 0),Zt({drawDefinition:r,structureIds:e}),{...$}}function ty(t){const{matchUpFormat:e,matchUpStatus:n,winningSide:r,score:s}=t;if(!s)return{sets:[]};const i=s.sets||[];let o=gs({winnerFirst:!1,matchUpFormat:e,matchUpStatus:n,sets:i}),c=gs({winnerFirst:!1,reversed:!0,matchUpFormat:e,matchUpStatus:n,sets:i});const a=gs({matchUpFormat:e,matchUpStatus:n,winningSide:r,sets:i}),u=o===a?c:o;return r&&(o=r===1?a:u,c=r===2?a:u),{score:{sets:i,scoreStringSide1:o,scoreStringSide2:c}}}function Qa(t){var m;const{tournamentRecords:e,policyDefinitions:n,tournamentRecord:r,disableAutoCalc:s,enableAutoCalc:i,drawDefinition:o,matchUpFormat:c,matchUpId:a,schedule:u,event:l,notes:f}=t;if(!o)return{error:Hn};if(!a)return{error:$e};const{policy:p}=Xi({policyType:Xo,tournamentRecord:r,event:l}),h=t.allowChangePropagation!==void 0&&t.allowChangePropagation||(p==null?void 0:p.allowChangePropagation)!==void 0&&p.allowChangePropagation||void 0,{outcome:d}=t;if(c){const g=Gl({tournamentRecord:r,drawDefinition:o,matchUpFormat:c,matchUpId:a,event:l});if(g.error)return g}if((m=d==null?void 0:d.score)!=null&&m.sets&&!d.score.scoreStringSide1){const{score:g}=ty(d);d.score=g,d.score.sets=d.score.sets.filter(I=>I.side1Score||I.side2Score||I.side1TiebreakScore||I.side2TiebreakScore)}return Ja({matchUpStatusCodes:d==null?void 0:d.matchUpStatusCodes,matchUpStatus:d==null?void 0:d.matchUpStatus,winningSide:d==null?void 0:d.winningSide,allowChangePropagation:h,score:d==null?void 0:d.score,tournamentRecords:e,policyDefinitions:n,tournamentRecord:r,disableAutoCalc:s,enableAutoCalc:i,drawDefinition:o,matchUpFormat:c,matchUpId:a,schedule:u,event:l,notes:f})}function ey(t){var o;if(!t.tournamentRecord)return{error:et};const{tournamentRecords:e,tournamentRecord:n,outcomes:r,policyDefinitions:s}=t,i={};r.forEach(c=>{const{eventId:a}=c;i[a]||(i[a]=[]),i[a].push(c)});for(const c of Object.keys(i)){const{event:a}=Je({tournamentRecord:n,eventId:c});for(const u of i[c]){const{drawId:l}=u,f=(o=a==null?void 0:a.drawDefinitions)==null?void 0:o.find(p=>p.drawId===l);if(f&&l){const{matchUpFormat:p,matchUpId:h}=u,d=Qa({schedule:u==null?void 0:u.schedule,tournamentRecords:e,policyDefinitions:s,tournamentRecord:n,drawDefinition:f,matchUpFormat:p,matchUpId:h,outcome:u,drawId:l,event:a});if(d.error)return d}}}return{...$}}function nD(t){const e=t.tournamentRecords,n=t.tournamentId||Fl(t);if(typeof n!="string")return{error:is};const r=e[n];if(!r)return{error:et};const{drawDefinition:s,event:i}=Je({eventId:t.eventId,drawId:t.drawId,tournamentRecord:r});return Qa({tournamentRecord:r,...t,drawDefinition:s,event:i})}function rD(t){const{tournamentRecords:e,outcomes:n}=t;if(!Array.isArray(n))return{error:Tt,info:sn("outcomes")};const r=n.reduce((s,i)=>s.includes(i.tournamentId)?s:s.concat(i.tournamentId),[]);for(const s of r){const i=e[s];if(!i)return{error:et};const o=n.filter(c=>c.tournamentId===s);if(o.length){const c=ey({tournamentRecord:i,outcomes:o});if(c.error)return c}}return{...$}}function ny({courtPrefix:t="C|",minRowsCount:e,courtsData:n}){if(!Array.isArray(n))return{error:tt};const r=n==null?void 0:n.reduce((o,c)=>{const a=c.matchUps||[],u=Math.max(0,...a.map(l=>l.schedule.courtOrder||0));return u>o?u:o},1),s=e?Math.max(e,r):r,i=ht(0,s).map(o=>({matchUps:ht(0,n.length).map(c=>{const a=n[c],{courtId:u,venueId:l}=a;return{schedule:{courtOrder:o+1,venueId:l,courtId:u}}})}));return n.forEach((o,c)=>{var a;for(const u of o.matchUps){const l=(a=u.schedule)==null?void 0:a.courtOrder;l&&(i[l-1].matchUps[c]=u)}}),{courtPrefix:t,rows:i.map((o,c)=>Object.assign({rowId:`rowId-${c+1}`},...o.matchUps.map((a,u)=>({[`${t}${u}`]:a}))))}}function Za(t){var D,M,w,k,_,F,L,W,j,H,B;const{flight:e,suppressNotifications:n,modifyEventEntries:r,existingDrawCount:s,allowReplacement:i,checkEntryStatus:o,tournamentRecord:c,drawDefinition:a,event:u}=t;if(!a)return{error:Hn};if(!u)return{error:Wt};u.drawDefinitions||(u.drawDefinitions=[]);const{drawId:l,drawName:f,entries:p}=a,{entries:h}=u;let d=0;if(s!==void 0&&s!==u.drawDefinitions.length)return{error:tt,info:"drawDefintions count mismatch"};const{flightProfile:m}=be({event:u}),g=e&&((D=m==null?void 0:m.flights)==null?void 0:D.find(R=>R.flightNumber===e.flightNumber)),I=(k=(w=(M=m==null?void 0:m.links)==null?void 0:M.find(R=>{var x;return((x=R==null?void 0:R.target)==null?void 0:x.drawId)===l}))==null?void 0:w.source)==null?void 0:k.drawId;if(I&&!u.drawDefinitions.find(R=>R.drawId===I))return G({result:{error:lt},info:{sourceDrawId:I}});if(g&&g.drawId!==a.drawId)return G({result:{error:Gi},info:{relevantFlight:g}});const E=p==null?void 0:p.every(({participantId:R,entryStatus:x})=>{const q=g==null?void 0:g.drawEntries.find(V=>V.participantId===R);return!x||(q==null?void 0:q.entryStatus)===x}),y=!o||h&&(p==null?void 0:p.every(({participantId:R,entryStatus:x,entryStage:q})=>{const V=h.find(Y=>Y.participantId===R&&(!Y.entryStage||Y.entryStage===q));return(V==null?void 0:V.entryStatus)===x}));if(g&&!E)return G({result:{error:Gi,context:{drawEntriesPresentInFlight:E,matchingEventEntries:y,relevantFlight:g},info:"Draw entries are not present in flight or do not match entryStatuses"}});if(r&&(p==null||p.filter(Boolean).forEach(R=>{if(R!=null&&R.entryStatus&&ps.includes(R==null?void 0:R.entryStatus)){const x=h==null?void 0:h.filter(Boolean).find(q=>q.participantId===R.participantId);x&&R.entryStatus&&(x==null?void 0:x.entryStatus)!==R.entryStatus&&(x.entryStatus=R.entryStatus,d+=1)}})),h&&!y)return G({result:{error:Gi,context:{matchingEventEntries:y,eventEntries:h},info:"Draw entries do not match event entryStatuses"}});const b=((F=(_=m==null?void 0:m.flights)==null?void 0:_.map(({flightNumber:R})=>!isNaN(R)&&vt(R)))==null?void 0:F.filter(Boolean))||[],N=((L=u.drawDefinitions.map(({drawOrder:R})=>R&&vt(R)))==null?void 0:L.filter(Boolean))||[];let A=Math.max(0,...N,...b)+1;const C=(W=m==null?void 0:m.flights)==null?void 0:W.find(R=>R.drawId===l);let v;if(C){C.drawName=a.drawName,v={name:ar,value:{...m,flights:m.flights}};const R=C.flightNumber;R&&!N.includes(R)?A=R:C.flightNumber=A}else{const R=(m==null?void 0:m.flights)||[];R.push({manuallyAdded:!0,flightNumber:A,drawEntries:p,drawName:f,drawId:l}),v={name:ar,value:{...m||{},flights:R}}}Yr({event:u,extension:v}),Object.assign(a,{drawOrder:A});const P=u.drawDefinitions.find(R=>R.drawId===l),U=c==null?void 0:c.tournamentId,O=u.eventId;if(P){if(!i)return{error:_1};const R=(j=tr({drawDefinition:P}))==null?void 0:j.matchUps,x=(R==null?void 0:R.map(Qe))??[],q=(H=tr({drawDefinition:a}))==null?void 0:H.matchUps;if(!n){x!=null&&x.length&&ei({matchUpIds:x,action:"modifyDrawDefinition",tournamentId:U,eventId:O}),q!=null&&q.length&&Oi({matchUps:q,tournamentId:U,eventId:O}),u.drawDefinitions=u.drawDefinitions.map(Y=>Y.drawId===l?a:Y);const V=(B=a.structures)==null?void 0:B.map(({structureId:Y})=>Y);Zt({drawDefinition:a,tournamentId:U,structureIds:V,eventId:O})}}else if(u.drawDefinitions.push(a),!n){const{matchUps:R}=tr({drawDefinition:a,event:u});R&&Oi({tournamentId:c==null?void 0:c.tournamentId,matchUps:R}),Ba({drawDefinition:a,tournamentId:U,eventId:O})}return{...$,modifiedEventEntryStatusCount:d}}function sD({tournamentRecords:t,existingDrawCount:e,allowReplacement:n,drawDefinition:r,tournamentId:s,eventId:i,flight:o}){if(!i)return{error:Wt};if(s=s??Fl({tournamentRecords:t,eventId:i}),!s)return{error:is};const c=t[s];if(!c)return{error:et};const a=Je({tournamentRecord:c,eventId:i});return a.event?a.error?a:Za({event:a.event,existingDrawCount:e,allowReplacement:n,drawDefinition:r,flight:o}):{error:wn}}function es({allowDuplicateParticipantIdPairs:t,returnParticipant:e,tournamentRecord:n,disableNotice:r,pairOverride:s,participant:i}){var m,g,I;const o="addParticipant";if(!n)return{error:et};if(!i)return G({result:{error:qo},stack:o});i.participantId||(i.participantId=Yt()),n.participants||(n.participants=[]);const{participantId:c,individualParticipantIds:a}=i;if(n.participants.reduce((S,T)=>T.participantId===c||S,!1))return{error:uv};const{participantType:l,participantRole:f}=i;if(!l||!Object.keys(Ea).includes(l))return{error:xr,participantType:l};if(!f)return{error:av};const p=n.participants||[],h=p.filter(S=>S.participantType===xt).map(S=>S.participantId);if(l!==xt&&i.person)return{error:tt,person:i.person};if(a&&!Array.isArray(a))return{error:tt,individualParticipantIds:a};if(l===_t){if(i.person)return{error:tt,person:i.person};if(i.individualParticipantIds){if(i.individualParticipantIds.length!==2&&!s)return G({result:{error:gr,info:"PAIR must be 2 individualParticipantIds"},stack:o});{const E=p.filter(b=>b.participantType===xt).map(b=>b.participantId);if(!Array.isArray(i.individualParticipantIds))return G({result:{error:gr},stack:o});if(!i.individualParticipantIds.reduce((b,N)=>E.includes(N)&&b,!0))return G({result:{error:gr},stack:o})}}else return G({result:{error:Ns},stack:o});const S=p.filter(E=>E.participantType===_t).map(E=>({individualParticipantIds:E.individualParticipantIds,participant:E})),T=i.participantType===_t&&S.find(E=>qe(E.individualParticipantIds,i.individualParticipantIds).length===2);if(T&&!t)return{...$,existingParticipant:!0,participant:e&&pt(T.participant)};if(!i.participantName){const E=p.filter(b=>{var N;return(N=i.individualParticipantIds)==null?void 0:N.includes(b.participantId)});let y=E.map(b=>{var N;return(N=b.person)==null?void 0:N.standardFamilyName}).filter(Boolean).join("/");E.length===1&&(y+="/Unknown"),i.participantName=y}}else if(l===xt){if(!((m=i.person)!=null&&m.standardFamilyName)||!((g=i.person)!=null&&g.standardGivenName))return{error:pv};if(!i.participantName){const S=`${i.person.standardFamilyName.toUpperCase()}, ${i.person.standardGivenName}`;i.participantName=S}}else if(l&&[se,Fn].includes(l)){if(a||(i.individualParticipantIds=[]),(I=i.individualParticipantIds)!=null&&I.length)for(const S of i.individualParticipantIds){if(typeof S!="string")return G({result:{participantId:S,error:tt},stack:o});if(!h.includes(S))return G({result:{participantId:S,error:_e},stack:o})}}else return{error:xr};n.participants.push(i),r||Ht({payload:{tournamentId:n.tournamentId,participants:[i]},topic:yi});const d={participant:e&&pt(i),...$};return bt(d)}function Ss({allowDuplicateParticipantIdPairs:t,returnParticipants:e,participants:n,tournamentRecord:r}){if(!r)return{error:et};r.participants||(r.participants=[]);const i=r.participants.map(p=>p.participantId)||[];n.forEach(p=>{p.participantId||(p.participantId=Yt())});const o=n.filter(p=>!i.includes(p.participantId)),c=n.filter(p=>i.includes(p.participantId)),a=o.filter(p=>p.participantType===xt),u=o.filter(p=>p.participantType!==xt),l=a.concat(...u),f=[];if(l.length){for(const h of l){const d=es({allowDuplicateParticipantIdPairs:t,returnParticipant:!0,disableNotice:!0,tournamentRecord:r,participant:h});if(d.error)return d;d.success&&!d.existingParticipant&&f.push(d.participant)}f.length&&Ht({topic:yi,payload:{tournamentId:r.tournamentId,participants:f}});const p={participants:e&&pt(f),addedCount:f.length,...$};return c.length&&Object.assign(p,{notAdded:c,info:Yd}),bt(p)}else return{info:"No new participants to add",addedCount:0,...$}}function iD({tournamentRecords:t,returnParticipant:e,pairOverride:n,tournamentId:r,participant:s}){if(typeof r!="string")return{error:is};const i=t[r];return i?es({returnParticipant:e,tournamentRecord:i,pairOverride:n,participant:s}):{error:et}}function oD({event:t}){var r;const e=`${Qn}.${Zn}`,{timeItem:n}=kr({element:t,itemType:e});if((r=n==null?void 0:n.itemValue)!=null&&r.PUBLIC){const{drawIds:s=[],seeding:i}=n.itemValue.PUBLIC||{},o={published:void 0,seedingScaleNames:[],drawIds:[]};return i&&Object.assign(o,n.itemValue.PUBLIC.seeding),{publishedDrawIds:s,publishedSeeding:o}}}function Ts({requireTimeStamp:t,scaleAttributes:e,participant:n}){var r;if(!n)return{error:qo};if(typeof e!="object")return{error:tt};if(n.timeItems||(n.timeItems=[]),n&&Array.isArray(n.timeItems)){const{accessor:s,scaleType:i,eventType:o,scaleName:c}=e,a=[eo,i,o,c].join("."),l=n.timeItems.filter(f=>(f==null?void 0:f.itemType)===a).filter(f=>!t||(f==null?void 0:f.itemDate)).sort((f,p)=>(f.createdAt?new Date(f.createdAt).getTime():0)-(p.createdAt?new Date(p.createdAt).getTime():0)).pop();if(l){const[f,p,h,d]=((r=l.itemType)==null?void 0:r.split("."))??[];if(f!==eo)return{error:Uu};const m=s&&Yi({element:l.itemValue,accessor:s}),g=(m==null?void 0:m.value)||l.itemValue;return{scaleItem:{eventType:h,scaleDate:l.itemDate,scaleValue:g,scaleName:d,scaleType:p}}}else return{error:Pv}}return{error:qo}}function cD({publishedSeeding:t,usePublishState:e,withSeeding:n,participant:r,event:s}){var f,p,h;const i={},o=d=>[eo,br,s.eventType,d].join("."),c=Object.assign({},...(r.timeItems||[]).filter(({itemType:d})=>d.split(".")[1]===br).map(({itemType:d,itemValue:m})=>({[d]:m}))),a=((t==null?void 0:t.stageSeedingScaleNames)&&Object.values(t==null?void 0:t.stageSeedingScaleNames)||Array.isArray(t==null?void 0:t.seedingScaleNames)&&t.seedingScaleNames||[]).map(o),u=qe(Object.keys(c),a);if(!!(!e||!Object.keys(c).length&&!((f=t==null?void 0:t.drawIds)!=null&&f.length)||u.length)&&u.length){if(t!=null&&t.stageSeedingScaleNames){const d=Object.keys(t.stageSeedingScaleNames).map(g=>{const I=o(t.stageSeedingScaleNames[g]),S=c[I];return[g,S]}).filter(g=>g[1]).map(g=>({[g[0]]:{seedValue:g[1]}})),m=Object.assign({},...d);i.seedAssignments=m}else if(u){const d=u.map(m=>c[m]);i.seedValue=d.pop()}}else if(!e&&typeof n=="object"){const d=Object.keys(n).map(g=>{const I=o(n[g]),S=c[I];return[g,S]}).filter(g=>g[1]).map(g=>({[g[0]]:{seedValue:g[1]}})),m=Object.assign({},...d);i.seedAssignments=m}else{const{categoryName:d,ageCategoryCode:m}=s.category||{};let g;for(const I of[m,s.eventId,d]){const S={eventType:s.eventType,scaleType:br,scaleName:I},T=Ts({scaleAttributes:S,participant:r});if(T.scaleItem){g=T.scaleItem;break}}if(g&&(!e||(t==null?void 0:t.published)&&!((h=(p=t==null?void 0:t.published)==null?void 0:p.drawIds)!=null&&h.length))){const S=g.scaleValue;i.seedValue=S}}return i}function ry({tournamentRecord:t,matchUpFormat:e,event:n}){if(!t)return{error:et};if(!nr(e))return{error:bu};const{extension:r}=Us({event:n,name:qr}),s=r==null?void 0:r.value,{extension:i}=Bn({tournamentRecord:t,name:qr}),o=i==null?void 0:i.value,c=(s==null?void 0:s.matchUpAverageTimes)&&la({...s,matchUpFormat:e}),a=(o==null?void 0:o.matchUpAverageTimes)&&la({...o,matchUpFormat:e}),u=[c,a].find(h=>h),l=(s==null?void 0:s.matchUpRecoveryTimes)&&da({...s,matchUpFormat:e}),f=(o==null?void 0:o.matchUpRecoveryTimes)&&da({...o,matchUpFormat:e}),p=[l,f].find(h=>h);return{matchUpFormat:e,averageTimes:u,recoveryTimes:p}}function Vp({tournamentRecord:t,recoveryTimes:e,matchUpFormat:n,averageTimes:r,event:s}){if(!t)return{error:et};if(r&&!Array.isArray(r))return{error:tt};if(e&&!Array.isArray(e))return{error:tt};const i=qr;if(s){const{extension:o}=Us({event:s,name:i}),c=(o==null?void 0:o.value)||{},a=sy({...c,matchUpFormat:n,averageTimes:r,recoveryTimes:e});Yr({event:s,extension:{name:i,value:a}})}else{const{extension:o}=Bn({tournamentRecord:t,name:i}),c=(o==null?void 0:o.value)||{},a=sy({...c,matchUpFormat:n,averageTimes:r,recoveryTimes:e});Ti({extension:{name:i,value:a},tournamentRecord:t})}return{...$}}function sy(t){const{matchUpRecoveryTimes:e=[],matchUpAverageTimes:n=[],matchUpFormat:r}=t;let{averageTimes:s,recoveryTimes:i}=t;s=(s||[]).filter(a=>{var u,l;return((u=a==null?void 0:a.categoryNames)==null?void 0:u.length)||((l=a==null?void 0:a.categoryTypes)==null?void 0:l.length)});const o=(s==null?void 0:s.length)&&n.map(a=>{var u;return a!=null&&a.matchUpFormatCodes.includes(r)?{...a,matchUpFormatCodes:(u=a.matchUpFormatCodes)==null?void 0:u.filter(l=>l!==r)}:a}).filter(({matchUpFormatCodes:a})=>a==null?void 0:a.length).concat({matchUpFormatCodes:[r],averageTimes:s});i=(i||[]).filter(a=>{var u,l;return((u=a==null?void 0:a.categoryNames)==null?void 0:u.length)||((l=a==null?void 0:a.categoryTypes)==null?void 0:l.length)});const c=(i==null?void 0:i.length)&&e.map(a=>{var u;return a!=null&&a.matchUpFormatCodes.includes(r)?{...a,matchUpFormatCodes:(u=a.matchUpFormatCodes)==null?void 0:u.filter(l=>l!==r)}:a}).filter(({matchUpFormatCodes:a,averageTimes:u})=>(a==null?void 0:a.length)||u).concat({matchUpFormatCodes:[r],recoveryTimes:i});return{matchUpAverageTimes:(o==null?void 0:o.length)&&o||n,matchUpRecoveryTimes:(c==null?void 0:c.length)&&c||e}}function iy({tournamentRecord:t,recoveryMinutes:e,averageMinutes:n,matchUpFormat:r,categoryType:s,event:i}){if(!t)return{error:et};if(!nr(r))return{error:tt};if(!i)return{error:Wt};const{averageTimes:o=[],recoveryTimes:c=[]}=ry({tournamentRecord:t,matchUpFormat:r,event:i}),a=i.category,u=(a==null?void 0:a.categoryName)||(a==null?void 0:a.ageCategoryCode)||(i==null?void 0:i.eventId);let l={categoryNames:[u],minutes:{}};const f={categoryNames:[u],minutes:{}},p=I=>{var S,T;if((S=I.categoryTypes)!=null&&S.includes(s)&&console.log("encountered:",{categoryType:s}),!((T=I.categoryNames)!=null&&T.includes(u)&&(I.categoryNames=I.categoryNames.filter(E=>E!==u),l={minutes:I.minutes,categoryNames:[u]},!I.categoryNames.length)))return I},h=!isNaN(vt(n)),d=!isNaN(vt(e)),m=o.map(p).filter(I=>{var S;return(S=I==null?void 0:I.categoryNames)==null?void 0:S.length}),g=c.map(p).filter(I=>{var S;return(S=I==null?void 0:I.categoryNames)==null?void 0:S.length});return h&&(Object.assign(l.minutes,{[(i==null?void 0:i.eventType)||Oe]:n}),m.push(l)),d&&(Object.assign(f.minutes,{[(i==null?void 0:i.eventType)||Oe]:e}),g.push(f)),!h&&!d?{error:tt}:Vp({averageTimes:h&&m,recoveryTimes:d&&g,tournamentRecord:t,matchUpFormat:r,event:i})}function aD({tournamentRecords:t,recoveryMinutes:e,averageMinutes:n,matchUpFormat:r,categoryType:s,tournamentId:i,eventId:o}){if(!o)return{error:Wt};const c=Object.keys(t).filter(a=>!i||i===a);if(i&&!c.includes(i))return{error:tt};for(const a of c){const u=t[a],{event:l}=Je({tournamentRecord:u,eventId:o});if(l)return iy({tournamentRecord:u,recoveryMinutes:e,averageMinutes:n,matchUpFormat:r,categoryType:s,event:l})}return{error:wn}}const Xa=({scheduleAttributes:t=["scheduledDate","scheduledTime"],schedule:e={}})=>!!Object.keys(e).filter(r=>t.includes(r)).filter(r=>e[r]).length;function tu({tournamentRecord:t}){if(!t)return{error:et};const e=(({tournamentId:n,tournamentRank:r,tournamentStatus:s,formalName:i,tournamentName:o,promotionalName:c,onlineResources:a,localTimeZone:u,startDate:l,endDate:f,hostCountryCode:p,tournamentContacts:h,tournamentAddresses:d})=>({tournamentId:n,tournamentRank:r,tournamentStatus:s,formalName:i,tournamentName:o,promotionalName:c,onlineResources:a,localTimeZone:u,startDate:l,endDate:f,hostCountryCode:p,tournamentContacts:h,tournamentAddresses:d}))(t);return{...$,tournamentInfo:pt(e,!1,!0)}}function oy({derivedDrawInfo:t,participantId:e,drawId:n}){var o,c,a,u;const r=(c=(o=t[n])==null?void 0:o.mainPositionAssignments)==null?void 0:c.find(l=>l.participantId===e),s=(u=(a=t[n])==null?void 0:a.qualifyingPositionAssignments)==null?void 0:u.find(l=>l.participantId===e),i={};if(r){const{participantId:l,...f}=r;l&&(i[It]={...f})}if(s){const{participantId:l,...f}=s;l&&(i[Pt]={...f})}return Object.keys(i).length?i:void 0}function uD({processParticipantId:t,tournamentRecords:e,tournamentRecord:n}){if(typeof n!="object"&&typeof e!="object")return{error:et};const r=e?Object.values(e).map(i=>(i==null?void 0:i.participants)||[]).flat():(n==null?void 0:n.participants)||[];return{relevantParticipantIdsMap:Object.assign({},...r.map(({participantId:i,participantType:o,individualParticipantIds:c})=>{typeof t=="function"&&t(i);const a=(c||[]).map(u=>({participantType:xt,relevantParticipantId:u}));return{[i]:a.concat({relevantParticipantId:i,participantType:o})}}))}}function Wl({derivedDrawInfo:t,participantId:e,drawId:n}){var o,c,a,u;const r=(c=(o=t[n])==null?void 0:o.mainSeedAssignments)==null?void 0:c.find(l=>l.participantId===e),s=(u=(a=t[n])==null?void 0:a.qualifyingSeedAssignments)==null?void 0:u.find(l=>l.participantId===e),i={};if(r){const{participantId:l,...f}=r;l&&(i[It]={...f})}if(s){const{participantId:l,...f}=s;l&&(i[Pt]={...f})}return Object.keys(i).length?i:void 0}function cy({scheduleAttributes:t=["scheduledDate","scheduledTime"],matchUps:e=[]}){if(!cr(e))return{error:$s};if(!Array.isArray(t))return{error:tt};const n=e.filter(Boolean).filter(({schedule:s})=>Xa({schedule:s,scheduleAttributes:t})).reduce((s,i)=>{const{schedule:o}=i,c=Bt(o==null?void 0:o.scheduledDate),a=de(o==null?void 0:o.scheduledTime);return c&&a&&(s[c]?s[c].push(i):s[c]=[i]),s},{});return Object.keys(n).forEach(s=>{n[s].sort((i,o)=>{var c,a;return _g(de((c=i.schedule)==null?void 0:c.scheduledTime),de((a=o.schedule)==null?void 0:a.scheduledTime))})}),{scheduledMatchUps:n}}function lD(t){var H,B,R,x,q,V,Y,z,J,Q,X;const{withScaleValues:e=!0,eventsPublishStatuses:n,withEvents:r=!0,withDraws:s=!0,participantIdMap:i,scheduleAnalysis:o,derivedDrawInfo:c,usePublishState:a,withStatistics:u,withOpponents:l,withMatchUps:f,withSeeding:p,participant:h,withISO2:d,withIOC:m}=t,g=[],I=[];if((m||d)&&yl({participant:h,withIOC:m,withISO2:d}),e){const{ratings:Z,rankings:nt}=sc({participant:h});h.rankings=nt,h.ratings=Z}const S=h==null?void 0:h.participantId;if(!S||!i[S])return{};const{potentialMatchUps:T,opponents:E,matchUps:y,events:b,losses:N,draws:A,wins:C}=i[S],v=C+N,P=C,U=v&&P/v,O={statCode:ua,denominator:v,numerator:P,statValue:U},D=Object.values(A),M=Object.values(b);if(s&&D){h.draws=D;for(const Z of D){const nt=(H=n[Z.eventId])==null?void 0:H.publishedSeeding;if(!a||(nt==null?void 0:nt.published)&&(((B=nt==null?void 0:nt.drawIds)==null?void 0:B.length)===0||((R=nt==null?void 0:nt.drawIds)==null?void 0:R.includes(Z.drawId)))){const K=Wl({drawId:Z.drawId,derivedDrawInfo:c,participantId:S});K&&(Z.seedAssignments=K)}}}if(r&&M&&(h.events=M,p)){const Z=Object.assign({},...(h.timeItems||[]).filter(({itemType:nt})=>nt.split(".")[1]===br).map(({itemType:nt,itemValue:rt})=>({[nt]:rt})));for(const nt of M){const rt=mt=>[eo,br,nt.eventType,mt].join("."),K=(x=n[nt.eventId])==null?void 0:x.publishedSeeding,it=((K==null?void 0:K.stageSeedingScaleNames)&&Object.values(K==null?void 0:K.stageSeedingScaleNames)||Array.isArray(K==null?void 0:K.seedingScaleNames)&&K.seedingScaleNames||[]).map(rt),st=qe(Object.keys(Z),it),dt=!!(!a||!Object.keys(Z).length&&!((q=K==null?void 0:K.drawIds)!=null&&q.length)||st.length);if(dt&&st.length){if(K!=null&&K.stageSeedingScaleNames){const mt=Object.keys(K.stageSeedingScaleNames).map(Nt=>{const St=rt(K.stageSeedingScaleNames[Nt]),ct=Z[St];return[Nt,ct]}).filter(Nt=>Nt[1]).map(Nt=>({[Nt[0]]:{seedValue:Nt[1]}})),Mt=Object.assign({},...mt);nt.seedAssignments=Mt}else if(st){const mt=st.map(Mt=>Z[Mt]);nt.seedValue=mt.pop()}}else if(!a&&typeof p=="object"){const mt=Object.keys(p).map(Nt=>{const St=rt(p[Nt]),ct=Z[St];return[Nt,ct]}).filter(Nt=>Nt[1]).map(Nt=>({[Nt[0]]:{seedValue:Nt[1]}})),Mt=Object.assign({},...mt);nt.seedAssignments=Mt}else{const{categoryName:mt,ageCategoryCode:Mt}=nt.category||{};let Nt;for(const St of[nt.eventId,Mt,mt]){const ct={eventType:nt.eventType,scaleType:br,scaleName:St},Et=Ts({scaleAttributes:ct,participant:h});if(Et.scaleItem){Nt=Et.scaleItem;break}}if(Nt){const St=Nt.scaleValue;(!a||(K==null?void 0:K.published)&&(((V=K==null?void 0:K.drawIds)==null?void 0:V.length)===0||((Y=K==null?void 0:K.drawIds)==null?void 0:Y.includes(nt.drawId))))&&(nt.seedValue=St)}}if((z=nt.drawIds)!=null&&z.length)for(const mt of nt.drawIds||[]){const Mt=((J=K==null?void 0:K.drawIds)==null?void 0:J.length)&&!((Q=K==null?void 0:K.drawIds)!=null&&Q.includes(mt));if(dt&&!Mt){const Nt=Wl({drawId:mt,derivedDrawInfo:c,participantId:S});if(Nt&&nt.seedAssignments)for(const St of Object.keys(nt.seedAssignments))nt.seedAssignments[St]=Nt[St];else nt.seedAssignments=Nt}}}}const w=Object.values(E).flat();l&&(w!=null&&w.length)&&(h.opponents=w,D==null||D.forEach(Z=>{Z.opponents=w.filter(nt=>nt.drawId===Z.drawId)}));const k=Object.values(T),_=Object.values(y);f&&(h.potentialMatchUps=k,h.matchUps=_);const F=_.concat(k),L=((X=cy({matchUps:F}))==null?void 0:X.scheduledMatchUps)||[],{scheduledMinutesDifference:W}=o||{};return Object.keys(L).forEach(Z=>{L[Z].filter(Boolean).forEach((nt,rt)=>{var yt,wt,Xt,$t;const{schedule:{scheduledTime:K,timeAfterRecovery:it,typeChangeTimeAfterRecovery:st},matchUpStatus:dt,roundPosition:mt,structureName:Mt,matchUpType:Nt,roundNumber:St,matchUpId:ct,drawId:Et,score:gt}=nt;I.push({...nt.schedule,scheduledTime:de((yt=nt.schedule)==null?void 0:yt.scheduledTime),roundPosition:mt,structureName:Mt,matchUpType:Nt,roundNumber:St,matchUpId:ct,drawId:Et});const Ft=dt===re||[ce,te].includes(dt)&&!Be({score:gt});if(K&&!Ft){const At=jt(K),Dt=L[Z].slice(rt+1);for(const at of Dt)if(!(at.matchUpStatus===re||[ce,te].includes(at.matchUpStatus)&&!Be(at))&&((wt=at.schedule)!=null&&wt.scheduledTime)){const ft=nt.matchUpType!==at.matchUpType&&st||it,Ct=nt.drawId===at.drawId,Ut=nt.potential&&at.potential,ut=jt((Xt=at.schedule)==null?void 0:Xt.scheduledTime)-At;(W&&!isNaN(W)?ut<=W:jt(ft)>jt(($t=at.schedule)==null?void 0:$t.scheduledTime))&&!(Ut&&Ct)&&g.push({priorScheduledMatchUpId:at.matchUpId,matchUpIdWithConflict:ct})}}})}),u&&(h.statistics=[O]),{scheduleConflicts:g,scheduleItems:I}}function dD({eventEntries:t,sortConfig:e,event:n}){const r={},s=Object.assign({},...(n.drawDefinitions??[]).map(i=>{var S,T,E,y,b,N,A,C,v;const o=Object.assign({},...(t??[]).filter(P=>P.participantId).map(P=>({[P.participantId]:P})),...i.entries.filter(P=>P.participantId).map(P=>({[P.participantId]:P}))),c=Object.values(o),a=(T=(S=lr({stageSequence:1,drawDefinition:i,stage:It}))==null?void 0:S.structures)==null?void 0:T[0],u=a&&((E=ee({structure:a}))==null?void 0:E.positionAssignments),l=u==null?void 0:u.length,f=(b=(y=lr({stageSequence:1,stage:Pt,drawDefinition:i}))==null?void 0:y.structures)==null?void 0:b[0],p=a&&((N=ee({structure:f}))==null?void 0:N.positionAssignments),h=p==null?void 0:p.length,d=a==null?void 0:a.seedAssignments,m=f==null?void 0:f.seedAssignments,g=(i.structures||[]).sort((P,U)=>Pi(P,U,e)).map(({structureId:P,structures:U})=>[P,...(U||[]).map(({structureId:O})=>O)]).flat(1/0),I=(v=(C=(A=n==null?void 0:n._flightProfile)==null?void 0:A.flights)==null?void 0:C.find(P=>P.drawId===i.drawId))==null?void 0:v.flightNumber;return r[i.drawId]={qualifyingPositionAssignments:p,qualifyingSeedAssignments:m,mainPositionAssignments:u,mainSeedAssignments:d,orderedStructureIds:g,qualifyingDrawSize:h,flightNumber:I,drawSize:l},{[i.drawId]:{drawType:i.drawType,drawEntries:c}}}));return{derivedInfo:r,drawDetails:s}}function fD({relevantParticipantIdsMap:t,participantFilters:e,participantIdMap:n,derivedDrawInfo:r,eventDrawsCount:s,drawDetails:i,eventType:o,matchUp:c}){var V;const{collectionId:a,collectionPosition:u,drawId:l,drawName:f,eventId:p,eventName:h,finishingRound:d,finishingPositionRange:m,processCodes:g,loserTo:I,matchUpId:S,matchUpType:T,matchUpFormat:E,matchUpStatus:y,matchUpStatusCodes:b,matchUpTieId:N,roundName:A,roundNumber:C,roundPosition:v,score:P,sides:U,stage:O,stageSequence:D,schedule:M,structureName:w,structureId:k,tieFormat:_,tieMatchUps:F,tournamentId:L,winnerTo:W,winningSide:j}=c,H=e==null?void 0:e.participantIds,B=Y=>{const z=Y&&t[Y]||[];return z.push(Y),z.some(J=>!H||H.includes(J.relevantParticipantId))?z:[]},{winner:R,loser:x}=m||{},q=(F==null?void 0:F.length)&&F.filter(({matchUpType:Y})=>Y===Tr).map(({sides:Y})=>Y.map(({sideNumber:z,participantId:J,participant:Q})=>z&&J&&{sideNumber:z,participantId:J,participant:Q})).flat().filter(Boolean)||[];if(o===ds&&T===Tr){const Y=(((V=c.sides)==null?void 0:V.filter(Boolean))||[]).map(({sideNumber:z,participantId:J,participant:Q})=>z&&J&&{sideNumber:z,participantId:J,participant:Q}).filter(Boolean);q.push(...Y)}if(U==null||U.forEach(Y=>{const{participantId:z,sideNumber:J}=Y;if(!z)return;const{drawType:Q,drawEntries:X}=i[l],Z=J===1?P==null?void 0:P.scoreStringSide1:P==null?void 0:P.scoreStringSide2,nt=j&&J===j,rt=c.sides.find(St=>St.sideNumber===3-J),K=rt==null?void 0:rt.participantId,it=K&&t[K]||[],st=nt?R:x,dt=X.find(St=>St.participantId===z),mt=B(z),Mt=[];q==null||q.filter(St=>St.sideNumber===J).forEach(St=>{const ct=St.participantId;ct&&!Mt.includes(ct)&&(mt.push({relevantParticipantId:ct,participantType:_t}),Mt.push(ct))});const Nt=mt.filter(St=>o!==ds||o===ds&&[Tr,yr].includes(T)&&[_t,vr].includes(St.participantType)||o===ds&&[gi,Tr].includes(T)&&[xt].includes(St.participantType));Nt==null||Nt.forEach(({relevantParticipantId:St,participantType:ct})=>{var Dt,at;const{entryStage:Et,entryStatus:gt,entryPosition:Ft}=dt||{};if(!n[St])return;if(!n[St].draws[l]){const ot=oy({participantId:St,derivedDrawInfo:r,drawId:l}),Lt=Wl({participantId:St,derivedDrawInfo:r,drawId:l});n[St].draws[l]=bt({qualifyingDrawSize:(Dt=r[l])==null?void 0:Dt.qualifyingDrawSize,drawSize:(at=r[l])==null?void 0:at.drawSize,partnerParticipantIds:[],positionAssignments:ot,seedAssignments:Lt,entryPosition:Ft,entryStatus:gt,entryStage:Et,drawName:f,drawType:Q,eventId:p,drawId:l})}n[St].events[p]||(n[St].events[p]={partnerParticipantIds:[],drawIds:[],eventName:h,eventId:p});const yt=n[St].events[p].drawIds;yt&&!(yt!=null&&yt.includes(l))&&n[St].events[p].drawIds.push(l);let wt;if(ct===xt&&T===Tr){const ot=Nt.find(Lt=>Lt.relevantParticipantId!==St&&Lt.participantType===xt);wt=ot==null?void 0:ot.relevantParticipantId}const Xt=(it==null?void 0:it.filter(ot=>T===yr&&ct===vr&&ot.participantType===vr||T===gi&&ot.participantType===xt||T===Tr&&(ct===xt?[xt,_t].includes(ot.participantType):ot.participantType===_t)))||[];Xt.forEach(({relevantParticipantId:ot,participantType:Lt})=>{n[St].opponents||(n[St].opponents={}),n[St].opponents[ot]={eventId:p,drawId:l,matchUpId:S,participantType:Lt,participantId:ot}});const $t=Xt.map(({relevantParticipantId:ot,participantType:Lt})=>({participantId:ot,participantType:Lt}));(T!==yr&&[xt,_t].includes(ct)||T===yr&&ct===vr)&&(n[St].matchUps[S]=bt({collectionId:a,collectionPosition:u,drawId:l,eventId:p,eventType:o,eventDrawsCount:s,finishingRound:d,finishingPositionRange:st,loserTo:I,matchUpId:S,matchUpType:T,matchUpFormat:E,matchUpStatus:y,matchUpStatusCodes:b,matchUpTieId:N,opponentParticipantInfo:$t,participantWon:nt,partnerParticipantId:wt,perspectiveScoreString:Z,processCodes:g,roundName:A,roundNumber:C,roundPosition:v,schedule:M,score:P,sides:U,stage:O,stageSequence:D,structureName:w,structureId:k,tieFormat:_,tournamentId:L,winnerTo:W,winningSide:j})),wt&&(n[St].events[p].partnerParticipantIds.push(wt),n[St].draws[l].partnerParticipantIds.push(wt),n[St].events[p].partnerParticipantId=wt,n[St].draws[l].partnerParticipantId=wt),j&&(nt?n[St].wins++:n[St].losses++)})}),Array.isArray(c.potentialParticipants)){const Y=xa(c.potentialParticipants.flat());Y==null||Y.forEach(z=>{const J=B(z);J==null||J.forEach(({relevantParticipantId:Q})=>{n[Q].potentialMatchUps[S]=bt({drawId:l,eventId:p,eventType:o,matchUpId:S,matchUpType:T,matchUpFormat:E,roundName:A,roundNumber:C,roundPosition:v,schedule:M,tieFormat:_,structureName:w,tournamentId:L,potential:!0})})})}}function pD(t){var p,h;const e=[],n={},r={},s={},i=d=>{s[d]||(s[d]={groupParticipantIds:[],teamParticipantIds:[],pairParticipantIds:[],potentialMatchUps:{},scheduleItems:[],opponents:{},matchUps:{},events:{},groups:[],teams:[],draws:{},losses:0,wins:0})},{tournamentRecord:o,participantFilters:c,allTournamentParticipants:a}=t,{relevantParticipantIdsMap:u}=uD({processParticipantId:i,tournamentRecord:o}),l=c==null?void 0:c.participantIds,f=d=>{const m=d&&u[d]||[];return m.push(d),m.some(g=>!l||l.includes(g.relevantParticipantId))?m:[]};return t.withGroupings&&a.forEach(d=>{var m,g,I;if(d.participantType===Fn){const S=d.participantId;(m=d==null?void 0:d.individualParticipantIds)==null||m.forEach(T=>{s[T].groupParticipantIds.includes(S)||(s[T].groupParticipantIds.push(S),s[T].groups.push({participantRoleResponsibilities:d.participantRoleResponsibilities,participantOtherName:d.participantOtherName,participantName:d.participantName,participantId:d.participantId}))})}if(d.participantType===Jt){const S=d.participantId;(g=d==null?void 0:d.individualParticipantIds)==null||g.forEach(T=>{var E,y,b,N;(y=(E=s[T])==null?void 0:E.teamParticipantIds)!=null&&y.includes(S)||((b=s[T])==null||b.teamParticipantIds.push(S),(N=s[T])==null||N.teams.push({participantRoleResponsibilities:d.participantRoleResponsibilities,participantOtherName:d.participantOtherName,participantName:d.participantName,participantId:d.participantId,teamId:d.teamId}))})}if(d.participantType===_t){const S=d.participantId;(I=d==null?void 0:d.individualParticipantIds)==null||I.forEach(T=>{s[T]&&!s[T].pairParticipantIds.includes(S)&&s[T].pairParticipantIds.push(S)})}}),t.withMatchUps&&fr({tournamentRecord:o}),(t.withScheduleItems||t.scheduleAnalysis||t.withStatistics||t.withOpponents||t.withMatchUps||t.withSeeding||t.withEvents||t.withDraws)&&((p=t.tournamentEvents)==null||p.forEach(d=>{var _,F,L,W,j,H,B;const m=pt(d,!0,!0),g=be({event:m}).flightProfile,I=((_=g==null?void 0:g.flights)==null?void 0:_.length)||((F=m.drawDefinitions)==null?void 0:F.length)||0;(m.drawDefinitions||[]).forEach((R,x)=>{if((m==null?void 0:m.eventType)===Jt){const{extension:q}=Ke({element:d.drawDefinitions[x],name:Wr});q&&(R.extensions=[q])}});const{eventId:S,eventName:T,eventType:E,category:y}=m,b={eventId:S,eventName:T,eventType:E,category:y},N=m&&Object.keys(m).filter(R=>R.startsWith("_"));N==null||N.forEach(R=>b[R]=m[R]);const A=m.entries||[],C=`${Qn}.${Zn}`,{timeItem:v}=ws({itemType:C,event:m});if((L=v==null?void 0:v.itemValue)!=null&&L.PUBLIC){const{drawIds:R=[],seeding:x}=v.itemValue.PUBLIC||{},q={published:void 0,seedingScaleNames:[],drawIds:[]};x&&Object.assign(q,v.itemValue.PUBLIC.seeding),n[S]={publishedDrawIds:R,publishedSeeding:q}}const U=[...Object.values(rI)].map(R=>`_${R}`),O=b&&Object.keys(b).filter(R=>!U.includes(R)).reduce((R,x)=>(R[x]=b[x],R),{});A==null||A.filter(R=>R==null?void 0:R.participantId).forEach(R=>{const{participantId:x,entryStage:q,entryStatus:V,entryPosition:Y}=R,z=f(x);z==null||z.forEach(({relevantParticipantId:J})=>{s[J]||i(J),s[J].events[S]={...O,partnerParticipantIds:[],entryPosition:Y,entryStatus:V,entryStage:q,drawIds:[],eventId:S}})});const D=({drawEntry:R,drawId:x})=>{const{participantId:q,entryStage:V,entryStatus:Y,entryPosition:z}=R,J=f(q);J==null||J.forEach(({relevantParticipantId:Q})=>{var Z,nt;if(s[Q].events[S]||(s[Q].events[S]={...O,partnerParticipantIds:[],entryPosition:z,entryStatus:Y,entryStage:V,drawIds:[],eventId:S}),!s[Q].draws[x]){const rt=oy({participantId:Q,derivedDrawInfo:r,drawId:x}),K=Wl({participantId:Q,derivedDrawInfo:r,drawId:x});s[Q].draws[x]=bt({qualifyingDrawSize:(Z=r[x])==null?void 0:Z.qualifyingDrawSize,drawSize:(nt=r[x])==null?void 0:nt.drawSize,partnerParticipantIds:[],positionAssignments:rt,eventDrawsCount:I,seedAssignments:K,entryPosition:z,entryStatus:Y,entryStage:V,eventId:S,drawId:x})}const X=s[Q].events[S].drawIds;X&&!(X!=null&&X.includes(x))&&s[Q].events[S].drawIds.push(x)})},M=((W=m.drawDefinitions)==null?void 0:W.map(({drawId:R})=>R))||[];(H=(j=b._flightProfile)==null?void 0:j.flights)==null||H.forEach(R=>{const{drawId:x,drawEntries:q}=R;M.includes(x)||q==null||q.forEach(V=>D({drawEntry:V,drawId:x}))});const{drawDetails:w,derivedInfo:k}=dD({eventEntries:A,event:m});if(Object.assign(r,k),m.eventType===Jt||t.withScheduleItems||t.scheduleAnalysis||t.withStatistics||t.withOpponents||t.withMatchUps||t.withDraws){const R=(B=si({afterRecoveryTimes:t.scheduleAnalysis,participants:a,nextMatchUps:!0,tournamentRecord:o,inContext:!0,event:m}))==null?void 0:B.matchUps;R==null||R.forEach(x=>fD({relevantParticipantIdsMap:u,participantFilters:c,participantIdMap:s,derivedDrawInfo:r,eventDrawsCount:I,drawDetails:w,eventType:E,matchUp:x}))}})),(h=t.tournamentParticipants)==null||h.forEach(d=>{const{scheduleConflicts:m,scheduleItems:g}=lD({...t,eventsPublishStatuses:n,participantIdMap:s,derivedDrawInfo:r,participant:d});if(t.withSignInStatus){const{timeItem:I}=kr({itemType:Ta,element:d});d.signedIn=(I==null?void 0:I.itemValue)===ya}if(t.withScheduleItems&&(d.scheduleItems=g),t.scheduleAnalysis&&(d.scheduleConflicts=m,m!=null&&m.length&&!e.includes(d.participantId)&&e.push(d.participantId)),t.withGroupings!==!1){const I=s[d.participantId];d.groupParticipantIds=I==null?void 0:I.groupParticipantIds,d.pairParticipantIds=I==null?void 0:I.pairParticipantIds,d.teamParticipantIds=I==null?void 0:I.teamParticipantIds,d.groups=I==null?void 0:I.groups,d.teams=I==null?void 0:I.teams}t.withTeamMatchUps}),{participantIdsWithConflicts:e,eventsPublishStatuses:n}}function Hl({participantFilters:t={},tournamentRecord:e,participants:n=[]}){var E;if(!Object.keys(t).length)return n;const{accessorValues:r,drawEntryStatuses:s,positionedParticipants:i,eventEntryStatuses:o,participantRoles:c,participantRoleResponsibilities:a,participantTypes:u,participantIds:l,signInStatus:f,enableOrFiltering:p,eventIds:h,genders:d}=t,m=ys(h)&&((E=e==null?void 0:e.events)==null?void 0:E.filter(y=>h==null?void 0:h.includes(y.eventId)))||(e==null?void 0:e.events)||[],g=s&&hD({drawEntryStatuses:s,tournamentEvents:m}),I=o&&mD({eventEntryStatuses:o,tournamentEvents:m}),S=i!==void 0&&[!0,!1].includes(i)&&m.reduce((y,b)=>y.concat(...(b.drawDefinitions||[]).map(N=>rS({drawDefinition:N}).allPositionedParticipantIds).filter(Boolean)),[]),T=y=>r==null?void 0:r.reduce((b,N)=>{const{accessor:A,value:C}=N,{values:v}=Yi({element:y,accessor:A});return b&&(v==null?void 0:v.includes(C))},!0);if(n=n==null?void 0:n.filter(y=>{var O,D;const b=(D=(O=kr({element:y,itemType:Ta}))==null?void 0:O.timeItem)==null?void 0:D.itemValue,{participantRoleResponsibilities:N,participantType:A,participantRole:C,participantId:v,person:P}=y,U=Array.isArray(d)&&(d==null?void 0:d.length)&&(P==null?void 0:P.sex)&&d.includes(P.sex);return p?d&&U||i&&S.includes(v)||i===!1&&!S.includes(v)||(g==null?void 0:g.includes(v))||(I==null?void 0:I.includes(v))||(l==null?void 0:l.includes(v))||f&&b===f||u&&A&&ys(u)&&u.includes(A)||c&&C&&ys(c)&&c.includes(C)||a&&ys(N)&&ys(a)&&a.find(M=>N==null?void 0:N.includes(M))||(r==null?void 0:r.length)&&ys(r)&&T(y):(!d||U)&&(i===void 0||i&&S.includes(v)||i===!1&&!S.includes(v))&&(!g||g.includes(v))&&(!I||I.includes(v))&&(!l||l.includes(v))&&(!f||b===f)&&(!u||A&&ys(u)&&u.includes(A))&&(!c||C&&ys(c)&&c.includes(C))&&(!a||ys(N)&&ys(a)&&a.find(M=>N==null?void 0:N.includes(M)))&&(!(r!=null&&r.length)||ys(r)&&T(y))}),m.length&&h){const y=m.filter(b=>h.includes(b.eventId)).map(b=>{const N=(b.entries||[]).map(C=>C.participantId);if(b.eventType===ls)return N;const A=((e==null?void 0:e.participants)||[]).filter(C=>N.includes(C.participantId)).map(C=>C.individualParticipantIds).flat(1);return N.concat(...A)}).flat(1);n=n==null?void 0:n.filter(b=>y.includes(b.participantId))}return n}function ys(t){return t&&Array.isArray(t)&&t.length}function hD({drawEntryStatuses:t,tournamentEvents:e}){const n=({entryStatus:r})=>Array.isArray(t)?t.includes(r):!0;return Vt(e.reduce((r,s)=>{var a,u;const{flightProfile:i}=be({event:s}),o=((a=i==null?void 0:i.flights)==null?void 0:a.map(({drawEntries:l})=>Array.isArray(l)?l.filter(n).map(fe):[]).flat())||[],c=((u=s.drawDefinitions)==null?void 0:u.map(({entries:l})=>l?l.filter(n).map(fe):[]))||[];return r.concat(...o,...c)},[]))}function mD({eventEntryStatuses:t,tournamentEvents:e}){return Vt(e.reduce((n,r)=>{const s=(r.entries||[]).filter(({entryStatus:i})=>Array.isArray(t)?t.includes(i):!0).map(fe);return n.concat(...s)},[]))}function dn(t){const{participantFilters:e={},convertExtensions:n,policyDefinitions:r,withScheduleItems:s,scheduleAnalysis:i,withSignInStatus:o,withTeamMatchUps:c,tournamentRecord:a,usePublishState:u,withScaleValues:l,withStatistics:f,withGroupings:p,withOpponents:h,withMatchUps:d,withSeeding:m,withEvents:g,withDraws:I,inContext:S,withISO2:T,withIOC:E}=t;if(!a)return{error:et};if(!a.participants)return{error:Yc};const y=a.participants.map(P=>pt(P,n));if(typeof e!="object")return{error:Ir,participantFilters:e};S&&(y==null||y.forEach(P=>{var U;[_t,se,Fn].includes(P.participantType)&&(P.individualParticipants=(U=P.individualParticipantIds)==null?void 0:U.map(O=>{const D=a.participants.find(w=>w.participantId===O),M=pt(D,n,!0);if(l){const{ratings:w,rankings:k}=sc({participant:M});M.ratings=w,M.rankings=k}return(E||T)&&yl({participant:M,withISO2:T,withIOC:E}),M}))}));let b=e?Hl({participants:y,participantFilters:e,tournamentRecord:a}):y,N,A;if(s||o||i||l||f||p||h||d||m||g||I||T||E){const P=pD({tournamentEvents:a.events,allTournamentParticipants:y,tournamentParticipants:b,participantFilters:e,withScheduleItems:s,withSignInStatus:o,tournamentRecord:a,scheduleAnalysis:i,withTeamMatchUps:c,usePublishState:u,withScaleValues:l,withStatistics:f,withGroupings:p,withOpponents:h,withMatchUps:d,withSeeding:m,withEvents:g,withDraws:I,withISO2:T,withIOC:E});N=P==null?void 0:P.participantIdsWithConflicts,A=P==null?void 0:P.eventsPublishStatuses}const v=r==null?void 0:r[oa];return v!=null&&v.participant&&(b=b.map(P=>Fu({template:v.participant,source:P}))),{participantIdsWithConflicts:N,tournamentParticipants:b,eventsPublishStatuses:A}}const gD="ADMINISTRATION",ID="CAPTAIN",SD="COACH",fn="COMPETITOR",TD="MEDIA",yD="MEDICAL",ay="OFFICIAL",uy="OTHER",ly={ADMINISTRATION:gD,CAPTAIN:ID,COACH:SD,COMPETITOR:fn,MEDIA:TD,MEDICAL:yD,OFFICIAL:ay,OTHER:uy,SECURITY:"SECURITY"};function dy(t){return kl(t)}function jp({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,scheduledDate:s,matchUpId:i}){return Cp({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,scheduledDate:s,matchUpId:i})}function Gp({removePriorValues:t,tournamentRecord:e,drawDefinition:n,scheduledTime:r,disableNotice:s,matchUpId:i}){return wi({removePriorValues:t,tournamentRecord:e,drawDefinition:n,scheduledTime:r,disableNotice:s,matchUpId:i})}function fy({tournamentRecord:t,drawDefinition:e,disableNotice:n,matchUpId:r,startTime:s}){return Up({tournamentRecord:t,drawDefinition:e,disableNotice:n,matchUpId:r,startTime:s})}function py({tournamentRecord:t,drawDefinition:e,disableNotice:n,matchUpId:r,endTime:s}){return Op({tournamentRecord:t,drawDefinition:e,disableNotice:n,matchUpId:r,endTime:s})}function hy({tournamentRecord:t,drawDefinition:e,disableNotice:n,matchUpId:r,stopTime:s}){return Mp({tournamentRecord:t,drawDefinition:e,disableNotice:n,matchUpId:r,stopTime:s})}function my({tournamentRecord:t,drawDefinition:e,disableNotice:n,resumeTime:r,matchUpId:s}){return Dp({tournamentRecord:t,drawDefinition:e,disableNotice:n,resumeTime:r,matchUpId:s})}function ED({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,courtOrder:s,matchUpId:i}){return Pp({removePriorValues:t,tournamentRecord:e,drawDefinition:n,disableNotice:r,courtOrder:s,matchUpId:i})}function gy({tournamentRecord:t,drawDefinition:e,disableNotice:n,participantId:r,officialType:s,matchUpId:i}){if(!r)return{error:Ce};const{tournamentParticipants:o}=dn({tournamentRecord:t,participantFilters:{participantTypes:[xt],participantRoles:[ay]}});return Ps({tournamentParticipants:o,participantId:r})?UT({drawDefinition:e,disableNotice:n,participantId:r,officialType:s,matchUpId:i}):{error:_e}}function Iy({tournamentRecord:t,scheduleChange:e,matchUpIds:n,dryRun:r}){if(!t)return{error:et};if(!n||!Array.isArray(n))return{error:qc};if(typeof e!="object")return{error:tt};const s=[],i=[],{minutesChange:o,daysChange:c}=e;if(!o&&!c)return{...$};if(o&&isNaN(o))return{error:tt};if(c&&isNaN(c))return{error:tt};const{matchUps:a}=He({matchUpFilters:{matchUpIds:n},tournamentRecord:t}),u=({matchUpStatus:E})=>!We.includes(E),l=a==null?void 0:a.filter(E=>Xa({schedule:E.schedule})).filter(E=>u({matchUpStatus:E.matchUpStatus}));if(!(l!=null&&l.length))return{...$};const{tournamentInfo:f}=tu({tournamentRecord:t}),{startDate:p,endDate:h}=f,d=l==null?void 0:l.reduce((E,y)=>{const{matchUpId:b,drawId:N}=y;return E[N]?E[N].push(b):E[N]=[b],E},{}),m=1440;for(const E of Object.keys(d)){const y=Ks({tournamentRecord:t,drawId:E});if(y.error)return y;const b=y.drawDefinition,N=d[E].filter(A=>n.includes(A));for(const A of N)if(A&&b){const C=l.find(w=>w.matchUpId===A),v=C==null?void 0:C.schedule,{scheduledTime:P,scheduledDate:U}=v;let O,D,M;if(!O&&c&&U){const w=Bt(U);M=fC(w,c),O=new Date(M)<new Date(p)||new Date(M)>new Date(h)}if(o&&P){const w=Bt(P),_=jt(de(P))+o;if(O=_<0||_>m,!O){const F=An(P,o);D=w&&M?`${M}T${F}`:F}}if(O)i.push(A);else{if(!r){if(D){const w=Gp({scheduledTime:D,drawDefinition:b,matchUpId:A});if(w.error)return w}if(M){const w=jp({scheduledDate:M,drawDefinition:b,matchUpId:A});if(w.error)return w}}(D||M)&&s.push(A)}}}const g=He({matchUpFilters:{matchUpIds:n},tournamentRecord:t}).matchUps||[],I=g.filter(({matchUpId:E})=>s.includes(E)),S=g.filter(({matchUpId:E})=>i.includes(E)),T=I.length&&!S.length;return{...$,rescheduled:I,notRescheduled:S,allRescheduled:T}}function bD({tournamentRecords:t,scheduleChange:e,matchUpIds:n,dryRun:r}){var c,a;if(!n||!Array.isArray(n))return{error:qc};if(typeof e!="object")return{error:tt};const s=[];let i=[];for(const u of Object.values(t)){const l=Iy({tournamentRecord:u,scheduleChange:e,matchUpIds:n,dryRun:r});if(l.error)return l;Array.isArray(l.notRescheduled)&&i.push(...l.notRescheduled);const f=Xf(l.notRescheduled),p=[];(c=l.rescheduled)==null||c.forEach(h=>{const{matchUpId:d}=h;f.includes(d)&&p.push(d),s.push(h)}),p.length&&(i=((a=l==null?void 0:l.notRescheduled)==null?void 0:a.filter(({matchUpId:h})=>!p.includes(h)))||[])}const o=!!(s.length&&!i.length);return{...$,rescheduled:s,notRescheduled:i,allRescheduled:o}}function Sy({tournamentRecord:t,dailyLimits:e}){return t?typeof e!="object"?{error:Ir}:Ti({extension:{name:Ji,value:{dailyLimits:e}},tournamentRecord:t}):{error:et}}function ND({tournamentRecords:t,tournamentId:e,dailyLimits:n}){if(typeof t!="object"||!Object.keys(t).length)return{error:Gt};const r=Object.keys(t).filter(s=>!e||e===s);if(e&&!r.includes(e))return{error:tt};for(const s of r){const i=t[s],o=Sy({tournamentRecord:i,dailyLimits:n});if(o.error)return o}return{...$}}function AD({extensionConversions:t,seedAssignments:e,participant:n,withSeeding:r,seedValue:s,eventId:i,ranking:o,entry:c}){const{entryStatus:a,entryStage:u,entryPosition:l,extensions:f}=c,p=f!=null&&f.length?Object.assign({},...rf(f)):{},h=Object.assign(p,{...t,entryPosition:l,entryStatus:a,entryStage:u,ranking:o,eventId:i});n.events[i]=bt(h,!1,!1,!0),r&&(e&&(n.events[i].seedAssignments=e),s&&(n.events[i].seedValue=s))}function Ty(t){const{participantMap:e,participantId:n,matchUpStatus:r,roundPosition:s,structureId:i,matchUpType:o,roundNumber:c,matchUpId:a,potential:u,schedule:l,drawId:f,score:p}=t;if(!l||!Object.keys(l).length)return;r===re||e[n].scheduleItems.push({...l,scheduledDate:Bt(l==null?void 0:l.scheduledDate),scheduledTime:de(l==null?void 0:l.scheduledTime),scoreHasValue:Be({score:p}),matchUpStatus:r,roundPosition:s,structureId:i,matchUpType:o,roundNumber:c,matchUpId:a,potential:u,drawId:f})}function vD({finishingPositionRange:t={},participantMap:e,finishingRound:n,participantWon:r,matchUpStatus:s,participantId:i,stageSequence:o,roundNumber:c,structureId:a,matchUpId:u,drawId:l,stage:f}){const p=e[i],h=S=>Math.abs(S[0]-S[1]);p.structureParticipation[a]||(p.structureParticipation[a]={rankingStage:f,walkoverWinCount:0,defaultWinCount:0,stageSequence:o,winCount:0,structureId:a,drawId:l});const d=p.structureParticipation[a],{winner:m,loser:g}=t,I=r?m:g;r&&(d.winCount+=1,s===ce&&(d.walkoverWinCount+=1),s===te&&(d.defaultWinCount+=1)),I&&(!d.finishingPositionRange||h(I)<h(d.finishingPositionRange))&&(d.finishingPositionRange=I),n&&((!d.finishingRound||n<d.finishingRound)&&(d.finishingMatchUpId=u,d.finishingRound=n,d.roundNumber=c),n===1&&(d.participantWon=r))}function yy(t){var M,w,k,_,F,L,W,j,H,B;const{withScheduleTimes:e,scheduleAnalysis:n,withTeamMatchUps:r,participantMap:s,withOpponents:i,withMatchUps:o,withEvents:c,withDraws:a,finishingPositionRange:u,finishingRound:l,matchUpStatus:f,stageSequence:p,roundNumber:h,structureId:d,score:m,stage:g,withRankingProfile:I,tieWinningSide:S,roundPosition:T,matchUpTieId:E,matchUpSides:y,collectionId:b,matchUpType:N,winningSide:A,matchUpId:C,schedule:v,eventId:P,drawId:U,sides:O}=t,D=i&&(O==null?void 0:O.length)===2&&Object.assign({},...O.map(({sideNumber:R},x)=>{const q=O[1-x].participantId;return R&&{[R]:q}}).filter(Boolean));for(const R of O){const{participantId:x,sideNumber:q,bye:V}=R;if(V)continue;const Y=A===q,z=Z=>{var it,st;const nt=(it=s[Z])==null?void 0:it.participant,rt=nt==null?void 0:nt.participantType,K=[{participantId:Z,participantType:rt}];if(rt!==vr)for(const dt of(nt==null?void 0:nt.individualParticipantIds)||[]){const mt=(st=s[dt])==null?void 0:st.participant;K.push({participantType:mt==null?void 0:mt.participantType,participantId:dt})}return K},J=(Z,nt)=>{if(o){if(s[Z].matchUps[C]={participantWon:Y,matchUpType:N,structureId:d,sideNumber:q,matchUpId:C,eventId:P,drawId:U},i){const rt=z(nt);s[Z].matchUps[C].opponentParticipantInfo=rt}b&&(s[Z].matchUps[C].collectionId=b)}I&&vD({finishingPositionRange:u,participantMap:s,participantWon:Y,finishingRound:l,matchUpStatus:f,participantId:Z,stageSequence:p,roundNumber:h,structureId:d,matchUpId:C,drawId:U,stage:g}),(n||e)&&Ty({participantMap:s,participantId:Z,matchUpStatus:f,roundPosition:T,matchUpType:N,roundNumber:h,structureId:d,matchUpId:C,schedule:v,drawId:U,score:m})},Q=(Z,nt)=>{Z&&(Z.partnerParticipantIds||(Z.partnerParticipantIds=[]),Z.partnerParticipantIds.includes(nt)||Z.partnerParticipantIds.push(nt))},X=({participantId:Z,partnerParticipantId:nt})=>{var rt,K,it,st,dt,mt;a&&Q((K=(rt=s[Z])==null?void 0:rt.draws)==null?void 0:K[U],nt),c&&Q((st=(it=s[Z])==null?void 0:it.events)==null?void 0:st[P],nt),o&&Q((mt=(dt=s[Z])==null?void 0:dt.matchUps)==null?void 0:mt[C],nt)};if(x&&s[x]){const Z=D==null?void 0:D[q];J(x,Z),i&&Z&&(s[x].opponents[Z]={participantId:Z,matchUpId:C,eventId:P,drawId:U});const nt=((M=s[x])==null?void 0:M.participant.participantType)===_t,rt=((w=s[x])==null?void 0:w.participant.individualParticipantIds)||[];if(E){if(r){const K=it=>s[it].matchUps[E]={participantWon:S===q,matchUpType:_n.Team,matchUpId:E,sideNumber:q};K(x),rt.forEach(K)}if(a&&!s[x].draws[U]){const K=(_=(k=y.find(dt=>dt.sideNumber===q))==null?void 0:k.participant)==null?void 0:_.participantId,it=(W=(L=(F=s[K])==null?void 0:F.draws)==null?void 0:L[U])==null?void 0:W.entryStatus,st=dt=>s[dt].draws[U]={entryStatus:it,eventId:P,drawId:U};st(x),rt.forEach(st)}}if(nt&&(rt.forEach(K=>s[K]&&J(K,Z)),rt.forEach((K,it)=>{const st=rt[1-it];X({participantId:K,partnerParticipantId:st})}),c&&y)){const K=(H=(j=y.find(it=>it.sideNumber===q))==null?void 0:j.participant)==null?void 0:H.participantId;if(K){const it=(B=s[K])==null?void 0:B.events[P];it?(s[x].events[P]=it,rt.forEach(st=>s[st].events[P]=it)):console.log("Missing teamEntry",{eventId:P,teamParticipantId:K})}}if(A){const K=it=>{Y?(s[it].counters[N].wins+=1,s[it].counters.wins+=1,f===ce&&(s[it].counters[N].walkoverWins+=1,s[it].counters.walkoverWins+=1),f===te&&(s[it].counters[N].defaultWins+=1,s[it].counters.defaultWins+=1)):(s[it].counters[N].losses+=1,s[it].counters.losses+=1,f===ce&&(s[it].counters[N].walkovers+=1,s[it].counters.walkovers+=1),f===te&&(s[it].counters[N].defaults+=1,s[it].counters.defaults+=1))};K(x),rt.forEach(K)}}}}function CD(t){var D,M,w,k,_;const{participantFilters:e,convertExtensions:n,policyDefinitions:r,tournamentRecord:s,usePublishState:i,contextProfile:o,participantMap:c,withPotentialMatchUps:a,withRankingProfile:u,withScheduleTimes:l,withScheduleItems:f,scheduleAnalysis:p,withTeamMatchUps:h,withStatistics:d,withOpponents:m,withMatchUps:g,withSeeding:I,withEvents:S,withDraws:T}=t;f&&console.log({withScheduleItems:f});const E=e==null?void 0:e.participantIds,y=F=>{var W,j;const L=[F];return L.push(F),(j=(W=c[F])==null?void 0:W.participant.individualParticipantIds)==null||j.forEach(H=>L.push(H)),L.some(H=>!(E!=null&&E.length)||E.includes(H.relevantParticipantId))?L:[]},b={withMatchUps:g||u,withEvents:S||u,withDraws:T||u,withPotentialMatchUps:a,withRankingProfile:u,withScheduleTimes:l,scheduleAnalysis:p,withTeamMatchUps:h,withStatistics:d,participantMap:c,withOpponents:m,withSeeding:I},N=[],A={},C=[],v={},P={},U={},O=({eventType:F,scaleNames:L,participantId:W})=>{var j,H,B,R;return(R=(B=(H=(j=c[W].participant)==null?void 0:j.rankings)==null?void 0:H[F])==null?void 0:B.find(x=>L.includes(x.scaleName)))==null?void 0:R.scaleValue};for(const F of(s==null?void 0:s.events)||[]){if(e!=null&&e.eventIds&&!e.eventIds.includes(F.eventId))continue;const{drawDefinitions:L=[],extensions:W,eventType:j,eventName:H,category:B,entries:R,eventId:x,gender:q}=F,{flightProfile:V}=be({event:F}),Y=V==null?void 0:V.flights,z=oD({event:F}),J=z==null?void 0:z.publishedSeeding;if(z&&(v[x]=z),S||I||u){const Q=n?Object.assign({},...rf(W)):{};P[x]={...Q,eventName:H,eventType:j,category:B,eventId:x,gender:q};const X=[B==null?void 0:B.categoryName,B==null?void 0:B.ageCategoryCode].filter(Boolean);for(const Z of R){const{participantId:nt}=Z;if(!nt||!c[nt])continue;const rt=O({eventType:j,scaleNames:X,participantId:nt});let K,it;if(I){const mt=c[nt].participant;({seedAssignments:K,seedValue:it}=cD({publishedSeeding:J,usePublishState:i,withSeeding:I,participant:mt,event:F}))}const st=mt=>{var Nt,St;if((St=(Nt=c[mt])==null?void 0:Nt.events)!=null&&St[x])return;const Mt=c[mt];AD({extensionConversions:Q,seedAssignments:K,participant:Mt,withSeeding:I,seedValue:it,eventId:x,ranking:rt,entry:Z})};st(nt),(c[nt].participant.individualParticipantIds||[]).forEach(st)}}if(T||u||I){const Q=X=>X?Object.assign({},...X.map(Z=>({[Z.participantId]:Z}))):void 0;for(const X of L){const{structures:Z=[],drawOrder:nt,drawName:rt,drawType:K,entries:it,drawId:st}=X,dt=(D=Y==null?void 0:Y.find(Dt=>Dt.drawId===st))==null?void 0:D.flightNumber,mt=[B==null?void 0:B.categoryName,B==null?void 0:B.ageCategoryCode].filter(Boolean),Mt=(X.structures||[]).sort((Dt,at)=>Pi(Dt,at)).map(({structureId:Dt,structures:at})=>[Dt,...(at||[]).map(({structureId:ot})=>ot)]).flat(1/0);let Nt,St,ct,Et,gt=0;const Ft=Z.filter(({stage:Dt,stageSequence:at})=>Dt===It&&at===1||Dt===Pt).flatMap(Dt=>{const{seedAssignments:at,stageSequence:ot,stage:Lt}=Dt,{positionAssignments:ft}=ee({structure:Dt});return Lt===It?(gt=(ft==null?void 0:ft.length)??0,ct=ft,Et=at):ot===1&&(Nt=ft,St=at),ft}).map(({participantId:Dt})=>Dt).filter(Boolean),yt=Q(Et),wt=Q(St),Xt=it.filter(({participantId:Dt})=>Ft.includes(Dt)),$t=(M=v==null?void 0:v[x])==null?void 0:M.publishedSeeding,At=!i||($t==null?void 0:$t.published)&&(((w=$t==null?void 0:$t.drawIds)==null?void 0:w.length)===0||((k=$t==null?void 0:$t.drawIds)==null?void 0:k.includes(st)));for(const Dt of Xt){const{entryStatus:at,entryStage:ot,entryPosition:Lt,participantId:ft}=Dt,Ct=O({participantId:ft,scaleNames:mt,eventType:j}),Ut=Kt=>{var Ee,Un,Xe,Lr,jn,ue;if((Ee=c[Kt].draws)!=null&&Ee[st])return;const ut=I&&At,Rt=ut?{}:void 0,ne=ut?((Un=yt==null?void 0:yt[ft])==null?void 0:Un.seedValue)||((Xe=yt==null?void 0:yt[ft])==null?void 0:Xe.seedNumber):void 0,Ae=ut?((Lr=wt==null?void 0:wt[ft])==null?void 0:Lr.seedValue)||((jn=wt==null?void 0:wt[ft])==null?void 0:jn.seedNumber):void 0;Rt&&ne&&(Rt[It]=ne),Rt&&Ae&&(Rt[Pt]=ne),(S||u)&&(ut?c[Kt].events[x].seedValue=ne||Ae:(ue=c[Kt].events[x])!=null&&ue.seedValue&&(c[Kt].events[x].seedValue=void 0)),(T||u)&&(c[Kt].draws[st]=bt({seedAssignments:Rt,entryPosition:Lt,entryStatus:at,entryStage:ot,eventId:x,ranking:Ct,drawId:st},!1,!1,!0))};if(![Or,po].includes(at)){Ut(ft);const Kt=c[ft].participant.individualParticipantIds||[];Kt==null||Kt.forEach(Ut)}}U[st]={qualifyingPositionAssignments:Nt,qualifyingSeedAssignments:St,mainPositionAssignments:ct,qualifyingSeedingMap:wt,mainSeedAssignments:Et,orderedStructureIds:Mt,mainSeedingMap:yt,flightNumber:dt,drawOrder:nt,drawName:rt,drawType:K,drawSize:gt,drawId:st}}}if(u||p||h||d||m||g||T){const Q=!!p||a,X=((_=si({afterRecoveryTimes:!!p,policyDefinitions:r,tournamentRecord:s,inContext:!0,contextProfile:o,participantMap:c,nextMatchUps:Q,event:F}))==null?void 0:_.matchUps)??[];for(const Z of X){const{finishingPositionRange:nt,potentialParticipants:rt,tieMatchUps:K=[],sides:it=[],winningSide:st,matchUpType:dt,matchUpId:mt,eventId:Mt,drawId:Nt,collectionId:St,stageSequence:ct,finishingRound:Et,matchUpStatus:gt,roundPosition:Ft,roundNumber:yt,structureId:wt,schedule:Xt,score:$t,stage:At}=Z;A[mt]=Z;const Dt={finishingPositionRange:nt,finishingRound:Et,stageSequence:ct,roundPosition:Ft,collectionId:St,roundNumber:yt,structureId:wt,schedule:Xt,eventId:Mt,drawId:Nt,score:$t,stage:At};yy({...Dt,...b,matchUpStatus:gt,winningSide:st,matchUpType:dt,matchUpId:mt,sides:it});for(const at of K){const{winningSide:ot,sides:Lt=[],matchUpId:ft,matchUpStatus:Ct,matchUpType:Ut}=at;yy({...Dt,...b,winningSide:ot,tieWinningSide:st,matchUpTieId:mt,matchUpId:ft,sides:Lt,matchUpSides:it,matchUpStatus:Ct,matchUpType:Ut})}if(Array.isArray(rt)&&(Q||p||l)){const at=rt.flat().map(kn("participantId")).filter(Boolean);at==null||at.forEach(ot=>{const Lt=y(ot);Lt==null||Lt.forEach(ft=>{c[ft]&&(c[ft].potentialMatchUps[mt]=bt({tournamentId:s==null?void 0:s.tournamentId,matchUpId:mt,eventId:Mt,drawId:Nt}))}),(p||l)&&Ty({potential:!0,participantMap:c,participantId:ot,matchUpStatus:gt,roundPosition:Ft,structureId:wt,matchUpType:dt,roundNumber:yt,matchUpId:mt,schedule:Xt,drawId:Nt,score:$t})})}}C.push(...X)}}if(d||u||p){const F=Object.values(c);for(const L of F){const{wins:W,losses:j,[Oe]:{wins:H,losses:B},[me]:{wins:R,losses:x}}=L.counters,q=(V,Y,z)=>{const J=Y+z,Q=Y,X=J&&Q/J;L.statistics[V]={denominator:J,numerator:Q,statValue:X,statCode:V}};if(d&&(q(ua,W,j),q(`${ua}.${Oe}`,H,B),q(`${ua}.${me}`,R,x)),u){const V=(Y=[])=>Math.abs(Y[0]-Y[1]);for(const Y of Object.keys(L.draws)){const{orderedStructureIds:z=[],flightNumber:J}=U[Y]||{};if(L.structureParticipation&&z.length){let Q,X=0;const Z=z.map(nt=>{const rt=L.structureParticipation[nt];if(!rt)return;Q||(Q=rt==null?void 0:rt.finishingPositionRange),V(Q)>V(rt==null?void 0:rt.finishingPositionRange)&&(Q=rt==null?void 0:rt.finishingPositionRange);const K=rt.stage!==Pt;return K&&(X+=1),bt({...rt,participationOrder:K?X:void 0,flightNumber:J})}).filter(Boolean);L.draws[Y]&&(L.draws[Y].finishingPositionRange=Q,L.draws[Y].structureParticipation=Z)}}}if(p){const V=or(p)?p.scheduledMinutesDifference:0,Y=L.scheduleItems||[],z=L.potentialMatchUps||{},J=Y.reduce((X,Z)=>{const{scheduledDate:nt,scheduledTime:rt}=Z;return X[nt]||(X[nt]=[]),rt&&X[nt].push(Z),X},{});Object.values(J).forEach(X=>X.sort(_g));for(const X of Y){const{typeChangeTimeAfterRecovery:Z,timeAfterRecovery:nt,scheduledDate:rt,scheduledTime:K}=X,it=J[rt],st=jt(K);for(const dt of it){if(dt.matchUpId===X.matchUpId||[ce,te].includes(dt.matchUpStatus)&&!dt.scoreHasValue)continue;const Nt=X.matchUpType!==dt.matchUpType&&Z||nt,St=X.drawId===dt.drawId,ct=z[X.matchUpId]&&z[dt.matchUpId],Et=jt(dt.scheduledTime),gt=Math.abs(Et-st);(V&&!isNaN(V)?gt<=V:jt(Nt)>jt(dt.scheduledTime))&&!(ct&&St)&&L.scheduleConflicts.push({priorScheduledMatchUpId:dt.matchUpId,matchUpIdWithConflict:X.matchUpId})}}const Q=L.participant.participantId;L.scheduleConflicts.length&&N.push(Q),c[Q].scheduleConflicts=L.scheduleConflicts}}}return{participantIdsWithConflicts:N,eventsPublishStatuses:v,derivedEventInfo:P,derivedDrawInfo:U,mappedMatchUps:A,participantMap:c,matchUps:C}}function Fi(t){const{withIndividualParticipants:e,participantFilters:n={},withPotentialMatchUps:r,withRankingProfile:s,convertExtensions:i,policyDefinitions:o,withScheduleItems:c,tournamentRecord:a,scheduleAnalysis:u,withSignInStatus:l,withTeamMatchUps:f,withScaleValues:p,usePublishState:h,contextProfile:d,withStatistics:m,withOpponents:g,withMatchUps:I,internalUse:S,withSeeding:T,withEvents:E,withDraws:y,withISO2:b,withIOC:N}=t;if(!a)return{error:et};(I||s)&&fr({tournamentRecord:a});let{participantMap:A}=dT({withIndividualParticipants:e,convertExtensions:i,policyDefinitions:o,tournamentRecord:a,withSignInStatus:l,withScaleValues:p,internalUse:S,withISO2:b,withIOC:N});const C=CD({withMatchUps:I??s,withEvents:E??s,withDraws:y??s,withPotentialMatchUps:r,participantFilters:n,withRankingProfile:s,convertExtensions:i,withScheduleItems:c,policyDefinitions:o,tournamentRecord:a,scheduleAnalysis:u,withTeamMatchUps:f,usePublishState:h,withStatistics:m,participantMap:A,withOpponents:g,contextProfile:d,withSeeding:T}),{participantIdsWithConflicts:v,eventsPublishStatuses:P,derivedEventInfo:U,derivedDrawInfo:O,mappedMatchUps:D}=C,M=C.matchUps;A=C.participantMap;const w=u??r,k=Object.values(A).map(({potentialMatchUps:F,scheduleConflicts:L,participant:W,statistics:j,opponents:H,matchUps:B,events:R,draws:x})=>{const q=Object.values(x),V=Object.values(H);return g&&(q==null||q.forEach(Y=>{Y.opponents=V.filter(z=>z.drawId===Y.drawId)})),bt({...W,scheduleConflicts:u?L:void 0,draws:y||s?q:void 0,events:E||s?Object.values(R):void 0,matchUps:I||s?Object.values(B):void 0,opponents:g?V:void 0,potentialMatchUps:w?Object.values(F):void 0,statistics:m?Object.values(j):void 0},!1,!1,!0)}),_=Hl({participants:k,participantFilters:n,tournamentRecord:a});return{participantIdsWithConflicts:v,eventsPublishStatuses:P,derivedEventInfo:U,derivedDrawInfo:O,mappedMatchUps:D,participantMap:A,participants:_,...$,matchUps:M}}function Wp(t,e,n){return!t&&e?e:t&&!e||typeof t!="object"||typeof e!="object"?t:Vt(Object.keys(t).concat(Object.keys(e))).reduce((s,i)=>{if(!e[i])s[i]=t[i];else if(!t[i])s[i]=e[i];else if(typeof t[i]!=typeof e[i])s[i]=e[i];else if(Array.isArray(t[i]))if(n===!0||Array.isArray(n)&&n.includes(i)){const o=Vt(t[i].map(c=>JSON.stringify(c)).concat(e[i].map(c=>JSON.stringify(c)))).map(c=>JSON.parse(c));s[i]=o}else s[i]=e[i];else typeof t[i]=="object"?s[i]=Wp(t[i],e[i],n):s[i]=e[i];return s},{})}function PD(t){const{tournamentRecords:e}=t||{};if(typeof e!="object"||!Object.keys(e).length)return{error:Gt};const n={},r=[],s={},i={},o=[],c={},a=[];for(const u of Object.values(e)){const{participantIdsWithConflicts:l,mappedMatchUps:f,participantMap:p,participants:h,matchUps:d,derivedEventInfo:m,derivedDrawInfo:g}=Fi({tournamentRecord:u,...t});Object.assign(c,f),Object.assign(n,p),Object.assign(s,m),Object.assign(i,g),r.push(...h??[]),o.push(...d??[]),l==null||l.forEach(I=>{a.includes(I)||a.push(I)})}return{participantIdsWithConflicts:a,derivedEventInfo:s,derivedDrawInfo:i,participantMap:n,mappedMatchUps:c,participants:r,...$,matchUps:o}}function UD(t){const{tournamentRecords:e}=t||{};if(typeof e!="object"||!Object.keys(e).length)return{error:Gt};let n=[];const r=[],s=[];for(const i of Object.values(e)){const{tournamentParticipants:o,participantIdsWithConflicts:c}=dn({tournamentRecord:i,...t});for(const a of o){const{participantId:u}=a;s.includes(u)?n=n.map(l=>l.participantId!==u?l:Wp(l,a,!0)):(s.push(u),n.push(a))}c==null||c.forEach(a=>{r.includes(a)||r.push(a)})}return{competitionParticipants:n,participantIdsWithConflicts:r,...$}}function Ey({policyDefinitions:t,tournamentRecords:e,participantId:n,inContext:r,personId:s}){if(!e)return{error:Gt};if(typeof n!="string"&&typeof s!="string")return{error:Tt,stack:"publicFindParticipant"};let i,o;for(const c of Object.values(e)){o=c.tournamentId;const{tournamentParticipants:a}=dn({policyDefinitions:t,tournamentRecord:c,inContext:r});if(i=Ps({tournamentParticipants:a,internalUse:!0,policyDefinitions:t,participantId:n,personId:s}),i)break}return{participant:i,tournamentId:o,...$}}const by=({penaltyId:t=Yt()}={})=>({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});function Ny({refereeParticipantId:t,tournamentRecord:e,participantIds:n,penaltyCode:r,penaltyType:s,extensions:i,penaltyId:o,matchUpId:c,issuedAt:a,notes:u}){if(!e)return{error:et};if(!n)return{error:Ce};if(!s)return{error:Tv};const f=((e==null?void 0:e.participants)||[]).filter(d=>n.includes(d.participantId));if(!f.length)return{error:_e};const p=new Date().toISOString(),h=Object.assign(by({penaltyId:o}),{refereeParticipantId:t,penaltyCode:r,penaltyType:s,matchUpId:c,notes:u,issuedAt:a,createdAt:p});return Array.isArray(i)&&i.forEach(d=>ae({element:h,extension:d})),f.forEach(d=>{d.penalties||(d.penalties=[]),d.penalties.push(h)}),Ht({topic:nn,payload:{tournamentId:e.tournamentId,participants:f}}),{...$,penaltyId:h.penaltyId}}function Ay({tournamentRecord:t,penaltyId:e}){if(!t)return{error:et};if(!e)return{error:hg};const n=(t==null?void 0:t.participants)||[],r=[];let s=!1,i;return n.forEach(o=>{let c=!1;o.penalties=(o.penalties||[]).filter(a=>(a.penaltyId===e&&(c=!0,s||(i=a,s=!0)),c&&r.push(o),a.penaltyId!==e))}),i&&Ht({topic:nn,payload:{tournamentId:t.tournamentId,participants:r}}),i?{...$,penalty:i}:{error:Cu}}function vy({tournamentRecord:t}){if(!t)return{error:et};const n=((t==null?void 0:t.participants)||[]).reduce((r,s)=>{const{participantId:i}=s;return(s.penalties||[]).forEach(o=>{const{penaltyId:c}=o||{};r[c]?r[c].participants.push(i):r[c]={...o,participantIds:[i]}}),r},{});return{penalties:Object.values(n)}}function Cy({tournamentRecord:t,modifications:e,penaltyId:n}){if(!t)return{error:et};if(!e)return{error:tt,modifications:e};if(!n)return{error:hg};const r=(t==null?void 0:t.participants)||[],s=Object.keys(by()).filter(a=>a!=="penaltyId"),i=Object.keys(e).filter(a=>s.includes(a));if(!i.length)return{error:Qd};let o;const c=[];return r.forEach(a=>{let u=!1;a.penalties=(a.penalties||[]).map(l=>(l.penaltyId===n&&(u=!0,i.forEach(f=>Object.assign(l,{[f]:e[f]})),o||(o=l)),l)),u&&c.push(a)}),o&&Ht({topic:nn,payload:{tournamentId:t.tournamentId,participants:c}}),o?{...$,penalty:o}:{error:Cu}}function OD(t){const{tournamentRecords:e,participantIds:n}=t;let r;for(const s of Object.values(e)){const{tournamentParticipants:i}=dn({tournamentRecord:s}),o=xa(i).filter(c=>n.includes(c));o.length&&(r=Ny({...t,penaltyId:t.penaltyId||r,tournamentRecord:s,participantIds:o}).penaltyId)}return r?{...$,penaltyId:r}:{error:_e}}function MD(t){const{tournamentRecords:e}=t;if(typeof e!="object"||!Object.keys(e).length)return{error:Gt};for(const n of Object.values(e)){const r=Cy({tournamentRecord:n,...t});if(r.error&&r.error!==Cu)return r}return{...$}}function DD(t){const{tournamentRecords:e}=t;if(typeof e!="object"||!Object.keys(e).length)return{error:Gt};for(const n of Object.values(e)){const r=Ay({tournamentRecord:n,...t});if(r.error&&r.error!==Cu)return r}return{...$}}function wD({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:Gt};const e=[];for(const n of Object.values(t)){const{penalties:r}=vy({tournamentRecord:n});e.push(...r||[])}return{penalties:e}}function wo({drawDefinition:t,structureId:e,matchUpId:n,structure:r,matchUp:s,eventId:i,event:o}){let c;if(e=(r==null?void 0:r.structureId)??e,n=(s==null?void 0:s.matchUpId)??n,(n||e)&&!t)return{error:lt};if(i&&o)c=Bs(o);else if(n){if(t&&(!s||!r)){const a=ie({drawDefinition:t,matchUpId:n});if(a.error)return a;r||(r=a.structure),s||(s=a.matchUp)}c=jc({item:s,drawDefinition:t,structure:r,event:o})||jc({item:r,drawDefinition:t,structure:r,event:o})||Bs(t)||Bs(o)}else if(t&&e){if(!r){const a=Ot({drawDefinition:t,structureId:e});if(a.error)return a;r=a==null?void 0:a.structure}c=jc({item:r,drawDefinition:t,structure:r,event:o})||Bs(t)||Bs(o)}else c=Bs(t)||Bs(o);return c?{...$,tieFormat:c,matchUp:s,structure:r}:G({result:{error:Nu}})}function ql({drawDefinition:t,auditData:e}){const{extension:n}=xn({name:Qi,element:t}),r={name:Qi,value:Array.isArray(n==null?void 0:n.value)?n==null?void 0:n.value.concat(e):[e]};ae({element:t,extension:r})}function Yl({matchUp:t,updateInProgressMatchUps:e}){return!t.winningSide&&![We].includes(t.matchUpStatus)&&(e||t.matchUpStatus!==Gr&&!Be(t))}function Hp(t,e){const n=Object.keys(t);return qe(n,Object.keys(e)).length===n.length}function kD({updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:n,structure:r,tieFormat:s,eventId:i,matchUp:o,event:c}){var I,S,T,E;const a="updateTieFormat";let u=0,l=0;const f=s==null?void 0:s.collectionDefinitions.reduce((y,b)=>(y[b.collectionId]=(y[b.collectionId]||0)+b.matchUpCount,y),{}),p=({tieFormat:y})=>{const b=y==null?void 0:y.collectionDefinitions.reduce((N,A)=>(N[A.collectionId]=(N[A.collectionId]||0)+A.matchUpCount,N),{});return Hp(f,b)},h=(I=wo({drawDefinition:n}))==null?void 0:I.tieFormat,d=(S=wo({event:c}))==null?void 0:S.tieFormat;if(c&&i){for(const y of c.drawDefinitions??[])m({drawDefinition:y});c.tieFormat=s,l+=1}else if(o){if(!o.tieMatchUps)return G({result:{error:qn},stack:a});const y=Mn((T=o.tieMatchUps)==null?void 0:T.map(({collectionId:b})=>b));if(Hp(f,y))if(Yl({matchUp:o,updateInProgressMatchUps:t}))o.tieFormat=s,l+=1;else return G({result:{error:cg},info:"matchUp is IN_PROGRESS or COMPLETE"});else return G({context:{collectionMap:f,matchUpMap:y},result:{error:li},info:"on matchUp",stack:a});qt({tournamentId:e==null?void 0:e.tournamentId,eventId:c==null?void 0:c.eventId,context:a,drawDefinition:n,matchUp:o})}else if(r){const b=(E=g({inheritedTieFormat:h||d,structure:r}))==null?void 0:E.modifiedCount;b&&(u+=b),r.tieFormat=s,l+=1,Zt({structureIds:[r.structureId],eventId:c==null?void 0:c.eventId,drawDefinition:n})}else if(n)m({drawDefinition:n}),n.tieFormat=s,l+=1;else return{error:lt};return{...$,modifiedCount:l,modifiedStructuresCount:u,tieFormat:s};function m({drawDefinition:y}){var A;const b=y.structures||[],N=[];for(const C of b){if(C.tieFormat)continue;const P=(A=g({inheritedTieFormat:d,structure:C}))==null?void 0:A.modifiedCount;if(P){u+=P;const U=C.structureId;N.push(U)}}return Zt({structureIds:N,eventId:c==null?void 0:c.eventId,drawDefinition:y}),N.length}function g({inheritedTieFormat:y,structure:b}){var C,v;let N=0;const A=((C=Qt({matchUpFilters:{matchUpTypes:[Jt]},structure:b}))==null?void 0:C.matchUps)||[];for(const P of A){let U=!1;const O=Mn((v=P.tieMatchUps)==null?void 0:v.map(({collectionId:D})=>D));if(Hp(f,O))P.tieFormat&&p(P)&&Yl({matchUp:P,updateInProgressMatchUps:t})&&(P.tieFormat=Dr(s),U=!0);else if(y)P.tieFormat=y,U=!0;else return G({result:{error:Nu},stack:a});U&&(N+=1,qt({tournamentId:e==null?void 0:e.tournamentId,drawDefinition:n,context:a,eventId:i,matchUp:P}))}return{modifiedCount:N}}}function zl({updateInProgressMatchUps:t=!1,tournamentRecord:e,collectionOrder:n,collectionName:r,drawDefinition:s,matchUpFormat:i,tieFormatName:o,matchUpCount:c,collectionId:a,matchUpType:u,structureId:l,matchUpId:f,category:p,eventId:h,gender:d,event:m,collectionValueProfiles:g,collectionValue:I,matchUpValue:S,scoreValue:T,setValue:E}){var F;if(i&&!nr(i))return{error:tt};if(r&&typeof r!="string")return{error:tt};if(d&&!Object.values(iS).includes(d))return{error:tt};if(p&&typeof p!="object")return{error:tt};const y="modifyCollectionDefinition",b={collectionValueProfiles:g,collectionValue:I,matchUpValue:S,scoreValue:T,setValue:E};if(!Object.values(b).filter(Boolean).length&&!n&&!r&&!c&&!i)return G({result:{error:Tt},stack:y});if(Object.values(b).filter(Boolean).length>1)return G({result:{info:"Only one value assignment allowed per collectionDefinition",error:tt},stack:y});let N=wo({drawDefinition:s,structureId:l,matchUpId:f,eventId:h,event:m});if(N.error)return G({result:N,stack:y});const{matchUp:A,structure:C,tieFormat:v}=N,P=Dr(v),U=P.collectionDefinitions.find(L=>L.collectionId===a);if(!U)return G({result:{error:an},stack:y});const O=I||S||T||E;if(O||g){if(O){if(!oe(O))return G({result:{error:tt,value:O}})}else if(g){const L=Bg({matchUpCount:U.matchUpCount,collectionValueProfiles:g});if(L.errors)return G({result:{error:tt,info:L.errors},stack:y})}U.collectionValue=void 0,U.matchUpValue=void 0,U.scoreValue=void 0,U.setValue=void 0,Object.assign(U,b)}if((T||E)&&U.collectionGroupNumber){const L=U.collectionGroupNumber;P.collectionDefinitions=P.collectionDefinitions.map(W=>{const{collectionGroupNumber:j,...H}=W;return j===L?H:W}),P.collectionGroups=P.collectionGroups.filter(({groupNumber:W})=>W!==L)}const{aggregateValue:D,valueGoal:M}=gc(P);P.winCriteria=bt({aggregateValue:D,valueGoal:M});const w=v==null?void 0:v.winCriteria.valueGoal,k=v==null?void 0:v.winCriteria.aggregateValue;(w&&w!==M||D&&!k)&&delete P.tieFormatName,o&&(P.tieFormatName=o),n&&(U.collectionOrder=n),r&&(U.collectionName=r),i&&(U.matchUpFormat=i),u&&(U.matchUpType=u),p&&(U.category=p),d&&(U.gender=d);const _=bt(P);if(N=vn({tieFormat:_}),N.error)return G({result:N,stack:y});if(N=kD({tieFormat:_,updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:s,structure:C,eventId:h,matchUp:A,event:m}),!N.error){const{appliedPolicies:L}=ge({tournamentRecord:e});if((F=L==null?void 0:L.audit)!=null&&F[Qi]){const W=bt({drawId:s==null?void 0:s.drawId,collectionDefinition:U,action:y,structureId:l,matchUpId:f,eventId:h});ql({drawDefinition:s,auditData:W})}}return G({result:N,stack:y})}function oi(t){const{method:e,tournamentRecords:n,...r}=t,s=t.tournamentId||Fl(r);if(typeof s!="string")return{error:is};const i=n[s];return i?e({...r,tournamentRecord:i}):{error:et}}function _D(t){return oi({...t,method:zl})}function Oc({tieFormat:t,orderMap:e}){const n=Dr(t);return n.collectionDefinitions.forEach(r=>{const s=e[r.collectionId];s&&(r.collectionOrder=s)}),n.collectionDefinitions.sort((r,s)=>jo(r.collectionOrder)-jo(s.collectionOrder)),n}function qp({tournamentRecord:t,drawDefinition:e,structureId:n,matchUpId:r,orderMap:s,eventId:i,matchUp:o,event:c}){if(typeof s!="object"||!Object.values(s).every(a=>oe(a)))return G({result:{error:tt},context:{orderMap:s}});if(i&&(c!=null&&c.tieFormat))Py({tournamentRecord:t,event:c,orderMap:s});else if(r){const a=e&&ie({drawDefinition:e,matchUpId:r});if(a!=null&&a.error)return a;if(o=a.matchUp,!o)return{error:Rn};o!=null&&o.tieFormat&&(o.tieFormat=Oc({tieFormat:o.tieFormat,orderMap:s}),qt({tournamentId:t==null?void 0:t.tournamentId,eventId:c==null?void 0:c.eventId,drawDefinition:e,matchUp:o}))}else if(n){const a=Ot({drawDefinition:e,structureId:n});if(a.error)return a;const u=a.structure;if(u!=null&&u.tieFormat)u.tieFormat=Oc({tieFormat:u.tieFormat,orderMap:s}),Uy({eventId:c==null?void 0:c.eventId,tournamentRecord:t,drawDefinition:e,structure:u,orderMap:s}),Zt({drawDefinition:e,structureIds:[u.structureId]});else if(e.tieFormat)Yp({structureIds:[n],tournamentRecord:t,drawDefinition:e,orderMap:s,event:c});else if(c!=null&&c.tieFormat)Py({structureIds:[n],tournamentRecord:t,orderMap:s,event:c});else return{error:an}}else if(e!=null&&e.tieFormat)Yp({tournamentRecord:t,drawDefinition:e,orderMap:s,event:c});else return{error:an};return{...$}}function Py({tournamentRecord:t,structureIds:e,orderMap:n,event:r}){const s=Oc({tieFormat:r.tieFormat,orderMap:n});e!=null&&e.length||(r.tieFormat=s);for(const i of r.drawDefinitions??[])Yp({tournamentRecord:t,drawDefinition:i,structureIds:e,orderMap:n,event:r})}function Yp({tournamentRecord:t,drawDefinition:e,structureIds:n,orderMap:r,event:s}){const i=e.tieFormat??(s==null?void 0:s.tieFormat),o=Oc({tieFormat:i,orderMap:r});n!=null&&n.length||(e.tieFormat=o);const c=[];for(const a of e.structures??[])n!=null&&n.length&&!n.includes(a.structureId)||((a.tieFormat||n!=null&&n.includes(a.structureId))&&(a.tieFormat=Oc({tieFormat:a.tieFormat??e.tieFormat??(s==null?void 0:s.tieFormat),orderMap:r})),Uy({eventId:s==null?void 0:s.eventId,tournamentRecord:t,drawDefinition:e,structure:a,orderMap:r}),c.push(a.structureId));Zt({drawDefinition:e,structureIds:c})}function Uy({tournamentRecord:t,drawDefinition:e,structure:n,orderMap:r,eventId:s}){var o;const i=(o=Qt({matchUpFilters:{matchUpTypes:[Jt]},structure:n}))==null?void 0:o.matchUps;for(const c of i)c.tieFormat&&(c.tieFormat=Oc({tieFormat:c.tieFormat,orderMap:r}),qt({tournamentId:t==null?void 0:t.tournamentId,drawDefinition:e,eventId:s,matchUp:c}))}function FD(t){return oi({...t,method:qp})}function Kl({updateInProgressMatchUps:t=!0,tieFormatComparison:e,tournamentRecord:n,drawDefinition:r,tieFormatName:s,collectionId:i,structureId:o,matchUpId:c,eventId:a,matchUp:u,event:l}){var v,P,U,O,D,M;const f="removeCollectionDefinition";let p=u?void 0:wo({drawDefinition:r,structureId:o,matchUpId:c,eventId:a,event:l});if(p!=null&&p.error)return G({result:p,stack:f});const h=p==null?void 0:p.structure;u=u??(p==null?void 0:p.matchUp);const d=p==null?void 0:p.tieFormat,m=Dr(d);if(p=vn({tieFormat:m}),p.error)return G({result:p,stack:f});const g=(v=m==null?void 0:m.collectionDefinitions)==null?void 0:v.find(w=>w.collectionId===i);if(!g)return G({result:{error:an,collectionId:i}});m.collectionDefinitions=m.collectionDefinitions.filter(w=>w.collectionId!==i),g.collectionGroupNumber&&(m.collectionDefinitions=m.collectionDefinitions.map(w=>{const{collectionGroupNumber:k,..._}=w;return _}),m.collectionGroups=m.collectionGroups.filter(({groupNumber:w})=>w!==g.collectionGroupNumber));const{aggregateValue:I,valueGoal:S}=gc(m);m.winCriteria=bt({aggregateValue:I,valueGoal:S});const T=d==null?void 0:d.winCriteria.valueGoal,E=d==null?void 0:d.winCriteria.aggregateValue;(T&&T!==S||I&&!E)&&(s?m.tieFormatName=s:delete m.tieFormatName);let y=[];c&&u?y=[u]:o&&h?y=((P=Qt({matchUpFilters:{matchUpTypes:[Jt]},structure:h}))==null?void 0:P.matchUps)||[]:r?y=((U=tr({matchUpFilters:{matchUpTypes:[Jt]},drawDefinition:r}))==null?void 0:U.matchUps)||[]:l&&(y=((O=si({matchUpFilters:{matchUpTypes:[Jt]},drawDefinition:r}))==null?void 0:O.matchUps)||[]);const b=(y||[]).filter(w=>{var L,W;const k=(L=w.tieMatchUps)==null?void 0:L.filter(j=>j.collectionId===i),_=k==null?void 0:k.some(Be),F=e&&w.tieFormat?(W=Sc({descendant:w.tieFormat,ancestor:m}))==null?void 0:W.different:!1;return t&&!_||!w.winningSide&&w.matchUpStatus!==De&&(t||w.matchUpStatus!==Gr&&!Be(w)&&!F)});if(!b.length)return{error:zc};if(c&&u&&t){const w=(D=u.tieMatchUps)==null?void 0:D.filter(k=>k.collectionId===i);for(const k of w??[]){let _=Ja({matchUpId:k.matchUpId,tieMatchUpId:u==null?void 0:u.matchUpId,winningSide:void 0,removeScore:!0,tournamentRecord:n,drawDefinition:r,event:l});if(_.error||(_=ie({drawDefinition:r,matchUpId:c}),_.error))return _;u=_==null?void 0:_.matchUp}}const N=[];for(const w of b){for(const k of(w==null?void 0:w.sides)??[])k.lineUp=(k.lineUp??[]).map(_=>({participantId:_.participantId,collectionAssignments:((_==null?void 0:_.collectionAssignments)??[]).filter(F=>F.collectionId!==i)}));if(w.tieMatchUps=(w.tieMatchUps??[]).filter(k=>{const _=k.collectionId===i;return _&&N.push(k.matchUpId),!_}),w.tieFormat&&(w.tieFormat=Dr(m)),t){const k=ms({matchUpId:w.matchUpId,exitWhenNoValues:!0,tournamentRecord:n,drawDefinition:r,event:l});if(k.error)return k}qt({tournamentId:n==null?void 0:n.tournamentId,eventId:l==null?void 0:l.eventId,drawDefinition:r,context:f,matchUp:w})}N.length&&ei({tournamentId:n==null?void 0:n.tournamentId,matchUpIds:N,eventId:l==null?void 0:l.eventId,drawDefinition:r});const A=bt(m);if(p=vn({tieFormat:A}),p.error)return G({result:p,stack:f});if(a&&l)l.tieFormat=A;else if(c&&u)u.tieFormat=A;else if(h)h.tieFormat=A;else if(r)r.tieFormat=A;else if(!u||!r)return{error:lt};Zt({drawDefinition:r,eventId:l==null?void 0:l.eventId});const{appliedPolicies:C}=ge({tournamentRecord:n});if((M=C==null?void 0:C.audit)!=null&&M[Qi]){const w=bt({drawId:r==null?void 0:r.drawId,action:f,collectionId:i,structureId:o,matchUpId:c,eventId:a});ql({drawDefinition:r,auditData:w})}return{tieFormat:A,deletedMatchUpIds:N,targetMatchUps:b,...$}}function LD(t){return oi({...t,method:Kl})}function Jl({tieFormat:t,isMock:e,uuids:n}){const{collectionDefinitions:r}=t||{};return{tieMatchUps:(r||[]).map(i=>Ql({collectionDefinition:i,uuids:n,isMock:e})).filter(Boolean).flat()}}function Ql({collectionDefinition:t,matchUpsLimit:e,isMock:n,uuids:r}){const{matchUpCount:s,matchUpType:i,collectionId:o,processCodes:c}=t||{};return ht(0,e||s||0).map(u=>{const l=u+1;return{sides:[{sideNumber:1},{sideNumber:2}],matchUpId:(r==null?void 0:r.pop())||Yt(),matchUpStatus:pe.ToBePlayed,collectionPosition:l,collectionId:o,processCodes:c,matchUpType:i,isMock:n}})}function Zl({updateInProgressMatchUps:t=!0,collectionDefinition:e,tournamentRecord:n,referenceGender:r,drawDefinition:s,tieFormatName:i,enforceGender:o,structureId:c,matchUpId:a,matchUp:u,eventId:l,uuids:f,event:p}){var D,M,w;const h=ge({tournamentRecord:n,drawDefinition:s,event:p}).appliedPolicies??{};o=o??((M=(D=h==null?void 0:h[Jn])==null?void 0:D.participants)==null?void 0:M.enforceGender);const d=!!(o!==!1&&(p!=null&&p.gender)),{valid:m,errors:g}=cf({collectionDefinition:e,referenceGender:r,checkGender:d,event:p});if(!m)return{error:tt,errors:g};const I="addCollectionDefinition";let S=u?void 0:wo({drawDefinition:s,structureId:c,matchUpId:a,eventId:l,event:p});if(S!=null&&S.error)return{error:S.error};const T=S==null?void 0:S.structure;u=u??(S==null?void 0:S.matchUp);const E=S==null?void 0:S.tieFormat,y=Dr(E);if(S=vn({tieFormat:y}),S!=null&&S.error)return{error:S.error};if(!e.collectionId)e.collectionId=Yt();else if(y.collectionDefinitions.map(({collectionId:_})=>_).includes(e.collectionId))return{collectionId:e.collectionId,error:Dv};y.collectionDefinitions.push(e),y.collectionDefinitions.sort((k,_)=>(k.collectionOrder||0)-(_.collectionOrder||0)).forEach((k,_)=>k.collectionOrder=_+1);const{aggregateValue:b,valueGoal:N}=gc(y);y.winCriteria=bt({aggregateValue:b,valueGoal:N});const A=E==null?void 0:E.winCriteria.valueGoal,C=E==null?void 0:E.winCriteria.aggregateValue;(A&&A!==N||b&&!C)&&(i?y.tieFormatName=i:delete y.tieFormatName);const v=[],P=[];let U=[];const O=bt(y);if(S=vn({tieFormat:O}),S!=null&&S.error)return{error:S.error};if(l&&p){p.tieFormat=O;for(const k of p.drawDefinitions??[])if(!k.tieFormat)for(const _ of k.structures??[]){if(_.tieFormat)continue;const F=zp({updateInProgressMatchUps:t,collectionDefinition:e,structure:_,uuids:f});P.push(...F.newMatchUps),U.push(...F.targetMatchUps),v.push(_.structureId)}Xl({modifiedMatchUps:U,eventId:p==null?void 0:p.eventId,modifiedStructureIds:v,tournamentRecord:n,drawDefinition:s,addedMatchUps:P,stack:I})}else if(c&&T){T.tieFormat=O;const k=zp({updateInProgressMatchUps:t,collectionDefinition:e,structure:T,uuids:f});P.push(...k.newMatchUps),U=k.targetMatchUps,Xl({modifiedMatchUps:U,eventId:p==null?void 0:p.eventId,modifiedStructureIds:v,tournamentRecord:n,drawDefinition:s,addedMatchUps:P,stack:I})}else if(a&&u){if(!Yl({matchUp:u,updateInProgressMatchUps:t}))return{error:cg};u.tieFormat=O;const k=Ql({collectionDefinition:e,uuids:f});Array.isArray(u.tieMatchUps)||(u.tieMatchUps=[]),u.tieMatchUps.push(...k),P.push(...k),Xl({modifiedMatchUps:[u],eventId:p==null?void 0:p.eventId,modifiedStructureIds:v,tournamentRecord:n,drawDefinition:s,addedMatchUps:P,stack:I})}else if(s){s.tieFormat=O;for(const k of s.structures??[]){const _=zp({updateInProgressMatchUps:t,collectionDefinition:e,structure:k,uuids:f});v.push(c),P.push(..._.newMatchUps),U.push(..._.targetMatchUps)}Xl({modifiedMatchUps:U,eventId:p==null?void 0:p.eventId,tournamentRecord:n,drawDefinition:s,addedMatchUps:P,stack:I})}else return{error:lt};if((w=h==null?void 0:h.audit)!=null&&w[Qi]){const k=bt({drawId:s==null?void 0:s.drawId,collectionDefinition:e,action:I,structureId:c,matchUpId:a,eventId:l});ql({drawDefinition:s,auditData:k})}return{...$,tieFormat:O,targetMatchUps:U,addedMatchUps:P}}function zp({updateInProgressMatchUps:t,collectionDefinition:e,structure:n,uuids:r}){var c;const s=[],o=((c=Qt({matchUpFilters:{matchUpTypes:[Jt]},structure:n}))==null?void 0:c.matchUps).filter(a=>Yl({matchUp:a,updateInProgressMatchUps:t})&&!a.tieFormat);for(const a of o){const u=Ql({collectionDefinition:e,uuids:r});Array.isArray(a.tieMatchUps)||(a.tieMatchUps=[]),a.tieMatchUps.push(...u),s.push(...u)}return{newMatchUps:s,targetMatchUps:o}}function Xl({modifiedStructureIds:t,tournamentRecord:e,modifiedMatchUps:n,drawDefinition:r,addedMatchUps:s,eventId:i,stack:o}){Oi({tournamentId:e==null?void 0:e.tournamentId,matchUps:s,drawDefinition:r,eventId:i}),n==null||n.forEach(c=>{qt({tournamentId:e==null?void 0:e.tournamentId,drawDefinition:r,context:o,matchUp:c,eventId:i})}),Zt({structureIds:t,drawDefinition:r,eventId:i})}function RD(t){return oi({...t,method:Zl})}function BD(t){Object.assign(t,{inContext:!0});const{matchUp:e,error:n}=eu(t);return{matchUp:pt(e,!0,!0),error:n}}function eu({participantsProfile:t,afterRecoveryTimes:e,tournamentRecord:n,contextContent:r,contextProfile:s,drawDefinition:i,matchUpId:o,inContext:c,eventId:a,drawId:u,event:l}){if(!n)return{error:et};if(typeof o!="string")return{error:$e};if(!i||!l){const g=(He({tournamentRecord:n}).matchUps||[]).find(I=>I.matchUpId===o);if(!g)return{error:Ye};({eventId:a,drawId:u}=g),{event:l,drawDefinition:i}=Je({tournamentRecord:n,eventId:a,drawId:u})}if(!i)return{error:rr};s&&!r&&(r=Cs({tournamentRecord:n,contextProfile:s}));const f={surfaceCategory:(l==null?void 0:l.surfaceCategory)||n.surfaceCategory,indoorOutDoor:(l==null?void 0:l.indoorOutdoor)||n.indoorOutdoor,endDate:(l==null?void 0:l.endDate)||n.endDate,tournamentId:n.tournamentId,eventId:a||(l==null?void 0:l.eventId),drawId:u},{participants:p=[]}=Ao({participantsProfile:t,tournamentRecord:n,contextProfile:s,inContext:c}),{matchUp:h,structure:d}=ie({context:c?f:void 0,tournamentParticipants:p,afterRecoveryTimes:e,contextContent:r,drawDefinition:i,contextProfile:s,matchUpId:o,inContext:c,event:l});return{matchUp:h,structure:d,drawDefinition:i}}function Oy({tournamentRecord:t,drawDefinition:e,structureId:n,matchUpId:r,structure:s,eventId:i,drawId:o,event:c}){var h,d,m,g,I;if(!t)return{error:et};if(!o&&!c&&!n&&!r)return G({result:{error:Tt},stack:"getTieFormat"});i&&!c&&(c=(h=t.events)==null?void 0:h.find(S=>S.eventId===i));const a=eu({tournamentRecord:t,drawDefinition:e,matchUpId:r,drawId:o,event:c});if(r&&(a!=null&&a.error))return a;if(!e&&(a!=null&&a.drawDefinition)&&(e=a==null?void 0:a.drawDefinition),s=s??(a==null?void 0:a.structure),!s&&n&&!r){if(!e)return{error:Hn};const S=Ot({drawDefinition:e,structureId:n});if(S.error)return S;s=S.structure}const u=((s==null?void 0:s.tieFormat)||(s==null?void 0:s.tieFormatId))&&((d=hn({structure:s,drawDefinition:e,event:c}))==null?void 0:d.tieFormat),l=((e==null?void 0:e.tieFormat)||(e==null?void 0:e.tieFormatId))&&((m=hn({drawDefinition:e,event:c}))==null?void 0:m.tieFormat),f=(g=hn({event:c}))==null?void 0:g.tieFormat,p=(I=hn({matchUp:a==null?void 0:a.matchUp,drawDefinition:e,structure:s,event:c}))==null?void 0:I.tieFormat;return{...$,matchUp:a==null?void 0:a.matchUp,structureDefaultTieFormat:u,eventDefaultTieFormat:f,drawDefaultTieFormat:l,tieFormat:p,structure:s}}function xD({updateInProgressMatchUps:t,tournamentRecord:e,drawDefinition:n,targetMatchUps:r,tieFormat:s,event:i}){for(const o of r){const c=!!o.tieFormat;c&&(o.tieFormat=Dr(s));let a;if(t){const u=ms({matchUpId:o.matchUpId,exitWhenNoValues:!0,tournamentRecord:e,drawDefinition:n,event:i});if(u.error)return u;a=u.score}c&&!a&&qt({tournamentId:e==null?void 0:e.tournamentId,context:"updateTargetTeamMatchUps",eventId:i==null?void 0:i.eventId,matchUp:o,drawDefinition:n})}return{...$}}function $D({updateInProgressMatchUps:t,drawDefinition:e,structureId:n,structure:r,matchUpId:s,matchUp:i}){var a,u;let o=[];return s&&i?o=[i]:n&&r?o=((a=Qt({matchUpFilters:{matchUpTypes:[Jt]},structure:r}))==null?void 0:a.matchUps)||[]:e&&(o=((u=tr({matchUpFilters:{matchUpTypes:[Jt]},drawDefinition:e}))==null?void 0:u.matchUps)||[]),{targetMatchUps:o.filter(l=>!l.winningSide&&l.matchUpStatus!==De&&(t||l.matchUpStatus!==Gr&&!Be(l)))}}function My({updateInProgressMatchUps:t,originalValueGoal:e,tournamentRecord:n,wasAggregateValue:r,tieFormatName:s,drawDefinition:i,structureId:o,structure:c,tieFormat:a,matchUpId:u,matchUp:l,eventId:f,event:p}){const{aggregateValue:h,valueGoal:d}=gc(a);a.winCriteria=bt({aggregateValue:h,valueGoal:d}),(e&&e!==d||h&&!r)&&(s?a.tieFormatName=s:delete a.tieFormatName);const{targetMatchUps:m}=$D({updateInProgressMatchUps:t,drawDefinition:i,structureId:o,structure:c,matchUpId:u,matchUp:l});xD({updateInProgressMatchUps:t,tournamentRecord:n,targetMatchUps:m,drawDefinition:i,tieFormat:a,event:p});const g=bt(a),I=vn({tieFormat:g});if(I.error)return I;if(f&&p)p.tieFormat=g;else if(u&&l)l.tieFormat=a;else if(c)c.tieFormat=g;else if(i)i.tieFormat=g;else if(!l||!i)return{error:lt};return Zt({drawDefinition:i,eventId:p==null?void 0:p.eventId}),{...$}}function Kp({updateInProgressMatchUps:t=!0,collectionGroupNumber:e,tournamentRecord:n,drawDefinition:r,tieFormatName:s,structureId:i,matchUpId:o,matchUp:c,eventId:a,event:u}){var S;if(!e)return{error:Tt};if(isNaN(e))return{error:tt};const l="removeCollectionGroup";let f=c?void 0:Oy({tournamentRecord:n,drawDefinition:r,structureId:i,matchUpId:o,eventId:a,event:u});if(f!=null&&f.error)return G({result:f,stack:l});const p=f==null?void 0:f.structure;c=c??(f==null?void 0:f.matchUp);const h=f==null?void 0:f.tieFormat,d=h==null?void 0:h.winCriteria.valueGoal,m=h==null?void 0:h.winCriteria.aggregateValue,g=Dr(h);if(f=vn({tieFormat:g}),f.error)return G({result:f,stack:l});const I=[];if(g.collectionDefinitions=g.collectionDefinitions.map(T=>{const{collectionGroupNumber:E,...y}=T;return E!==e?T:(I.push(T.collectionId),y)}),g.collectionGroups=g.collectionGroups.filter(({groupNumber:T})=>T!==e),f=My({updateInProgressMatchUps:t,originalValueGoal:d,wasAggregateValue:m,tournamentRecord:n,drawDefinition:r,tieFormatName:s,structureId:i,structure:p,tieFormat:g,matchUpId:o,matchUp:c,eventId:a,event:u}),!f.error){const{appliedPolicies:T}=ge({tournamentRecord:n});if((S=T==null?void 0:T.audit)!=null&&S[Qi]){const E=bt({drawId:r==null?void 0:r.drawId,collectionGroupNumber:e,action:l,structureId:i,matchUpId:o,eventId:a});ql({drawDefinition:r,auditData:E})}}return G({result:{...f,modifiedCollectionIds:I},stack:l})}function VD(t){return oi({...t,method:Kp})}function Jp({updateInProgressMatchUps:t=!0,tournamentRecord:e,groupDefinition:n,drawDefinition:r,collectionIds:s,tieFormatName:i,structureId:o,matchUpId:c,matchUp:a,eventId:u,event:l}){const f="addCollectionGroup";if(!Array.isArray(s))return G({result:{error:Tt},stack:f});let p=a?void 0:wo({drawDefinition:r,structureId:o,matchUpId:c,eventId:u,event:l});if(p!=null&&p.error)return G({result:p,stack:f});const h=p==null?void 0:p.structure;a=a||(p==null?void 0:p.matchUp);const d=p==null?void 0:p.tieFormat,m=d==null?void 0:d.winCriteria.valueGoal,g=Dr(d);if(p=vn({tieFormat:g}),p.error)return G({result:p,stack:f});for(const T of g.collectionDefinitions){const{collectionId:E,collectionGroupNumber:y}=T;if(y&&s.includes(E))return G({result:{error:tt,info:"collectionIds cannot be part of other collectionGroups"},stack:f})}const S=(g.collectionGroups||[]).reduce((T,E)=>E.groupNumber>T?E.groupNumber:T,0)+1;return n.groupNumber=S,g.collectionDefinitions=g.collectionDefinitions.map(T=>s.includes(T.collectionId)?{...T,collectionGroupNumber:S}:T),g.collectionGroups=[...g.collecitonGroups||[],n],My({updateInProgressMatchUps:t,originalValueGoal:m,tournamentRecord:e,drawDefinition:r,tieFormatName:i,structureId:o,structure:h,tieFormat:g,matchUpId:c,matchUp:a,eventId:u,event:l})}function jD(t){return oi({...t,method:Jp})}function Qp({updateInProgressMatchUps:t=!1,tieFormatComparison:e,modifiedTieFormat:n,tournamentRecord:r,drawDefinition:s,structureId:i,matchUpId:o,eventId:c,uuids:a,event:u}){const l="updateTieFormat";if(!vn(n))return{error:li};const f=wo({drawDefinition:s,structureId:i,matchUpId:o,eventId:c,event:u});if(f.error)return G({result:f,stack:l});const{matchUp:p,tieFormat:h}=f,d=Dr(h),m=d.collectionDefinitions.map(({collectionId:b})=>b),g=[],I=[],S=[];n.collectionDefinitions.forEach(b=>{var N;S.push(b.collectionId),n&&m.includes(b.collectionId)?(N=Sc({descendant:n,ancestor:d}))!=null&&N.different&&g.push(b):I.push(b)});const T=m.filter(b=>!S.includes(b)),E=n.tieFormatName;let y;for(const b of g){const N=zl({updateInProgressMatchUps:t,...b,tournamentRecord:r,drawDefinition:s,tieFormatName:E,structureId:i,matchUpId:o,eventId:c,event:u});if(N.error)return G({result:N,stack:l});N.tieFormat&&(y=N.tieFormat)}for(const b of I){const N=Zl({updateInProgressMatchUps:t,collectionDefinition:b,tournamentRecord:r,drawDefinition:s,tieFormatName:E,structureId:i,matchUpId:o,matchUp:p,eventId:c,uuids:a,event:u});if(N.error)return G({result:N,stack:l});N.tieFormat&&(y=N.tieFormat)}for(const b of T){const N=Kl({updateInProgressMatchUps:t,tieFormatComparison:e,tournamentRecord:r,drawDefinition:s,tieFormatName:E,collectionId:b,structureId:i,matchUpId:o,eventId:c,matchUp:p,event:u});if(N.error)return G({result:N,stack:l});N.tieFormat&&(y=N.tieFormat)}return y.collectionDefinitions=y.collectionDefinitions.sort((b,N)=>jo(b.collectionOrder)-jo(N.collectionOrder)).map((b,N)=>({...b,collectionOrder:N+1})),{...$,processedTieFormat:y}}function GD(t){return oi({...t,method:Qp})}function Zp({tournamentRecord:t,drawDefinition:e,matchUpId:n,event:r,uuids:s}){var d;const i="resetTieFormat";if(!t)return G({result:{error:et},stack:i});if(typeof n!="string")return G({result:{error:$e},stack:i});const o=eu({tournamentRecord:t,matchUpId:n});if(o.error)return o;const{matchUp:c,structure:a}=o;if(!(c!=null&&c.tieMatchUps))return G({result:{error:qn},info:"Must be a TEAM matchUp",stack:i});if(!c.tieFormat)return{...$};const u=(d=hn({structure:a,drawDefinition:e,event:r}))==null?void 0:d.tieFormat;if(!u)return G({result:{error:an},info:"No inherited tieFormat",stack:i});const l=[],f=[],p=[],h=[];for(const m of u.collectionDefinitions){const{matchUpCount:g,collectionId:I}=m;f.push(I);const S=(c.tieMatchUps||[]).filter(T=>T.collectionId===I);if(S.length>g)S.sort((T,E)=>(T.matchUpStatus===Le?1:0)-(E.matchUpStatus===Le?1:0)),p.push(...S.slice(0,g)),l.push(...S.slice(3).map(Qe));else if(p.push(...S),S.length<g){const T=g-S.length,E=Ql({collectionDefinition:m,matchUpsLimit:T,uuids:s});h.push(...E)}}for(const m of(c==null?void 0:c.tieMatchUps)||[])m.collectionId&&!f.includes(m.collectionId)&&l.push(m.matchUpId);return h.length&&(p.push(...h),Oi({tournamentId:t==null?void 0:t.tournamentId,eventId:r==null?void 0:r.eventId,matchUps:h,drawDefinition:e})),l.length&&ei({tournamentId:t==null?void 0:t.tournamentId,matchUpIds:l,eventId:r==null?void 0:r.eventId,drawDefinition:e}),c&&(c.tieMatchUps=p,c.tieFormatId=void 0,c.tieFormat=void 0,qt({tournamentId:t==null?void 0:t.tournamentId,structureId:a==null?void 0:a.structureId,eventId:r==null?void 0:r.eventId,context:i,drawDefinition:e,matchUp:c})),{...$,newMatchUps:h,deletedMatchUpIds:l}}function Xp(t){var m;const{tournamentRecord:e,drawDefinition:n,matchUpId:r,event:s}=t,i="resetScorecard";if(!n)return G({result:{error:lt},stack:i});if(!r)return G({result:{error:$e},stack:i});if(typeof r!="string")return G({result:{error:tt,matchUpId:r},stack:i});const o=ln({drawDefinition:n}),{matchUps:c}=xe({nextMatchUps:!0,inContext:!0,drawDefinition:n,matchUpsMap:o}),a=o.drawMatchUps.find(g=>g.matchUpId===r),u=c==null?void 0:c.find(g=>g.matchUpId===r);if(!a||!c)return{error:Ye};if(a.matchUpType!==_n.Team)return{error:qn};const l=gn({inContextDrawMatchUps:c,drawDefinition:n,matchUpId:r}),f=u==null?void 0:u.structureId,{structure:p}=Ot({drawDefinition:n,structureId:f});if(Object.assign(t,{inContextDrawMatchUps:c,inContextMatchUp:u,matchUpsMap:o,targetData:l,structure:p,matchUp:a}),_i(t))return{error:ag};for(const g of a.tieMatchUps??[]){const I=Ja({matchUpId:g.matchUpId,matchUpTieId:r,winningSide:void 0,removeScore:!0,tournamentRecord:e,drawDefinition:n,event:s});if(I.error)return G({result:I,stack:i})}const d=ms({event:t.event,removeScore:!0,tournamentRecord:e,drawDefinition:n,matchUpsMap:o,matchUpId:r});if(d.error)return G({result:d,stack:i});if(t.tiebreakReset&&!d.tieFormatRemoved){const g=(m=hn({drawDefinition:n,structure:p,event:s}))==null?void 0:m.tieFormat;if(a.tieFormat&&g){const{matchUpCountDifference:I,descendantDifferences:S,ancestorDifferences:T,valueDifference:E}=Sc({descendant:a.tieFormat,ancestor:g});if(S.collectionIds.length===1&&!T.collectionIds.length&&!T.groupsCount&&I===1&&E===1){const y=Zp({tournamentRecord:e,drawDefinition:n,matchUpId:r,event:s});if(y.error)return y}}}return{...$}}function WD(t){return oi({...t,method:Xp})}function HD(t){return oi({...t,method:Zp})}const qD={modifyCollectionDefinition:_D,removeCollectionDefinition:LD,orderCollectionDefinitions:FD,addCollectionDefinition:RD,removeCollectionGroup:VD,addCollectionGroup:jD,modifyTieFormat:GD,resetScorecard:WD,resetTieFormat:HD,addExtension:vf,findExtension:zu,removeExtension:Ku,addEventExtension:pP,linkTournaments:hP,unlinkTournament:gP,unlinkTournaments:mP,getLinkedTournamentIds:Cf,addDrawDefinition:sD,getCompetitionParticipants:UD,getParticipants:PD,addParticipant:iD,courtGridRows:ny,setMatchUpStatus:nD,bulkMatchUpStatusUpdate:rD,bulkScheduleMatchUps:MT,addPenalty:OD,removePenalty:DD,modifyPenalty:MD,getCompetitionPenalties:wD,findParticipant:Ey};function Dy({removePriorValues:t=!0,tournamentRecord:e,status:n=Kr}){if(!e)return{error:et};const r=`${Qn}.${Zn}`,{timeItem:s}=El({tournamentRecord:e,itemType:r}),i=(s==null?void 0:s.itemValue)||{[n]:{}};return i[n]&&delete i[n].orderOfPlay,_s({timeItem:{itemValue:i,itemType:r},removePriorValues:t,tournamentRecord:e}),Ht({topic:_I,payload:{tournamentId:e.tournamentId}}),{...$}}function wy({scheduledDates:t=[],removePriorValues:e,tournamentRecord:n,status:r=Kr,eventIds:s=[]}){if(!n)return{error:et};const i=`${Qn}.${Zn}`,{timeItem:o}=El({tournamentRecord:n,itemType:i}),c=(o==null?void 0:o.itemValue)||{[r]:{}};return c[r].orderOfPlay={published:!0,scheduledDates:t,eventIds:s},_s({timeItem:{itemValue:c,itemType:i},removePriorValues:e,tournamentRecord:n}),Ht({topic:bP,payload:{tournamentId:n.tournamentId,scheduledDates:t,eventIds:s}}),{...$}}function YD(t){const e=t==null?void 0:t.tournamentRecords;if(!e)return{error:Gt};for(const n of Object.values(e)){const r=Dy({tournamentRecord:n,...t});if(r.error)return r}return{...$}}function zD(t){const e=t==null?void 0:t.tournamentRecords;if(!e)return{error:Gt};for(const n of Object.values(e)){const r=wy({tournamentRecord:n,...t});if(r.error)return r}return{...$}}const KD={unPublishOrderOfPlay:YD,publishOrderOfPlay:zD};function ky({tournamentRecords:t,extensionName:e}){if(typeof t!="object"||!Object.keys(t).length)return{error:Gt};const n=[];let r;for(const s of Object.values(t)){const{extension:i}=Bn({name:e,tournamentRecord:s});i&&!r&&(n.push({method:"addExtension",params:{extension:i}}),r=!0);const o=s.events||[];for(const c of o){const{eventId:a}=c,{extension:u}=Us({name:e,event:c});u&&n.push({params:{eventId:a,extension:u},method:"addEventExtension"})}}return{methods:n}}function JD({tournamentRecords:t}){return ky({extensionName:qr,tournamentRecords:t})}function _y({tournamentRecord:t,matchUpFormats:e,categoryType:n,event:r}){if(!t)return{error:et};if(!r)return{error:Wt};let s=[];if(e!=null&&e.length){const l=[];s=e.map(f=>{const p=typeof f=="string"?{matchUpFormat:f}:f;if(!l.includes(p==null?void 0:p.matchUpFormat)&&nr(p==null?void 0:p.matchUpFormat))return l.push(p.matchUpFormat),p}).filter(Boolean)}else{const{policy:l}=Xi({policyType:Xo,tournamentRecord:t,event:r});if(l!=null&&l.matchUpFormats)s=l==null?void 0:l.matchUpFormats;else{const{extension:f}=Us({name:qr,event:r});if(f!=null&&f.value)s=Vt([...(f.value.matchUpAverageTimes||[]).map(p=>p.matchUpFormatCodes),...(f.value.matchUpRecoveryTimes||[]).map(p=>p.matchUpFormatCodes)].flat()).map(p=>({matchUpFormat:p}));else return{error:tv}}}const{eventType:i,eventId:o,category:c}=r,a=(c==null?void 0:c.categoryName)||(c==null?void 0:c.ageCategoryCode)||o;return o?{eventMatchUpFormatTiming:s.map(({matchUpFormat:l,description:f})=>{const p=yf({tournamentRecord:t,matchUpFormat:l,categoryName:a,categoryType:n,eventType:i,event:r});return Object.assign({},{...p,description:f,matchUpFormat:l})})}:{error:Wt}}function QD({tournamentRecords:t,matchUpFormats:e,categoryType:n,tournamentId:r,eventId:s}){if(!s)return{error:Wt};const i=Object.keys(t).filter(u=>!r||u===r);if(r&&!i.length)return{error:tt};let o,c,a;return i.forEach(u=>{const l=t[u],{event:f}=Je({tournamentRecord:l,eventId:s});if(!f)return!1;a=!0;const{eventMatchUpFormatTiming:p,error:h}=_y({tournamentRecord:l,matchUpFormats:e,categoryType:n,event:f});h&&(c=h),o=p}),!a&&{error:wn}||c&&{error:c}||{eventMatchUpFormatTiming:o}}function td({tournamentRecords:t,schedulingProfile:e}){if(!e)return{valid:!0};if(!Array.isArray(e))return{valid:!1,error:tt};const{venueIds:n,tournamentsMap:r}=ZD({tournamentRecords:t});let s,i;const o=e.every(c=>{const{scheduleDate:a,venues:u}=c;return Yn(a)?u.every(l=>{const{venueId:f,rounds:p}=l;return typeof f!="string"?(i="venueId should be a string",!1):Array.isArray(p)?n.includes(f)?!!p.every(d=>{var v,P,U;if(!d)return i="empty round",!1;const{roundSegment:m,tournamentId:g,structureId:I,roundNumber:S,eventId:T,drawId:E}=d,y=(U=(P=(v=r==null?void 0:r[g])==null?void 0:v[T])==null?void 0:P[E])==null?void 0:U[I],b=y==null?void 0:y.includes(S);b||(i="Invalid rounds");const{segmentNumber:N,segmentsCount:A}=m||{},C=!m||oe(N)&&mr(A)&&N<=A;return C||(i="Invalid segment"),b&&C}):(s=di,!1):(i="rounds should be an array",!1)}):!1});return!o&&!s&&(s=tt),{valid:!!o,error:s,info:i}}function Fy(t){const{tournamentRecord:e={},tournamentMap:n={},requireCourts:r}=t,s=[],i=[],o=[],c=[],a=((e==null?void 0:e.venues)||[]).map(({venueId:l,courts:f})=>(!r||(f==null?void 0:f.length))&&l),u=e==null?void 0:e.tournamentId;return u&&(s.push(u),n[u]={},((e==null?void 0:e.events)||[]).forEach(f=>{const p=f.eventId;o.push(p),n[u][p]={},(f.drawDefinitions||[]).forEach(h=>{const d=h.drawId;c.push(d),n[u][p][d]={};const{structures:m}=lr({drawDefinition:h});(m||[]).forEach(g=>{var y;const I=g.structureId,{matchUps:S}=Qt({structure:g}),{roundMatchUps:T}=Cn({matchUps:S}),E=T&&Object.keys(T).map(b=>parseInt(b));n[u][p][d][I]=E,i.push(I),(y=g.structures)!=null&&y.length&&g.structures.forEach(b=>{i.push(b.structureId),n[u][p][d][b.structureId]=E})})})})),{tournamentMap:n,tournamentIds:s,structureIds:i,venueIds:a,eventIds:o,drawIds:c}}function ZD(t){const e=(t==null?void 0:t.tournamentRecords)&&Object.values(t==null?void 0:t.tournamentRecords)||[],n={},{venueIds:r,eventIds:s,drawIds:i,structureIds:o,tournamentIds:c}=e.reduce((a,u)=>{const{tournamentIds:l,tournamentMap:f,structureIds:p,venueIds:h,eventIds:d,drawIds:m}=Fy({tournamentRecord:u});return h.forEach(g=>{a.venueIds.includes(g)||a.venueIds.push(g)}),a.tournamentIds.push(...l),a.structureIds.push(...p),a.eventIds.push(...d),a.drawIds.push(...m),Object.assign(n,f),a},{tournamentIds:[],structureIds:[],venueIds:[],eventIds:[],drawIds:[]});return{tournamentsMap:n,tournamentIds:c,structureIds:o,venueIds:r,eventIds:s,drawIds:i}}function XD({tournamentRecords:t,matchUpFormat:e,recoveryTimes:n,averageTimes:r,tournamentId:s,eventId:i}){if(typeof t!="object"||!Object.keys(t).length)return{error:Gt};const o=Object.keys(t).filter(a=>!s||s===a);if(s&&!o.includes(s))return{error:tt};let c;for(const a of o){const u=t[a],{event:l}=Je({tournamentRecord:u,eventId:i});i&&l&&(c=!0);const f=Vp({tournamentRecord:u,event:l,matchUpFormat:e,averageTimes:r,recoveryTimes:n});if(f.error)return f}return!i||c?{...$}:{error:wn}}function th({defaultRecoveryMinutes:t=0,defaultAverageMinutes:e,tournamentRecords:n,matchUpFormat:r,categoryName:s,categoryType:i,tournamentId:o,eventType:c,eventId:a}){if(!nr(r))return{error:bu};const u=Object.keys(n).filter(f=>!o||f===o);let l;return u.forEach(f=>{var d;if(l)return;const p=n[f],h=a?(d=Je({tournamentRecord:p,eventId:a}))==null?void 0:d.event:void 0;return l=yf({tournamentRecord:p,matchUpFormat:r,categoryName:s,categoryType:i,eventType:c,event:h}),(l==null?void 0:l.averageMinutes)||(l==null?void 0:l.recoveryMinutes)}),{recoveryMinutes:(l==null?void 0:l.recoveryMinutes)||t,averageMinutes:(l==null?void 0:l.averageMinutes)||e,typeChangeRecoveryMinutes:(l==null?void 0:l.typeChangeRecoveryMinutes)||(l==null?void 0:l.recoveryMinutes)||t}}function eh({scheduleCompletedMatchUps:t,containedStructureIds:e,tournamentRecords:n,periodLength:r=30,matchUps:s,rounds:i}){if(typeof n!="object")return{error:Gt};if(!Array.isArray(i))return{error:Tt,info:sn("rounds")};const o={},c=[];i.sort((h,d)=>(h.sortOrder??0)-(d.sortOrder??0)),e=e??Object.assign({},...Object.values(n).map(h=>Nc({tournamentRecord:h}).containedStructures)),s||({matchUps:s}=ks({nextMatchUps:!0,tournamentRecords:n}));let a=0;const u={},l={},f={};return{scheduledRoundsDetails:i.flatMap(h=>{var b;const d=h.periodLength||r,m=[];e!=null&&e[h.structureId]?m.push(...e[h.structureId]):m.push(h.structureId);let g=s?go({tournamentIds:[h.tournamentId],roundNumbers:[h.roundNumber],matchUpIds:h.matchUpIds,eventIds:[h.eventId],drawIds:[h.drawId],processContext:!0,structureIds:m,matchUps:s}).sort(vo):[];const{segmentNumber:I,segmentsCount:S}=h.roundSegment||{};if(oe(I)&&mr(g==null?void 0:g.length)&&mr(S)&&I>0&&I<=S&&S<(g==null?void 0:g.length)&&!((b=h.matchUpIds)!=null&&b.length)){const N=g.length/S,A=N*(I-1);g=g.slice(A,A+N)}const T=n[h.tournamentId],E=Je({drawId:h.drawId,tournamentRecord:T}).event,y=[];for(const N of g){const A=N.matchUpFormat;A&&(o[A]||(o[A]=[],o[A].push(N)),y.push(A))}for(const N of y){const{eventType:A,category:C}=E??{},{categoryName:v,ageCategoryCode:P}=C??{},{typeChangeRecoveryMinutes:U,recoveryMinutes:O,averageMinutes:D,error:M}=th({categoryName:v??P,categoryType:C==null?void 0:C.categoryType,tournamentId:h.tournamentId,eventId:h.eventId,tournamentRecords:n,matchUpFormat:N,eventType:A});if(M)return{error:M,round:h};const w=g.filter(_=>(t||!We.includes(_.matchUpStatus))&&_.matchUpStatus!==re).map(Qe);w.forEach(_=>{f[_]={typeChangeRecoveryMinutes:U,recoveryMinutes:O,averageMinutes:D},u[_]=O,l[_]=D}),c.push(...w),a=Math.max(D||0,a);const k=`${D}|${d}`;return{roundPeriodLength:d,recoveryMinutes:O,averageMinutes:D,matchUpIds:w,hash:k}}}),greatestAverageMinutes:a,matchUpFormatCohorts:o,recoveryMinutesMap:u,averageMinutesMap:l,orderedMatchUpIds:c,minutesMap:f,...$}}function Ly({tournamentRecords:t}){const n=Object.keys(t).reduce((i,o)=>{const c=t[o],{tournamentInfo:{startDate:a,endDate:u}}=tu({tournamentRecord:c}),l=a&&new Date(Bt(a));(!i.startDate||l&&l<i.startDate)&&(i.startDate=l);const f=u&&new Date(Bt(u));return(!i.endDate||f&&f>i.endDate)&&(i.endDate=f),i},{startDate:void 0,endDate:void 0}),r=n.startDate&&Bt(n.startDate.toISOString()),s=n.endDate&&Bt(n.endDate.toISOString());return!r||!s?{error:sg}:{startDate:r,endDate:s}}function Mc({tournamentRecords:t}){if(typeof t!="object"||!Object.keys(t).length)return{error:Gt};const{extension:e}=zu({name:qs,tournamentRecords:t});let n=(e==null?void 0:e.value)||[];if(n.length){const{venueIds:r}=Ap({requireCourts:!0,tournamentRecords:t}),{eventIds:s,drawIds:i}=_l({tournamentRecords:t}),{updatedSchedulingProfile:o,modifications:c,issues:a}=ed({schedulingProfile:n,venueIds:r,eventIds:s,drawIds:i});if(c){n=o;const u=nu({tournamentRecords:t,schedulingProfile:n});return u.error?u:{schedulingProfile:n,modifications:c,issues:a}}}return{schedulingProfile:n,modifications:0}}function nu({tournamentRecords:t,schedulingProfile:e}){const n=td({tournamentRecords:t,schedulingProfile:e});return n.error?n:e?vf({tournamentRecords:t,extension:{name:qs,value:e}}):Ku({tournamentRecords:t,name:qs})}function Ry({tournamentRecords:t,scheduleDate:e,venueId:n,round:r}){if(!Yn(e))return{error:bn};const s="addSchedulingProfileRound",{extension:i}=zu({tournamentRecords:t,name:qs}),o=(i==null?void 0:i.value)||[];let c=o.find(h=>as(e,h.scheduleDate));if(!c){const{startDate:h,endDate:d}=Ly({tournamentRecords:t}),m=new Date(e);if(h&&m<new Date(h)||d&&m>new Date(d))return{error:bn};c={scheduleDate:e,venues:[]},o.push(c)}let a=c.venues.find(h=>h.venueId===n);a||(a={venueId:n,rounds:[]},c.venues.push(a));const u=["notBeforeTime"],l=h=>Object.keys(h).filter(d=>!u.includes(d)).sort().map(d=>or(h[d])?l(h[d]):h[d]).flat().join("|");if(a.rounds.find(h=>l(h)===l(r)))return G({result:{error:j1},stack:s});a.rounds.push(r);const p=nu({tournamentRecords:t,schedulingProfile:o});return p.error?p:{...$}}function ed({schedulingProfile:t,venueIds:e,eventIds:n,drawIds:r}){const s=[],i=t==null?void 0:t.map(c=>{const a=Bt(c==null?void 0:c.scheduleDate);if(!a){s.push(`Invalid date: ${c==null?void 0:c.scheduledDate}`);return}const u=((c==null?void 0:c.venues)||[]).map(l=>{const{rounds:f,venueId:p}=l;if(!e.includes(p)){s.push(`Missing venueId: ${p}`);return}const d=f.filter(m=>{const g=n.includes(m.eventId)&&r.includes(m.drawId);return g||s.push(`Invalid eventId: ${m.eventId} or drawId: ${m.drawId}`),g});if(d.length)return{venueId:p,rounds:d}}).filter(Boolean);return u.length&&a&&{...c,venues:u}}).filter(Boolean),o=s.length;return{updatedSchedulingProfile:i,modifications:o,issues:s}}function By({tournamentRecords:t}){const{schedulingProfile:e}=Mc({tournamentRecords:t});if(e){const{venueIds:n}=Ap({tournamentRecords:t}),{eventIds:r,drawIds:s}=_l({tournamentRecords:t}),{updatedSchedulingProfile:i,modifications:o}=ed({schedulingProfile:e,venueIds:n,eventIds:r,drawIds:s});if(o)return nu({tournamentRecords:t,schedulingProfile:i})}return{...$}}function nd({schedulingProfile:t,matchUps:e=[]}){const n={},r=({eventId:c,drawId:a,structureId:u,roundNumber:l})=>`${c}|${a}|${u}${l}`;t!=null&&t.length&&t.map(({venues:a})=>a.map(({rounds:u})=>u)).flat().forEach(a=>{a.sort((l,f)=>(l.sortOrder||0)-(f.sortOrder||0)).forEach(({eventId:l,drawId:f,structureId:p,roundNumber:h},d)=>{const m=r({eventId:l,drawId:f,structureId:p,roundNumber:h});n[m]=d})});const s=[],i={noScheduledDate:[]};for(const c of e){const a=c.schedule||{},u=a.scheduledDate&&Bt(a.scheduledDate)||a.scheduledTime&&Bt(a.scheduledTime)||"noScheduledDate";i[u]||(i[u]=[]),i[u].push(c)}const o=Object.keys(i).sort();for(const c of o){const a=i[c],u={noScheduledTime:[]};for(const f of a){const p=f.schedule||{},h=p.scheduledTime&&de(p.scheduledTime)||"noScheduledTime";u[h]||(u[h]=[]),u[h].push(f)}const l=Object.keys(u).sort();for(const f of l){const p=u[f];p.sort((h,d)=>{const m=n[r(h)]||0,g=n[r(d)]||0;return m-g}),s.push(...p)}}return s}function nh(t){var P,U,O,D,M,w,k;if(typeof(t==null?void 0:t.tournamentRecords)!="object"||!Object.keys(t==null?void 0:t.tournamentRecords).length)return{error:Gt};const{courts:e,venues:n}=Co(t),s=Mc(t).schedulingProfile,{sortDateMatchUps:i=!0,courtCompletedMatchUps:o,alwaysReturnCompleted:c,activeTournamentId:a,tournamentRecords:u,withCourtGridRows:l,minCourtGridRows:f,usePublishState:p,status:h=Kr,sortCourtsData:d}=t,m=p?El({tournamentRecord:u[a??os()],itemType:`${Qn}.${Zn}`}).timeItem:void 0,g=(P=m==null?void 0:m.itemValue)==null?void 0:P[h],I=c?Ip({...t,matchUpFilters:{...t.matchUpFilters,matchUpStatuses:[pe.Completed]},contextFilters:t.contextFilters}).completedMatchUps:[];if(p&&(!g||!Object.keys(g).length))return{completedMatchUps:I,dateMatchUps:[],courtsData:[],venues:n};const S=p?tw({tournamentRecords:u}).drawIds:void 0;S!=null&&S.length&&(t.contextFilters||(t.contextFilters={}),(U=t.contextFilters)!=null&&U.drawIds?t.contextFilters.drawIds=t.contextFilters.drawIds.filter(_=>S.includes(_)):t.contextFilters.drawIds=S),(O=g==null?void 0:g.eventIds)!=null&&O.length&&(t.matchUpFilters||(t.matchUpFilters={}),(D=t.matchUpFilters)!=null&&D.eventIds&&t.matchUpFilters.eventIds.length?t.matchUpFilters.eventIds=t.matchUpFilters.eventIds.filter(_=>g.eventIds.includes(_)):t.matchUpFilters.eventIds=g.eventIds),(M=g==null?void 0:g.scheduledDates)!=null&&M.length&&(t.matchUpFilters||(t.matchUpFilters={}),t.matchUpFilters.scheduledDates&&t.matchUpFilters.scheduledDates.length?t.matchUpFilters.scheduledDates=t.matchUpFilters.scheduledDates.filter(_=>g.scheduledDates.includes(_)):t.matchUpFilters.scheduledDates=g.scheduledDates),c&&(t.matchUpFilters||(t.matchUpFilters={}),(k=(w=t.matchUpFilters)==null?void 0:w.excludeMatchUpStatuses)!=null&&k.length?t.matchUpFilters.excludeMatchUpStatuses.includes(De)||t.matchUpFilters.excludeMatchUpStatuses.push(De):t.matchUpFilters.excludeMatchUpStatuses=[De]);const{completedMatchUps:T,upcomingMatchUps:E,pendingMatchUps:y}=Ip({...t,matchUpFilters:t.matchUpFilters,contextFilters:t.contextFilters}),b=[...E??[],...y??[]],N=i?nd({matchUps:b,schedulingProfile:s}):b,A=e==null?void 0:e.map(_=>{const F=v(_);return{surfaceCategory:(_==null?void 0:_.surfaceCategory)??"",matchUps:F,..._}}),C={courtsData:A,completedMatchUps:c?I:T,dateMatchUps:N,venues:n};if(l){const{rows:_,courtPrefix:F}=ny({minRowsCount:f,courtsData:A});C.courtPrefix=F,C.rows=_}return C;function v({courtId:_}){const L=(o?N.concat(T??[]):N).filter(W=>{var j,H,B;return((j=W.schedule)==null?void 0:j.courtId)===_||((B=(H=W.schedule)==null?void 0:H.allocatedCourts)==null?void 0:B.map(({courtId:R})=>R).includes(_))});return d?nd({matchUps:L,schedulingProfile:s}):L}}function tw({tournamentRecords:t}){var n,r;const e=[];for(const s of Object.values(t))for(const i of s.events??[]){const{timeItem:o}=ws({itemType:`${Qn}.${Zn}`,event:i}),c=(n=o==null?void 0:o.itemValue)==null?void 0:n[Kr];if((r=c==null?void 0:c.drawIds)!=null&&r.length)e.push(...c.drawIds);else{const a=(i.drawDefinitions??[]).map(({drawId:u})=>u).filter(Boolean);e.push(...a)}}return{drawIds:e}}function xy({calculateStartTimeFromCourts:t=!0,defaultRecoveryMinutes:e=0,averageMatchUpMinutes:n=90,remainingScheduleTimes:r,clearScheduleDates:s,tournamentRecords:i,periodLength:o,scheduleDate:c,startTime:a,venueIds:u,endTime:l}){if(typeof i!="object"||!Object.keys(i).length)return{error:Gt};o=o||Al({recoveryMinutes:e,averageMatchUpMinutes:n});const{courts:f,venues:p}=Co({dates:[c],ignoreDisabled:!0,tournamentRecords:i}),h=f==null?void 0:f.filter(P=>!u||u.includes(P.venueId));a||(a=h==null?void 0:h.reduce((P,U)=>{var M;const O=(M=U.dateAvailability)==null?void 0:M.find(w=>!w.date||as(c,w.date)),D=(O==null?void 0:O.startTime)||U.startTime;return D&&(!P||jt(D)<jt(P))?D:P},void 0)),l||(l=h==null?void 0:h.reduce((P,U)=>{var M;const O=(M=U.dateAvailability)==null?void 0:M.find(w=>!w.date||as(c,w.date)),D=(O==null?void 0:O.endTime)||U.endTime;return D&&(!P||jt(D)>jt(P))?D:P},void 0));const d=Object.values(i),m=Object.assign({},...d.map(P=>(P.events||[]).map(U=>{const{scheduleTiming:O}=pa({tournamentRecord:P,event:U});return{[U.eventId]:{event:U,scheduleTiming:O}}})).flat()),I=nh({sortDateMatchUps:!1,tournamentRecords:i,matchUpFilters:{scheduledDate:c,venueIds:u}}),S=(I==null?void 0:I.dateMatchUps)||[],T=(I==null?void 0:I.completedMatchUps)||[],E=[];E.push(...S),E.push(...T);const y={averageTimes:[{minutes:{default:n}}],recoveryTimes:[{minutes:{default:e}}]},b=E==null?void 0:E.map(({eventId:P,schedule:U,matchUpFormat:O})=>{const{event:D,scheduleTiming:M}=m[P],w=D==null?void 0:D.eventType,k={...M,defaultTiming:y,matchUpFormat:O},{averageMinutes:_,recoveryMinutes:F}=qu({eventType:w,timingDetails:k}),{courtId:L,venueId:W}=U,j=de(U.scheduledTime),H=An(j,_);return{recoveryMinutes:F,averageMinutes:_,periodLength:o,startTime:j,endTime:H,courtId:L,venueId:W}}),N={calculateStartTimeFromCourts:t,remainingScheduleTimes:r,averageMatchUpMinutes:n,date:c,clearScheduleDates:s,periodLength:o,startTime:a,endTime:l,bookings:b,courts:h},{scheduleTimes:A}=Tp(N),C=(u==null?void 0:u.length)===1&&u[0]||(p==null?void 0:p.length)===1&&p[0].venueId||void 0,v=E.map(Qe);return{venueId:C,scheduleTimes:A,dateScheduledMatchUpIds:v}}function rh({matchUpScheduleTimes:t,matchUpDependencies:e,allDateMatchUpIds:n,matchUp:r}){var c;const i=(((c=e==null?void 0:e[r.matchUpId])==null?void 0:c.matchUpIds)||[]).filter(a=>n.includes(a)).filter(a=>!t[a]);return{dependenciesScheduled:!(i!=null&&i.length),remainingDependencies:i}}function Dc({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:e,timeAfterRecovery:n,matchUp:r}){var u,l,f,p;const{individualParticipantIds:s}=bl(r);n=n||((u=r.schedule)==null?void 0:u.timeAfterRecovery);const i=h=>{t[h]||(t[h]=[]),t[h]=Vt(t[h].concat(...s))},o=h=>{n&&(!e[h]||n>e[h])&&(e[h]=n)},c=((l=r.winnerTo)==null?void 0:l.matchUpId)||r.winnerMatchUpId;c&&(n&&o(c),i(c));const a=((f=r.loserTo)==null?void 0:f.matchUpId)||r.loserMatchUpId;a&&(n&&o(a),i(a)),(p=r.sidesTo)!=null&&p.length&&r.sidesTo.forEach(({matchUpId:h})=>{h&&(n&&o(h),i(h))})}function ru({individualParticipantProfiles:t,participantId:e}){t[e]||(t[e]={typeChangeTimeAfterRecovery:void 0,timeAfterRecovery:void 0,priorMatchUpType:void 0,potentialRecovery:{},potentialCounted:{},potentialBookings:{},bookings:[],counters:{}})}function ew({individualParticipantProfiles:t,recoveryValue:e,participantId:n,scheduleTime:r,drawId:s}){t[n].potentialRecovery[s]||(t[n].potentialRecovery[s]=[]),t[n].potentialRecovery[s].push(e),t[n].potentialBookings[s]||(t[n].potentialBookings[s]=[]),t[n].potentialBookings[s].push({timeAfterRecovery:e,scheduleTime:r})}function su({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,typeChangeRecoveryMinutes:n,averageMatchUpMinutes:r=0,matchUpNotBeforeTimes:s,matchUpDependencies:i,recoveryMinutes:o=0,scheduleTime:c,matchUp:a}){var d,m;const u=de((d=a==null?void 0:a.schedule)==null?void 0:d.endTime),l=u?An(u,vt(o)):An(c,vt(r)+vt(o)),f=n&&(u?An(de(u),n):An(c,vt(r)+vt(n))),p=((m=i==null?void 0:i[a.matchUpId])==null?void 0:m.participantIds)||[],h=(a.roundPosition&&t[a.matchUpId]||[]).flat();p.forEach(g=>{ru({individualParticipantProfiles:e,participantId:g});const S=e[g].priorMatchUpType!==a.matchUpType&&f||l;h.includes(g)?ew({individualParticipantProfiles:e,drawId:a.drawId,recoveryValue:S,participantId:g,scheduleTime:c}):(e[g].timeAfterRecovery=S,e[g].bookings.push({scheduleTime:c,timeAfterRecovery:S}))}),Dc({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:s,timeAfterRecovery:l,matchUp:a})}function $y({matchUpScheduleTimes:t,matchUpDependencies:e,scheduleTime:n,matchUpId:r,details:s}){var f,p,h,d,m;let i;const o=(p=(f=s.minutesMap)==null?void 0:f[r])==null?void 0:p.recoveryMinutes,a=(((d=(h=s.minutesMap)==null?void 0:h[r])==null?void 0:d.averageMinutes)||0)+(o||0),u=An(n,a),l=((m=e==null?void 0:e[r])==null?void 0:m.dependentMatchUpIds)||[];if(l.length){const g=l.reduce((I,S)=>{const T=t[S];if(!T)return I;const E={scheduleTime:T,matchUpId:S};return T&&!I.matchUpId||jt(T)<jt(I.scheduleTime)?E:I},{});g.scheduleTime&&jt(u)>jt(g.scheduleTime)&&(i=g)}return{scheduledDependent:i}}function nw(t){const{sides:e,matchUpType:n}=t||{};return(e||[]).map(r=>{var s;return n===me&&(((s=r==null?void 0:r.participant)==null?void 0:s.individualParticipants)||[])||(r==null?void 0:r.participant)&&[r.participant]||[]}).flat()}const rd="DO_NOT_SCHEDULE";function sh({averageMatchUpMinutes:t=90,requestConflicts:e={},potentials:n=!0,personRequests:r,scheduleTime:s,scheduleDate:i,matchUp:o}){const c=nw(o).map(({person:h})=>h==null?void 0:h.personId);if(n){const h=((o==null?void 0:o.potentialParticipants)||[]).flat().map(({person:d})=>d==null?void 0:d.personId);c.push(...h)}const a=c.map(h=>{var d;return(d=r[h])==null?void 0:d.map(m=>({...m,personId:h}))}).filter(Boolean).flat().filter(h=>h.requestType===rd&&as(i,h.date)),u=[],l=o==null?void 0:o.matchUpId,f=Pe(de(s),Bt(i)),p=de(nf(f,t).toISOString());for(const h of a){const{requestId:d,startTime:m,endTime:g}=h;(s>m&&s<g||p>m&&p<g)&&(u.push({matchUpId:l,request:h,scheduleTime:s}),e[d]?(e[d].scheduleTimes.includes(s)||e[d].scheduleTimes.push(s),e[d].matchUpIds.includes(l)||e[d].matchUpIds.push(l)):e[d]={request:h,scheduleTimes:[s],matchUpIds:[l]})}return{conflicts:u}}function ih({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,matchUp:n,value:r}){const{matchUpType:s}=n,{individualParticipantIds:i}=bl(n),c=(t[n.matchUpId]||[]).filter(u=>!tn(u,i)).flat();[...i,...c].forEach(u=>{if(ru({individualParticipantProfiles:e,participantId:u}),!e[u].potentialCounted[n.drawId]){const l=e[u].counters;l[s]?l[s]+=r:r>0&&(l[s]=r),l[Nr]?l[Nr]+=r:r>0&&(l[Nr]=r),c.includes(u)&&(e[u].potentialCounted[n.drawId]=!0)}})}function rw({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,dateScheduledMatchUpIds:n,greatestAverageMinutes:r,dateScheduledMatchUps:s,matchUpNotBeforeTimes:i,matchUpScheduleTimes:o,matchUpDependencies:c,clearScheduleDates:a,scheduleDate:u,minutesMap:l,matchUps:f}){var d,m;n||(s=f==null?void 0:f.filter(g=>{const I=g.schedule||{};return Xa({schedule:I})&&(!u||g.schedule.scheduledDate===u)}),n=s.map(Qe));const p=Array.isArray(a)?a.includes(u):a,h=p?[]:f.filter(({matchUpId:g})=>n.includes(g));for(const g of h){ih({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,value:1,matchUp:g});const I=(d=g.schedule)==null?void 0:d.scheduledTime;if(I){o[g.matchUpId]=I;const S=(m=l==null?void 0:l[g.matchUpId])==null?void 0:m.recoveryMinutes;su({individualParticipantProfiles:e,matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:i,matchUpDependencies:c,averageMatchUpMinutes:r,recoveryMinutes:S,scheduleTime:I,matchUp:g})}}return{clearDate:p,dateScheduledMatchUpIds:n,dateScheduledMatchUps:s}}function sw({scheduledRoundsDetails:t,greatestAverageMinutes:e,garmanSinglePass:n}){const r=[];let s=[],i,o,c,a;for(const u of t.filter(Boolean))a||(a=u.hash),(u.hash===a||n)&&(s=s.concat(u.matchUpIds)),u.hash!==a&&!n&&(a=u.hash,r.push({averageMinutes:c,recoveryMinutes:o,roundPeriodLength:i,matchUpIds:s}),s=u.matchUpIds),c=n?e:u.averageMinutes,o=u.recoveryMinutes,i=u.roundPeriodLength;return s.length&&r.push({averageMinutes:c,recoveryMinutes:o,roundPeriodLength:i,matchUpIds:s}),{groupedRounds:r}}function iw({matchUpPotentialParticipantIds:t,scheduleCompletedMatchUps:e,dateScheduledMatchUpIds:n,matchUpNotBeforeTimes:r,orderedMatchUpIds:s,clearDate:i,matchUps:o}){const c=s.map(u=>o.find(l=>l.matchUpId===u)).filter(Boolean).filter(u=>{const l=!i&&n.includes(u.matchUpId),f=[re,te,De,zn,In,ce,Fe,en].includes(u==null?void 0:u.matchUpStatus);return e||!l&&!u.winningSide&&!f}),{matchUpMap:a}=c.reduce((u,l)=>{const{drawId:f,tournamentId:p}=l;return u.matchUpMap[p]||(u.matchUpMap[p]={}),u.matchUpMap[p][f]?u.matchUpMap[p][f].push(l):u.matchUpMap[p][f]=[l],Dc({matchUpPotentialParticipantIds:t,matchUpNotBeforeTimes:r,matchUp:l}),u},{matchUpMap:{}});return{matchUpsToSchedule:c,matchUpMap:a}}function oh({defaultRecoveryMinutes:t=0,averageMatchUpMinutes:e=90,dateScheduledMatchUps:n,tournamentRecords:r,venueIds:s=[],periodLength:i,scheduleDate:o,matchUps:c}){if(typeof r!="object")return{error:Gt};if(!cr(c)&&!Array.isArray(n))return{error:$s};i=i||Al({recoveryMinutes:t,averageMatchUpMinutes:e});const a=Object.assign({},...Object.values(r).map(p=>(p.events||[]).map(h=>{const{scheduleTiming:d}=pa({tournamentRecord:p,event:h});return{[h.eventId]:{event:h,scheduleTiming:d}}})).flat()),u={averageTimes:[{minutes:{default:e}}],recoveryTimes:[{minutes:{default:t}}]};n||(n=c==null?void 0:c.filter(p=>{const h=p.schedule;return Xa({schedule:h})&&(!o||p.schedule.scheduledDate===o)}));const l=n==null?void 0:n.filter(p=>!s.length||s.includes(p.schedule.venueId));return{bookings:l==null?void 0:l.map(({eventId:p,schedule:h,matchUpFormat:d})=>{const{event:m,scheduleTiming:g}=a[p],I=m==null?void 0:m.eventType,S={...g,defaultTiming:u,matchUpFormat:d},{averageMinutes:T,recoveryMinutes:E}=qu({timingDetails:S,eventType:I}),{courtId:y,venueId:b}=h,N=de(h.scheduledTime),A=An(N,T);return{recoveryMinutes:E,averageMinutes:T,periodLength:i,startTime:N,courtId:y,endTime:A,venueId:b}}).filter(Boolean),relevantMatchUps:l,dateScheduledMatchUps:n}}function ow({calculateStartTimeFromCourts:t=!0,remainingScheduleTimes:e,defaultRecoveryMinutes:n,averageMatchUpMinutes:r,clearScheduleDates:s,tournamentRecords:i,tournamentRecord:o,periodLength:c,scheduleDate:a,startTime:u,venueIds:l,matchUps:f,endTime:p}){if(o&&!i&&(i={[o.tournamentId]:o}),typeof i!="object"||!Object.keys(i).length)return{error:Gt};c=c??Al({recoveryMinutes:n,averageMatchUpMinutes:r});const{courts:h,venues:d}=Co({dates:[a],ignoreDisabled:!0,tournamentRecords:i}),m=(h==null?void 0:h.filter(b=>!l||l.includes(b.venueId)))??[];u=u??yc({courts:m,scheduleDate:a,startTime:!0}),p=p??yc({courts:m,scheduleDate:a,endTime:!0});const{bookings:g,dateScheduledMatchUps:I}=oh({defaultRecoveryMinutes:n,averageMatchUpMinutes:r,tournamentRecords:i,scheduleDate:a,periodLength:c,venueIds:l,matchUps:f}),S={calculateStartTimeFromCourts:t,remainingScheduleTimes:e,averageMatchUpMinutes:r,clearScheduleDates:s,date:a,periodLength:c,startTime:u,bookings:g,endTime:p,courts:m},{scheduleTimes:T}=Tp(S),E=(l==null?void 0:l.length)===1&&l[0]||(d==null?void 0:d.length)===1&&d[0].venueId||void 0;return{dateScheduledMatchUpIds:I==null?void 0:I.map(kn("matchUpId")),dateScheduledMatchUps:I,scheduleTimes:T,venueId:E}}function Vy({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,scheduleCompletedMatchUps:n,containedStructureIds:r,matchUpNotBeforeTimes:s,matchUpScheduleTimes:i,matchUpDependencies:o,clearScheduleDates:c,tournamentRecords:a,periodLength:u,scheduleDate:l,useGarman:f,matchUps:p,courts:h,venues:d}){var S;const m={},g=[],I=[];for(const T of d){const{rounds:E=[],venueId:y}=T,{scheduledRoundsDetails:b,greatestAverageMinutes:N,orderedMatchUpIds:A,minutesMap:C}=eh({scheduleCompletedMatchUps:n,containedStructureIds:r,tournamentRecords:a,periodLength:u,matchUps:p,rounds:E});I.push(...A??[]);const{groupedRounds:v}=sw({scheduledRoundsDetails:b,greatestAverageMinutes:N,garmanSinglePass:!0});let P,U,O=[];f&&({scheduleTimes:O,dateScheduledMatchUpIds:P,dateScheduledMatchUps:U}=ow({averageMatchUpMinutes:(S=v[0])==null?void 0:S.averageMinutes,scheduleDate:Bt(l),venueIds:[T.venueId],clearScheduleDates:c,tournamentRecords:a,periodLength:u,matchUps:p}));const D=rw({matchUpPotentialParticipantIds:t,individualParticipantProfiles:e,dateScheduledMatchUpIds:P,greatestAverageMinutes:N,matchUpNotBeforeTimes:s,matchUpScheduleTimes:i,matchUpDependencies:o,clearScheduleDates:c,scheduleDate:l,minutesMap:C,matchUps:p}),M=D.clearDate;({dateScheduledMatchUpIds:P,dateScheduledMatchUps:U}=D);const{matchUpsToSchedule:w,matchUpMap:k}=iw({matchUpPotentialParticipantIds:t,scheduleCompletedMatchUps:n,dateScheduledMatchUpIds:P,matchUpNotBeforeTimes:s,orderedMatchUpIds:A,clearDate:M,matchUps:p}),_=h.filter(F=>F.venueId===y);m[y]={previousRemainingScheduleTimes:[],courtsCount:_.length,greatestAverageMinutes:N,scheduledRoundsDetails:b,dateScheduledMatchUps:U,matchUpsToSchedule:w,scheduleTimes:O,groupedRounds:v,venueCourts:_,minutesMap:C,matchUpMap:k},c||g.push(...P)}return{allDateScheduledMatchUpIds:g,venueScheduledRoundDetails:m,allDateMatchUpIds:I}}function cw(t,e){const n=jt(t.scheduleTime),r=jt(t.timeAfterRecovery),s=jt(e.scheduleTime),i=jt(e.timeAfterRecovery),o=n===s||r===i,c=n>s&&n<i,a=s>n&&s<r,u=r>s&&r<i,l=i>n&&i<r;return bt({hasOverlap:o||c||u||a||l,startAisContained:c,endAisContained:u,startBisContained:a,endBisContained:l},!0)}function ch({individualParticipantProfiles:t,matchUpNotBeforeTimes:e,matchUpDependencies:n,scheduleTime:r,matchUp:s,details:i}){var d,m,g,I,S;const o=(((d=n==null?void 0:n[s.matchUpId])==null?void 0:d.participantIds)||[]).flat(),c=((g=(m=i==null?void 0:i.minutesMap)==null?void 0:m[s.matchUpId])==null?void 0:g.averageMinutes)||0,a=((S=(I=i==null?void 0:i.minutesMap)==null?void 0:I[s.matchUpId])==null?void 0:S.recoveryMinutes)||0,u=o.every(T=>{var v;ru({individualParticipantProfiles:t,participantId:T});const E=t[T];if(!E.timeAfterRecovery)return!0;const y=de((v=s==null?void 0:s.schedule)==null?void 0:v.endTime),b=y?An(y,vt(a)):An(r,vt(c)+vt(a));return!!![...Object.keys(E.potentialBookings).filter(P=>P!==s.drawId).map(P=>E.potentialBookings[P]).flat(),...E.bookings].find(P=>cw({scheduleTime:r,timeAfterRecovery:b},P).hasOverlap)}),l=e[s.matchUpId],p=(l?ea(Pe(l),Pe(r),!1):0)>=0;return{enoughTime:u&&p}}function ah({individualParticipantProfiles:t,matchUpPotentialParticipantIds:e,matchUpDailyLimits:n={},matchUp:r}){const{matchUpId:s,matchUpType:i}=r,{enteredIndividualParticipantIds:o}=bl(r),c=(r.roundPosition&&e[s]||[]).flat(),a=Vt(o.concat(...c));return a.forEach(l=>{ru({individualParticipantProfiles:t,participantId:l})}),{participantIdsAtLimit:a.filter(l=>{const f=t[l];if(f)return[i,Nr].find(p=>{var m;const h=((m=f.counters)==null?void 0:m[p])||0,d=n[p]||0;return h&&d&&h>=d})}),relevantParticipantIds:a}}const aw="deleteDrawDefinitions",uw="autoSchedulingAudit",jy="deleteEvents";function Gy({autoSchedulingAudit:t,tournamentRecords:e}){var o;Ht({topic:ha,payload:t});const n=c=>c?Object.values(c).reduce((u,l)=>u+l.length||0,0):0,r=((t==null?void 0:t.schedulingProfile)||[]).reduce((c,a)=>c+a.venues.reduce((u,l)=>u+l.rounds.length,0),0),s={scheduledDatesCount:(o=t.scheduledDates)==null?void 0:o.length,noTimeMatchUpIdsCount:n(t==null?void 0:t.noTimeMatchUpIds),scheduledMatchUpIdsCount:n(t==null?void 0:t.scheduledMatchUpIds),overLimitMatchUpIdsCount:n(t==null?void 0:t.overLimitMatchUpIds),requestConflictsCount:n(t==null?void 0:t.requestConflicts),profileRoundsCount:r},i={itemType:uw,itemValue:s};for(const c of Object.values(e))_s({tournamentRecord:c,timeItem:i})}function lw({schedulingProfileModifications:t,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:n,schedulingProfileIssues:r,dateSchedulingProfiles:s,containedStructureIds:i,matchUpDependencies:o,matchUpDailyLimits:c,clearScheduleDates:a,schedulingProfile:u,tournamentRecords:l,personRequests:f,periodLength:p,matchUps:h,courts:d,dryRun:m}){var U,O,D,M,w,k,_;const g={},I={},S={},T={},E={},y={},b={},N={},A={},C={};for(const F of s){const L=Bt(F==null?void 0:F.scheduleDate),W=(F==null?void 0:F.venues)||[],j={},H={},B=(Q,X)=>{Q.forEach(Z=>{const nt=H[Z].counters;nt[X]?nt[X]+=1:nt[X]=1,nt[Nr]?nt[Nr]+=1:nt[Nr]=1})};S[L]={},T[L]={},g[L]={},I[L]={},b[L]=[],N[L]=[],A[L]=[],C[L]=[];const R={};h.forEach(Q=>{var X;(X=Q.schedule)!=null&&X.scheduledDate&&as(L,Bt(Q.schedule.scheduledDate))&&Dc({matchUpPotentialParticipantIds:j,matchUpNotBeforeTimes:R,matchUp:Q})});const{venueScheduledRoundDetails:x,allDateMatchUpIds:q}=Vy({matchUpPotentialParticipantIds:j,individualParticipantProfiles:H,scheduleCompletedMatchUps:n,containedStructureIds:i,matchUpNotBeforeTimes:R,matchUpScheduleTimes:y,matchUpDependencies:o,clearScheduleDates:a,tournamentRecords:l,useGarman:!0,periodLength:p,scheduleDate:L,matchUps:h,courts:d,venues:W}),V=10;let Y=0,z;const J=10;for(;!z;){for(const{venueId:Q}of W){let X=0;const Z=x[Q];for(;Z.courtsCount&&((U=Z.scheduleTimes)!=null&&U.length)&&((O=Z.matchUpsToSchedule)!=null&&O.length)&&X<=Z.courtsCount;){const{scheduleTime:nt,attempts:rt=0}=Z.scheduleTimes.shift(),K=Z.matchUpsToSchedule.find(it=>{var wt,Xt;const{matchUpId:st,matchUpType:dt}=it,{participantIdsAtLimit:mt,relevantParticipantIds:Mt}=ah({matchUpPotentialParticipantIds:j,individualParticipantProfiles:H,matchUpDailyLimits:c,matchUp:it});if(mt.length)return N[L].includes(st)||N[L].push(st),!1;const{scheduledDependent:Nt}=$y({matchUpScheduleTimes:y,matchUpDependencies:o,scheduleTime:nt,matchUpId:st,details:Z});if(Nt)return!1;const{dependenciesScheduled:St,remainingDependencies:ct}=rh({matchUpScheduleTimes:y,matchUpDependencies:o,allDateMatchUpIds:q,matchUp:it});if(!St)return T[L][st]||(T[L][st]=[]),T[L][st].push({scheduleTime:nt,remainingDependencies:ct}),!1;const{enoughTime:Et}=ch({individualParticipantProfiles:H,matchUpNotBeforeTimes:R,matchUpDependencies:o,scheduleTime:nt,details:Z,matchUp:it});if(!Et)return S[L][st]||(S[L][st]=[]),S[L][st].push({scheduleTime:nt}),!1;const gt=Z.greatestAverageMinutes,{conflicts:Ft}=sh({potentials:e,averageMatchUpMinutes:gt,requestConflicts:C,personRequests:f,scheduleTime:nt,scheduleDate:L,matchUp:it});if(Ft!=null&&Ft.length)return E[L]||(E[L]=[]),E[L].push(...Ft),!1;B(Mt,dt);const yt=(Xt=(wt=Z.minutesMap)==null?void 0:wt[st])==null?void 0:Xt.recoveryMinutes;return su({matchUpPotentialParticipantIds:j,individualParticipantProfiles:H,matchUpNotBeforeTimes:R,averageMatchUpMinutes:gt,matchUpDependencies:o,recoveryMinutes:yt,scheduleTime:nt,matchUp:it}),y[st]=nt,!0});Z.matchUpsToSchedule=Z.matchUpsToSchedule.filter(({matchUpId:it})=>it!==(K==null?void 0:K.matchUpId)),K?X+=1:(I[L][Q]||(I[L][Q]=[]),I[L][Q].push({scheduleTime:nt,attempts:rt+1}))}(D=Z.matchUpsToSchedule)!=null&&D.length&&(I[L][Q]=(M=I[L][Q])==null?void 0:M.filter(nt=>{const rt=nt.attempts<V;return rt&&Z.scheduleTimes.push(nt),!rt})),(!((w=Z.scheduleTimes)!=null&&w.length)||!((k=Z.matchUpsToSchedule)!=null&&k.length))&&(Z.complete=!0)}Y+=1,z=W.every(({venueId:Q})=>x[Q].complete)||Y===J}for(const{venueId:Q}of W){const X=x[Q].matchUpMap;Object.keys(X).forEach(Z=>{const nt=l[Z];nt&&Object.keys(X[Z]).forEach(rt=>{const{drawDefinition:K}=Ks({tournamentRecord:nt,drawId:rt});K&&X[Z][rt].forEach(({matchUpId:st})=>{const dt=y[st];if(dt){const mt=dt.split(":").map(cs).join(":"),Mt=`${Bt(L)}T${mt}`;m?b[L].push(st):(wi({drawDefinition:K,scheduledTime:Mt,matchUpId:st}).success&&b[L].push(st),Q&&bc({tournamentRecord:nt,drawDefinition:K,matchUpId:st,venueId:Q}))}})})}),A[L]=x[Q].matchUpsToSchedule.map(Qe),g[L][Q]=x[Q].scheduleTimes.sort((Z,nt)=>jt(Z.scheduleTime)-jt(nt.scheduleTime))}for(const Q of F.venues)for(const X of Q.rounds){const nt=(((_=X.matchUps)==null?void 0:_.map(({matchUpId:K})=>K))||[]).filter(K=>b[L].includes(K));X.canScheduledMatchUpIds=nt;let rt=Math.round(nt.length/X.matchUpsCount*1e4)/100;(rt===1/0||isNaN(rt))&&(rt=0),X.possibleToSchedulePct=rt,X.matchUpsCount===nt.length&&(X.possibleToSchedule=!0)}}const v=s.map(({scheduleDate:F})=>F),P={timeStamp:Date.now(),overLimitMatchUpIds:N,scheduledMatchUpIds:b,schedulingProfile:u,noTimeMatchUpIds:A,requestConflicts:C,scheduledDates:v};return Gy({tournamentRecords:l,autoSchedulingAudit:P}),{...$,schedulingProfileModifications:t,schedulingProfileIssues:r,scheduleTimesRemaining:g,dateSchedulingProfiles:s,skippedScheduleTimes:I,recoveryTimeDeferredMatchUpIds:S,dependencyDeferredMatchUpIds:T,matchUpScheduleTimes:y,overLimitMatchUpIds:N,scheduledMatchUpIds:b,noTimeMatchUpIds:A,requestConflicts:C,scheduledDates:v}}function Wy({averageMinutes:t,startTime:e,endTime:n,court:r,date:s}){if(!Array.isArray(r.dateAvailability))return{error:Tt,stack:"getEarliestCourtTime"};const i=yc({scheduleDate:s,courts:[r],startTime:!0}),o=yc({scheduleDate:s,courts:[r],endTime:!0});e=e||i,n=n||o;const c=Ga({court:r,date:s}),a=Tc({courtDate:c}),u=Pe(e),l=Pe(n);return{earliestCourtTime:a.reduce((p,h)=>{const d=Pe(h.startTime),m=Pe(h.endTime);if(d>l||m<u)return p;const g=u>d?u:d;if(ea(g,m)>=t){const T=de(g.toISOString());(!p||T<p)&&(p=T)}return p},void 0),courtStartTime:i,courtEndTime:o}}function dw({schedulingProfileModifications:t,checkPotentialRequestConflicts:e,scheduleCompletedMatchUps:n,schedulingProfileIssues:r,dateSchedulingProfiles:s,containedStructureIds:i,matchUpDependencies:o,matchUpDailyLimits:c,clearScheduleDates:a,tournamentRecords:u,periodLength:l=30,schedulingProfile:f,personRequests:p,matchUps:h,courts:d,dryRun:m}){var P;const g={},I={},S={},T={},E={},y={},b={},N={},A={};for(const U of s){const O=Bt(U==null?void 0:U.scheduleDate),D=(U==null?void 0:U.venues)||[],M={},w={},k=(J,Q)=>{J.forEach(X=>{const Z=w[X].counters;Z[Q]?Z[Q]+=1:Z[Q]=1,Z[Nr]?Z[Nr]+=1:Z[Nr]=1})};g[O]={},I[O]={},y[O]=[],b[O]=[],N[O]=[],A[O]=[];const _={};h.forEach(J=>{var Q;(Q=J.schedule)!=null&&Q.scheduledDate&&as(O,Bt(J.schedule.scheduledDate))&&Dc({matchUpPotentialParticipantIds:M,matchUpNotBeforeTimes:_,matchUp:J})});const{allDateScheduledMatchUpIds:F,venueScheduledRoundDetails:L,allDateMatchUpIds:W}=Vy({matchUpPotentialParticipantIds:M,individualParticipantProfiles:w,scheduleCompletedMatchUps:n,containedStructureIds:i,matchUpNotBeforeTimes:_,matchUpScheduleTimes:E,matchUpDependencies:o,clearScheduleDates:a,tournamentRecords:u,periodLength:l,scheduleDate:O,matchUps:h,courts:d,venues:D}),j=h.filter(({matchUpId:J})=>F.includes(J)),{bookings:H}=oh({dateScheduledMatchUps:j,tournamentRecords:u,scheduleDate:O,periodLength:l}),{virtualCourts:B}=Sp({scheduleDate:O,periodLength:l,bookings:H,courts:d}),R=B==null?void 0:B.reduce((J,Q)=>{const{earliestCourtTime:X,courtEndTime:Z}=Wy({date:O,averageMinutes:0,court:Q});return(!J.startTime||Pe(X)<Pe(J.startTime))&&(J.startTime=X),(!J.endTime||Pe(Z)>Pe(J.endTime))&&(J.endTime=Z),J},{});let x=R.startTime;const q=({courtId:J,booking:Q})=>{var X;return(X=B==null?void 0:B.find(Z=>Z.courtId===J))==null?void 0:X.dateAvailability[0].bookings.push(Q)},V=10;let Y=0,z;for(;!z;){for(const{venueId:J}of D){const Q=L[J],X=Q.matchUpsToSchedule.length,Z=[],nt=[];let rt,K=0;for(;!rt;){for(const it of Q.matchUpsToSchedule){if(nt.length===Q.courtsCount||Z.length===Q.courtsCount){rt=!0;break}const{matchUpId:st,matchUpType:dt}=it,{participantIdsAtLimit:mt,relevantParticipantIds:Mt}=ah({matchUpPotentialParticipantIds:M,individualParticipantProfiles:w,matchUpDailyLimits:c,matchUp:it});if(mt.length){b[O].includes(st)||b[O].push(st);continue}const{dependenciesScheduled:Nt,remainingDependencies:St}=rh({matchUpScheduleTimes:E,matchUpDependencies:o,allDateMatchUpIds:W,matchUp:it});if(!Nt){I[O][st]||(I[O][st]=[]),I[O][st].push({remainingDependencies:St});continue}const ct=[],Et=B==null?void 0:B.reduce((gt,Ft)=>{var at,ot,Lt,ft;if(nt.includes(Ft.courtId))return gt;const{earliestCourtTime:yt}=Wy({averageMinutes:Q.greatestAverageMinutes,startTime:x,date:O,court:Ft});if(gt.scheduleTime&&jt(yt)>=jt(gt.scheduleTime))return gt;const{scheduledDependent:wt}=$y({matchUpScheduleTimes:E,matchUpDependencies:o,scheduleTime:yt,matchUpId:st,details:Q});if(wt)return gt;const{enoughTime:Xt}=ch({individualParticipantProfiles:w,matchUpNotBeforeTimes:_,matchUpDependencies:o,scheduleTime:yt,details:Q,matchUp:it});if(!Xt)return g[O][st]||(g[O][st]=[]),g[O][st].includes(yt)||g[O][st].push(yt),gt;const $t=((ot=(at=Q.minutesMap)==null?void 0:at[st])==null?void 0:ot.averageMinutes)||Q.greatestAverageMinutes,{conflicts:At}=sh({potentials:e,averageMatchUpMinutes:$t,requestConflicts:A,personRequests:p,scheduleTime:yt,scheduleDate:O,matchUp:it});if(At!=null&&At.length)return ct.push(...At),!1;k(Mt,dt);const Dt=(ft=(Lt=Q.minutesMap)==null?void 0:Lt[st])==null?void 0:ft.recoveryMinutes;return su({matchUpPotentialParticipantIds:M,individualParticipantProfiles:w,matchUpNotBeforeTimes:_,averageMatchUpMinutes:$t,matchUpDependencies:o,recoveryMinutes:Dt,scheduleTime:yt,matchUp:it}),(!gt.scheduleTime||jt(yt)<jt(gt.scheduleTime))&&(gt.averageMatchUpMinutes=$t,gt.recoveryMinutes=Dt,gt.scheduleTime=yt,gt.courtName=Ft.courtName,gt.courtId=Ft.courtId),gt},{});if(Et.scheduleTime){const{averageMatchUpMinutes:gt,recoveryMinutes:Ft,scheduleTime:yt,courtId:wt}=Et;E[st]=yt,T[st]=wt,Z.push(st),nt.push(wt);const Xt=yt,$t=An(Xt,gt);q({courtId:wt,booking:{averageMatchUpMinutes:gt,recoveryMinutes:Ft,periodLength:l,matchUpId:st,startTime:Xt,courtId:wt,endTime:$t,venueId:J}}),Q.matchUpsToSchedule=Q.matchUpsToSchedule.filter(Dt=>Dt.matchUpId!==st)}else ct!=null&&ct.length&&(S[O]||(S[O]=[]),S[O].push(...ct))}(nt.length===Q.courtsCount||Z.length===Q.courtsCount||!Q.matchUpsToSchedule.length)&&(rt=!0),Q.matchUpsToSchedule.length&&Z<Q.courtsCount&&(Pe(x)<Pe(R.endTime)?x=An(x,l):(rt=!0,Q.complete=!0)),K+=1,!rt&&K>=X&&(rt=!0)}(P=Q.matchUpsToSchedule)!=null&&P.length||(Q.complete=!0)}Y+=1,z=D.every(({venueId:J})=>L[J].complete)||Y===V}for(const{venueId:J}of D){const Q=L[J].matchUpMap;Object.keys(Q).forEach(X=>{const Z=u[X];Z&&Object.keys(Q[X]).forEach(nt=>{const{drawDefinition:rt}=Ks({tournamentRecord:Z,drawId:nt});rt&&Q[X][nt].forEach(({matchUpId:it})=>{const st=E[it],dt=T[it];if(st){const mt=st.split(":").map(cs).join(":"),Mt=`${Bt(O)}T${mt}`;m||(wi({drawDefinition:rt,scheduledTime:Mt,matchUpId:it}),Po({courtDayDate:O,tournamentRecords:u,tournamentRecord:Z,drawDefinition:rt,matchUpId:it,courtId:dt})),y[O].push(it)}})})}),N[O]=L[J].matchUpsToSchedule.map(Qe)}for(const J of U.venues)for(const Q of J.rounds){const X=(Q.matchUps??[]).map(({matchUpId:rt})=>rt),Z=X==null?void 0:X.filter(rt=>y[O].includes(rt));Q.canScheduledMatchUpIds=Z;let nt=Math.round(((Z==null?void 0:Z.length)||0)/Q.matchUpsCount*1e4)/100;(nt===1/0||isNaN(nt))&&(nt=void 0),Q.possibleToSchedulePct=nt,Q.matchUpsCount===(Z==null?void 0:Z.length)&&(Q.possibleToSchedule=!0)}}const C=s.map(({scheduleDate:U})=>U),v={timeStamp:Date.now(),overLimitMatchUpIds:b,scheduledMatchUpIds:y,schedulingProfile:f,noTimeMatchUpIds:N,requestConflicts:A,scheduledDates:C};return Gy({tournamentRecords:u,autoSchedulingAudit:v}),{...$,schedulingProfileModifications:t,schedulingProfileIssues:r,dateSchedulingProfiles:s,recoveryTimeDeferredMatchUpIds:g,dependencyDeferredMatchUpIds:I,matchUpScheduleTimes:E,overLimitMatchUpIds:b,scheduledMatchUpIds:y,noTimeMatchUpIds:N,requestConflicts:A,scheduledDates:C}}function wc({tournamentRecords:t,requestType:e}){if(typeof t!="object"||!Object.keys(t).length)return{error:Gt};const n={};for(const r of Object.values(t)){const{extension:s}=Bn({name:nc,tournamentRecord:r}),i=(s==null?void 0:s.value)||[];for(const o of i){const{personId:c,requests:a}=o||{};n[c]||(n[c]=[]);for(const u of a)e&&u.requestType!==e||n[c].push(u)}}return{personRequests:n}}function uh({tournamentRecords:t,personRequests:e}){if(!t)return{error:Gt};if(!e)return{...$};const n=Object.values(t);for(const r of n){const s=r.participants??[],i=[];for(const o of Object.keys(e))if(Ps({tournamentParticipants:s,personId:o})){const c=e[o];c.length&&i.push({personId:o,requests:c})}Object.keys(i).length&&Ti({tournamentRecord:r,extension:{name:nc,value:i}})}return{...$}}function fw({tournamentRecords:t,personId:e,requests:n}){if(!t)return{error:Gt};if(typeof e!="string")return{error:tt};if(!Array.isArray(n))return{error:tt};const{personRequests:r}=wc({tournamentRecords:t}),{mergeCount:s}=Hy({personRequests:r,personId:e,requests:n});return s&&r?uh({tournamentRecords:t,personRequests:r}):{error:tt}}function Hy({personRequests:t,personId:e,requests:n}){t[e]||(t[e]=[]);const r=n.filter(({requestType:s})=>s).map(s=>{let{date:i,startTime:o,endTime:c}=s;return s.requestType===rd&&(i=Bt(i),o=de(o),c=de(c),i&&o&&c)?{date:i,startTime:o,endTime:c,requestType:s.requestType}:s}).filter(Boolean);for(const s of r)s.requestId=Lg(),t[e].push(s);return{mergeCount:r.length}}function pw({tournamentRecords:t,requestType:e,requestId:n,personId:r,date:s}){if(typeof t!="object"||!Object.keys(t).length)return{error:Gt};const{personRequests:i}=wc({tournamentRecords:t}),o=a=>{var u;i&&(i[a]=i[a].filter(l=>(!e||l.requestType!==e)&&(!n||l.requestId!==n)&&(!s||l.date!==s)),(u=i==null?void 0:i[a])!=null&&u.length||delete i[a])},c=!e&&!n&&!r&&!s;if(!c){if(r&&(i!=null&&i[r]))o(r);else if(i)for(const a of Object.keys(i))o(a)}return c||!i||!Object.keys(i).length?Ku({tournamentRecords:t,name:nc}):uh({tournamentRecords:t,personRequests:i})}function hw({tournamentRecords:t,requests:e,personId:n}){if(!t)return{error:Gt};if(!Array.isArray(e))return{error:tt};const r=e.map(({requestId:c})=>c).filter(Boolean),{personRequests:s}=wc({tournamentRecords:t}),i=c=>{s&&(s[c]=s[c].map(a=>{if(!r.includes(a.requestId))return a;const u=e.find(l=>l.requestId===a.requestId);if(u.requestType)return Object.assign(a,u)}).filter(Boolean))};if(n&&(s!=null&&s[n]))i(n);else if(s)for(const c of Object.keys(s))i(c);const o=e.filter(c=>!c.requestId);return o.length&&Hy({personRequests:s,personId:n,requests:o}),uh({tournamentRecords:t,personRequests:s})}function lh({scheduleAttributes:t=["scheduledDate","scheduledTime"],ignoreMatchUpStatuses:e=We,tournamentRecord:n,scheduledDates:r,venueIds:s=[]}){if(typeof n!="object")return{error:et};if(!Array.isArray(e)||!Array.isArray(s))return{error:tt};s.length&&t.push("venueId");const o=(He({matchUpFilters:{scheduledDates:r},tournamentRecord:n}).matchUps||[]).filter(u=>u.matchUpStatus&&!e.includes(u.matchUpStatus)&&Xa({schedule:u.schedule,scheduleAttributes:t})&&(!(s!=null&&s.length)||s.includes(u.schedule.venueId))).map(Qe),c=He({tournamentRecord:n,inContext:!1}).matchUps||[];let a=0;for(const u of c)o.includes(u.matchUpId)&&(u.timeItems=(u.timeItems||[]).filter(l=>(l==null?void 0:l.itemType)&&![Qs,oo,ga,Ia,Sa].includes(l==null?void 0:l.itemType)),a+=1);return{...$,clearedScheduleCount:a}}function qy({scheduleAttributes:t=["scheduledDate","scheduledTime"],ignoreMatchUpStatuses:e=We,tournamentRecords:n,scheduledDates:r,venueIds:s}){const i=or(n)?Object.values(n).map(({tournamentId:o})=>o).filter(Boolean):[];if(!(i!=null&&i.length))return{error:Gt};for(const o of i){const c=n[o],a=lh({ignoreMatchUpStatuses:e,scheduleAttributes:t,tournamentRecord:c,scheduledDates:r,venueIds:s});if(a.error)return a}return{...$}}function Yy({tournamentRecord:t}){var i;if(!t)return{error:et};const{policy:e}=Xi({policyType:ff,tournamentRecord:t}),{extension:n}=Bn({name:Ji,tournamentRecord:t}),r=(i=n==null?void 0:n.value)==null?void 0:i.dailyLimits,s=e==null?void 0:e.defaultDailyLimits;return{matchUpDailyLimits:r||s}}function zy({tournamentRecords:t,tournamentId:e}){if(typeof t!="object"||!Object.keys(t).length)return{error:Gt};const n=Object.keys(t).filter(s=>!e||s===e);let r;return n.forEach(s=>{const i=t[s],{matchUpDailyLimits:o}=Yy({tournamentRecord:i});r=o}),{matchUpDailyLimits:r}}function dh({checkPotentialRequestConflicts:t=!0,scheduleCompletedMatchUps:e,clearScheduleDates:n,scheduleDates:r=[],tournamentRecords:s,periodLength:i,dryRun:o,pro:c}){if(!s)return{error:Gt};if(!Array.isArray(r))return{error:tt};const a=Mc({tournamentRecords:s});if(a.error)return a;const{schedulingProfile:u=[],issues:l=[],modifications:f}=a,p=Object.assign({},...Object.values(s).map(b=>Nc({tournamentRecord:b}).containedStructures)),h=r.map(b=>{if(Yn(b))return Bt(b)}).filter(Boolean),d=u.map(b=>b.scheduleDate).map(b=>Yn(b)&&Bt(b)).filter(b=>b&&(!r.length||h.includes(b)));if(!d.length)return{error:ev};if(n&&!o){const b=Array.isArray(n)?n:[];qy({tournamentRecords:s,scheduledDates:b})}const{courts:m}=Co({dates:r,ignoreDisabled:!0,tournamentRecords:s}),{matchUps:g}=ks({matchUpFilters:{matchUpTypes:[Oe,me]},afterRecoveryTimes:!0,nextMatchUps:!0,tournamentRecords:s}),{matchUpDependencies:I}=fr({includeParticipantDependencies:!0,tournamentRecords:s,matchUps:g}),{matchUpDailyLimits:S}=zy({tournamentRecords:s}),{personRequests:T}=wc({requestType:rd,tournamentRecords:s}),E=u.filter(b=>{const N=Bt(b==null?void 0:b.scheduleDate);return d.includes(N)}).sort((b,N)=>new Date(b.scheduleDate).getTime()-new Date(N.scheduleDate).getTime()),y={schedulingProfileModifications:f,checkPotentialRequestConflicts:t,scheduleCompletedMatchUps:e,schedulingProfileIssues:l,dateSchedulingProfiles:E,containedStructureIds:p,matchUpDependencies:I,matchUpDailyLimits:S,clearScheduleDates:n,tournamentRecords:s,schedulingProfile:u,personRequests:T,periodLength:i,matchUps:g,dryRun:o,courts:m};return c?dw(y):lw(y)}function Ky({event:t}){return t?Yu({event:t,name:qr}):{error:Wt}}function mw({tournamentRecords:t,eventId:e}){if(!t)return{error:Gt};if(typeof e!="string")return{error:Tt,info:"missing eventId"};for(const n of Object.values(t)){const{event:r}=Je({tournamentRecord:n,eventId:e});if(r)return Ky({event:r})}return{error:wn}}function fh({tournamentParticipants:t,tournamentRecord:e,drawDefinition:n,participantId:r,matchUpId:s,matchUp:i,event:o}){if(!r)return{error:Ce};if(!s)return{error:Rn};if(t=t??(e==null?void 0:e.participants),t!=null&&t.length){if(!i&&n){const f=ie({tournamentParticipants:t,inContext:!0,drawDefinition:n,matchUpId:s,event:o});if(!f.matchUp)return{error:Ye};i=f.matchUp}const a=Fa({matchUp:i});if(a.error)return a;const{checkedInParticipantIds:u,allRelevantParticipantIds:l}=a;if(!l.includes(r))return{error:bs};if(u.includes(r))return{error:ug}}return Ln({tournamentRecord:e,drawDefinition:n,matchUpId:s,timeItem:{itemType:Mf,itemValue:r}})}function ph({tournamentParticipants:t,tournamentRecord:e,drawDefinition:n,participantId:r,matchUpId:s,matchUp:i,event:o}){if(!r)return{error:Ce};if(!s&&!i)return{error:$e};if(t=t??(e==null?void 0:e.participants),!i){const l=ie({tournamentParticipants:t,inContext:!0,drawDefinition:n,matchUpId:s,event:o});if(l.error)return l;if(!l.matchUp)return{error:Ye};i=l.matchUp}const{matchUpStatus:c,score:a}=i;if(c&&xg.includes(c)||c&&We.includes(c)||Be({score:a}))return{error:B1};if(t!=null&&t.length){const{checkedInParticipantIds:l,allRelevantParticipantIds:f}=Fa({matchUp:i});if(!(f!=null&&f.includes(r)))return{error:bs};if(!l.includes(r))return{error:fv};const{sideParticipantIds:p,nestedIndividualParticipantIds:h}=Hf({matchUp:i}),d=p.indexOf(r);[0,1].includes(d)&&(h[d]||[]).forEach(m=>{Ln({drawDefinition:n,matchUpId:s,timeItem:{itemType:Df,itemValue:m}})})}return Ln({tournamentRecord:e,drawDefinition:n,matchUpId:s,timeItem:{itemType:Df,itemValue:r}})}function Jy(t){if(!(t!=null&&t.tournamentRecord))return{error:et};const{tournamentRecord:e,participantId:n,matchUpId:r,drawDefinition:s,event:i}=t,o=e.participants||[],c=eu({tournamentRecord:e,inContext:!0,drawDefinition:s,matchUpId:r,event:i});if(!c.matchUp)return{error:Ye};const a=c.matchUp,{checkedInParticipantIds:u=[]}=Fa({matchUp:a});return u.includes(n)?ph({tournamentParticipants:o,tournamentRecord:e,drawDefinition:s,participantId:n,matchUpId:r,matchUp:a}):fh({tournamentParticipants:o,tournamentRecord:e,drawDefinition:s,participantId:n,matchUpId:r,matchUp:a})}function gw(t){const{tournamentRecords:e}=t,{participantId:n,tournamentId:r,matchUpId:s,drawId:i}=t;if(!e||!r||!n||!s)return{error:Tt,stack:"toggleParticipantCheckInState"};const o=e[r],{drawDefinition:c,event:a}=Ks({tournamentRecord:o,drawId:i});return Object.assign(t,{drawDefinition:c,event:a,tournamentRecord:o}),Jy(t)}function Qy(t){var p;const{tournamentRecords:e}=t;if(!e)return{error:Gt};const{removePriorValues:n,tournamentId:r,courtDayDate:s,matchUpId:i,courtId:o,drawId:c}=t,a=e[r];if(!a)return{error:et};const{drawDefinition:u,event:l}=Ks({tournamentRecord:a,drawId:c}),f=ie({drawDefinition:u,event:l,matchUpId:i});if(f.error)return f;if(((p=f==null?void 0:f.matchUp)==null?void 0:p.matchUpType)===yr){const{itemValue:h}=Ei({timeItems:f.matchUp.timeItems||[],itemType:Qs}),d=o&&h.filter(g=>g.courtId!==o);return Ln({duplicateValues:!1,removePriorValues:n,tournamentRecord:a,drawDefinition:u,matchUpId:i,timeItem:{itemType:Qs,itemValue:d}})}else return Po({tournamentRecord:a,drawDefinition:u,courtDayDate:s,courtId:"",matchUpId:i})}function Iw({tournamentRecords:t}){return ky({extensionName:Ji,tournamentRecords:t})}const{stageOrder:Zy}=$P;function hh({tournamentRecords:t,schedulingProfile:e,tournamentRecord:n,withRoundId:r}){if(n&&!t){if(typeof n!="object")return{error:Tu};t={[n.tournamentId]:n}}if(e){const o=td({tournamentRecords:t,schedulingProfile:e});if(o.error)return o}if(!e&&t){const o=Mc({tournamentRecords:t});if(o.error)return o;e=o.schedulingProfile}if(!e)return{error:an};const s={};return{profileRounds:e.map(({venues:o,scheduleDate:c})=>o.map(({rounds:a})=>a.map(u=>{var f;const l=mh(u);return(f=l.roundSegment)!=null&&f.segmentsCount&&(s[l.id]=l.roundSegment.segmentsCount),bt({id:r?l.id:void 0,scheduleDate:c,...l})}))).flat(1/0),segmentedRounds:s}}function mh(t){const{containerStructureId:e,roundSegment:n,isRoundRobin:r,tournamentId:s,roundNumber:i,structureId:o,eventId:c,drawId:a}=t,u=r?e:o,l=[s,c,a,u,i].join("|");return bt({id:l,roundSegment:n,tournamentId:s,eventId:c,drawId:a,structureId:u,roundNumber:i})}function Xy(t){const e=t.length,n=t.filter(({sides:l})=>l==null?void 0:l.some(({bye:f})=>f)).length||0,r=t.filter(({winningSide:l,matchUpStatus:f})=>l||We.includes(f)).length||0,s=t.filter(({schedule:l})=>(l==null?void 0:l.scheduledDate)&&(l==null?void 0:l.scheduledTime)).length||0,i=e-n,o=i===r,c=i-s,a=i-s;return{unscheduledCount:c,incompleteCount:a,scheduledCount:s,completedCount:r,matchUpsCount:e,isScheduled:i===s,isComplete:o,byeCount:n}}function tE({excludeScheduleDateProfileRounds:t,excludeScheduledRounds:e,excludeCompletedRounds:n,inContextMatchUps:r,tournamentRecords:s,schedulingProfile:i,tournamentRecord:o,withSplitRounds:c,matchUpFilters:a,withRoundId:u,context:l}){var E;if(r&&!Array.isArray(r||typeof r[0]!="object"))return{error:tt,inContextMatchUps:r};if(o&&!s){if(typeof o!="object")return{error:Tu};s={[o.tournamentId]:o}}const f=typeof s!="object"||!Object.keys(s).length;if((!r||!i&&(t||n||i||c))&&f)return{error:Gt};const h=Object.values(s??{}).map(({events:y})=>y).flat(),{segmentedRounds:d,profileRounds:m}=s&&(t||n||i||c)&&hh({tournamentRecords:s,schedulingProfile:i})||{},g=t&&Object.assign({},...m.map(y=>({[y.id]:y}))),I=r||s&&((E=ks({tournamentRecords:s,matchUpFilters:a}))==null?void 0:E.matchUps)||[],S=[],T=I&&Object.values(I.reduce((y,b)=>{var R;const N=mh(b).id,A=d==null?void 0:d[N],C=[...((R=y[N])==null?void 0:R.matchUps)??[],b],{containerStructureId:v,stageSequence:P,structureName:U,tournamentId:O,isRoundRobin:D,matchUpType:M,roundNumber:w,roundOffset:k,structureId:_,eventName:F,roundName:L,drawName:W,eventId:j,drawId:H}=b,B=D?v:_;return{...y,[N]:{id:u?N:void 0,structureId:B,stageSequence:P,segmentsCount:A,structureName:U,tournamentId:O,matchUpType:M,roundNumber:w,roundOffset:k,eventName:F,roundName:L,drawName:W,matchUps:C,eventId:j,drawId:H}}},{})).map(y=>{const{minFinishingSum:b,winnerFinishingPositionRange:N}=Tw(y.matchUps),A=y.segmentsCount;if(A){const w=y.matchUps.length/A;return Ge(y.matchUps.sort((_,F)=>_.roundPosition-F.roundPosition),w).map((_,F)=>{const{unscheduledCount:L,incompleteCount:W,matchUpsCount:j,isScheduled:H,isComplete:B,byeCount:R}=Xy(_),x=eE({matchUps:y.matchUps,tournamentRecords:s,events:h,round:y});return bt({...y,...l,roundSegment:{segmentsCount:A,segmentNumber:F+1},winnerFinishingPositionRange:N,unscheduledCount:L,incompleteCount:W,minFinishingSum:b,matchUpsCount:j,isScheduled:H,roundTiming:x,isComplete:B,byeCount:R,matchUps:_})})}const{unscheduledCount:C,incompleteCount:v,matchUpsCount:P,isScheduled:U,isComplete:O,byeCount:D}=Xy(y.matchUps),M=eE({matchUps:y.matchUps,tournamentRecords:s,events:h,round:y});return bt({...y,...l,winnerFinishingPositionRange:N,unscheduledCount:C,incompleteCount:v,minFinishingSum:b,matchUpsCount:P,isScheduled:U,roundTiming:M,isComplete:O,byeCount:D})}).flat().filter(y=>{if(t){const P=Bt(t),U=u?y.id:mh(y).id;if(P&&g[U]&&Bt(g[U].scheduleDate)===P)return!1}const{isComplete:b,isScheduled:N}=y,v=(!n||!b)&&(!e||!N);return v||S.push(y),v}).sort(Sw)||[];return{...$,rounds:T,excludedRounds:S}}function eE({round:t,matchUps:e,events:n,tournamentRecords:r}){const s=n.find(p=>p.eventId===t.eventId),{eventType:i,category:o,categoryType:c}=s||{},{categoryName:a,ageCategoryCode:u}=o||{},l=Mn(e.map(({matchUpFormat:p})=>p));let f=0;return Object.keys(l).forEach(p=>{const h=l[p],d=th({categoryName:a||u,tournamentId:t.tournamentId,eventId:t.eventId,tournamentRecords:r,matchUpFormat:p,categoryType:c,eventType:i});if(d.error)return d;const m=d.averageMinutes*h;isNaN(f)||(f+=m)}),{roundMinutes:f}}function Sw(t,e){return t.eventName.localeCompare(e.eventName)||t.eventId.localeCompare(e.eventId)||(Zy[t==null?void 0:t.stage]||0)-(Zy[e==null?void 0:e.stage]||0)||e.matchUpsCount-t.matchUpsCount||`${t.stageSequence}-${t.roundNumber}-${t.minFinishingSum}`.localeCompare(`${e.stageSequence}-${e.roundNumber}-${e.minFinishingSum}`)}function Tw(t){return(t||[]).reduce((e,n)=>{var i,o;const r=(((i=n.finishingPositionRange)==null?void 0:i.winner)||[]).reduce((c,a)=>c+a,0),s=(((o=n.finishingPositionRange)==null?void 0:o.winner)||[]).join("-")||"";return!e.minFinishingSum||r<e.minFinishingSum?{minFinishingSum:r,winnerFinishingPositionRange:s}:e},{minFinishingSum:0,winnerFinishingPositionRange:""})}function yw({tournamentRecords:t,courtAssignments:e,courtDayDate:n}){if(!t)return{error:Gt};if(!Array.isArray(e))return{error:Tt,info:sn("courtAssignments")};const r=e.reduce((o,c)=>{const{tournamentId:a}=c;return o[a]||(o[a]=[]),o[a].push(c),o},{});let s;return Object.keys(r).every(o=>{const c=t[o];if(!c)return s={error:et},!1;const a=r[o].reduce((l,f)=>{const{drawId:p}=f;return l[p]||(l[p]=[]),l[p].push(f),l},{});Object.keys(a).every(l=>{const{drawDefinition:f}=Je({tournamentRecord:c,drawId:l});return f?(a[l].every(p=>{const{matchUpId:h,courtId:d}=p,m=Po({tournamentRecord:c,drawDefinition:f,courtDayDate:n,matchUpId:h,courtId:d});if(m.success)return m==null?void 0:m.success;s={error:Ov}}),!0):(s={error:lt},!1)})}),s||$}function Ew({tournamentRecords:t,competitionMatchUps:e,matchUpDependencies:n,allDateMatchUpIds:r=[],averageMatchUpMinutes:s=90,recoveryMinutes:i=0,recoveryMinutesMap:o,matchUpPotentialParticipantIds:c={},individualParticipantProfiles:a={},matchUpNotBeforeTimes:u={},matchUpDailyLimits:l={},checkPotentialRequestConflicts:f=!0,remainingScheduleTimes:p,clearScheduleDates:h,periodLength:d=30,scheduleDate:m,matchUpIds:g,venueIds:I,startTime:S,endTime:T,dryRun:E}){if(!t)return{error:Gt};if(!g)return{error:qc};if(!Yn(m))return{error:bn};if(isNaN(d)||isNaN(s)||isNaN(i))return{error:tt};e||({matchUps:e}=ks({tournamentRecords:t,nextMatchUps:!0})),n||({matchUpDependencies:n}=fr({includeParticipantDependencies:!0,matchUps:e,tournamentRecords:t})),e.forEach(B=>{var R;(R=B.schedule)!=null&&R.scheduledDate&&as(m,Bt(B.schedule.scheduledDate))&&Dc({matchUpPotentialParticipantIds:c,matchUpNotBeforeTimes:u,matchUp:B})});const y=g.map(B=>e.find(R=>R.matchUpId===B)).filter(Boolean),{venueId:b,scheduleTimes:N,dateScheduledMatchUpIds:A}=xy({tournamentRecords:t,remainingScheduleTimes:p,startTime:de(S),endTime:de(T),scheduleDate:Bt(m),averageMatchUpMinutes:s,clearScheduleDates:h,periodLength:d,venueIds:I}),C={},v=[],P={},U={},O={};e.filter(({matchUpId:B})=>A==null?void 0:A.includes(B)).forEach(B=>{var x;ih({matchUpPotentialParticipantIds:c,individualParticipantProfiles:a,matchUp:B,value:1});const R=(x=B.schedule)==null?void 0:x.scheduledTime;if(R){P[B.matchUpId]=R;const q=o==null?void 0:o[B.matchUpId];su({recoveryMinutes:q||i,matchUpPotentialParticipantIds:c,individualParticipantProfiles:a,matchUpNotBeforeTimes:u,averageMatchUpMinutes:s,matchUpDependencies:n,scheduleTime:R,matchUp:B})}});let M=y.filter(B=>{const R=A==null?void 0:A.includes(B.matchUpId),x=[re,te,De,zn,In,ce].includes(B==null?void 0:B.matchUpStatus);return!R&&!B.winningSide&&!x});const{matchUpMap:w,overLimitMatchUpIds:k,participantIdsAtLimit:_}=M.reduce((B,R)=>{const{drawId:x,tournamentId:q,matchUpType:V}=R,{participantIdsAtLimit:Y,relevantParticipantIds:z}=ah({individualParticipantProfiles:a,matchUpPotentialParticipantIds:c,matchUpDailyLimits:l,matchUp:R});return Y!=null&&Y.length?(B.overLimitMatchUpIds.push(R.matchUpId),B.participantIdsAtLimit.push(...Y),B):(z.forEach(J=>{ru({individualParticipantProfiles:a,participantId:J});const Q=a[J].counters;Q[V]?Q[V]+=1:Q[V]=1,Q[Nr]?Q[Nr]+=1:Q[Nr]=1}),B.matchUpMap[q]||(B.matchUpMap[q]={}),B.matchUpMap[q][x]?B.matchUpMap[q][x].push(R):B.matchUpMap[q][x]=[R],Dc({matchUpPotentialParticipantIds:c,matchUpNotBeforeTimes:u,matchUp:R}),B)},{matchUpMap:{},overLimitMatchUpIds:[],participantIdsAtLimit:[]});M=M.filter(({matchUpId:B})=>!k.includes(B));let F=0;const L=(N==null?void 0:N.length)||0,{personRequests:W}=wc({tournamentRecords:t,requestType:rd});for(;N!=null&&N.length&&M.length&&F<=L;){F++;const{scheduleTime:B}=N.shift(),R=M.find(x=>{const{matchUpId:q}=x,{dependenciesScheduled:V,remainingDependencies:Y}=rh({matchUpScheduleTimes:P,matchUpDependencies:n,allDateMatchUpIds:r,matchUp:x});if(!V)return O[q]||(O[q]=[]),O[q].push({scheduleTime:B,remainingDependencies:Y}),!1;const{enoughTime:z}=ch({individualParticipantProfiles:a,matchUpNotBeforeTimes:u,matchUpDependencies:n,scheduleTime:B,matchUp:x});if(!z)return U[q]||(U[q]=[]),U[q].push({scheduleTime:B}),!1;const{conflicts:J}=sh({potentials:f,averageMatchUpMinutes:s,requestConflicts:C,personRequests:W,scheduleTime:B,scheduleDate:m,matchUp:x});if(J!=null&&J.length)return!1;const Q=o==null?void 0:o[x.matchUpId];return su({recoveryMinutes:Q||i,matchUpPotentialParticipantIds:c,individualParticipantProfiles:a,matchUpNotBeforeTimes:u,averageMatchUpMinutes:s,matchUpDependencies:n,scheduleTime:B,matchUp:x}),P[x.matchUpId]=B,!0});M=M.filter(({matchUpId:x})=>x!==(R==null?void 0:R.matchUpId)),R||v.push(B)}M.forEach(B=>{ih({individualParticipantProfiles:a,matchUpPotentialParticipantIds:c,value:-1,matchUp:B})});const j=[];Object.keys(w).forEach(B=>{const R=t[B];R?Object.keys(w[B]).forEach(x=>{const{drawDefinition:q}=Ks({tournamentRecord:R,drawId:x});q&&w[B][x].forEach(({matchUpId:Y})=>{const z=P[Y];if(z){const J=z.split(":").map(cs).join(":"),Q=`${Bt(m)}T${J}`;E?j.push(Y):(wi({drawDefinition:q,matchUpId:Y,scheduledTime:Q}).success&&j.push(Y),b&&bc({tournamentRecords:t,tournamentRecord:R,drawDefinition:q,matchUpId:Y,venueId:b}))}})}):ze()&&console.log(is)});const H=Xf(M);return{...$,requestConflicts:Object.values(C),remainingScheduleTimes:N==null?void 0:N.map(({scheduleTime:B})=>B),individualParticipantProfiles:a,matchUpNotBeforeTimes:u,participantIdsAtLimit:_,skippedScheduleTimes:v,overLimitMatchUpIds:k,scheduledMatchUpIds:j,noTimeMatchUpIds:H,recoveryTimeDeferred:U,dependencyDeferred:O}}function bw(t){const e="reorderUpcomingMatchUps",{tournamentRecords:n}=t;if(typeof n!="object"||!Object.keys(n).length)return G({result:{error:Gt},stack:e});const{matchUpsContextIds:r,firstToLast:s}=t;if(!r)return G({result:{error:Tt},stack:e});const i=r==null?void 0:r.length;if(!i)return{...$};let o=0;return r.forEach((a,u)=>{const{tournamentId:l,drawId:f,matchUpId:p}=a;let h=u+(s?-1:1);h<0&&(h=i-1),h===i&&(h=0);const d=r[h].schedule.scheduledTime,m=c({tournamentId:l,scheduledTime:d,matchUpId:p,drawId:f});if(m.success)o++;else return m}),o===i?$:G({result:{error:Uv},stack:e});function c({tournamentId:a,scheduledTime:u,matchUpId:l,drawId:f}){const p=n[a],{drawDefinition:h}=Ks({tournamentRecord:p,drawId:f});return wi({drawDefinition:h,scheduledTime:u,matchUpId:l})}}function Nw({scheduleCompletedMatchUps:t,tournamentRecords:e,scheduledDate:n,matchUps:r}){if(!cr(r))return{error:tt};if(r.some(({hasContext:m})=>!m))return{info:"matchUps must have { inContext: true, nextMatchUps: true }",error:Pu};let i=nh({courtCompletedMatchUps:!0,withCourtGridRows:!0,minCourtGridRows:10,tournamentRecords:e,matchUpFilters:{localPerspective:!0,scheduledDate:n}});if(i.error)return i;const{rows:o}=i,c=[],a=m=>[(m.sides||[]).map(g=>{var I;return[g.participantId,(I=g.participant)==null?void 0:I.individualParticipantIds]}),(m.potentialParticipants||[]).flat().map(g=>[g.participantId,g.individualParticipantIds])].flat(1/0).filter(Boolean),u=o==null?void 0:o.reduce((m,g)=>{const I=[],S=[];Object.values(g).forEach(E=>{if(or(E)&&(E.matchUpId&&(I.push(E.matchUpId),c.push(E)),E.sides)){const y=a(E);S.push(...y)}});const T=Object.values(g).filter(E=>or(E)&&!E.matchUpId);return m.concat({matchUpIds:I,availableCourts:T,rowId:g.rowId,participantIds:S})},[]);r.filter(({matchUpStatus:m})=>m&&m!==pe.Bye&&(t||!We.includes(m))).sort(vo);const l=fr({matchUps:r.concat(c),includeParticipantDependencies:!0,tournamentRecords:e}).matchUpDependencies,f=[],p=[];for(;r.length&&u.length;){const m=u.shift(),g=[];for(;r.length&&m.availableCourts.length;){const I=r.concat(g).map(v=>v.matchUpId),S=r.shift(),T=S==null?void 0:S.matchUpId,E=T&&l[T].matchUpIds.concat(l[T].dependentMatchUpIds),y=T&&I.some(v=>l[T].matchUpIds.includes(v)),b=T&&p.some(v=>l[T].dependentMatchUpIds.includes(v)),N=m.matchUpIds.some(v=>E.includes(v)),A=a(S),C=m.participantIds.some(v=>A.includes(v));if(S&&!N&&!y&&!C&&!b){const v=m.availableCourts.shift();Object.assign(S.schedule,v.schedule),Object.assign(v,S),f.push(S),m.participantIds.push(...A),m.matchUpIds.push(T)}else S&&g.push(S)}r.push(...g),p.push(...m.matchUpIds)}const h=f.map(({matchUpId:m,tournamentId:g,schedule:I,drawId:S})=>({tournamentId:g,matchUpId:m,drawId:S,schedule:{...I,scheduledDate:n}}));return i=MT({tournamentRecords:e,matchUpDetails:h}),{...i,scheduled:f,notScheduled:r}}function Aw(t){const e="matchUpScheduleChange",{tournamentRecords:n}=t;if(typeof n!="object"||!Object.keys(n).length)return{error:Gt};const{sourceMatchUpContextIds:r,targetMatchUpContextIds:s,sourceCourtId:i,targetCourtId:o,courtDayDate:c}=t||{},{drawId:a,matchUpId:u,tournamentId:l}=r||{},{drawId:f,matchUpId:p,tournamentId:h}=s||{};if(!u&&!p)return G({result:{error:Tt},stack:e});const{matchUps:d}=ks({matchUpFilters:{matchUpIds:[u,p].filter(Boolean),drawIds:[a,f].filter(Boolean)},tournamentRecords:t.tournamentRecords}),m=d==null?void 0:d.find(({matchUpId:y})=>y===u),g=d==null?void 0:d.find(({matchUpId:y})=>y===p);let I=0;if(o&&u&&!p){const y=S({tournamentId:l,matchUpId:u,courtId:o,matchUp:m,drawId:a,tournamentRecords:n,sourceCourtId:i,courtDayDate:c});if(y!=null&&y.success&&I++,y.error)return G({result:y,stack:e})}else if(i&&o&&u&&p){const y=S({tournamentId:l,matchUpId:u,courtId:o,matchUp:m,drawId:a,tournamentRecords:n,sourceCourtId:i,courtDayDate:c});if(y.success&&I++,y.error)return G({result:y,stack:e,info:"source"});const b=S({tournamentId:h,sourceCourtId:o,matchUpId:p,matchUp:g,courtId:i,drawId:f,tournamentRecords:n,courtDayDate:c});if(b.success&&I++,b.error)return G({result:b,stack:e,info:"target"})}else return{error:Tt};return I?$:G({result:{error:zc},stack:e});function S(y){const{tournamentRecords:b,tournamentId:N,matchUp:A,drawId:C}=y,v=b[N],{drawDefinition:P}=Ks({tournamentRecord:v,drawId:C});return A.matchUpType===Jt?T({...y,tournamentRecord:v,drawDefinition:P}):E({...y,tournamentRecord:v,drawDefinition:P})}function T({removePriorValues:y,tournamentRecords:b,tournamentRecord:N,drawDefinition:A,sourceCourtId:C,courtDayDate:v,matchUpId:P,matchUp:U,courtId:O}){const D=[O].concat(U.schedule.allocatedCourts.map(({courtId:M})=>M).filter(M=>M!==C));return wl({removePriorValues:y,tournamentRecords:b,tournamentRecord:N,drawDefinition:A,courtDayDate:v,matchUpId:P,courtIds:D})}function E({tournamentRecords:y,tournamentRecord:b,drawDefinition:N,courtDayDate:A,matchUpId:C,courtId:v}){return Po({tournamentRecords:y,tournamentRecord:b,drawDefinition:N,courtDayDate:A,matchUpId:C,courtId:v})}}function vw(t){const e=ns(t);if(e.error)return e;const{tournamentRecord:n,drawDefinition:r}=e;return dy({...t,tournamentRecord:n,drawDefinition:r})}function Cw(t){const e=ns(t);if(e.error)return e;const{tournamentRecord:n,drawDefinition:r}=e;if(!r)return{error:lt};const{disableNotice:s,scheduledDate:i,matchUpId:o,removePriorValues:c}=t;return jp({removePriorValues:c,tournamentRecord:n,drawDefinition:r,disableNotice:s,scheduledDate:i,matchUpId:o})}function Pw(t){const e=ns(t);if(e.error)return e;const{tournamentRecord:n,drawDefinition:r}=e,{disableNotice:s,scheduledTime:i,matchUpId:o,removePriorValues:c}=t;return r?Gp({removePriorValues:c,tournamentRecord:n,drawDefinition:r,disableNotice:s,scheduledTime:i,matchUpId:o}):{error:lt}}function Uw(t){const e=ns(t);if(e.error)return e;const{tournamentRecord:n,drawDefinition:r}=e,{disableNotice:s,startTime:i,matchUpId:o}=t;return fy({tournamentRecord:n,drawDefinition:r,disableNotice:s,startTime:i,matchUpId:o})}function Ow(t){const e=ns(t);if(e.error)return e;const{tournamentRecord:n,drawDefinition:r}=e,{disableNotice:s,endTime:i,matchUpId:o}=t;return py({tournamentRecord:n,drawDefinition:r,disableNotice:s,endTime:i,matchUpId:o})}function Mw(t){const e=ns(t);if(e.error)return e;const{tournamentRecord:n,drawDefinition:r}=e,{disableNotice:s,stopTime:i,matchUpId:o}=t;return hy({tournamentRecord:n,drawDefinition:r,disableNotice:s,stopTime:i,matchUpId:o})}function Dw(t){const e=ns(t);if(e.error)return e;const{tournamentRecord:n,drawDefinition:r}=e,{disableNotice:s,resumeTime:i,matchUpId:o}=t;return my({tournamentRecord:n,drawDefinition:r,disableNotice:s,resumeTime:i,matchUpId:o})}function ww(t){const e=ns(t);if(e.error)return e;const{tournamentRecord:n,drawDefinition:r}=e,{disableNotice:s,participantId:i,officialType:o,matchUpId:c}=t;return gy({tournamentRecord:n,drawDefinition:r,disableNotice:s,participantId:i,officialType:o,matchUpId:c})}function kw(t){const e=ns(t);if(e.error)return e;const{tournamentRecord:n,drawDefinition:r}=e,{matchUpId:s,venueId:i,disableNotice:o,removePriorValues:c}=t;return r?bc({tournamentRecords:t.tournamentRecords,removePriorValues:c,tournamentRecord:n,drawDefinition:r,disableNotice:o,matchUpId:s,venueId:i}):{error:lt}}function _w(t){const e=ns(t);if(e.error)return e;const{tournamentRecord:n,drawDefinition:r}=e;if(!n)return{error:et};if(!r)return{error:lt};const{removePriorValues:s,tournamentRecords:i,disableNotice:o,courtDayDate:c,matchUpId:a,courtId:u}=t;return Po({removePriorValues:s,tournamentRecords:i,tournamentRecord:n,drawDefinition:r,disableNotice:o,courtDayDate:c,matchUpId:a,courtId:u})}function Fw(t){const e=ns(t);if(e.error)return e;const{tournamentRecord:n,drawDefinition:r}=e;if(!r)return{error:lt};const{removePriorValues:s,tournamentRecords:i,disableNotice:o,courtDayDate:c,matchUpId:a,courtIds:u}=t;return wl({removePriorValues:s,tournamentRecords:i,tournamentRecord:n,drawDefinition:r,disableNotice:o,courtDayDate:c,matchUpId:a,courtIds:u})}function Lw(t){const e=ns(t);if(e.error)return e;const{tournamentRecord:n,drawDefinition:r}=e,{removePriorValues:s,disableNotice:i,courtOrder:o,matchUpId:c}=t;return ED({removePriorValues:s,tournamentRecord:n,drawDefinition:r,disableNotice:i,courtOrder:o,matchUpId:c})}function ns({tournamentRecords:t,tournamentId:e,drawId:n}){if(!t)return{error:Gt};if(!n)return{error:Hn};if(typeof e!="string"&&(e=Fl({tournamentRecords:t,drawId:n}),!e))return{error:is};const r=t[e];if(!r)return{error:et};const s=Je({tournamentRecord:r,drawId:n});return s.error?G({stack:"addScheduleItems.getDrawDefinition",result:s}):{drawDefinition:s.drawDefinition,tournamentRecord:r}}const Rw={scheduleMatchUps:Ew,scheduleProfileRounds:dh,clearScheduledMatchUps:qy,bulkRescheduleMatchUps:bD,getScheduledRoundsDetails:eh,getMatchUpDependencies:fr,generateVirtualCourts:Sp,generateBookings:oh,proAutoSchedule:Nw,proConflicts:hT,matchUpScheduleChange:Aw,calculateScheduleTimes:xy,reorderUpcomingMatchUps:bw,bulkUpdateCourtAssignments:yw,removeMatchUpCourtAssignment:Qy,toggleParticipantCheckInState:gw,findMatchUpFormatTiming:th,modifyMatchUpFormatTiming:XD,modifyEventMatchUpFormatTiming:aD,getMatchUpFormatTimingUpdate:JD,getEventMatchUpFormatTiming:QD,removeEventMatchUpFormatTiming:mw,getMatchUpDailyLimitsUpdate:Iw,getMatchUpDailyLimits:zy,setMatchUpDailyLimits:ND,getProfileRounds:hh,getRounds:tE,assignMatchUpVenue:kw,assignMatchUpCourt:_w,allocateTeamMatchUpCourts:Fw,addMatchUpScheduleItems:vw,addMatchUpScheduledDate:Cw,addMatchUpScheduledTime:Pw,addMatchUpCourtOrder:Lw,addMatchUpStartTime:Uw,addMatchUpStopTime:Mw,addMatchUpResumeTime:Dw,addMatchUpEndTime:Ow,addMatchUpOfficial:ww,getSchedulingProfile:Mc,setSchedulingProfile:nu,addSchedulingProfileRound:Ry,validateSchedulingProfile:td,addPersonRequests:fw,getPersonRequests:wc,modifyPersonRequests:hw,removePersonRequests:pw};function gh({tournamentRecord:t,policyDefinitions:e,allowReplacement:n}){if(!t)return{error:et};if(!e||typeof e!="object")return{error:Au};t.extensions||(t.extensions=[]);const r=ge({tournamentRecord:t}).appliedPolicies??{},s=Object.keys(e).map(i=>{if(!r[i]||n)return r[i]=e[i],i}).filter(Boolean);if(s!=null&&s.length){const o=Ti({tournamentRecord:t,extension:{name:zi,value:r}});if(o.error)return o}return s!=null&&s.length?{...$,applied:s}:{error:ng}}function nE({policyDefinitions:t,allowReplacement:e,event:n}){if(!n)return{error:Wt};if(!t)return{error:Au};let r=0;n.extensions||(n.extensions=[]);const s=ge({event:n}).appliedPolicies??{};return Object.keys(t).forEach(i=>{(!s[i]||e)&&(s[i]=t[i],r++)}),r&&Yr({event:n,extension:{name:zi,value:s}}),r?$:{error:X1}}function Bw({event:t,policyType:e}){if(!e)return{error:Tt};if(!t)return{error:Wt};let n;if(t.extensions){const{appliedPolicies:r}=ge({event:t});r!=null&&r[e]&&(delete r[e],n=!0,Object.keys(r).length?Yr({event:t,extension:{name:zi,value:r}}):Yu({event:t,name:zi}))}return n?$:{error:jd}}function xw({tournamentRecords:t,policyDefinitions:e}){if(typeof t!="object"||!Object.keys(t).length)return{error:Gt};for(const n of Object.values(t)){const r=gh({allowReplacement:!0,tournamentRecord:n,policyDefinitions:e});if(r.error)return r}return{...$}}const $w={attachPolicies:xw};function Vw({tournamentRecords:t,policyDefinitions:e,scaleAttributes:n,participantId:r,inContext:s,personId:i}){let o=Ey({tournamentRecords:t,policyDefinitions:e,participantId:r,inContext:s,personId:i});if(o.error)return o;const{participant:c,tournamentId:a}=o;return o=Ts({participant:c,scaleAttributes:n}),o.error?{...o,tournamentId:a}:{...$,tournamentId:a,...o}}function jw(t){const{scheduleDates:e=[],tournamentRecords:n,periodLength:r=30}=t||{};if(typeof n!="object")return{error:Tu};if(!Array.isArray(e))return{error:tt};if(!e.every(Yn))return{error:bn};const i=[];let o=0;const c={},{schedulingProfile:a}=Mc({tournamentRecords:n});if(!a)return{issues:i,...$};const{matchUps:u}=ks({nextMatchUps:!0,tournamentRecords:n});for(const f of a){const{scheduleDate:p,venues:h=[]}=f;if(!(e!=null&&e.length)||e.includes(p)){for(const d of h||[])if(d){const{rounds:m}=d,g=[],{orderedMatchUpIds:I,scheduledRoundsDetails:S}=eh({tournamentRecords:n,periodLength:r,matchUps:u,rounds:m}),{matchUpDependencies:T}=fr({tournamentRecords:n,matchUps:u}),E=y=>{let b;return S==null||S.find((N,A)=>{const C=N.matchUpIds.includes(y);return C&&(b=A),C}),b};if(I==null||I.forEach((y,b)=>{var C;const N=I.slice(b+1),A=qe(N,((C=T==null?void 0:T[y])==null?void 0:C.matchUpIds)||[]);A.length&&g.push({matchUpId:y,shouldBeAfter:A})}),g.length){o+=g.length;const y=g.map(({matchUpId:b,shouldBeAfter:N})=>{const A=E(b),C=Vt(N.map(E));return c[p]||(c[p]={}),c[p][A]||(c[p][A]=[]),C.forEach(v=>{c[p][A].includes(v)||c[p][A].push(v)}),{matchUpId:b,matchUpRoundIndex:A,earlierRoundIndices:C,shouldBeAfter:N}});i.push(...y)}}}}const l={matchUpIdShouldBeAfter:Object.assign({},...i.map(f=>{const{matchUpId:p,shouldBeAfter:h,earlierRoundIndices:d}=f;return{[p]:{earlierRoundIndices:d,shouldBeAfter:h}}}))};return{issuesCount:o,profileIssues:l,roundIndexShouldBeAfter:c,...$}}function sd(){return`
8
8
  This project would not have been possible without the generous input and patience
@@ -23,14 +23,14 @@
23
23
 
24
24
  And a special thanks to my family for putting up with the long days and weeks and months of coding
25
25
  and conversations at all hours.
26
- `}function Gw({tournamentParticipants:t=[],possiblyDisablingAction:e,activeDrawPositions:n,positionAssignments:r,returnParticipants:s,appliedPolicies:i,drawDefinition:o,drawPosition:c,validActions:a,structureId:u,structure:l,drawId:f,event:p}){var A,C,v,P;if(n.includes(c))return{};const h=(A=a.find(U=>U.type===pc))==null?void 0:A.availableParticipantIds,d=(C=i==null?void 0:i[vs])==null?void 0:C.otherFlightEntries,m=(v=i==null?void 0:i[vs])==null?void 0:v.restrictQualifyingAlternates,g=(o.entries??[]).filter(({entryStage:U})=>!m||(l.stage===Pt?U===Pt:U!==Pt)).sort((U,O)=>(U.entryPosition??1/0)-(O.entryPosition??1/0)).map(({participantId:U})=>U).filter(Boolean),{allPositionedParticipantIds:I}=rS({drawDefinition:o}),S=r.map(U=>U.participantId).filter(Boolean),T=g.filter(U=>l.stage&&[Pt,It,Ie].includes(l.stage)?!(I!=null&&I.includes(U)):!S.includes(U)),y=((p==null?void 0:p.entries)??[]).filter(U=>U.entryStatus===dr&&rE({restrictQualifyingAlternates:m,structure:l,entry:U})&&(l.stage&&[Pt,It,Ie].includes(l.stage)?!(I!=null&&I.includes(U.participantId)):!S.includes(U.participantId))).sort((U,O)=>(U.entryPosition??1/0)-(O.entryPosition??1/0)).map(U=>U.participantId);let b=Vt(T.concat(y));if(d){const U=p?be({event:p}).flightProfile:void 0,O=(P=U==null?void 0:U.flights)==null?void 0:P.filter(D=>D.drawId!==f).map(D=>D.drawEntries.filter(M=>M.participantId&&![ti,Or,po].includes(M.entryStatus)&&!g.includes(M.participantId)).map(({participantId:M})=>M)).flat().filter(Boolean);O!=null&&O.length&&b.push(...O)}h!=null&&h.length&&(b=b.filter(U=>!h.includes(U)));const N=s?t==null?void 0:t.filter(U=>b.includes(U.participantId)):void 0;return N==null||N.forEach(U=>{const O=(o.entries??[]).find(D=>D.participantId===U.participantId);U.entryPosition=O==null?void 0:O.entryPosition}),N==null||N.sort((U,O)=>(U.entryPosition||1/0)-(O.entryPosition||1/0)),b.length?{validAlternatesAction:bt({payload:{drawId:f,structureId:u,drawPosition:c},willDisableLinks:e,method:tO,availableAlternatesParticipantIds:b,type:iT,availableAlternates:N})}:{}}function rE({restrictQualifyingAlternates:t,structure:e,entry:n}){const{stage:r}=e;if(!n.entryStage||n.entryStage===r||r===Pt&&!t||n.entryStage===It&&r===Re)return!0}const iu={[Jn]:{policyName:"matchUpActionsDefault",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[],disabledActions:[]}],participants:{enforceGender:!0},processCodes:{substitution:["RANKING.IGNORE","RATING.IGNORE"]}}},id="positionAction",Ih="matchUpAction";function sE({actionType:t=id,appliedPolicies:e,drawDefinition:n,structure:r}){var p;const s=t===id&&vs||t===Ih&&Jn,i=t===id&&lT||t===Ih&&iu,o=s&&((e==null?void 0:e[s])||(i==null?void 0:i[s])),c=(p=n.links)==null?void 0:p.filter(h=>{var d;return((d=h==null?void 0:h.target)==null?void 0:d.structureId)===(r==null?void 0:r.structureId)}),a=(c==null?void 0:c.map(({target:h})=>h.feedProfile))??[],{enabledStructures:u,disabledStructures:l}=o||{},f=l==null?void 0:l.find(h=>{const{stages:d,stageSequences:m,structureTypes:g,feedProfiles:I}=h;return(!(I!=null&&I.length)||Array.isArray(I)&&I.some(S=>a.includes(S)))&&(!(d!=null&&d.length)||Array.isArray(d)&&(d==null?void 0:d.includes(r==null?void 0:r.stage)))&&(!(g!=null&&g.length)||Array.isArray(g)&&(g==null?void 0:g.includes(r==null?void 0:r.structureType)))&&(!(m!=null&&m.length)||Array.isArray(m)&&m.includes(r==null?void 0:r.stageSequence))});return{enabledStructures:u,actionsDisabled:f,actionsPolicy:o}}function iE({activePositionOverrides:t,activeDrawPositions:e,action:n}){return n&&t.includes(n)?!0:!e.length}function oE({enabledStructures:t,drawDefinition:e,structure:n}){var u;if(t===!1)return{};if(!(t!=null&&t.length))return{policyActions:{enabledActions:[],disabledActions:[]}};const{stage:r,stageSequence:s,structureType:i}=n||{},o=(u=e.links)==null?void 0:u.filter(l=>{var f;return((f=l==null?void 0:l.target)==null?void 0:f.structureId)===(n==null?void 0:n.structureId)}),c=(o==null?void 0:o.map(({target:l})=>l.feedProfile))||[];return{policyActions:t.find(l=>{const{stages:f,stageSequences:p,structureTypes:h,feedProfiles:d}=l||{},m=!(f!=null&&f.length)||Array.isArray(f)&&f.includes(r),g=!(p!=null&&p.length)||Array.isArray(p)&&p.includes(s),I=!(h!=null&&h.length)||Array.isArray(h)&&h.includes(i),S=!(d!=null&&d.length)||Array.isArray(d)&&d.some(T=>c.includes(T));return g&&I&&S&&l&&m})}}function Pn({action:t,policyActions:e}){var s;const n=!(e!=null&&e.enabledActions)||((s=e==null?void 0:e.disabledActions)==null?void 0:s.length)&&e.disabledActions.includes(t);return n?!1:((e==null?void 0:e.enabledActions.length)===0||(e==null?void 0:e.enabledActions.includes(t)))&&!n}const Ww="replaceTieMatchUpParticipantId",Hw="assignTieMatchUpParticipantId",cE="removeTieMatchUpParticipantId",aE="assignMatchUpSideParticipant",qw="removeMatchUpSideParticipant",Yw="substituteParticipant",uE="REMOVE_SUBSTITUTION",zw="REPLACE_PARTICIPANT",lE="REMOVE_PARTICIPANT",dE="setMatchUpStatus",fE="SUBSTITUTION",Kw="SCHEDULE",pE="REFEREE",Jw="STATUS",hE="START",Qw="SCORE",mE="END";function Sh({restrictAdHocRoundParticipants:t=!0,policyDefinitions:e,tournamentParticipants:n=[],inContextDrawMatchUps:r,tournamentRecord:s,drawDefinition:i,participantId:o,matchUpsMap:c,sideNumber:a,matchUpId:u,event:l}){var Y,z,J,Q,X,Z,nt,rt,K,it,st,dt,mt,Mt,Nt,St,ct,Et,gt,Ft,yt,wt,Xt,$t;if(!i)return{error:lt};if(!u)return{error:$e};if(a&&![1,2].includes(a))return G({result:{error:tt},context:{sideNumber:a}});const f=(Y=e==null?void 0:e[vs])==null?void 0:Y.otherFlightEntries,{drawId:p}=i,{matchUp:h,structure:d}=ie({drawDefinition:i,matchUpId:u,event:l});if(!h)return{error:Ye};const m=ge({tournamentRecord:s,drawDefinition:i,structure:d,event:l}).appliedPolicies??{};Object.assign(m,e??{});const g=Qr({drawDefinition:i,structure:d}),I=(m==null?void 0:m[Jn])??iu[Jn],{enabledStructures:S}=sE({actionType:Ih,appliedPolicies:m,drawDefinition:i,structure:d}),{policyActions:T}=oE({enabledStructures:S,drawDefinition:i,structure:d});c=c??ln({drawDefinition:i}),r||({matchUps:r}=xe({tournamentParticipants:n,inContext:!0,drawDefinition:i,matchUpsMap:c,event:l}));const E=r==null?void 0:r.find(At=>At.matchUpId===u),y=a&&((z=E==null?void 0:E.sides)==null?void 0:z.find(At=>At.sideNumber===a)),b=((J=E==null?void 0:E.sides)==null?void 0:J.map(At=>{var Dt;return At.participantId||((Dt=At.participant)==null?void 0:Dt.participantid)}).filter(Boolean))??[],{assignedPositions:N,allPositionsAssigned:A}=ke({structure:d}),{structureId:C}=d??{},v=[];if(!C)return{validActions:v};if(g){const At=((d==null?void 0:d.matchUps)??[]).filter(({roundNumber:ut})=>ut===h.roundNumber),Dt=((Q=i==null?void 0:i.entries)==null?void 0:Q.filter(({entryStatus:ut})=>ut&&ho.includes(ut)).map(fe))??[],at=At.map(ut=>(ut.sides??[]).flatMap(fe)).flat().filter(Boolean),ot=Dt.filter(ut=>!b.includes(ut)&&(!t||!at.includes(ut))),Lt=n==null?void 0:n.filter(ut=>ot==null?void 0:ot.includes(ut.participantId)).map(ut=>pt(ut,void 0,!0));Lt==null||Lt.forEach(ut=>{const Rt=(i.entries??[]).find(ne=>ne.participantId===ut.participantId);ut.entryPosition=Rt==null?void 0:Rt.entryPosition}),ot.length&&v.push({payload:{drawId:p,matchUpId:u,structureId:C,sideNumber:a},method:aE,type:pc,availableParticipantIds:ot,participantsAvailable:Lt});const ft=(l==null?void 0:l.entries)??[],Ct=Zw({eventEntries:ft,structure:d});let Ut=Vt(Dt.concat(Ct));if(f){const ut=l?be({event:l}):void 0,Rt=(X=ut==null?void 0:ut.flights)==null?void 0:X.filter(ne=>ne.drawId!==p).flatMap(ne=>ne.drawEntries.filter(Ae=>Ae.participantId&&![ti,Or,po].includes(Ae.entryStatus)).map(({participantId:Ae})=>Ae)).filter(Boolean);Rt!=null&&Rt.length&&Ut.push(...Rt)}Ut=Ut.filter(ut=>!b.includes(ut)&&!ot.includes(ut)&&(!t||!at.includes(ut)));const Kt=n==null?void 0:n.filter(ut=>Ut.includes(ut.participantId)).map(ut=>pt(ut,void 0,!0));if(Kt.forEach(ut=>{const Rt=(i.entries??[]).find(ne=>ne.participantId===ut.participantId);ut.entryPosition=Rt==null?void 0:Rt.entryPosition}),Kt.sort((ut,Rt)=>(ut.entryPosition||1/0)-(Rt.entryPosition||1/0)),Ut.length&&v.push({payload:{drawId:p,matchUpId:u,structureId:C,sideNumber:a},availableParticipantIds:Ut,participantsAvailable:Kt,method:aE,type:dr}),!Be(h)&&a){const ut=(Z=h.sides)==null?void 0:Z.find(Rt=>Rt.sideNumber===a);ut!=null&&ut.participantId&&v.push({payload:{drawId:p,matchUpId:u,structureId:C,sideNumber:a},method:qw,type:lE})}}const P=ki({drawDefinition:i,structure:d}),U=N==null?void 0:N.filter(At=>At.participantId).map(At=>At.drawPosition),O=N==null?void 0:N.filter(At=>At.bye).map(At=>At.drawPosition),D=h.collectionId,M=h.matchUpStatus===re||!D&&((nt=h.drawPositions)==null?void 0:nt.reduce((At,Dt)=>(O==null?void 0:O.includes(Dt))||At,!1));if(M)return{validActions:v,isByeMatchUp:M};Pn({policyActions:T,action:pE})&&v.push({type:pE,payload:{matchUpId:u}});const w=!Ra({matchUpStatus:h.matchUpStatus}),k=(rt=m==null?void 0:m.scoring)==null?void 0:rt.structures,_=(d==null?void 0:d.stage)&&(k==null?void 0:k.stage)&&(k==null?void 0:k.stage[d.stage]),F=(d==null?void 0:d.stageSequence)&&(_==null?void 0:_.stageSequence)&&_.stageSequence[d.stageSequence],W=!(((K=m==null?void 0:m.scoring)==null?void 0:K.requireAllPositionsAssigned)||(_==null?void 0:_.requireAllPositionsAssigned)||(F==null?void 0:F.requireAllPositionsAssigned))||A,j=h.sides&&h.sides.filter(At=>At==null?void 0:At.participantId).length===2,H=h.matchUpStatus&&[Fe,en].includes(h.matchUpStatus),B=gn({inContextDrawMatchUps:r,drawDefinition:i,matchUpId:u}),R=_i({inContextDrawMatchUps:r,drawDefinition:i,targetData:B}),q=(((it=E==null?void 0:E.drawPositions)==null?void 0:it.length)===2&&E.drawPositions.every(At=>U==null?void 0:U.includes(At))&&((st=E==null?void 0:E.sides)==null?void 0:st.length)===2&&E.sides.every(({participantId:At})=>At)||j)&&!(H&&R),V={method:rT,type:mc,payload:{drawId:p,matchUpId:u,penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0}};if(w&&v.push({payload:{drawId:p,matchUpId:u,schedule:{}},method:dE,type:Kw}),Pn({policyActions:T,action:mc})&&(y!=null&&y.participant||!a&&(b!=null&&b.length))&&v.push(V),w&&q&&v.push({type:Jw}),W&&q){const{matchUpId:At,matchUpFormat:Dt}=h,at={drawId:p,matchUpId:At,matchUpFormat:Dt,outcome:{scoreStringSide1:void 0,scoreStringSide2:void 0,sets:[]},winningSide:void 0};v.push({info:"set outcome and winningSide",method:dE,type:Qw,payload:at}),Pn({policyActions:T,action:hE})&&v.push({type:hE}),Pn({policyActions:T,action:mE})&&v.push({type:mE})}if(D&&E){const At=(dt=E.sides)==null?void 0:dt.find(ue=>ue.participant),Dt=E.gender===hs&&E.sideNumber&&((mt=E.sides)==null?void 0:mt.filter(ue=>ue.particiapntId).length)===1&&((Nt=(Mt=At==null?void 0:At.participant)==null?void 0:Mt.person)==null?void 0:Nt.sex),at=E.matchUpType,ot=(St=I==null?void 0:I.participants)!=null&&St.enforceGender?E.gender:void 0,Lt=(ct=E.sides)==null?void 0:ct.flatMap(ue=>{var he;return((he=ue.participant)==null?void 0:he.individualParticipants)||ue.participant}).filter(Boolean),ft=Lt==null?void 0:Lt.map(fe),Ct=(Et=E.sides)==null?void 0:Et.filter(ue=>!a||ue.sideNumber===a).flatMap(ue=>{var he;return((he=ue.participant)==null?void 0:he.individualParticipants)||ue.participant}).filter(Boolean),Ut=Ct==null?void 0:Ct.map(fe),Kt=r==null?void 0:r.find(ue=>ue.matchUpId===E.matchUpTieId),ut=(gt=Kt==null?void 0:Kt.sides)==null?void 0:gt.map(ue=>ue.participant.individualParticipants.filter(({participantId:he,person:$i})=>!(Ut!=null&&Ut.includes(he))&&(!ot||ot===Io||$i.sex===ot||ot===hs&&Dt&&$i.sex!==Dt))),Rt=a?ut==null?void 0:ut[a-1]:ut==null?void 0:ut.map((ue,he)=>({participants:ue,sideNumber:he+1})),ne=a?(Ft=ut==null?void 0:ut[a-1])==null?void 0:Ft.map(fe):ut==null?void 0:ut.map((ue,he)=>({participants:ue==null?void 0:ue.map(fe),sideNumber:he+1})),Ae=a&&(at===gi&&!(Ut!=null&&Ut.length)||at===Tr&&((Ut==null?void 0:Ut.length)??0)<2)||!a&&(at===gi&&((Ut==null?void 0:Ut.length)??0)<2||at===Tr&&((Ut==null?void 0:Ut.length)??0)<4),Ee=ne==null?void 0:ne.filter(ue=>!(ft!=null&&ft.includes(ue))),Un=Rt==null?void 0:Rt.filter(({participantId:ue})=>Ee.includes(ue));if(Ae&&(Ee!=null&&Ee.length)&&v.push({availableParticipantIds:Ee,method:Hw,availableParticipants:Un,type:pc,payload:{participantId:void 0,tieMatchUpId:u,drawId:p}}),Ut!=null&&Ut.length&&(!Be(h)||(yt=y==null?void 0:y.substitutions)!=null&&yt.length)&&v.push({method:cE,type:lE,existingParticipantIds:Ut,payload:{participantId:void 0,tieMatchUpId:u,drawId:p}}),Un!=null&&Un.length&&(!a&&(Ut!=null&&Ut.length)||a&&(y!=null&&y.participant))&&v.push({availableParticipantIds:Ee,method:Ww,availableParticipants:Un,type:zw,existingParticipantIds:Ut,payload:{existingParticipantId:void 0,participantId:void 0,tieMatchUpId:u,drawId:p}}),Pn({policyActions:T,action:uE})&&((wt=y==null?void 0:y.substitutions)!=null&&wt.length)){const ue=((Xt=y.participant)==null?void 0:Xt.participantType)===xt&&[y.participantId]||(($t=y.participant)==null?void 0:$t.participantType)===_t&&y.participant.individualParticipantIds||[],he=y.substitutions.map($i=>$i.participantId).filter($i=>ue.includes($i));(!o||he.includes(o))&&v.push({method:cE,type:uE,substitutedParticipantIds:he,payload:{participantId:void 0,tieMatchUpId:u,drawId:p}})}const Xe=e==null?void 0:e[Jn],Lr=Xe==null?void 0:Xe.substituteWithoutScore,jn=Xe==null?void 0:Xe.substituteAfterCompleted;if(Pn({policyActions:T,action:fE})&&b.length===2&&(!a&&(Ut!=null&&Ut.length)||a&&(y!=null&&y.participant))&&(Lr||Be(h))&&(jn||h.matchUpStatus&&!We.includes(h.matchUpStatus))&&(Ct!=null&&Ct.length)&&Rt.length){const ue=Ct.map(fe);v.push({info:"list of team players available for substitution",method:Yw,availableParticipantIds:ne,existingParticipantIds:ue,availableParticipants:Rt,existingParticipants:Ct,type:fE,payload:{substituteParticipantId:void 0,existingParticipantId:void 0,sideNumber:a,matchUpId:u,drawId:p}})}}return{structureIsComplete:P,validActions:v,isDoubleExit:H}}function Zw({eventEntries:t,structure:e}){const n=s=>s.entryStatus===dr&&rE({structure:e,entry:s}),r=(s,i)=>(s.entryPosition||1/0)-(i.entryPosition||1/0);return t.filter(n).sort(r).map(fe)}function gE({policyDefinitions:t,tournamentRecord:e,drawDefinition:n,participantId:r,sideNumber:s,matchUpId:i,drawId:o,event:c}){if(!e)return{error:et};o||(o=(He({tournamentRecord:e}).matchUps||[]).reduce((p,h)=>h.matchUpId===i?h.drawId:p,void 0),n=(e.events||[]).map(p=>p.drawDefinitions||[]).flat().reduce((p,h)=>h.drawId===o?h:p,void 0));const{policyDefinitions:a}=Zi({policyTypes:[vs],tournamentRecord:e,drawDefinition:n,event:c});return t=t||a,n?Sh({tournamentParticipants:e.participants,policyDefinitions:t,drawDefinition:n,participantId:r,sideNumber:s,matchUpId:i,event:c}):{error:rr}}function Xw(t){const{tournamentRecords:e,participantId:n,tournamentId:r,sideNumber:s,matchUpId:i,eventId:o,drawId:c}=t??{};if(typeof e!="object"||typeof r!="string"||typeof i!="string"||typeof c!="string")return{error:tt};const a=e[r];if(!a)return{error:et};const u=Je({tournamentRecord:a,eventId:o,drawId:c});return u.error?u:gE({drawDefinition:u.drawDefinition,tournamentRecord:a,participantId:n,sideNumber:s,matchUpId:i,drawId:c})}function tk({ignoreDisabled:t=!0,tournamentRecords:e,venueIds:n=[],dates:r=[]}){var f,p;if(!Array.isArray(r))return{error:tt,dates:r};if(!Array.isArray(n))return{error:tt,venueIds:n};if(!r.every(Yn))return{error:bn};const i=Co({tournamentRecords:e,ignoreDisabled:t,dates:r});if(i.error)return i;const o=(f=i==null?void 0:i.venues)==null?void 0:f.filter(({venueId:h})=>!(n!=null&&n.length)||n.includes(h)),c=(p=i.courts)==null?void 0:p.reduce((h,d)=>{var m;return(m=d.dateAvailability)==null||m.forEach(g=>{const I=g.date;h.includes(I)||h.push(I)}),h},[]).filter(h=>!r.length||r.includes(h)),a={venueIds:o==null?void 0:o.map(({venueId:h})=>h)},{matchUps:u}=ks({afterRecoveryTimes:!0,tournamentRecords:e,matchUpFilters:a});return{venuesReport:o==null?void 0:o.map(h=>ek(c,h,u))}}function ek(t,e,n){const{venueId:r,courts:s,venueName:i}=e,o={};return t.forEach(c=>{let a=0,u=0,l=0;for(const h of s){const d=h.dateAvailability.find(I=>I.date===c),m=d&&Tc({courtDate:d}),g=m==null?void 0:m.reduce((I,S)=>{const{startTime:T,endTime:E}=S,y=jt(E)-jt(T);return I+y},0);g&&(l+=1),a+=g}const f=n.filter(({schedule:h})=>h.venueId===r&&as(c,h.scheduledDate));f.forEach(({schedule:h})=>{const d=de(h.scheduledTime),m=An(d,h.averageMinutes),g=jt(m)-jt(d);u+=g});const p=a?(u/a*100).toFixed(2):"100";o[c]={scheduledMatchUpsCount:f.length,availableCourts:l,availableMinutes:a,scheduledMinutes:u,percentUtilization:p}}),{venueId:r,venueName:i,venueReport:o}}function nk({tournamentRecords:t}){const e=Object.keys(t);return{...$,tournamentIds:e}}const rk={getParticipantScaleItem:Vw,getCompetitionDateRange:Ly,getTournamentIds:nk,competitionScheduleMatchUps:nh,getSchedulingProfileIssues:jw,allCompetitionMatchUps:ks,competitionMatchUps:Ip,matchUpActions:Xw,getCompetitionVenues:Ap,getVenuesAndCourts:Co,getVenuesReport:tk,credits:sd};function IE({tournamentRecord:t,courtIds:e,dates:n}){if(!t)return{error:et};if(!Array.isArray(e))return{info:sn("courtIds"),error:Tt};const r=Array.isArray(n)&&n.length?{dates:n}:!0,s=i=>ae({creationTime:!1,element:i,extension:{value:r,name:Er}});for(const i of t.venues||[])for(const o of i.courts||[])if(e!=null&&e.includes(o.courtId)){const c=s(o);if(c.error)return c}return{...$}}function sk({tournamentRecords:t,courtIds:e,dates:n}){if(!t)return{error:Gt};if(!Array.isArray(e))return{error:Tt,info:sn("courtIds")};for(const r of Object.values(t))IE({tournamentRecord:r,courtIds:e,dates:n});return{...$}}function SE({tournamentRecord:t,venueIds:e}){if(!t)return{error:et};if(!Array.isArray(e))return{error:Tt,info:sn("venueIds")};for(const n of t.venues||[])if(e!=null&&e.includes(n.venueId)){const r=ae({creationTime:!1,element:n,extension:{name:Er,value:!0}});if(r.error)return r}return{...$}}function ik({tournamentRecords:t,venueIds:e}){if(!t)return{error:Gt};if(!Array.isArray(e))return{error:Tt,info:sn("venueIds")};for(const n of Object.values(t))SE({tournamentRecord:n,venueIds:e});return{...$}}function TE({tournamentRecord:t,courtIds:e,enableAll:n,dates:r}){if(!t)return{error:et};if(!Array.isArray(e)&&!n)return{error:Tt,info:sn("courtIds")};for(const s of t.venues||[])for(const i of s.courts||[])if(n||e!=null&&e.includes(i.courtId))if(Array.isArray(r)){const{extension:o}=xn({element:i,name:Er});if(o){const c=o.value;Array.isArray(c.dates)&&(c.dates=c.dates.filter(a=>!r.includes(a))),ae({creationTime:!1,element:i,extension:{name:Er,value:c}})}}else Ar({element:i,name:Er});return{...$}}function ok({tournamentRecords:t,enableAll:e,courtIds:n,dates:r}){if(!t)return{error:Gt};if(!e&&!Array.isArray(n))return{error:Tt,info:sn("courtIds")};for(const s of Object.values(t))TE({tournamentRecord:s,courtIds:n,enableAll:e,dates:r});return{...$}}function yE({tournamentRecord:t,venueIds:e,enableAll:n}){if(!t)return{error:et};if(!Array.isArray(e)&&!n)return{error:Tt,info:sn("venueIds")};for(const r of t.venues||[])(n||e!=null&&e.includes(r.venueId))&&Ar({element:r,name:Er});return{...$}}function ck({tournamentRecords:t,venueIds:e,enableAll:n}){if(!t)return{error:Gt};if(!n&&!Array.isArray(e))return{error:Tt,info:sn("venueIds")};for(const r of Object.values(t))yE({tournamentRecord:r,venueIds:e,enableAll:n});return{...$}}function EE({tournamentRecord:t,drawDefinition:e,matchUpId:n,drawId:r}){const s="removeCourtAssignment";if(!n)return{error:$e};if(!e&&!r)return{error:Hn};let i;if(!e){if(!t)return{error:et};({drawDefinition:e}=Je({tournamentRecord:t,drawId:r}))}if(e)({matchUp:i}=ie({drawDefinition:e,matchUpId:n}));else{if(!t)return{error:et};const o=He({tournamentRecord:t,inContext:!1}).matchUps||[];({matchUp:i}=cI({matchUps:o,matchUpId:n}))}return i?(i.timeItems&&i.timeItems.find(c=>[oo,Qs].includes(c.itemType))&&(i.timeItems=i.timeItems.filter(({itemType:c})=>![oo,Qs].includes(c)),qt({tournamentId:t==null?void 0:t.tournamentId,context:s,drawDefinition:e,matchUp:i})),{...$}):{error:Ye}}function Th({matchUpsCount:t=0}){const n=`Schedule would be deleted from ${t} ${t===1?"matchUp":"matchUps"}; use { force: true }`;return{error:Rv,info:n}}function yh({tournamentRecord:t,venueId:e,force:n}){if(!t)return{error:et};if(typeof e!="string")return{error:Vs};const s=He({tournamentRecord:t,contextFilters:{venueIds:[e]}}).matchUps||[];if(!s.length||n)for(const o of s){const c=EE({matchUpId:o.matchUpId,drawId:o.drawId,tournamentRecord:t});if(c.error)return c}else return Th({matchUpsCount:s.length});let i;return t.venues=(t.venues||[]).filter(o=>(o==null?void 0:o.venueId)!==e?!0:(i=!0,!1)),i?(Ht({payload:{venueId:e,tournamentId:t.tournamentId},topic:AI,key:e}),{...$}):{error:di}}function ak({tournamentRecord:t,venueIds:e,force:n}){if(!t)return{error:et};if(!Array.isArray(e))return{error:tt};for(const r of t.venues||[]){const{venueId:s}=r;if(e.includes(s)){const{venueId:i}=r,o=yh({tournamentRecord:t,venueId:i,force:n});if(o.error)return o}}return{...$}}function uk({tournamentRecords:t,venueId:e,force:n}){if(!t)return{error:Gt};if(typeof e!="string")return{error:Vs};let r;for(const s of Object.values(t)){const i=yh({tournamentRecord:s,venueId:e,force:n});if(i.error&&i.error!==di)return i;i.success&&(r=!0)}return By({tournamentRecords:t}),r?$:{error:di}}function lk({tournamentRecord:t,schedulingProfile:e}){return t?Array.isArray(e)?cd({tournamentRecord:t,schedulingProfile:e}):{error:tt}:{error:et}}function dk({tournamentRecord:t,schedulingProfile:e}){return Ti({tournamentRecord:t,extension:{name:qs,value:e}})}function od({tournamentRecord:t}){var s;if(!t)return{error:et};const e=t.tournamentId,{extension:n}=Bn({name:qs,tournamentRecord:t});let r=(n==null?void 0:n.value)||[];if(r.length){const i=(s=t.venues)==null?void 0:s.map(({venueId:p,courts:h})=>(h==null?void 0:h.length)&&p),o=_l({tournamentRecords:{[e]:t}}),{eventIds:c,drawIds:a}=o,{updatedSchedulingProfile:u,modifications:l,issues:f}=ed({schedulingProfile:r,venueIds:i,eventIds:c,drawIds:a});if(l){r=u;const p=dk({tournamentRecord:t,schedulingProfile:r});return p.error?p:{schedulingProfile:r,modifications:l,issues:f}}}return{schedulingProfile:r,modifications:0}}function cd({requireCourts:t=!0,tournamentRecord:e,schedulingProfile:n}){if(!n){const{modifications:a,issues:u}=od({tournamentRecord:e});return{success:!a,modifications:a,issues:u}}const{venueIds:r,eventIds:s,drawIds:i}=Fy({tournamentRecord:e,requireCourts:t}),{modifications:o,issues:c}=ed({schedulingProfile:n,venueIds:r,eventIds:s,drawIds:i});return{success:!o,modifications:o,issues:c}}function Eh(t){if(!(t!=null&&t.tournamentRecord)&&!Array.isArray(t==null?void 0:t.venueMatchUps))return{error:et};if(!(t!=null&&t.courtId))return{error:Ho};const{scheduleVisibilityFilters:e,tournamentRecord:n,matchUpFilters:r,venueMatchUps:s,courtId:i}=t,{schedulingProfile:o}=od({tournamentRecord:n});if(Array.isArray(s))return{matchUps:u({matchUps:s,courtId:i})};const{matchUps:c}=He({scheduleVisibilityFilters:e,tournamentRecord:n,matchUpFilters:r});return{matchUps:u({matchUps:c,courtId:i})};function u({matchUps:l,courtId:f}){const p=l.filter(h=>{var m,g,I;const d=(g=(m=h.schedule)==null?void 0:m.allocatedCourts)==null?void 0:g.map(({courtId:S})=>S);return((I=h.schedule)==null?void 0:I.courtId)===f||(d==null?void 0:d.includes(f))});return nd({matchUps:p,schedulingProfile:o})}}function fk({scheduleVisibilityFilters:t,tournamentRecord:e,matchUpFilters:n,venueId:r}){if(!e)return{error:et};if(!r)return{error:Vs};const{schedulingProfile:s}=od({tournamentRecord:e}),{matchUps:i}=He({scheduleVisibilityFilters:t,tournamentRecord:e,matchUpFilters:n});return{matchUps:c({matchUps:i,venueId:r})};function c({matchUps:a,venueId:u}){const l=a.filter(f=>{var h,d,m;const p=(d=(h=f.schedule)==null?void 0:h.allocatedCourts)==null?void 0:d.map(({venueId:g})=>g);return((m=f.schedule)==null?void 0:m.venueId)===u||(p==null?void 0:p.includes(u))});return nd({matchUps:l,schedulingProfile:s})}}function bE({tournamentRecord:t,drawDefinition:e,disableNotice:n,courtId:r,force:s}){const i=io({tournamentRecord:t,courtId:r});if(i.error)return i;const o=i.venue,{matchUps:c}=Eh({tournamentRecord:t,courtId:r});if(!(c!=null&&c.length)||s){for(const a of c||[]){const u=EE({matchUpId:a.matchUpId,drawId:a.drawId,tournamentRecord:t,drawDefinition:e});if(u.error)return u}o&&(o.courts=(o.courts||[]).filter(a=>a.courtId!==r),n||Ht({topic:so,payload:{venue:o,tournamentId:t.tournamentId},key:o.venueId}))}else return Th({matchUpsCount:c.length});return{...$}}function pk({tournamentRecords:t,courtId:e,force:n}){if(!t)return{error:Gt};if(typeof e!="string")return{error:Ho};let r,s;for(const i of Object.values(t)){if(s=bE({tournamentRecord:i,courtId:e,force:n}),s.error&&s.error!==Kd)return s;s.success&&(r=!0)}return r?{...$}:s}function ad(t){return parseInt(t)}function NE({startTime:t="",endTime:e=""}={}){if(!t||!e||!pi.test(t)||!pi.test(e))return!1;const[n,r]=t.split(":").map(ad),[s,i]=e.split(":").map(ad);return s<n?!1:!(n===s&&i<r)}function hk(t,e){const[n,r]=t.startTime.split(":").map(ad),[s,i]=e.startTime.split(":").map(ad);return n<s?-1:n>s?1:r<i?-1:r>i?1:0}function AE({dateAvailability:t}){if(!t)return{error:nv};if(!Array.isArray(t))return{error:Hd};const e="Dates must be formated => YYYY-MM-DD",n="Times must be 24 hour => 00:00";for(const r of t){if(typeof r!="object")return{error:Hd};const{date:s,startTime:i,endTime:o,bookings:c=[]}=r;if(!i||!o)return{error:Hd};if(s&&!Vr.test(s))return{error:bn,dateAvailability:{date:s},info:e};if(!pi.test(i))return{error:sr,dateAvailability:{startTime:i},info:n};if(!pi.test(o))return{error:sr,dateAvailability:{endTime:o},info:n};if(i===o)return{error:sr,dateAvailability:{startTime:i,endTime:o},info:"startTime and endTime are equivalent"};if(!NE({startTime:i,endTime:o}))return{error:sr,dateAvailability:{startTime:i,endTime:o},info:"endTime must be after startTime"};if(c){if(!Array.isArray(c))return{error:Wd};for(const a of c){if(typeof a!="object")return{error:Wd};const{startTime:u,endTime:l}=a;if(!pi.test(u))return{error:sr,booking:{startTime:u},info:n};if(!pi.test(l))return{error:sr,booking:{endTime:l},info:n};if(u===l)return{error:sr,dateAvailability:{startTime:u,endTime:l},info:"startTime and endTime are equivalent"};if(!NE({startTime:u,endTime:l}))return{error:sr,dateAvailability:{startTime:u,endTime:l},info:"endTime must be after startTime"}}}}return{valid:!0}}function vE({tournamentRecord:t,dateAvailability:e,disableNotice:n,venueMatchUps:r,courtId:s,force:i}){if(!t)return{error:et};if(!s)return{error:Ho};const o=AE({dateAvailability:e});if(o.error)return o;const{updatedDateAvailability:c,totalMergeCount:a}=mk(e);e=c;const u=io({tournamentRecord:t,courtId:s});if(u.error)return u;const{court:l,venue:f}=u,{matchUps:p}=Eh({tournamentRecord:t,venueMatchUps:r,courtId:s});return p!=null&&p.length&&console.log("scheduled court matchUps",p.length),l&&(l.dateAvailability=e,!n&&f&&Ht({payload:{venue:f,tournamentId:t.tournamentId},topic:so,key:f.venueId})),{...$,totalMergeCount:a}}function mk(t){let e=0;const n=t.reduce((s,i)=>{const{date:o,startTime:c,endTime:a,bookings:u}=i;return s[o]||(s[o]=[]),s[o].push({startTime:c,endTime:a,bookings:u}),s},{}),r=[];return Object.keys(n).forEach(s=>{n[s].sort(hk);const{mergedAvailability:i,mergeCount:o}=gk(n[s]);r.push(...i.map(c=>({date:s,...c}))),e+=o}),{updatedDateAvailability:r,totalMergeCount:e}}function gk(t){let e,n,r,s=t.length,i=0;const o=[];for(;t.length&&s;){const a=t.shift(),{startTime:u,endTime:l,bookings:f}=a;if(s-=1,!e)e=u,r=f,n=l;else if(ea(Pe(n),Pe(u),!1)>0){const h={startTime:e,endTime:n};r!=null&&r.length&&(h.bookings=r),o.push(h),e=u,r=f,n=l}else f&&(r?r.push(f):r=f),n=l,i+=1}const c={startTime:e,endTime:n};return r!=null&&r.length&&(c.bookings=r),o.push(c),{mergedAvailability:o,mergeCount:i}}const CE=()=>({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});function bh({tournamentRecord:t,disableNotice:e,venueMatchUps:n,modifications:r,courtId:s,force:i}){if(!t)return{error:et};if(!s)return{error:Ho};if(!r||typeof r!="object")return{error:Ir};const o=io({tournamentRecord:t,courtId:s});if(o.error)return o;const{venue:c,court:a}=o,u=Object.keys(CE()).filter(h=>h!=="courtId");if(!Object.keys(r).filter(h=>u.includes(h)).length)return{error:Qd};const f=u.filter(h=>!["dateAvailability"].includes(h)),p=Object.keys(r).filter(h=>f.includes(h));if(a&&p.forEach(h=>Object.assign(a,{[h]:r[h]})),r.dateAvailability){const h=vE({dateAvailability:r.dateAvailability,tournamentRecord:t,venueMatchUps:n,disableNotice:e,courtId:s,force:i});if(h.error)return h}return e||Ht({payload:{venue:c,tournamentId:t.tournamentId},topic:so,key:c==null?void 0:c.venueId}),{...$,court:pt(a)}}function Ik({tournamentRecords:t,disableNotice:e,modifications:n,courtId:r,force:s}){if(!t)return{error:Gt};if(!r)return{error:Tt,info:"missing courtId"};let i,o;for(const c of Object.values(t)){const a=bh({tournamentRecord:c,disableNotice:e,modifications:n,courtId:r,force:s});a!=null&&a.error&&(o=a),i=!0}return i?{...$}:o}const Sk=()=>({venueId:void 0,venueName:"",venueAbbreviation:"",onlineResources:[],venueType:void 0,addresses:[],contacts:[],courts:[],roles:[]});function Nh({tournamentRecord:t,disableNotice:e,venueId:n,courtId:r,court:s}){const{venue:i}=Js({tournamentRecord:t,venueId:n});if(!i)return{error:di};i.courts||(i.courts=[]);const o={...CE(),venueId:n,courtId:r};if(o.courtId||(o.courtId=Yt()),i.courts.some(a=>a.courtId===o.courtId))return{error:Ev};{const a=((s==null?void 0:s.dateAvailability)||[]).map(f=>{var p;return{...f,date:Bt(f.date),startTime:de(f.startTime),endTime:de(f.endTime),bookings:(p=f.bookings)==null?void 0:p.map(({startTime:h,endTime:d,bookingType:m})=>({startTime:de(h),endTime:de(d),bookingType:m}))}}),u=Object.keys(o);for(const f of u)if(s!=null&&s[f])if(f==="dateAvailability"){const p=AE({dateAvailability:a});if(!p.valid&&p.error)return p;o.dateAvailability=a}else o[f]=s[f];const l=o;return i.courts.push(l),e||Ht({payload:{venue:i,tournamentId:t.tournamentId},topic:so,key:i.venueId}),{...$,court:pt(o),venueId:n}}}function Ah({courtNameRoot:t="Court",dateAvailability:e=[],venueAbbreviationRoot:n,tournamentRecord:r,courtNames:s=[],courtTimings:i,courtsCount:o,startTime:c,courtIds:a,endTime:u,idPrefix:l,venueId:f,dates:p}){if(!f)return{error:Vs};const h=Js({tournamentRecord:r,venueId:f});if(h.error)return h;const{venue:d}=h;if(!Me(o)||!s)return{error:yv};o=o??s.length;const I=ht(0,o).map(S=>{const T=i==null?void 0:i[S],E=T?p.map(y=>({date:Sr(y),startTime:c,endTime:u,...T})):e;return T&&c&&u&&E.push({startTime:c,endTime:u}),{courtName:s[S]||n&&(d==null?void 0:d.venueAbbreviation)&&`${d==null?void 0:d.venueAbbreviation} ${S+1}`||`${t} ${S+1}`,dateAvailability:E}}).map((S,T)=>{const E=(a==null?void 0:a.pop())||l&&`${l}-${T+1}`;return Nh({disableNotice:!0,tournamentRecord:r,courtId:E,venueId:f,court:S})}).map(S=>S.court).filter(Boolean);return I.length!==o?{error:"Not all courts could be generated",result:h}:(d&&Ht({payload:{venue:d,tournamentId:r.tournamentId},topic:so,key:d.venueId}),{...$,courts:pt(I)})}function PE({tournamentRecord:t,modifications:e,venueId:n,force:r}){var d,m,g,I;if(!t)return{error:et};if(!e||typeof e!="object")return{error:Ir};if(!n)return{error:Vs};const{matchUps:s}=fk({tournamentRecord:t,venueId:n}),i=Js({tournamentRecord:t,venueId:n});if(i.error)return i;const o=i.venue,c=Object.keys(Sk()).filter(S=>S!=="venueId");if(!Object.keys(e).filter(S=>c.includes(S)).length)return{error:Qd};const u=c.filter(S=>!["courts","onlineResources"].includes(S)),l=Object.keys(e).filter(S=>u.includes(S));o&&l.forEach(S=>Object.assign(o,{[S]:e[S]}));const f=((d=o==null?void 0:o.courts)==null?void 0:d.map(S=>S.courtId))??[],p=((m=e.courts)==null?void 0:m.map(S=>S.courtId))||[],h=f.filter(S=>!p.includes(S));if(h.length){const S=(g=o==null?void 0:o.courts)==null?void 0:g.filter(E=>h.includes(E.courtId)),T=S==null?void 0:S.map(E=>{var b;return((b=Eh({courtId:E.courtId,tournamentRecord:t,venueMatchUps:s}).matchUps)==null?void 0:b.length)??0}).reduce((E,y)=>E+y);if(o&&(!T||r))o.courts=(I=o.courts)==null?void 0:I.filter(E=>p.includes(E.courtId));else return Th({matchUpsCount:T})}if(e.courts)for(const S of e.courts){const{courtId:T}=S||{};let E=bh({modifications:S,disableNotice:!0,tournamentRecord:t,venueMatchUps:s,courtId:T,force:r});if(E.error===Kd&&(E=Nh({disableNotice:!0,tournamentRecord:t,venueId:n,court:S})),E.error)return E}return cd({tournamentRecord:t}),o&&Ht({payload:{venue:o,tournamentId:t.tournamentId},topic:so,key:o==null?void 0:o.venueId}),{...$,venue:pt(o)}}function Tk({tournamentRecords:t,modifications:e,venueId:n,force:r}){if(!t)return{error:Gt};if(typeof n!="string")return{error:Vs};let s,i;for(const o of Object.values(t)){const c=PE({tournamentRecord:o,modifications:e,venueId:n,force:r});if(c.success&&(i=!0),c.error&&(s=c.error),c.error&&c.error!==di)return c}return By({tournamentRecords:t}),i?{...$}:{error:s}}function yk(t){const{tournamentRecords:e,venueId:n}=t;if(typeof n!="string"||!n)return{error:Vs};let r;for(const s of Object.values(e)){const{venue:i}=Js({tournamentRecord:s,venueId:n});if(i){const o=Ah({...t,tournamentRecord:s});if(o.error)return o;r=!0}}return r?$:{error:di}}function Ek({tournamentRecords:t,disableNotice:e,venue:n,context:r}){if(typeof n!="object")return{error:tt};n.venueId||(n.venueId=Yt());let s;for(const i of Object.values(t)){const o=ma({disableNotice:!0,tournamentRecord:i,context:r,venue:n});if(o!=null&&o.error)return o;s=o.venue}return e||Ht({topic:bI,payload:{venue:n}}),bt({...$,venue:s})}const bk={disableCourts:sk,disableVenues:ik,enableCourts:ok,enableVenues:ck,deleteCourt:pk,deleteVenue:uk,modifyCourt:Ik,modifyVenue:Tk,addCourts:yk,addVenue:Ek};function Nk({convertExtensions:t,removeExtensions:e}){const n=Ou();return{tournamentId:os(),tournamentRecords:pt(n,t,!1,e)}}function Ak(){var r;const t=Ou(),{extension:e}=zu({name:Ki,tournamentRecords:t}),n=((r=e==null?void 0:e.value)==null?void 0:r.tournamentIds)||[];return Object.keys(t).forEach(s=>{n.includes(s)||delete t[s]}),Qc(t)}function vk(t,e=!0){return typeof t!="object"||Array.isArray(t)?{error:Ir}:t!=null&&t.tournamentId?Dg(e?pt(t):t):{error:tt}}function vh(t,e=!0){if(typeof t!="object")return{error:Ir};if(Array.isArray(t)){if(!(t.filter(r=>r==null?void 0:r.tournamentId).length===t.length))return{error:Wm};t=Object.assign({},...t.map(r=>({[r.tournamentId]:r})))}else if(t!=null&&t.tournamentId)t={[t.tournamentId]:t};else if(!Object.keys(t).every(r=>t[r].tournamentId===r))return{error:Wm};return Qc(e?pt(t):t)}(function(){const t={getState:o=>Nk({convertExtensions:o==null?void 0:o.convertExtensions,removeExtensions:o==null?void 0:o.removeExtensions}),version:()=>Es(),reset:()=>(Qc({}),e())};return s([qD,$w,rk,KD,Rw,bk]),t.devContext=o=>(zo(o),e()),t.getDevContext=o=>ze(o),t.setState=(o,c,a)=>{Hi(c,a);const u=vh(o,c);return e(u)},t.setTournamentRecord=(o,c,a)=>{Hi(c,a);const u=vk(o,c);return e(u)},t.removeTournamentRecord=o=>{const c=Xd(o);return e(c)},t.removeUnlinkedTournamentRecords=()=>{const o=Ak();return e(o)},t.executionQueue=(o,c)=>i(o,c),t;function e(o){return o!=null&&o.error?(t.error=o.error,t.success=!1):(t.error=void 0,t.success=!0),t}function n(o,c,a,u){var g,I;delete t.success,delete t.error;const l=Date.now(),f=c({tournamentRecords:o,...a}),p=Date.now()-l,h=ze(),d={method:u},m=typeof h.result=="object"&&h.result.error;return![void 0,!1].includes(h.perf)&&(isNaN(h.perf)||p>h.perf)&&(d.elapsed=p),(m||h.params&&!Array.isArray(h.params)||Array.isArray(h.params)&&((g=h.params)!=null&&g.includes(u)))&&(d.params=a),(m||!m&&h.result&&!Array.isArray(h.result)||Array.isArray(h.result)&&((I=h.result)!=null&&I.includes(u)))&&(d.result=f),Object.keys(d).length>1&&console.log("ce:",d),f}function r(o,c,a){const u=Ou(),l=os(),f=(c==null?void 0:c.rollbackOnError)&&pt(u,!1,!0),p=n(u,o,{activeTournamentId:l,...c},a);p!=null&&p.error&&f&&vh(f);const h=(p==null?void 0:p.success)&&(c==null?void 0:c.delayNotify)!==!0&&(c==null?void 0:c.doNotNotify)!==!0,d=Kc(),m=Date.now();return d&&(Object.values(u).forEach(g=>{Dl({tournamentRecord:g,value:{version:Es(),timeStamp:m}})}),p.modificationsApplied=!0),h&&Di({directives:[{method:o,params:c}],mutationStatus:d,timeStamp:m}),(h||!(p!=null&&p.success)||c!=null&&c.doNotNotify)&&fi(),p}function s(o){o.forEach(c=>{Object.keys(c).forEach(a=>{t[a]=u=>{if(ze())return r(c[a],u,a);try{return r(c[a],u,a)}catch(l){Xc({engineName:"competitionEngine",methodName:a,params:u,err:l})}}})})}function i(o,c){var m;if(!Array.isArray(o))return{error:tt};const a=Ou(),u=os(),l=c&&pt(a,!1,!0);let f;const p=[];for(const g of o){if(typeof g!="object")return{error:tt};const{method:I,params:S}=g;if(!t[I]){const E={error:vg,methodName:I},y=ze();return(y.result&&!Array.isArray(y.result)||Array.isArray(y.result)&&((m=y.result)!=null&&m.includes(I)))&&console.log("ce:",E),E}const T=n(a,t[I],{activeTournamentId:u,...S},I);if(T!=null&&T.error)return l&&vh(l),{...T,rolledBack:!!l};p.push({...T,methodName:I}),f=Date.now()}const h=Kc();return h&&Object.values(a).forEach(g=>{Dl({tournamentRecord:g,value:{version:Es(),timeStamp:f}})}),Di({directives:o,mutationStatus:h,timeStamp:f}),fi(),{success:p.every(g=>g.success),results:p}}})();function Ch({structureName:t=je,structureAbbreviation:e,drawDefinition:n,matchUpType:r,structureId:s}){if(!n)return{error:lt};const i=Ze({stage:je,structureAbbreviation:e,structureName:t,matchUps:[],structureId:s,matchUpType:r});return n.structures.push(i),Zt({drawDefinition:n,structureIds:[s]}),{...$}}function kc({targetEntryRound:t=1,finishingPositions:e,sourceRoundNumber:n,sourceStructureId:r,targetStructureId:s,linkType:i=js.Winner}){return!r||!s?{error:En}:{link:bt({linkType:i,source:{roundNumber:n,structureId:r,finishingPositions:e},target:{feedProfile:Cr,roundNumber:t,structureId:s}})}}function Ph({idPrefix:t,roundNumber:e,roundPosition:n,uuids:r}){return t?`${t}-${e}-${n}`:(r==null?void 0:r.pop())||Yt()}function ud({includeMatchUpType:t,matchUpType:e,roundNumber:n,matchUps:r,idPrefix:s,isMock:i,uuids:o,nodes:c}){let a=0;const u=[];let l=1;const f=n-1,p=c==null?void 0:c.length;for(;a<(p||0);){const h=c==null?void 0:c[a],d=c==null?void 0:c[a+1];f&&(h.roundNumber=f),d&&f&&(d.roundNumber=f);const m=Ph({roundPosition:l,roundNumber:n,idPrefix:s,uuids:o}),g={roundPosition:l,children:[h,d],matchUpId:m};u.push(g);const I={drawPositions:g.children.map(S=>S==null?void 0:S.drawPosition).filter(Boolean),matchUpStatus:Le,matchUpId:g.matchUpId,roundPosition:l,roundNumber:n};t&&e&&(I.matchUpType=e),i&&(I.isMock=!0),r.push(I),l++,a+=2}return{roundNodes:u,matchUps:r}}function rs({finishingPositionOffset:t,finishingPositionLimit:e,qualifyingRoundNumber:n,qualifyingPositions:r,matchUpType:s,roundLimit:i,idPrefix:o,drawSize:c,isMock:a,uuids:u}){if(isNaN(c)||c<2||r&&c<=r)return{matchUps:[],roundsCount:0};if(r&&(!mr(c)||c%r)){let g=r;for(;g<c;)g=2*g;c=g}const l=r&&!(c%2)&&(!isNaN(r)||n&&!isNaN(n))&&(c/r===Math.round(c/r)||n&&c/n===Math.round(c/n));if(!mr(c)&&!l)return{matchUps:[],roundsCount:0};const f=ht(1,c+1).map(g=>({drawPosition:g}));let p,h=[],d=1;for({roundNodes:p,matchUps:h}=ud({matchUpType:s,roundNumber:d,idPrefix:o,matchUps:h,isMock:a,nodes:f,uuids:u}),d++,i=i||n;p.length>1;)r&&p.length===r&&(i=d-1),{roundNodes:p,matchUps:h}=ud({nodes:p,matchUpType:s,roundNumber:d,idPrefix:o,matchUps:h,isMock:a,uuids:u}),d++;const m=d-1;return h=ja({finishingPositionOffset:t,finishingPositionLimit:e,roundsCount:m,roundLimit:i,matchUps:h}),i?h=h.filter(g=>i&&(g.roundNumber||0)<=i):i=d-1,{drawSize:c,matchUps:h,roundsCount:m,roundLimit:i}}function UE({qualifyingProfiles:t,appliedPolicies:e,idPrefix:n,isMock:r,uuids:s}){var m;const i="generateQualifyingSTructures",o=[],c=[],a=[],u=(g,I)=>g.stageSequence-I.stageSequence,l=(g,I)=>g.roundTarget-I.roundTarget;let f=0,p=0,h,d=1;for(const g of t.sort(l)){const I=g.structureProfiles||[];d=g.roundTarget||d;let S=1,T=0,E,y,b;for(const N of(I||[]).sort(u)){let A=N.drawSize||_d(N.participantsCount);const{qualifyingRoundNumber:C,qualifyingPositions:v,structureOptions:P,matchUpFormat:U,structureName:O,structureId:D,drawType:M}=N,w=N.matchUpType;let k,_,F;if(!oe(A))return G({result:{error:Eu},stack:i});const L=t.length>1?`${d}-`:"",W=I.length>1||L?S:"",j=O||(L||W?`${Pt} ${L}${W}`:Pt);if(M===Pr){const{structures:H,groupCount:B,maxRoundNumber:R}=za({structureName:N.structureName||j,structureId:D||(s==null?void 0:s.pop()),stage:Pt,structureOptions:P,appliedPolicies:e,stageSequence:S,matchUpType:w,roundTarget:d,drawSize:A,idPrefix:n,isMock:r,uuids:s});T=B,k=R,_=H[0],h=[1]}else({drawSize:A,matchUps:F,roundLimit:k}=rs({qualifyingRoundNumber:C,qualifyingPositions:v,matchUpType:w,drawSize:A,idPrefix:n,isMock:r,uuids:s})),_=Ze({structureName:N.structureName||j,structureId:D||(s==null?void 0:s.pop()),qualifyingRoundNumber:k,stage:Pt,matchUpFormat:U,stageSequence:S,matchUpType:w,roundLimit:k,matchUps:F}),d&&ae({element:_,extension:{name:Hr,value:d}}),T=((m=F==null?void 0:F.filter(H=>H.roundNumber===k))==null?void 0:m.length)||0;if(S>1){const{link:H}=kc({sourceStructureId:y,sourceRoundNumber:E,targetStructureId:_.structureId,finishingPositions:b===Ai?[1]:void 0,linkType:b});a.push(H),f+=(A||0)-T}else f+=A||0;b=M===Pr?Ai:vi,y=_.structureId,E=k,c.push(_),S+=1}p+=T,o.push({qualifiersCount:T,finalQualifyingRoundNumber:E,finalQualifyingStructureId:y,finishingPositions:h,roundTarget:d,linkType:b}),T=0,d+=1}return{qualifiersCount:p,qualifyingDrawPositionsCount:f,qualifyingDetails:o,structures:c,...$,links:a}}function Uh({drawDefinition:t,structureId:e}){const n=Ot({drawDefinition:t,structureId:e});if(n.error)return n;const{matchUps:r}=Qt({structure:n.structure});return Cn({matchUps:r})}function OE({finishingPositions:t,drawDefinition:e,structureId:n}){const{roundProfile:r}=Uh({drawDefinition:e,structureId:n}),s=r&&Object.keys(r);return s==null?void 0:s.reduce((i,o)=>(ME(r==null?void 0:r[o]).forEach(a=>{t.forEach(u=>{Ck({position:u,rangeDefinition:a})&&(i[u]={roundNumber:o})})}),i),{})}function Ck({position:t,rangeDefinition:e}){if(!Array.isArray(e)||e.reduce((i,o)=>i||isNaN(o),!1))return!1;const[n,r]=e;return ht(n,(r||n)+1).includes(t)}function ME(t){var e,n;return[Vt(((e=t==null?void 0:t.finishingPositionRange)==null?void 0:e.loser)||[]),Vt(((n=t==null?void 0:t.finishingPositionRange)==null?void 0:n.winner)||[])]}function Pk(t){return ME(t).map(e=>ht(e[0],e[1]&&e[1]+1||e[0]+1))}function ld({drawDefinition:t,structureIds:e}){if(e&&!Array.isArray(e))return{error:tt,context:{structureIds:e}};if(!t)return{error:lt};e=e||(t.structures||[]).filter(o=>o.stage!==Pt).map(({structureId:o})=>o);const n=e.map(o=>{const{roundProfile:c}=Uh({drawDefinition:t,structureId:o}),a=c&&Object.values(c);return a==null?void 0:a.map(Pk).flat()}).flat(),r=n.filter(o=>(o==null?void 0:o.length)===1).sort(Ve).flat();return{positionsNotPlayedOff:Vt(n.flat()).filter(o=>!r.includes(o)),positionsPlayedOff:r}}function Oh({excludeRoundNumbers:t=[],playoffPositions:e=[],drawDefinition:n,structureId:r}){if(!n)return{error:lt};if(!r)return{error:En};if(!e)return{error:Tt,info:"missing playoffPositions"};const s=ld({drawDefinition:n});if(s.error)return s;const i=s.positionsPlayedOff,o=e.filter(g=>!i.includes(g)),c=OE({finishingPositions:o,drawDefinition:n,structureId:r}),a=Object.values(c).reduce((g,I)=>g.includes(I.roundNumber)?g:g.concat(I.roundNumber),[]).map(g=>vt(g)).filter(g=>!t.includes(g)),u=OE({finishingPositions:i,drawDefinition:n,structureId:r}),l=u?Object.values(u).reduce((g,I)=>g.includes(I.roundNumber)?g:g.concat(I.roundNumber),[]).map(g=>vt(g)):[],f=a.filter(g=>!l.includes(g)).sort(Ve),{roundProfile:p}=Uh({drawDefinition:n,structureId:r}),h=f.map(g=>{const I=p==null?void 0:p[g].finishingPositionRange.loser,[S,T]=I??[0,0];return ht(S,(T||S)+1)}).flat().sort(Ve),{playoffRoundsRanges:d}=Uk({playoffSourceRounds:f,roundProfile:p}),m=[...f,...l];return{playoffPositionsReturned:h,playedOffSourceRounds:l,playoffRoundsRanges:d,playoffSourceRounds:f,sourceRounds:m,roundProfile:p}}function Uk({playoffSourceRounds:t,roundProfile:e}){return{playoffRoundsRanges:t.map(r=>{const s=e[r].finishingPositionRange.loser,[i,o]=s,c=ht(i,(o||i)+1);return{finishingPositionRange:s.join("-"),finishingPositions:c,roundNumber:r}})}}function ou({drawDefinition:t,structureId:e}){if(!t)return{error:lt};const{positionsNotPlayedOff:n,positionsPlayedOff:r}=ld({drawDefinition:t}),{structures:s}=lr({drawDefinition:t}),i=s.filter(a=>!e&&a.stage!==je||a.structureId===e),o={},c=tr({inContext:!0,drawDefinition:t}).matchUps;for(const a of i){const u=a==null?void 0:a.structureId,l=Ok({playoffPositions:n,drawDefinition:t,structure:a,matchUps:c}),{error:f,...p}=l;if(f)return l;o[u]={structureId:u,...p}}return e?{positionsPlayedOff:r,...o[e]}:{availablePlayoffProfiles:Object.values(o),availablePlayoffRounds:Object.values(o),positionsPlayedOff:r}}function Ok({playoffPositions:t,drawDefinition:e,structure:n,matchUps:r}){var p,h,d,m,g,I,S,T;const s=n==null?void 0:n.structureId,{links:i}=$a({drawDefinition:e,structureId:s});if(n.structureType===mn||n.structures){const E=(h=(p=ee({structure:n}))==null?void 0:p.positionAssignments)==null?void 0:h.length,y=n.structures.length,b=(E??0)/y,N=((d=i.source)==null?void 0:d.flatMap(({source:k})=>(k==null?void 0:k.finishingPositions)||[]))||[],A=ht(1,b+1).filter(k=>!N.includes(k)),C=((g=(m=r.find(k=>k.containerStructureId===s&&k.finishingPositionRange))==null?void 0:m.finishingPositionRange)==null?void 0:g.winner)||[0,1],v=i==null?void 0:i.source.map(({target:k})=>k.structureId),{positionsPlayedOff:P,positionsNotPlayedOff:U}=ld({structureIds:v,drawDefinition:e}),O=[...P??[],...U],D=ht(C[0],C[1]+1).filter(k=>!O.includes(k)),M=Ge(D,D.length/A.length),w=A.map((k,_)=>{const F=M[_],L=[Math.min(...F||[]),Math.max(...F||[])].join("-");return{finishingPosition:k,finishingPositions:F,finishingPositionRange:L}});return{positionsNotPlayedOff:D,playoffFinishingPositionRanges:w,finishingPositionsAvailable:A,finishingPositionsPlayedOff:N,positionsPlayedOff:P,groupCount:y,groupSize:b}}const o=((I=i==null?void 0:i.source)==null?void 0:I.filter(E=>E.linkCondition!==fs).map(E=>{var y;return(y=E.source)==null?void 0:y.roundNumber}))||[],c=((S=i==null?void 0:i.source)==null?void 0:S.filter(E=>E.linkCondition===fs).map(E=>{var y;return(y=E.source)==null?void 0:y.roundNumber}))||[],{playoffSourceRounds:a,playoffRoundsRanges:u,roundProfile:l,error:f}=Oh({excludeRoundNumbers:o,playoffPositions:t,drawDefinition:e,structureId:s});for(const E of c){const y=i==null?void 0:i.source.find(v=>v.source.roundNumber===E),b=y==null?void 0:y.target.roundNumber,N=y==null?void 0:y.target.structureId,A=r.filter(({roundNumber:v,structureId:P})=>P===N&&v===b),C=A.filter(({sides:v})=>v.find(P=>P.participantFed&&!P.participantId)).length;if(a&&C===A.length){a.push(E);const v=(T=l==null?void 0:l[E].finishingPositionRange)==null?void 0:T.loser;if(v){const P=Math.min(...v),U=P+C,O=ht(P,U),D={finishingPositionRange:[P,U-1].join("-"),finishingPositions:O,roundNumber:E};u.push(D)}}}return a&&a.sort(Ve),u.sort((E,y)=>E.roundNumber-y.roundNumber),{playoffRounds:a,playoffRoundsRanges:u,error:f}}function Mk({playoffGroups:t,drawDefinition:e,structureId:n}){var c;if(!e)return{error:lt};if(typeof n!="string"||!Array.isArray(t))return{error:tt};const r=t.map(({finishingPositions:a})=>a).flat(),i=(c=ou({drawDefinition:e,structureId:n}).playoffFinishingPositionRanges)==null?void 0:c.filter(a=>r.includes(a.finishingPosition));return{positionRangeMap:i==null?void 0:i.reduce((a,u)=>(a[u.finishingPosition]=u,a),{})}}function Dk({includeMatchUpType:t,drawPosition:e,roundNumber:n,matchUpType:r,idPrefix:s,matchUps:i,isMock:o,uuids:c,nodes:a,fed:u}){const l=a.length,f=e?e-l:void 0,p=ht(0,l).map(m=>f?f+m:void 0),h=[];for(let m=0;m<l;m++){const g=p.shift(),I={drawPosition:g,fed:u+1,feed:!0},S=a[m];S.roundNumber=n-1;const T=Ph({roundPosition:S.roundPosition,roundNumber:n,idPrefix:s,uuids:c}),E={roundPosition:S.roundPosition,drawPositions:[g],matchUpStatus:Le,roundNumber:n,matchUpId:T};t&&(E.matchUpType=r),o&&(E.isMock=!0),i.push(E);const y={children:[S,I]};h.push(y)}const d=e?e-l:void 0;return{roundNodes:h,matchUps:i,drawPosition:d}}function ci(t){let{feedRoundsProfile:e,feedRounds:n=0,skipRounds:r=0,baseDrawSize:s,drawSize:i}=t;const{linkFedFinishingRoundNumbers:o,finishingPositionOffset:c,linkFedRoundNumbers:a,feedsFromFinal:u,isConsolation:l,matchUpType:f,idPrefix:p,isMock:h,uuids:d,fmlc:m}=t;s=s||k(i);const g=wk({drawSize:s}),I=g.length;let S=0;if(e!=null&&e.length)S=e.reduce((_,F)=>_+F,0);else if(i){let _=i-s;e=g.filter(F=>F<=_?(_-=F,!0):!1),S=e.reduce((F,L)=>F+L,0),n=e.length}else r>=I?n=0:u&&(n=I-u,r=0),e=g.filter((_,F)=>u&&!n||n&&F>=r+n||F<r?0:_),S=e.reduce((_,F)=>_+F,0),i=s+S,n=e.length;const T=[...g,...e].sort((_,F)=>F-_),E=T.length,b=[...(a??[]).map(_=>_-1),...(o??[]).map(_=>E-_)].map(_=>T[_]).reduce((_,F)=>_+F,0);S=S-b;let N=0,A=[],C,v=1,U=ht(0,s).map((_,F)=>({drawPosition:F+1+S})),O=S+1;for(const _ of g){if({roundNodes:C,matchUps:A}=ud({matchUpType:f,roundNumber:v,idPrefix:p,matchUps:A,isMock:h,nodes:U,uuids:d}),v++,e.includes(_)){const F=Mn(e)[_],L=ht(0,F),W=E+1-v,j=(o==null?void 0:o.includes(W))||(a==null?void 0:a.includes(v));L.forEach(()=>{({roundNodes:C,matchUps:A,drawPosition:O}=Dk({drawPosition:!j&&O||void 0,nodes:C,matchUpType:f,roundNumber:v,idPrefix:p,matchUps:A,isMock:h,uuids:d,fed:N})),v++,N+=1})}U=C}E!==v-1&&console.log("ERROR");const D=s-S;A=ja({finishingPositionOffset:l?D:c,positionsFed:S,roundsCount:E,matchUps:A,fmlc:m});const w=C!=null&&C.length?C[0]:C;return w&&(w.roundNumber=v-1,w.matchUps=A),{draw:w,matchUps:A,roundsCount:E};function k(_){const F=Fd(_);return F>_?F/2:F}}function wk({drawSize:t}){const e=Math.ceil(Math.log(t)/Math.log(2));return ht(0,e).reverse().map(r=>Math.pow(2,r))}function DE(t){const{finishingPositionOffset:e=0,stageSequence:n=1,staggeredEntry:r,structureName:s,stage:i=It,matchUpType:o,structureId:c,idPrefix:a,drawSize:u,isMock:l,uuids:f}=t,p={finishingPositionOffset:e,matchUpType:o,drawSize:u,idPrefix:a,isMock:l,uuids:f},{matchUps:h}=r?ci(p):rs(p),d=Ze({structureId:c||(f==null?void 0:f.pop()),structureName:s||It,stageSequence:n,matchUpType:o,matchUps:h,stage:i}),m=[d],g=[];if(u>2){const I=u/2,{matchUps:S}=rs({finishingPositionOffset:e+I,idPrefix:a&&`${a}-c`,drawSize:I,matchUpType:o,isMock:l}),T=t.consolationStructureName||(s?`${s} ${Re}`:Re),E=Ze({structureName:T,matchUps:S,structureId:f==null?void 0:f.pop(),stage:Re,stageSequence:1,matchUpType:o});m.push(E);const y={linkType:js.Loser,source:{roundNumber:1,structureId:d.structureId},target:{roundNumber:1,feedProfile:ra.TopDown,structureId:E.structureId}};g.push(y)}return{...$,structures:m,links:g}}function wE({consolationStructure:t,roundOffset:e=0,mainStructure:n,roundsCount:r,feedPolicy:s,fmlc:i}){const c=t.matchUps.reduce((l,f)=>(f.drawPositions||[]).filter(Boolean).length&&!l.includes(f.roundNumber)?l.concat(f.roundNumber):l,[]),a=(s==null?void 0:s.roundGroupedOrder)||[],u=s==null?void 0:s.roundFeedProfiles;return ht(1+e,r+1+e).map(l=>{const f=u&&u[l-1]?u[l-1]:l%2?Ni:uo,p=l-e<=2?l-e:(l-e-2)*2+2,h={linkType:lo,source:{roundNumber:l,structureId:n.structureId},target:{feedProfile:f,roundNumber:p,structureId:t.structureId}},d=a[l-1];return d&&(h.target.groupedOrder=d),ze()&&(h.source.structureName=n.structureName,h.target.structureName=t.structureName),l===2&&i&&(h.linkCondition=fs,h.target.feedProfile=Ni),c.includes(p)?h:void 0}).filter(Boolean)}function kE(t){const{finishingPositionOffset:e,structureName:n=It,stageSequence:r=1,structureNameMap:s,staggeredEntry:i,stage:o=It,matchUpType:c,structureId:a,drawSize:u,idPrefix:l,isMock:f,uuids:p}=t,h={finishingPositionOffset:e,matchUpType:c,drawSize:u,idPrefix:l,isMock:f,uuids:p},{matchUps:d,roundsCount:m}=i?ci(h):rs(h),g=Ze({structureId:a||(p==null?void 0:p.pop()),structureName:n,stageSequence:r,matchUpType:c,matchUps:d,stage:o}),I=[g],S=[];if(u>2){const y=[0,2].slice(0,u/16).map((b,N)=>{const A=N+1,{consolationStructure:C}=kk({idPrefix:l&&`${l}-c${N}`,structureId:p==null?void 0:p.pop(),structureNameMap:s,stageSequence:A,roundOffset:b,matchUpType:c,drawSize:u,isMock:f,index:N,uuids:p});I.push(C);const v=wE({consolationStructure:C,roundsCount:2,mainStructure:g,roundOffset:b});return{consolationStructure:C,links:v}}).map(b=>b.links).flat();if(S.push(...y),u>=4&&u<=16||u>32){const{matchUps:b}=rs({idPrefix:l&&`${l}-p3t4`,finishingPositionOffset:2,drawSize:2,matchUpType:c,isMock:f}),N=Ze({structureName:(s==null?void 0:s[Ie])||Ie,structureId:p==null?void 0:p.pop(),matchUps:b,stageSequence:2,stage:Ie,matchUpType:c}),A={linkType:js.Loser,source:{roundNumber:m-1,structureId:g.structureId},target:{structureId:N.structureId,feedProfile:ra.TopDown,roundNumber:1}};I.push(N),S.push(A)}}return{structures:I,links:S,...$}}function kk({stageSequence:t=1,structureNameMap:e,roundOffset:n=0,matchUpType:r,structureId:s,idPrefix:i,drawSize:o,isMock:c,index:a,uuids:u}){const l=o/(2*Math.pow(2,n)),{matchUps:f,roundsCount:p}=ci({finishingPositionOffset:l,baseDrawSize:l,isConsolation:!0,feedRounds:1,matchUpType:r,idPrefix:i,isMock:c,uuids:u}),h=`${Re} ${a+1}`,d=(e==null?void 0:e[h])||h;return{consolationStructure:Ze({matchUps:f,stage:Re,structureName:d,stageSequence:t,matchUpType:r,structureId:s}),consolationRoundsCount:p}}function _c(t){let{matchUpType:e}=t;const{finishingPositionOffset:n=0,addNameBaseToAttributeName:r,playoffStructureNameBase:s,finishingPositionNaming:i,finishingPositionLimit:o,playoffAttributes:c,stageSequence:a=1,exitProfile:u="0",exitProfileLimit:l,roundOffsetLimit:f,roundOffset:p=0,drawDefinition:h,staggeredEntry:d,sequenceLimit:m,stage:g=It,structureId:I,drawSize:S,idPrefix:T,isMock:E,uuids:y}=t;if(!(!c||!l||(c==null?void 0:c[u]))||S<2||m&&a>m)return{};const N=[],A=[],C=[];e=e||(h==null?void 0:h.matchUpType);const v=n+1,P=n+S,U=`${v}-${P}`,O=c==null?void 0:c[u],D=s&&`${s} `||"",M=i==null?void 0:i[U],w=(M==null?void 0:M.name)||(O==null?void 0:O.name)&&(r?`${D}${O==null?void 0:O.name}`:O.name)||`${D}${U}`,k=(M==null?void 0:M.abbreviation)||(O==null?void 0:O.abbreviation),_={idPrefix:T&&`${T}-${w}-RP`,finishingPositionOffset:n,matchUpType:e,drawSize:S,isMock:E,uuids:y},{matchUps:F}=d?ci(_):rs(_),L=Ze({structureId:I||(y==null?void 0:y.pop()),structureAbbreviation:k,stageSequence:a,structureName:w,matchUpType:e,roundOffset:p,matchUps:F,stage:g});N.push(...F),A.push(L);const W=Math.ceil(Math.log(S)/Math.log(2)),j=f?Math.min(f-p,W):!o||v<o?W:0;return S>2&&ht(1,j+1).forEach(B=>H(B)),{structureId:L.structureId,matchUps:N,structureName:w,structures:A,links:C,...$};function H(B){const R=S/Math.pow(2,B);if(R<2)return;const x=S/Math.pow(2,B)+n;if(x+1>o)return;const{structures:q,structureId:V,matchUps:Y,links:z}=_c({finishingPositionOffset:x,exitProfile:`${u}-${B}`,roundOffset:p+B,stageSequence:a+1,drawSize:R,addNameBaseToAttributeName:r,playoffStructureNameBase:s,finishingPositionNaming:i,finishingPositionLimit:o,playoffAttributes:c,exitProfileLimit:l,roundOffsetLimit:f,drawDefinition:h,sequenceLimit:m,matchUpType:e,idPrefix:T,uuids:y,stage:g});if(L.structureId&&V){const J={linkType:js.Loser,source:{roundNumber:B,structureId:L.structureId},target:{roundNumber:1,feedProfile:ra.TopDown,structureId:V}};z&&L&&z.push(J),z!=null&&z.length&&C.push(...z)}return q!=null&&q.length&&A.push(...q),Y!=null&&Y.length&&N.push(...Y),{structureId:V,childLinks:z,structures:A}}}function ko(t){const{finishingPositionOffset:e,stageSequence:n=1,policyDefinitions:r,feedsFromFinal:s,staggeredEntry:i,structureName:o,stage:c=It,structureId:a,matchUpType:u,skipRounds:l,feedRounds:f,idPrefix:p,drawSize:h,isMock:d,uuids:m,fmlc:g}=t,I=t.feedPolicy||(r==null?void 0:r[Bu]),S={finishingPositionOffset:e,matchUpType:u,skipRounds:l,drawSize:h,idPrefix:p,isMock:d,uuids:m},{matchUps:T}=i?ci(S):rs(S),E=Ze({structureId:a||(m==null?void 0:m.pop()),structureName:o||It,stageSequence:n,matchUpType:u,matchUps:T,stage:c}),y=[E],b=[],N=h/2,{matchUps:A,roundsCount:C}=ci({finishingPositionOffset:N,idPrefix:p&&`${p}-c`,isConsolation:!0,feedsFromFinal:s,baseDrawSize:N,matchUpType:u,feedRounds:f,skipRounds:l,isMock:d,uuids:m,fmlc:g});if(h>2){const v=Ze({matchUps:A,structureId:m==null?void 0:m.pop(),structureName:Re,stage:Re,stageSequence:1,matchUpType:u});y.push(v);const P=wE({consolationStructure:v,mainStructure:E,roundsCount:C,feedPolicy:I,fmlc:g});b.push(...P)}return{...$,structures:y,links:b}}function _E({compassAttributes:t=Vf,olympicAttributes:e=jf,requireSequential:n=!0,playoffMatchUpFormat:r,sourceStructureId:s,policyDefinitions:i,stageSequence:o,drawDefinition:c,playoffGroups:a,matchUpType:u,feedPolicy:l,groupCount:f,idPrefix:p,isMock:h,uuids:d}){var N,A;l=l||(i==null?void 0:i[Bu]);const m="processPlayoffGroups";let g=0;const I=[],S=[],T=[],{error:E,positionRangeMap:y}=Mk({structureId:s,drawDefinition:c,playoffGroups:a});if(E)return G({result:{error:E},stack:m});if(!(!y||(a==null?void 0:a.every(C=>{const{finishingPositions:v=[]}=C;if(!v.length)return!1;const P=v.sort(Ve).map((U,O)=>(v[O+1]||U)-U).every(U=>U<2);return(!n||P)&&v.every(U=>y[U])}))))return G({context:{validFinishingPositions:Object.values(y)},result:{error:tt},stack:m});for(const C of a){const v=C.finishingPositions,P=y&&v.map(k=>{var _;return(_=y[k])==null?void 0:_.finishingPositions}).flat(),U=f*v.length,O=Vo(U),D=O===2&&Ms||C.drawType||Ms;P&&(g=Math.min(...P)-1);const M={structureId:C.structureId??(d==null?void 0:d.pop()),structureNameMap:C.structureNameMap,structureName:C.structureName,idPrefix:p&&`${p}-po`,appliedPolicies:i,finishingPositionOffset:g,stage:Ie,stageSequence:o,matchUpType:u,drawSize:O,isMock:h,uuids:d},w=({playoffStructures:k,playoffLinks:_})=>{const[F]=k,L=dd({playoffStructureId:F.structureId,finishingPositions:v,sourceStructureId:s});T.push(L),T.push(..._),S.push(...k),I.push({structureId:F.structureId,finishingPositions:v}),g+=U};if(D===Ms){const{matchUps:k}=rs({finishingPositionLimit:g+U,idPrefix:p&&`${p}-po`,finishingPositionOffset:g,matchUpType:u,drawSize:O,isMock:h,uuids:d}),_=Ze({structureId:C.structureId??(d==null?void 0:d.pop()),structureName:C.structureName,matchUpFormat:r,stage:Ie,stageSequence:o,matchUps:k});S.push(_);const F=dd({playoffStructureId:_.structureId,finishingPositions:v,sourceStructureId:s});T.push(F),g+=U,I.push({structureId:_.structureId,finishingPositions:v})}else if([oc,cc,Ie].includes(D)){const{structureName:k}=C,_={structureId:C.structureId??(d==null?void 0:d.pop()),playoffStructureNameBase:k,idPrefix:p&&`${p}-po`,addNameBaseToAttributeName:!0,finishingPositionOffset:g,stage:Ie,roundOffset:0,stageSequence:o,drawSize:O,isMock:h,uuids:d};D===oc?Object.assign(_,{playoffAttributes:t,roundOffsetLimit:3}):D===cc&&Object.assign(_,{playoffAttributes:e,roundOffsetLimit:2});const F=_c(_);if(F.error)return F;if((N=F.links)!=null&&N.length&&T.push(...F.links),(A=F.structures)!=null&&A.length&&S.push(...F.structures),S.sort(Pi),F.structureId){const L=dd({playoffStructureId:F.structureId,finishingPositions:v,sourceStructureId:s});T.push(L),I.push({structureId:F.structureId,finishingPositions:v})}g+=U}else if([ac,Da,Oa,Ua,Pa,Ma].includes(D)){const k=[d==null?void 0:d.pop(),d==null?void 0:d.pop()],_={structureId:C.structureId??(d==null?void 0:d.pop()),structureName:C.structureName,idPrefix:p&&`${p}-po`,finishingPositionOffset:g,uuids:k,stage:Ie,matchUpType:u,feedPolicy:l,drawSize:O,isMock:h},F={[ac]:{fmlc:!0,feedRounds:1},[Ma]:{feedRounds:1},[Oa]:{feedsFromFinal:3},[Ua]:{feedsFromFinal:2},[Pa]:{feedsFromFinal:1}};Object.assign(_,F[D]||{});const{structures:L,links:W}=ko(_),[j]=L,H=dd({playoffStructureId:j.structureId,finishingPositions:v,sourceStructureId:s});T.push(H),T.push(...W),S.push(...L),I.push({structureId:j.structureId,finishingPositions:v}),g+=U}else if([Pr].includes(D)){const{structures:k,links:_}=za({...M,structureOptions:C.structureOptions||{groupSize:4}});w({playoffStructures:k,playoffLinks:_})}else if([Ca].includes(D)){const{structures:k,links:_}=DE(M);w({playoffStructures:k,playoffLinks:_})}else if([xP].includes(D)){const{structures:k,links:_}=kE(M);w({playoffStructures:k,playoffLinks:_})}else if([Xn].includes(D)){const k=Ze({structureId:C.structureId??(d==null?void 0:d.pop()),structureName:C.structureName,finishingPosition:ua,stage:Ie,stageSequence:o,matchUps:[]});w({playoffStructures:[k],playoffLinks:[]})}}return{finishingPositionTargets:I,positionRangeMap:y,structures:S,links:T}}function dd({playoffStructureId:t,finishingPositions:e,sourceStructureId:n}){return{linkType:Ai,source:{structureId:n,finishingPositions:e},target:{structureId:t,feedProfile:Cr,roundNumber:1}}}function _k(t){const{drawDefinition:e,structureOptions:n,requireSequential:r}=t,s={structureName:It,...t,stage:It},{structures:i,groupCount:o,groupSize:c}=za(s);o<1&&console.log(Mv);const a=(n==null?void 0:n.playoffGroups)||[{finishingPositions:[1],structureName:Ie}],[u]=i,{structures:l,links:f}=_E({sourceStructureId:u.structureId,requireSequential:r,drawDefinition:e,playoffGroups:a,groupCount:o,groupSize:c,...t});return l&&i.push(...l),{...$,structures:i,links:f}}function Fk({mainStructure:t,consolationStructure:e,deciderStructure:n}){const s=e.matchUps.reduce((l,f)=>(f.drawPositions||[]).filter(Boolean).length&&!l.includes(f.roundNumber)?l.concat(f.roundNumber):l,[]),i=t.matchUps.reduce((l,f)=>!l||f.roundNumber>l?f.roundNumber:l,void 0),o=e.matchUps.reduce((l,f)=>!l||f.roundNumber>l?f.roundNumber:l,void 0),c=s.map((l,f)=>{const h=s.indexOf(l)%2?Ni:uo,d=1+f;return{linkType:lo,source:{roundNumber:d,structureId:t.structureId},target:{feedProfile:h,roundNumber:l,structureId:e.structureId}}}),a={linkType:vi,source:{roundNumber:o,structureId:e.structureId},target:{feedProfile:Ni,roundNumber:i,structureId:t.structureId}},u=[{linkType:vi,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:Ni,roundNumber:1,structureId:n.structureId}},{linkType:lo,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:Ni,roundNumber:1,structureId:n.structureId}}];return[...c,a,...u]}function Lk({structureName:t,matchUpType:e,idPrefix:n,drawSize:r,isMock:s,uuids:i}){const o=[],{matchUps:c}=ci({linkFedFinishingRoundNumbers:[1],drawSize:r+1,matchUpType:e,idPrefix:n,isMock:s}),a=Ze({structureName:t||It,structureId:i==null?void 0:i.pop(),stageSequence:1,stage:It,matchUpType:e,matchUps:c});o.push(a);const u=r/2,{matchUps:l}=ci({finishingPositionOffset:u,idPrefix:n&&`${n}-c`,drawSize:r-1,isConsolation:!0,matchUpType:e,isMock:s,uuids:i}),f=Ze({matchUps:l,structureId:i==null?void 0:i.pop(),structureName:ZI,stage:Re,stageSequence:2,matchUpType:e});o.push(f);const{matchUps:p}=rs({idPrefix:n&&`${n}-p1t2`,drawSize:2,matchUpType:e,isMock:s}),h=Ze({matchUps:p,structureId:i==null?void 0:i.pop(),structureName:QI,stageSequence:3,stage:Ie,matchUpType:e});o.push(h);const d=Fk({mainStructure:a,consolationStructure:f,deciderStructure:h});return{structures:o,links:d,...$}}function Rk(t){const{qualifyingRoundNumber:e,finishingPositionOffset:n,qualifyingPositions:r,matchUpType:s,idPrefix:i,drawSize:o,isMock:c,uuids:a}=t;if(!oe(o)||o<2)return{matchUps:[],roundsCount:0};if(mr(o))return rs(t);const u=Bk(o),l=u.shift(),f=ht(1,((l==null?void 0:l.participantsCount)||0)+1).map(g=>({drawPosition:g}));let p=[],h=1;({matchUps:p}=ud({roundNumber:h,matchUpType:s,idPrefix:i,matchUps:p,isMock:c,nodes:f,uuids:a})),h++;let d=t.roundLimit||e;for(const g of u){const I=g.participantsCount/2,S=ht(1,I+1);r&&I===r&&(d=h-1);const T=S.map(E=>{const y=Ph({roundPosition:E,roundNumber:h,idPrefix:i,uuids:a});return{roundPosition:E,roundNumber:h,matchUpId:y}});p.push(...T),h++}const m=h-1;return p=ja({finishingPositionOffset:n,lucky:!0,roundsCount:m,roundLimit:d,matchUps:p}),d&&(p=p.filter(g=>g.roundNumber<=d)),{matchUps:p,roundsCount:m,roundLimit:d}}function Bk(t){const e=vt(t);let n=e%2?e+1:e;const r=!!(Math.ceil(n/2)%2),s=[{participantsCount:n,preFeedRound:r}];for(;n>2;){const i=Math.ceil(n/2),o=i===1,c=!!(!o&&i%2);n=!o&&c?i+1:i;const a=!!(n!==2&&Math.ceil(n/2)%2);s.push({participantsCount:n,preFeedRound:a,feedRound:c})}return s}function FE(t){var d;const{compassAttributes:e=Vf,olympicAttributes:n=jf,stageSequence:r=1,structureName:s,structureId:i,stage:o=It,matchUpType:c,drawSize:a,uuids:u}=t,{appliedPolicies:l}=ge(t),f=((d=t.policyDefinitions)==null?void 0:d[Bu])||(l==null?void 0:l[Bu]);t.skipRounds=t.skipRounds||a<=4&&(f!=null&&f.feedMainFinal?0:1)||0;const p=()=>{const{matchUps:m}=rs(t);return{structures:[Ze({structureName:s||It,structureId:i||(u==null?void 0:u.pop()),stageSequence:r,matchUpType:c,matchUps:m,stage:o})],links:[],...$}};return{generators:{[Xn]:()=>({structures:[Ze({structureName:s||It,structureId:i||(u==null?void 0:u.pop()),finishingPosition:uc,stageSequence:r,matchUps:[],matchUpType:c,stage:o})],links:[],...$}),[Ci]:()=>{const{matchUps:m}=Rk(t);return{structures:[Ze({structureName:s||It,structureId:i||(u==null?void 0:u.pop()),stageSequence:r,matchUpType:c,matchUps:m,stage:o})],links:[],...$}},[Ms]:()=>p(),[va]:()=>Lk(t),[oc]:()=>_c({...t,roundOffsetLimit:3,playoffAttributes:e}),[cc]:()=>_c({...t,roundOffsetLimit:2,playoffAttributes:n}),[Ie]:()=>_c(t),[ic]:()=>{const{matchUps:m}=ci({drawSize:a,uuids:u,matchUpType:c});return{structures:[Ze({structureName:s||It,structureId:i||(u==null?void 0:u.pop()),stageSequence:r,matchUpType:c,stage:It,matchUps:m})],links:[],...$}},[Ca]:()=>DE(t),[ac]:()=>ko({...t,feedRounds:1,fmlc:!0}),[JI]:()=>ko({...t,feedRounds:1}),[Bf]:()=>ko({...t,feedsFromFinal:1}),[xf]:()=>ko({...t,feedsFromFinal:2}),[$f]:()=>ko({...t,feedsFromFinal:3}),[Da]:()=>ko(t),[el]:()=>kE(t),[Pr]:()=>za(t),[Ds]:()=>_k(t)}}}function Mh(t){var j,H,B,R,x,q;const{enforceMinimumDrawSize:e=!0,overwriteExisting:n,appliedPolicies:r,staggeredEntry:s,drawDefinition:i,tieFormat:o,drawSize:c,isMock:a,uuids:u}=t||{},l=t.drawTypeCoercion??((j=r==null?void 0:r[pf])==null?void 0:j.drawTypeCoercion)??!0,f="generateDrawStructuresAndLinks";let p=l&&t.drawSize===2&&na.SingleElimination||t.drawType||na.SingleElimination;const h=[],d=[],m=(t==null?void 0:t.matchUpType)??Oe,g=(H=i==null?void 0:i.structures)==null?void 0:H.filter(({stage:V})=>V===Pt);g&&h.push(...g);const I=g==null?void 0:g.map(({structureId:V})=>V),S=(B=i==null?void 0:i.structures)==null?void 0:B.find(({stage:V,stageSequence:Y})=>V===It&&Y===1),T=(R=i==null?void 0:i.links)==null?void 0:R.filter(V=>V.target.structureId===(S==null?void 0:S.structureId)&&(I==null?void 0:I.includes(V.source.structureId))),E=(V,Y)=>{var z;if(V.linkType===Ai&&(Y!=null&&Y.structures)){const J=V.source.finishingPositions||[];return Y.structures.length*J.length}else if(V.linkType===vi&&((z=Y==null?void 0:Y.matchUps)!=null&&z.length)){const J=V.source.roundNumber;return Y.matchUps.filter(({roundNumber:X})=>X===J).length}},y=g==null?void 0:g.map(V=>{var Z,nt,rt;const Y=T==null?void 0:T.find(K=>K.target.structureId===V.structureId),z=((nt=(Z=ee({structure:V}))==null?void 0:Z.positionAssignments)==null?void 0:nt.length)??0;if(!Y)return z;const J=Y==null?void 0:Y.source.structureId,Q=(rt=i.structures)==null?void 0:rt.find(K=>K.structureId===J),X=E(Y,Q)||0;return z-X}).filter(Boolean).reduce((V,Y)=>V+Y,0),b=T==null?void 0:T.map(V=>{const Y=V.source.structureId,z=g==null?void 0:g.find(J=>J.structureId===Y);return E(V,z)}).filter(Boolean).reduce((V,Y)=>V+Y,0),N=!!(S&&!((x=S==null?void 0:S.matchUps)!=null&&x.length));if(g!=null&&g.length&&!N)return{error:Ag};const A=!(g!=null&&g.length)&&t.qualifyingProfiles,C=(A==null?void 0:A.length)&&UE({idPrefix:t.idPrefix,qualifyingProfiles:A,appliedPolicies:r,isMock:a,uuids:u});if(C!=null&&C.error)return C;const{qualifyingDrawPositionsCount:v,qualifyingDetails:P,qualifiersCount:U}=C||{qualifyingDrawPositionsCount:y,qualifiersCount:b};v&&(C!=null&&C.structures&&h.push(...C.structures),C!=null&&C.links&&d.push(...C.links)),Object.assign(t,bt({drawSize:c,matchUpType:m,tieFormat:o}));const O=p!==Xn&&(isNaN(c)||c<2||!s&&![ic,Ci].includes(p)&&([Ds,Pr].includes(p)&&c<3||![Pr,Ds].includes(p)&&!mr(c)));if(O&&!v)return G({context:{drawSize:c,invalidDrawSize:O},result:{error:xd},stack:f});const D=XI.includes(p);if(vt(c)<4&&D){if(l)p=Ms;else if(e)return G({context:{enforceMinimumDrawSize:e,invalidDrawSize:O,drawSize:c,drawType:p},result:{error:xd},stack:f})}const{generators:M,error:w}=FE(t);if(w)return{error:w};const k=M[p];if(!k)return{error:Ym};const _=k==null?void 0:k();if(_.error)return _;const{structures:F,links:L}=_;if(F!=null&&F.length){const V=F.find(({stage:Y,stageSequence:z})=>Y===It&&z===1);if(S&&V){if(N){const Y=V.structureId;if(V.structureId=S.structureId,L!=null&&L.length)for(const z of L)z.source.structureId===Y&&(z.source.structureId=S.structureId),z.target.structureId===Y&&(z.target.structureId=S.structureId)}else if(!n)return{error:Ag}}h.push(...F)}h.sort(Pi),L!=null&&L.length&&d.push(...L);const W=_.structures.find(({stage:V,stageSequence:Y})=>V===It&&Y===1);for(const V of P||[]){const{finalQualifyingRoundNumber:Y,finalQualifyingStructureId:z,roundTarget:J,finishingPositions:Q,linkType:X}=V,Z=W&&((q=kc({targetStructureId:W.structureId,sourceStructureId:z,sourceRoundNumber:Y,finishingPositions:Q,targetEntryRound:J,linkType:X}))==null?void 0:q.link);if(Z!=null&&Z.error)return Z;Z&&d.push(Z)}return T&&d.push(...T),{...$,qualifyingResult:{qualifyingDrawPositionsCount:v,qualifiersCount:U},structures:h,links:d}}function Li(t){var h,d,m,g,I,S,T,E;const{provisionalPositioning:e,drawDefinition:n,stageSequence:r,structureId:s,stage:i}=t;if(!n)return{error:lt};const{entryProfile:o}=Aa({drawDefinition:n}),c=i&&r&&((m=(d=(h=o==null?void 0:o[i])==null?void 0:h.stageSequence)==null?void 0:d[r])==null?void 0:m.qualifiersCount)||i&&((g=o==null?void 0:o[i])==null?void 0:g.qualifiersCount)||0,a={};if(!s)return{qualifiersCount:c,roundQualifiersCounts:a};const{structure:u}=Ot({drawDefinition:n,structureId:s}),l=(I=n.links)==null?void 0:I.filter(y=>{var b;return((b=y==null?void 0:y.target)==null?void 0:b.structureId)===(u==null?void 0:u.structureId)});let f=0;if(l!=null&&l.length)for(const y of l){const b=(S=Ot({structureId:y.source.structureId,drawDefinition:n}))==null?void 0:S.structure;if((b==null?void 0:b.stage)===Pt){const N=y.source.roundNumber,A=y.target.roundNumber;let C=0;if(b.structureType===mn){const v=((T=b.structures)==null?void 0:T.length)||0,P=((E=y.source.finishingPositions)==null?void 0:E.length)||0;C=v*P}else{const v=Qt({matchUpFilters:{roundNumbers:[N]},structure:b,afterRecoveryTimes:!1,provisionalPositioning:e,inContext:!1}).matchUps;C=(v==null?void 0:v.length)||0}a[A]||(a[A]=0),a[A]+=C,f+=C}}const p=Object.keys(a);if(p.length<=1){const y=p[0]||1;a[y]=Math.max(a[y]||0,c)}return f=Math.max(f,c),{qualifiersCount:f,roundQualifiersCounts:a}}function cu({stage:t,drawDefinition:e}){var r;const{entryProfile:n}=Aa({drawDefinition:e});return((r=n==null?void 0:n[t])==null?void 0:r.drawSize)||0}function xk(t){const{provisionalPositioning:e,drawDefinition:n,stageSequence:r,stage:s}=t,i=cu({stage:s,drawDefinition:n}),{qualifiersCount:o}=Li({provisionalPositioning:e,drawDefinition:n,stageSequence:r,stage:s});return i&&i-o}function au({stageSequence:t=1,drawDefinition:e,drawSize:n,stage:r}){if(!e)return{error:lt};if(!_a({drawDefinition:e,stage:r}))return{error:xs};const s=eS({drawDefinition:e,stage:r}),{qualifiersCount:i}=Li({drawDefinition:e,stageSequence:t,stage:r}),o=s+i;if(n<o)return{error:yu};const{entryProfile:c}=Na({attributes:[{[r]:{drawSize:n}}],drawDefinition:e});return Zt({drawDefinition:e}),{...$,entryProfile:c}}function $k({alternatesCount:t,drawDefinition:e,stage:n}){var r;return e?_a({drawDefinition:e,stage:n})?(Na({attributes:[{[n]:{alternates:t}}],drawDefinition:e}),t||(e.entries=((r=e.entries)==null?void 0:r.filter(s=>s.entryStatus!==dr))||[]),Zt({drawDefinition:e}),{...$}):{error:xs}:{error:lt}}function Vk({wildcardsCount:t=0,drawDefinition:e,stageSequence:n,stage:r}){if(!e)return{error:lt};if(!_a({drawDefinition:e,stage:r}))return{error:xs};const s=cu({drawDefinition:e,stage:r}),{qualifiersCount:i}=Li({drawDefinition:e,stageSequence:n,stage:r}),o=YP({drawDefinition:e,stage:r}),c=eS({drawDefinition:e,stage:r});return t<o?{error:Object.assign(yu,{message:"Number of Wildcards cannot be less than number of Wildcards already entered"})}:c+t+i>s?{error:yu,info:"Total stage Entries cannot be greater than drawPositions"}:(Na({attributes:[{[r]:{wildcardsCount:t}}],drawDefinition:e}),Zt({drawDefinition:e}),{...$})}function Dh({qualifiersCount:t=0,drawDefinition:e,stage:n}){return e?_a({drawDefinition:e,stage:n})?n!==It?{error:yu,info:"qualifiersCount can only be set for main stage"}:(Na({attributes:[{[n]:{qualifiersCount:t}}],drawDefinition:e}),Zt({drawDefinition:e}),{...$}):{error:xs}:{error:lt}}function wh(t){var T;const{modifyOriginal:e=!0,stageSequence:n=1,isMock:r}=t||{},s="generateDrawTypeAndModifyDrawDefinition";if(!t.drawDefinition)return G({result:{error:lt},stack:s});const i=e?t.drawDefinition:pt(t.drawDefinition,!1,!0);let{tieFormat:o,matchUpType:c}=t;if(o){const E=vn({tieFormat:o});if(E.error)return E}o=Dr(o||((T=hn({drawDefinition:i}))==null?void 0:T.tieFormat)),c=c||i.matchUpType||Oe,t.tieFormat=o,t.matchUpType=c;const a=cu({drawDefinition:i,stage:It});t.drawSize=t.drawSize||a,!a&&t.drawSize&&au({drawSize:t.drawSize,drawDefinition:i,stageSequence:n,stage:It});const u=ln({drawDefinition:i}).drawMatchUps.map(Qe),l=Mh(t);if(l.error)return G({result:l,stack:s});const{structures:f,links:p,qualifyingResult:h}=l;i.structures=f,i.links=p;const d=Math.max(t.qualifiersCount||0,(h==null?void 0:h.qualifiersCount)||0);if(h!=null&&h.qualifyingDrawPositionsCount&&!cu({stage:Pt,drawDefinition:i})){const y=au({drawSize:h.qualifyingDrawPositionsCount,stage:Pt,drawDefinition:i});if(y.error)return y}if(d){const E=Dh({qualifiersCount:d,drawDefinition:i,stage:It});if(E.error)return E}const m=t.drawSize||a;Object.assign(t,bt({drawSize:m,matchUpType:c,tieFormat:o}));const{matchUps:g,matchUpsMap:I}=xe({drawDefinition:i});o&&(g==null||g.forEach(E=>{if(!u.includes(E.matchUpId)){const{tieMatchUps:y}=Jl({tieFormat:o,isMock:r});Object.assign(E,{tieMatchUps:y,matchUpType:c})}}));const{inContextDrawMatchUps:S}=Ic({drawDefinition:i,matchUpsMap:I});return Zt({drawDefinition:i}),{inContextDrawMatchUps:S,drawDefinition:i,matchUpsMap:I,...$,structures:f,matchUps:g,links:p}}function jk({targetParticipantIds:t,policyAttributes:e,idCollections:n,participants:r}){if(!Array.isArray(e))return{error:eg};if(!Array.isArray(r))return{error:Yc};const s={};return t.forEach(i=>{const o=r.find(a=>a.participantId===i),{values:c}=LE({policyAttributes:e,idCollections:n,participants:r,participant:o});c&&c.forEach(a=>{s[a]||(s[a]=[]),s[a].includes(i)||s[a].push(i)})}),s}function LE({policyAttributes:t,idCollections:e,participants:n,participant:r}){if(!Array.isArray(t))return{error:eg};if(!r)return{error:qo};const s=[];return t.forEach(c=>{const{directive:a,groupings:u,key:l,significantCharacters:f}=c||{};if(l){const p=l.split(".");o({value:r,keys:p,significantCharacters:f})}else if(a){const p=c==null?void 0:c.includeIds,h=((e==null?void 0:e[a])||[]).filter(d=>!p||p.includes(d));h!=null&&h.length&&(n!=null&&n.length)&&h.forEach(d=>{var g;const m=n.find(I=>I.participantId===d);if((g=m==null?void 0:m.individualParticipantIds)!=null&&g.includes(r.participantId)){const I=m==null?void 0:m.participantId;s.push(I)}})}else u&&Object.keys(u).forEach(p=>{u[p].includes(r.participantId)&&s.push(p)})}),{values:Vt(s)};function o({value:c,keys:a=[],significantCharacters:u}){for(const[f,p]of a.entries())if(c!=null&&c[p])if(Array.isArray(c[p])){const h=c[p],d=a.slice(f);h.forEach(m=>o({value:m,keys:d,significantCharacters:u}))}else c=c[p],l({value:c,index:f});function l({value:f,index:p}){if(f&&p===a.length-1&&["string","number"].includes(typeof f)){const h=u?f.slice(0,u):f;s.push(h)}}}}function RE({candidatePositionAssignments:t,participantsWithGroupings:e,policyAttributes:n,idCollections:r}){const s=Object.assign({},...e.map(i=>({[i.participantId]:i})));return t.map(i=>{const o=s[i.participantId],{values:c}=LE({participants:e,policyAttributes:n,idCollections:r,participant:o});return{...i,values:c}})}function BE({participantIdGroups:t,positionAssignments:e,groupsToAvoid:n}){return Object.assign({},...e.filter(r=>r==null?void 0:r.participantId).map(r=>{const{drawPosition:s,participantId:i}=r,o=t?t[i]||[]:[],c=!!n.some(a=>o.includes(a));return{[s]:{participantGroups:o,includesGroupsToAvoid:c}}}))}function Gk(t){const{unfilledPositions:e,chunkedDrawPositions:n}=t,r=BE(t);return n.map(o=>{const c=e.filter(f=>o.includes(f)),a=i(c),l=c.filter(f=>!a.includes(f)).filter(f=>{var h;const p=xE(f);return!((h=r[p])!=null&&h.includesGroupsToAvoid)});return{unassigned:c,unpaired:a,pairedNoConflict:l}});function i(o){return o.filter(a=>!c(a));function c(a){const u=xE(a);return!o.includes(u)}}}function Wk(t){const{unfilledPositions:e,chunkedDrawPositions:n}=t,r=BE(t);return n.map(s=>{const i=e.filter(u=>s.includes(u)),o=i.length===s.length?i:[],c=s.filter(u=>{var l;return(l=r[u])==null?void 0:l.includesGroupsToAvoid}).length;return{unassigned:i,unpaired:o,pairedNoConflict:c?[]:i,conflictsCount:c}})}function xE(t){return Number(t%2?t+1:t-1)}function Hk({allGroups:t,participantId:e}){return Object.keys(t).filter(n=>t[n].includes(e))}function qk({selectedParticipantGroups:t,participantIdGroups:e,positionAssignments:n,drawPositionChunks:r,unfilledPositions:s,isRoundRobin:i}){const o=r.map(c=>i?Wk({groupsToAvoid:t,chunkedDrawPositions:c,participantIdGroups:e,positionAssignments:n,unfilledPositions:s}):Gk({groupsToAvoid:t,chunkedDrawPositions:c,participantIdGroups:e,positionAssignments:n,unfilledPositions:s}));if(i){const c=o.map(l=>l.map(f=>f.unassigned).filter(f=>f==null?void 0:f.length)).filter(l=>l==null?void 0:l.length).sort((l,f)=>(f.length||0)-(l.length||0)),a=o.map(l=>l.map(f=>f.unpaired).filter(f=>f==null?void 0:f.length)).filter(l=>l==null?void 0:l.length),u=o.map(l=>l.map(f=>f.pairedNoConflict).filter(f=>f==null?void 0:f.length)).filter(l=>l==null?void 0:l.length).sort((l,f)=>(f.length||0)-(l.length||0));return{unassigned:c,unpaired:a,pairedNoConflict:u}}else{const c=o.map(l=>l.map(f=>f.unassigned).filter(f=>f==null?void 0:f.length)).filter(l=>l==null?void 0:l.length),a=o.map(l=>l.map(f=>f.unpaired).filter(f=>f==null?void 0:f.length)).filter(l=>l==null?void 0:l.length),u=o.map(l=>l.map(f=>f.pairedNoConflict).filter(f=>f==null?void 0:f.length)).filter(l=>l==null?void 0:l.length);return{unassigned:c,unpaired:a,pairedNoConflict:u}}}function $E({participantIds:t,positionAssignments:e}){const n=e.map(r=>r.participantId);return t.filter(r=>!n.includes(r))}function Yk({useSpecifiedGroupKey:t=!1,targetParticipantIds:e,largestFirst:n=!0,allGroups:r,groupKey:s}){var l;const i=Object.assign({},...Object.keys(r).map(f=>[f,r[f].filter(p=>e.includes(p))]).filter(f=>f[1].length).map(([f,p])=>({[f]:p}))),o=Object.keys(i).reduce((f,p)=>i[p].length>f?i[p].length:f,0),c=Object.keys(i).filter(f=>i[f].length===o),a=Dn(n?c:Object.keys(i));return s=t&&((l=i[s])!=null&&l.length)?s:a,{participantId:s&&i[s]?Dn(i[s]):Dn(e),groupKey:s}}function zk({drawPositionGroups:t,positionAssignments:e}){const n=Object.assign({},...e.map(r=>({[r.drawPosition]:r})));return t.map(r=>r.filter(Boolean).map(s=>n[s]).filter(Boolean).filter(s=>!s.participantId&&!s.bye).map(s=>s.drawPosition)).flat().filter(Boolean)}function Kk({candidatePositionAssignments:t,unseededParticipantIds:e,participantIdGroups:n,drawPositionChunks:r,drawPositionGroups:s,pairedPriority:i,allGroups:o,groupKey:c}){const u=s.reduce((C,v)=>v.length>C?v.length:C,0)<=2,l=$E({positionAssignments:t,participantIds:e}),f=zk({positionAssignments:t,drawPositionGroups:s}),{participantId:p,groupKey:h}=Yk({targetParticipantIds:l,useSpecifiedGroupKey:u,allGroups:o,groupKey:c}),d=Hk({participantId:p,allGroups:o}),m=qk({positionAssignments:t,isRoundRobin:u,selectedParticipantGroups:d,participantIdGroups:n,drawPositionChunks:r,unfilledPositions:f}),{unassigned:g,unpaired:I,pairedNoConflict:S}=m,T=(S==null?void 0:S.length)&&S[0],E=(I==null?void 0:I.length)&&I[0],y=i&&T?T:E,b=i?E:T,N=(y==null?void 0:y.length)&&y||(b==null?void 0:b.length)&&b;let A;if(N!=null&&N.length){const C=cn(N);A=cn(C)}else{const C=cn(g[0]);A=cn(C)}return{newGroupKey:h,selectedParticipantId:p,targetDrawPosition:A}}function fd({isRoundRobin:t,groupedParticipants:e}){const n=[];return t?e.forEach(r=>{const s=r.map(c=>c.drawPosition),{uniqueMatchUpGroupings:i}=yp({drawPositions:s}),o=Object.assign({},...r.map(c=>({[c.drawPosition]:c})));i.forEach(c=>{tn(o[c[0]].values||[],o[c[1]].values||[])&&(n.push(c),r.conflict=!0)})}):e.forEach(r=>{var i,o;tn(((i=r[0])==null?void 0:i.values)||[],((o=r[1])==null?void 0:o.values)||[])&&(n.push(r),r.conflict=!0)}),n}function Jk({positionedParticipants:t,potentialDrawPositions:e,avoidanceConflicts:n,drawPositionGroups:r,isRoundRobin:s}){return n.map(i=>{const o=i.map(a=>a.drawPosition);return i.filter(a=>e.includes(a.drawPosition)).map(a=>{const l=e.filter(f=>!(o!=null&&o.includes(f))).filter(f=>{const p=r.find(T=>T.includes(f)).find(T=>T!==f),h=t.find(T=>T.drawPosition===p),m=fd({isRoundRobin:s,groupedParticipants:[[a,h]]}),I=[t.find(T=>T.drawPosition===f),h],S=fd({isRoundRobin:s,groupedParticipants:[I]});return!m.length&&!S.length});if(l.length)return{drawPosition:a.drawPosition,possibleDrawPositions:l}}).filter(Boolean)}).flat(1)}function VE(t){const{initialPositionAssignments:e,participantsWithGroupings:n,opponentsToPlaceCount:r,unseededByePositions:s,drawPositionGroups:i,policyAttributes:o,idCollections:c,allGroups:a}=t,u=[];let l;const f=Math.min(...(i||[]).map(T=>T==null?void 0:T.length).filter(Boolean)),p=f>2,h=pt(e,!1,!0).filter(T=>!T.qualifier),d=e.filter(T=>!T.participantId&&(!T.bye||(s==null?void 0:s.includes(T.drawPosition)))).map(T=>T.drawPosition);ht(0,r).forEach(()=>{const{newGroupKey:T,selectedParticipantId:E,targetDrawPosition:y}=Kk({...t,candidatePositionAssignments:h,allGroups:a,groupKey:l});l=T,h.forEach(b=>{b.drawPosition===y&&(b.participantId=E)})});let m=RE({candidatePositionAssignments:h,participantsWithGroupings:n,policyAttributes:o,idCollections:c}),g=Ge(m,f),I=fd({groupedParticipants:g,isRoundRobin:p}),S=0;for(;S<20&&I.length;){const T=Jk({positionedParticipants:m,potentialDrawPositions:d,avoidanceConflicts:I,drawPositionGroups:i,isRoundRobin:p});if(T.length){const E=Qk({candidatePositionAssignments:h,swapOptions:T});E.error&&console.log({result:E}),m=RE({candidatePositionAssignments:h,participantsWithGroupings:n,policyAttributes:o,idCollections:c}),g=Ge(m,f),I=fd({groupedParticipants:g,isRoundRobin:p}),S++}else S=20}return h.forEach(T=>{if(T.bye&&T.participantId){const E=zm;u.push(E)}if(T.qualifier&&T.participantId){const E=zm;u.push(E)}}),{positionAssignments:h,conflicts:I.length,groupedParticipants:g,errors:u}}function Qk({candidatePositionAssignments:t,swapOptions:e}){const n=cn(e);if(!n)return{error:{message:"No swap options"}};const r=n.drawPosition,s=cn(n.possibleDrawPositions),i=t.find(u=>u.drawPosition===r),o=t.find(u=>u.drawPosition===s),c={participantId:o.participantId,qualifier:o.qualifier,bye:o.bye},a={participantId:i.participantId,qualifier:i.qualifier,bye:i.bye};return Object.assign(i,c),Object.assign(o,a),{...$}}function Zk({provisionalPositioning:t,unseededParticipantIds:e,inContextDrawMatchUps:n,unseededByePositions:r,tournamentRecord:s,drawDefinition:i,seedBlockInfo:o,participants:c,matchUpsMap:a,structureId:u,avoidance:l,drawSize:f,entries:p,event:h}){var j;if(!l)return{error:Q1};const{candidatesCount:d=1,policyAttributes:m,targetDivisions:g}=l;let{roundsToSeparate:I}=l;const S="randomUnseededSeparation",{structure:T}=Ot({drawDefinition:i,structureId:u}),{matchUps:E}=Qt({provisionalPositioning:t,matchUpsMap:a,structure:T,event:h});if(g&&mr(g)&&!I){const H=I1(g)||0,B=E.reduce((R,x)=>x.roundNumber>R?x.roundNumber:R,0);I=B<H?1:B-H+1}const{positionAssignments:y}=ke({structure:T}),b=Qf({participantsProfile:{convertExtensions:!0},participants:c}),N=y==null?void 0:y.filter(H=>!H.participantId),A=y==null?void 0:y.map(H=>H.drawPosition),C=(T==null?void 0:T.structureType)===mn,v=C?{structure:T,matchUps:E,allDrawPositions:A,roundsToSeparate:I}:{matchUps:E,allDrawPositions:A,roundsToSeparate:I},{drawPositionGroups:P,drawPositionChunks:U}=C?Xk(v):t_(v),O={};O.groupParticipants=c.filter(H=>H.participantType===Fn).map(H=>H.participantId),O.teamParticipants=c.filter(H=>H.participantType===se).map(H=>H.participantId),O.pairParticipants=c.filter(H=>H.participantType===_t).map(H=>H.participantId);const D=jk({targetParticipantIds:e,policyAttributes:m,idCollections:O,participants:c}),M=Object.assign({},...e.map(H=>{const B=Object.keys(D).filter(R=>D[R].includes(H));return{[H]:B}})),w=$E({participantIds:e,positionAssignments:y});if(w.length>((N==null?void 0:N.length)||0))return{error:pg};let k;const _=w.length,F=ht(0,d).map(()=>VE({initialPositionAssignments:y,participantsWithGroupings:b,unseededParticipantIds:e,opponentsToPlaceCount:_,pairedPriority:!1,unseededByePositions:r,participantIdGroups:M,drawPositionChunks:U,drawPositionGroups:P,policyAttributes:m,idCollections:O,allGroups:D,drawSize:f}));if(k=F.reduce((H,B)=>!H||(B.conflicts||0)<(H.conflicts||0)?B:H,void 0),!k||k.conflicts){const H=ht(0,d).map(()=>VE({initialPositionAssignments:y,participantsWithGroupings:b,unseededParticipantIds:e,opponentsToPlaceCount:_,pairedPriority:!0,unseededByePositions:r,participantIdGroups:M,drawPositionChunks:U,drawPositionGroups:P,policyAttributes:m,idCollections:O,allGroups:D,drawSize:f,entries:p}));k=F.concat(...H).filter(R=>{var x;return!((x=R.errors)!=null&&x.length)}).reduce((R,x)=>!R||(x.conflicts||0)<(R.conflicts||0)?x:R,void 0)}if(!k)return{error:Jd};const L=(((j=ee({structure:T}))==null?void 0:j.positionAssignments)??[]).filter(H=>H.participantId).map(H=>H.participantId),W=k.positionAssignments.filter(H=>!L.includes(H.participantId));for(const H of W)if(H.bye){const B=Vn({tournamentRecord:s,drawDefinition:i,seedBlockInfo:o,structureId:u,matchUpsMap:a,event:h,...H});if(B.error)return G({result:B,stack:S})}else{const B=_r({automaticPlacement:!0,inContextDrawMatchUps:n,tournamentRecord:s,drawDefinition:i,seedBlockInfo:o,structureId:u,matchUpsMap:a,event:h,...H});if(B.error)return G({result:B,stack:S,context:{assignment:H}})}return{...$}}function Xk(t){const{structure:{structures:e}}=t,n=e.map(r=>r.positionAssignments.map(s=>s.drawPosition));return{drawPositionGroups:n,drawPositionChunks:[n]}}function t_({allDrawPositions:t,roundsToSeparate:e,matchUps:n}){const r=n.filter(p=>p.roundNumber===1).map(p=>p.drawPositions),s=r.flat().sort(Ve),i=Math.max(...s),o=t.filter(p=>p>i),c=s.length,u=ht(c===2?1:2,c).filter(p=>p===Fd(p)),f=u.slice(0,e||u.length).reverse().map(p=>Ge(s,p));return o.length&&console.log({fedDrawPositions:o}),{drawPositionGroups:r,drawPositionChunks:f}}function e_({provisionalPositioning:t,inContextDrawMatchUps:e,unseededByePositions:n,multipleStructures:r,tournamentRecord:s,drawDefinition:i,seedBlockInfo:o,participants:c,matchUpsMap:a,structureId:u,structure:l,drawSize:f,event:p}){var P,U;const h="positionUnseededParticipants";l||({structure:l}=Ot({drawDefinition:i,structureId:u})),u||({structureId:u}=l);const{positionAssignments:d}=ke({structure:l}),{seedAssignments:m}=Mr({provisionalPositioning:t,drawDefinition:i,structure:l}),g=m==null?void 0:m.map(O=>O.participantId).filter(Boolean),{stage:I,stageSequence:S}=l,T=I===Pt?(U=(P=Ke({element:l,name:Hr}))==null?void 0:P.extension)==null?void 0:U.value:void 0,y=mo({provisionalPositioning:t,drawDefinition:i,stageSequence:S,entryStatuses:ho,structureId:u,roundTarget:T,stage:I}),N=y.filter(O=>!(g!=null&&g.includes(O.participantId))).map(O=>O.participantId),A=d==null?void 0:d.filter(O=>!O.participantId&&!O.bye&&!O.qualifier).map(O=>O.drawPosition);if(!r&&N.length>((A==null?void 0:A.length)||0))return G({result:{error:pg},context:{unseededParticipantsCount:N.length,unfilledDrawPositionsCount:A==null?void 0:A.length},stack:h});const{appliedPolicies:C}=ge({tournamentRecord:s,drawDefinition:i,event:p});let{avoidance:v}=C??{};if(l.stage===Ie){const O=y.reduce((D,M)=>(D[M.groupingValue]||(D[M.groupingValue]=[]),D[M.groupingValue].push(M.participantId),D),{});Object.keys(O).length&&(v||(v={policyName:"Playoff Avoidance"}),v.policyAttributes||(v.policyAttributes=[]),v.policyAttributes.push({groupings:O}))}return v&&c?Zk({provisionalPositioning:t,unseededParticipantIds:N,inContextDrawMatchUps:e,unseededByePositions:n,tournamentRecord:s,drawDefinition:i,seedBlockInfo:o,participants:c,matchUpsMap:a,structureId:u,avoidance:v,drawSize:f,entries:y}):n_({provisionalPositioning:t,unseededParticipantIds:N,inContextDrawMatchUps:e,unfilledDrawPositions:A,multipleStructures:r,tournamentRecord:s,drawDefinition:i,seedBlockInfo:o,structureId:u,matchUpsMap:a,drawSize:f,event:p})}function n_({provisionalPositioning:t,unseededParticipantIds:e,inContextDrawMatchUps:n,unfilledDrawPositions:r,multipleStructures:s,tournamentRecord:i,drawDefinition:o,seedBlockInfo:c,matchUpsMap:a,structureId:u,drawSize:l,event:f}){const p=l>2?on(r):r.reverse();for(const h of e){const d=p.pop();if(!s||d){const m=_r({provisionalPositioning:t,inContextDrawMatchUps:n,tournamentRecord:i,drawDefinition:o,seedBlockInfo:c,participantId:h,drawPosition:d,matchUpsMap:a,structureId:u,event:f});if(m!=null&&m.error&&console.log("!!!!!",{result:m}),m!=null&&m.error)return G({result:m,stack:"randomUnseededDistribution"})}}return{...$}}function r_({provisionalPositioning:t,drawDefinition:e,structure:n}){const{positionAssignments:r}=ke({structure:n}),{seedAssignments:s}=Mr({provisionalPositioning:t,drawDefinition:e,structure:n}),i=Object.assign({},...(s||[]).filter(o=>o.participantId).map(o=>({[o.participantId]:o})));return r==null?void 0:r.map(o=>i[o.participantId]?{...o,seedNumber:i[o.participantId].seedNumber,seedValue:i[o.participantId].seedValue}:"").filter(Boolean)}function s_({orderedSortedFirstRoundSeededDrawPositions:t,validSeedBlocks:e,byesToPlace:n}){const r=[];e.forEach(i=>{if(n-r.length>i.drawPositions.length)r.push(...i.drawPositions);else{const c=kh(Ge(i.drawPositions,2));let a,u=t[r.length];for(;a=uu(c,u);)r.push(a),u=t[r.length]}});const s=r.map(i=>Array.isArray(i)?on(i):i).flat(1/0);return S1(n)&&e.map(o=>o.seedNumbers[0]).includes(n)?t:s}function uu(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();const n=t[0].flat(1/0).length,r=t[1].flat(1/0).length;if(n===r){const s=t[0].flat(1/0).includes(e)?t[0]:t[1];return uu(e?s:t[Math.round(Math.random())],e)}return n<r?uu(t[1],e):uu(t[0],e)}function kh(t){const e=Math.floor(t.length/2);return t.length>2?[kh(t.slice(0,e)),kh(t.slice(e))]:t}function i_({provisionalPositioning:t,relevantMatchUps:e,appliedPolicies:n,drawDefinition:r,seedBlockInfo:s,byesToPlace:i,structure:o}){var E;s||(s=Oo({provisionalPositioning:t,appliedPolicies:n,drawDefinition:r,structure:o}));const{isFeedIn:c,isLuckyStructure:a,isContainer:u}=s;let{validSeedBlocks:l}=s;(E=n==null?void 0:n.seeding)!=null&&E.containerByesIgnoreSeeding&&(l=[]);const f=r_({provisionalPositioning:t,drawDefinition:r,structure:o})??[],p=Vt([].concat(...e.map(y=>y.drawPositions))),h=f.filter(y=>p.includes(y.drawPosition)),d=(y,b)=>Pc(y.seedValue)-Pc(b.seedValue),g=l.reduce((y,b)=>{const N=h.filter(A=>{var C;return(C=b.drawPositions)==null?void 0:C.includes(A.drawPosition)}).sort(d);return y.concat(...N)},[]).map(y=>y.drawPosition),I=s_({orderedSortedFirstRoundSeededDrawPositions:g,validSeedBlocks:l,byesToPlace:i}),S=jE({orderedSeedDrawPositions:g,relevantMatchUps:e}).slice(0,f.length),T=jE({orderedSeedDrawPositions:I,relevantMatchUps:e}).slice(0,f.length);return{strictSeedOrderByePositions:S,blockSeedOrderByePositions:T,isLuckyStructure:a,positionedSeeds:f,isContainer:u,isFeedIn:c}}function jE({orderedSeedDrawPositions:t,relevantMatchUps:e}){const r=e.map(i=>i.drawPositions).map(i=>i==null?void 0:i.sort((o,c)=>o-c)).filter(i=>(i==null?void 0:i[0])+1===(i==null?void 0:i[1]));return t.map(i=>r.find(o=>o==null?void 0:o.includes(i))).filter(Boolean).map(i=>i==null?void 0:i.reduce((o,c)=>t.includes(c)?o:c,void 0)).filter(Boolean)}function o_({provisionalPositioning:t,seedOrderByePositions:e,isLuckyStructure:n,appliedPolicies:r,drawDefinition:s,seedLimit:i,structure:o,isFeedIn:c}){var M,w;const a=(M=r==null?void 0:r.seeding)==null?void 0:M.seedingProfile,u=o.stage===Pt,{positionAssignments:l}=ke({structure:o}),f=l==null?void 0:l.filter(k=>k.participantId).map(k=>k.drawPosition),p={isCollectionMatchUp:!1},{matchUps:h,roundMatchUps:d}=Qt({provisionalPositioning:t,matchUpFilters:p,structure:o}),m=(d==null?void 0:d[1])||[],g=o.structureType===mn?h:m,I=Vt([].concat(...g.map(k=>k.drawPositions))),S=Math.min(...I)-1,T=f==null?void 0:f.filter(k=>I.includes(k)),E=k=>{const _=Math.ceil(k.length/2),F=[k.slice(0,_),k.slice(_)],L=F.map(V=>[].concat(...V.flat(1/0)).length),W=Math.min(...L.flat(1/0)),j=Math.max(...L.flat(1/0)),H=L.indexOf(j),B=W!==j,R=on(F),[x,q]=!W||B?[F[H],F[1-H]]:[R[0],R[1]];return{greaterHalf:x,lesserHalf:q}},y=k=>{const{greaterHalf:_,lesserHalf:F}=E(k),{greaterHalf:L,lesserHalf:W}=E(_),H=on(L.flat(1/0)).pop(),B=L.flat().filter(x=>x!==H);return{newlyFilteredChunks:[...F,...W,B],drawPosition:H}},b=k=>!e.includes(k),N=k=>!(T!=null&&T.includes(k)),A=k=>{let F=Ge(k.sort(Ve),Math.ceil(k.length/4)).map(j=>j.filter(N));const L=[].concat(...F.flat(1/0)).length,W=[];for(let j=0;j<L;j++){const{newlyFilteredChunks:H,drawPosition:B}=y(F);W.push(B),F=H}return W},{validSeedBlocks:C}=Oo({provisionalPositioning:t,allPositions:!0,appliedPolicies:r,drawDefinition:s,structure:o}),v=C==null?void 0:C.map(k=>{var _;return(_=k.drawPositions)==null?void 0:_.map(F=>F+S)});let P;if(c){const k=I.length,{seedBlocks:_}=xl({cluster:Ka(a)===Lf,participantsCount:k});P=_.map(L=>L.map(W=>W+S)).map(A).filter(L=>L.length)}else u?P=v==null?void 0:v.map(k=>k.filter(N)):P=v==null?void 0:v.map(A).filter(k=>k.length);const U=g.map(k=>k.drawPositions).map(k=>k==null?void 0:k.sort((_,F)=>_-F)).filter(k=>(k==null?void 0:k[0])+1===(k==null?void 0:k[1])),O=k=>U.reduce((_,F)=>F.includes(k)?F.reduce((L,W)=>W!==k?W:L,void 0):_,void 0);let D=P.map(k=>k.map(O)).flat(1/0).filter(N).filter(b).filter(Boolean);if(u&&!o.structures){const k=i%4,_=D.slice(0,k),F=(w=d[o.roundLimit])==null?void 0:w.length,L=Ge(D.slice(k),F).map(on).flat();D=_.concat(L)}return{unseededByePositions:D}}function c_({provisionalPositioning:t,drawDefinition:e,matchUpsMap:n,structure:r,event:s}){var v;const i={isCollectionMatchUp:!1},{matchUps:o,roundMatchUps:c}=Qt({afterRecoveryTimes:!1,provisionalPositioning:t,drawDefinition:e,matchUpFilters:i,matchUpsMap:n,structure:r,event:s}),a=(c==null?void 0:c[1])||[],u=(r==null?void 0:r.structureType)===mn,l=u?o:a,f=u?((v=r==null?void 0:r.structures)==null?void 0:v.length)||0:o.length,{structureId:p,stage:h,stageSequence:d}=r,m=mo({entryStatuses:ps,provisionalPositioning:t,drawDefinition:e,stageSequence:d,structureId:p,stage:h}),{qualifiersCount:g}=Li({provisionalPositioning:t,drawDefinition:e,stageSequence:d,structureId:p,stage:h}),I=m.length+g,{positionAssignments:S,unassignedPositions:T}=ke({structure:r}),E=T==null?void 0:T.map(P=>P.drawPosition),y=S==null?void 0:S.filter(P=>P.bye).length,b=S==null?void 0:S.filter(P=>P.bye).map(P=>P.drawPosition),N=l.map(P=>P.drawPositions).filter(P=>P==null?void 0:P.reduce((U,O)=>!(b!=null&&b.includes(O))&&U,!0)).flat(1/0).filter(P=>E==null?void 0:E.includes(P)),A=S==null?void 0:S.length;let C=A?A-I:0;return C>f&&r.stageSequence===1&&r.stage!==Re&&(C=f),{placedByes:y,byesCount:C,relevantMatchUps:l,placedByePositions:b,roundMatchUps:c,positionsToAvoidDoubleBye:N}}function GE({provisionalPositioning:t,tournamentRecord:e,appliedPolicies:n,drawDefinition:r,seedBlockInfo:s,matchUpsMap:i,structureId:o,structure:c,seedLimit:a,seedsOnly:u,event:l}){var P;c||({structure:c}=Ot({drawDefinition:r,structureId:o})),o||(o=c==null?void 0:c.structureId);const f=!((c==null?void 0:c.structures)??(c==null?void 0:c.stage)===Pt),{byesCount:p,placedByes:h,relevantMatchUps:d}=c_({provisionalPositioning:t,drawDefinition:r,matchUpsMap:i,structure:c,event:l}),m=p-(h||0);if(m<=0)return{...$};const{strictSeedOrderByePositions:g,blockSeedOrderByePositions:I,isLuckyStructure:S,isFeedIn:T}=i_({provisionalPositioning:t,relevantMatchUps:d,appliedPolicies:n,drawDefinition:r,seedBlockInfo:s,byesToPlace:m,structure:c}),E=(c==null?void 0:c.structureType)&&[mn,tl].includes(c.structureType)&&((P=n==null?void 0:n.seeding)==null?void 0:P.containerByesIgnoreSeeding),y=f&&(I!=null&&I.length)?I:g;let{unseededByePositions:b}=o_({provisionalPositioning:t,seedOrderByePositions:y,isLuckyStructure:S,appliedPolicies:n,drawDefinition:r,seedLimit:a,structure:c,isFeedIn:T});const N=U=>U%2,A=(U,O)=>(U||[]).every(D=>N(D)?O!==D+1:O!==D-1);let C=[].concat(...y);if(!u)for(;b.length;){const U=b.find(O=>A(C,O));U?(C.push(U),b=b.filter(O=>O!==U)):(C.push(...b),b=[])}E&&(C=on(C),ze({ignoreSeededByes:E})&&console.log({byePositions:C}));const v=C.slice(0,m);for(const U of v){const O=Vn({provisionalPositioning:t,tournamentRecord:e,drawDefinition:r,drawPosition:U,matchUpsMap:i,structureId:o,structure:c,event:l});if(O!=null&&O.error)return O}return{...$,unseededByePositions:b,byeDrawPositions:v}}function a_(t){let{structure:e,structureId:n}=t;e||({structure:e}=Ot(t)),n||({structureId:n}=e);const r="positionQualifiers",s=[];if(e.stage===Re)return G({result:{error:xs},stack:r});const{unplacedRoundQualifierCounts:i,positionAssignments:o,roundDrawPositions:c}=u_(t);for(const a of Object.keys(i)){const u=o==null?void 0:o.filter(l=>c[a].includes(l.drawPosition)&&!l.participantId&&!l.qualifier&&!l.bye).map(l=>l.drawPosition);if(i[a]>(u||0))return G({result:{error:Sv},context:{unfilledDrawPositions:u},stack:r});ht(0,i[a]).forEach(()=>{const l=cn(u);s.push(l),o==null||o.forEach(f=>{f.drawPosition===l&&(f.qualifier=!0,delete f.participantId,delete f.bye)})})}return{...$,qualifierDrawPositions:s}}function u_({drawDefinition:t,structure:e,structureId:n}){e||({structure:e}=Ot({drawDefinition:t,structureId:n})),n||({structureId:n}=e);const{positionAssignments:r}=ke({structure:e}),{stage:s,stageSequence:i}=e,{qualifiersCount:o,roundQualifiersCounts:c}=Li({drawDefinition:t,stageSequence:i,structureId:n,stage:s}),u=(c?Object.keys(c):[]).map(I=>vt(I)),{matchUps:l}=Qt({structure:e}),{roundProfile:f}=Cn({matchUps:l}),p=Object.assign({},...u.filter(I=>f==null?void 0:f[I]).map(I=>{var S,T;return{[I]:((T=(S=f==null?void 0:f[I])==null?void 0:S.drawPositions)==null?void 0:T.filter(Boolean))??[]}})),h=r==null?void 0:r.filter(I=>I.qualifier).map(I=>I.drawPosition),d=o-((h==null?void 0:h.length)??0),m=h==null?void 0:h.length;return{unplacedRoundQualifierCounts:Object.assign({},...u.map(I=>{const S=r==null?void 0:r.filter(T=>{var E,y;return T.qualifier&&((y=(E=p[I])==null?void 0:E.drawPositions)==null?void 0:y.includes(T.drawPosition))}).map(T=>T.drawPosition);return{[I]:((c==null?void 0:c[I])??0)-((S==null?void 0:S.length)??0)}})),unplacedQualifiersCount:d,placedQualifiersCount:m,roundQualifiersCounts:c,positionAssignments:r,roundDrawPositions:p,qualifiersCount:o}}function WE({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:n,appliedPolicies:r,validSeedBlocks:s,drawDefinition:i,seedingProfile:o,seedBlockInfo:c,participants:a,groupsCount:u,structureId:l,matchUpsMap:f,structure:p,event:h}){const d=[],m=[];let g=0;if(p||({structure:p}=Ot({drawDefinition:i,structureId:l})),l||(l=p==null?void 0:p.structureId),r||(r=ge({drawDefinition:i}).appliedPolicies),!s){const I=p&&Oo({provisionalPositioning:t,appliedPolicies:r,drawDefinition:i,structure:p});I!=null&&I.error&&m.push(I.error),s=I==null?void 0:I.validSeedBlocks}return u=u??(s==null?void 0:s.length)??0,ht(0,u).forEach(()=>{if(g<(u||0)){const I=l_({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:i,seedingProfile:o,seedBlockInfo:c,participants:a,structureId:l,matchUpsMap:f,event:h});I!=null&&I.success&&(g++,d.push(...I.seedPositions??[])),I.error&&m.push({seedPositionError:I.error})}}),m.length?{error:m}:{...$,seedPositions:d}}function l_({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:r,seedingProfile:s,seedBlockInfo:i,participants:o,structureId:c,matchUpsMap:a,event:u}){const{unplacedSeedParticipantIds:l,unfilledPositions:f}=jl({provisionalPositioning:t,randomize:!0,drawDefinition:r,seedBlockInfo:i,structureId:c,event:u}),{appliedPolicies:p}=ge({drawDefinition:r}),{avoidance:h}=p??{};h&&o&&(l==null?void 0:l.length)>2;const d=[];for(const m of l){const g=f.pop();if(!g)return{error:Wc};d.push(g);const I=_r({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:r,seedingProfile:s,participantId:m,seedBlockInfo:i,drawPosition:g,matchUpsMap:a,structureId:c,event:u});if(!I.success)return I}return{...$,seedPositions:d}}function lu({applyPositioning:t=!0,provisionalPositioning:e,inContextDrawMatchUps:n,multipleStructures:r,placeByes:s=!0,tournamentRecord:i,appliedPolicies:o,placementGroup:c,drawDefinition:a,seedingProfile:u,participants:l,structureId:f,matchUpsMap:p,seedLimit:h,seedsOnly:d,drawType:m,drawSize:g,event:I}){var M;const S=[];t||(rC(),a=pt(a,!1,!0));const T=w=>(t||Zd(),G({result:w,stack:"automatedPositioning"})),E=w=>(t||Zd(),w),y=Ot({drawDefinition:a,structureId:f});if(y.error)return T(y);const b=y.structure;if(!b)return{error:Te};o||(o=(M=ge({drawDefinition:a,structure:b,event:I}))==null?void 0:M.appliedPolicies);const{qualifiersCount:N}=Li({stageSequence:b.stageSequence,provisionalPositioning:e,stage:b.stage,drawDefinition:a,structureId:f}),A=ho,C=mo({stageSequence:b.stageSequence,provisionalPositioning:e,stage:b.stage,placementGroup:c,drawDefinition:a,entryStatuses:A,structureId:f});if(!(C!=null&&C.length)&&!N)return E({...$});p=p??ln({drawDefinition:a}),n||({matchUps:n}=xe({inContext:!0,drawDefinition:a,matchUpsMap:p}));let v=[];const P=Oo({provisionalPositioning:e,appliedPolicies:o,drawDefinition:a,structure:b});if(P.error)return P;const{validSeedBlocks:U}=P;if(S.push({validSeedBlocks:U}),Ka(b.seedingProfile||u)===Rf){let w=s?GE({provisionalPositioning:e,tournamentRecord:i,appliedPolicies:o,drawDefinition:a,seedBlockInfo:P,matchUpsMap:p,structure:b,seedLimit:h,seedsOnly:d,event:I}):void 0;if(w!=null&&w.error)return T(w);v=w.unseededByePositions,S.push({action:"positionByes",unseededByePositions:v});const k=b.seedingProfile?{positioning:b.seedingProfile}:u;if(w=WE({seedingProfile:k,provisionalPositioning:e,inContextDrawMatchUps:n,tournamentRecord:i,appliedPolicies:o,validSeedBlocks:U,drawDefinition:a,seedBlockInfo:P,participants:l,matchUpsMap:p,structure:b,event:I}),w.error)return T(w);S.push({seedPositions:w.seedPositions,action:"positionSeedBlocks"})}else{if(m!==Ci){const k=b.seedingProfile?{positioning:b.seedingProfile}:u,_=WE({seedingProfile:k,provisionalPositioning:e,inContextDrawMatchUps:n,tournamentRecord:i,appliedPolicies:o,validSeedBlocks:U,drawDefinition:a,seedBlockInfo:P,participants:l,matchUpsMap:p,structure:b,event:I});if(_.error)return T(_);S.push({action:"positionSeedBlocks",seedPositions:_.seedPositions})}const w=s?GE({provisionalPositioning:e,tournamentRecord:i,appliedPolicies:o,drawDefinition:a,seedBlockInfo:P,matchUpsMap:p,structure:b,seedLimit:h,seedsOnly:d,event:I}):void 0;if(w!=null&&w.error)return console.log("positionByes",{result:w}),T(w);v=w==null?void 0:w.unseededByePositions,S.push({action:"positionByes",byeDrawPositions:w==null?void 0:w.byeDrawPositions,unseededByePositions:v})}const O={};if(!d){let w=a_({inContextDrawMatchUps:n,tournamentRecord:i,appliedPolicies:o,validSeedBlocks:U,drawDefinition:a,seedBlockInfo:P,participants:l,matchUpsMap:p,structure:b});if(w.error||(w.conflicts&&(O.qualifierConflicts=w.conflicts),S.push({action:"positionQualifiers",qualifierDrawPositions:w.qualifierDrawPositions}),w=e_({provisionalPositioning:e,inContextDrawMatchUps:n,unseededByePositions:v,multipleStructures:r,tournamentRecord:i,drawDefinition:a,seedBlockInfo:P,participants:l,matchUpsMap:p,structureId:f,structure:b,drawSize:g,event:I}),w.error))return T(w);w.conflicts&&(O.unseededConflicts=w.conflicts),S.push({action:"positionUnseededParticipants"})}const{positionAssignments:D}=ee({drawDefinition:a,structure:b});return Zt({drawDefinition:a,structureIds:[f]}),t||Zd(),{positionAssignments:D,conflicts:O,...$,positioningReport:S}}function d_({applyPositioning:t=!0,tournamentRecord:e,drawDefinition:n,seedingProfile:r,structureId:s,placeByes:i,seedsOnly:o,drawSize:c,event:a}){if(!a)return{error:wn};if(!n)return{error:rr};const u=e==null?void 0:e.participants;return lu({tournamentRecord:e,applyPositioning:t,drawDefinition:n,seedingProfile:r,participants:u,structureId:s,placeByes:i,seedsOnly:o,drawSize:c})}function pd(t){var d;const{applyPositioning:e=!0,provisionalPositioning:n,tournamentRecord:r,drawDefinition:s,seedingProfile:i,structureId:o,placeByes:c,seedsOnly:a,event:u}=t;if(!u)return{error:wn};if(!s)return{error:rr};if(!ki({drawDefinition:s,structureId:o})&&!n)return{error:Hm};const f=(d=jT({drawDefinition:s,structureId:o}).playoffStructures)==null?void 0:d.sort((m,g)=>nl(m)-nl(g)),p=[],h=r==null?void 0:r.participants;if(f)for(const m of f){const{structureId:g}=m,I=lu({structureId:g,provisionalPositioning:n,applyPositioning:e,drawDefinition:s,seedingProfile:i,participants:h,placeByes:c,seedsOnly:a});if(I.error)return I;I.positionAssignments&&p.push({positionAssignments:I.positionAssignments,structureId:g})}return{...$,structurePositionAssignments:p}}function f_(t){var N,A,C;const e="generateAndPopulateRRplayoffStructures";if(!t.playoffGroups)return G({result:{error:Tt},info:"playoffGroups required",stack:e});const{sourceStructureId:n,requireSequential:r,drawDefinition:s,playoffGroups:i,groupCount:o,groupSize:c,event:a}=t,{structures:u=[],links:l=[],finishingPositionTargets:f,positionRangeMap:p,error:h}=_E({requireSequential:r,sourceStructureId:n,playoffGroups:i,groupCount:o,groupSize:c,...t});if(h)return{error:h};const d=f==null?void 0:f.map(({finishingPositions:v})=>v).flat().map(v=>p[v].finishingPositions).flat();s.structures.push(...u),s.links.push(...l);const{matchUps:m,matchUpsMap:g}=xe({inContext:!0,drawDefinition:s}),I=u.map(({structureId:v})=>v),S=m==null?void 0:m.filter(({structureId:v})=>I.includes(v)).map(Qe),T=(N=g==null?void 0:g.drawMatchUps)==null?void 0:N.filter(({matchUpId:v})=>S==null?void 0:S.includes(v));if(T!=null&&T.length){const v=(A=hn({drawDefinition:s,event:a}))==null?void 0:A.tieFormat;v&&T.forEach(P=>{const{tieMatchUps:U}=Jl({isMock:t.isMock,tieFormat:v});Object.assign(P,{tieMatchUps:U,matchUpType:yr})})}const{positionAssignments:E}=ee({structureId:n,drawDefinition:s}),y={};E==null||E.forEach(v=>{var D;const P=xn({element:v,name:Ys}),U=(D=P==null?void 0:P.extension)==null?void 0:D.value,O=U==null?void 0:U.groupOrder;O&&(y[O]||(y[O]=[]),y[O].push(v.participantId))});const b=pd({provisionalPositioning:t.provisionalPositioning,structureId:n,applyPositioning:!0,event:t.event,drawDefinition:s});return b.error&&((C=b.error)==null?void 0:C.code)!==Hm.code?G({result:b,stack:e}):{structures:u,links:l,positionsPlayedOff:d,drawDefinition:s,...$}}function _h(t){var x,q;const e="genPlayoffStructure";if(!t.drawDefinition)return G({result:{error:lt},stack:e});const n=ou(t);if(n.error)return G({result:n,stack:e});const{structureId:r,addNameBaseToAttributeName:s,playoffStructureNameBase:i,playoffAttributes:o,playoffPositions:c,tournamentRecord:a,exitProfileLimit:u,roundProfiles:l,roundNumbers:f,idPrefix:p,isMock:h,event:d,uuids:m}=t,g=pt(t.drawDefinition,!1,!0),{structure:I}=Ot({structureId:r,drawDefinition:g});if(!I)return G({result:{error:Te}});if(I.structureType===mn||I.structures)return f_({sourceStructureId:I.structureId,...t,...n,drawDefinition:g});const{playoffRoundsRanges:S,playoffRounds:T}=n,{playoffPositionsReturned:E,error:y,playoffSourceRounds:b,playoffRoundsRanges:N}=Oh(t);if(y)return G({result:{error:y},stack:e});const A=(l==null?void 0:l.length)&&Object.assign({},...l),C=f||typeof l=="object"&&l.map(V=>Object.keys(V)).flat(),v=Array.isArray(C)&&C.map(V=>!isNaN(V)&&vt(V)).filter(Boolean);if(v){if(!Array.isArray(v))return G({result:{error:tt},context:{validRoundNumbers:v},stack:e});v.forEach(V=>{if(!(T!=null&&T.includes(V)))return G({result:{error:tt},context:{roundNumber:V},stack:e})})}c&&c.forEach(V=>{if(!(E!=null&&E.includes(V)))return G({result:{error:tt},context:{playoffPosition:V},stack:e})});const P=v||b,U=v?S:N,O=[],D=[];for(const V of P??[]){const Y=U==null?void 0:U.find(K=>K.roundNumber===V);if(!Y)return G({result:{error:tt},context:{roundNumber:V},stack:e});const z=Y.finishingPositions.length,J=Math.min(...Y.finishingPositions)-1,Q=2,X=V&&(A==null?void 0:A[V])&&Q+A[V]-1,Z=_c({exitProfile:`0-${V}`,addNameBaseToAttributeName:s,playoffStructureNameBase:i,finishingPositionOffset:J,playoffAttributes:o,exitProfileLimit:u,stage:Ie,roundOffset:0,drawDefinition:g,sequenceLimit:X,stageSequence:Q,drawSize:z,idPrefix:p,isMock:h,uuids:m});if(Z.error)return G({result:Z,stack:e});const{structures:nt,links:rt}=Z;if(nt!=null&&nt.length&&O.push(...nt),rt!=null&&rt.length&&D.push(...rt),Z.structureId&&V){const K={linkType:js.Loser,source:{structureId:r,roundNumber:V},target:{structureId:Z.structureId,feedProfile:ra.TopDown,roundNumber:1}};D.push(K)}}if(!O.length)return G({result:{error:tt},info:"No structures generated",stack:e});g.structures.push(...O),g.links.push(...D);const{matchUps:M,matchUpsMap:w}=xe({inContext:!0,drawDefinition:g}),k=O.map(({structureId:V})=>V),_=M==null?void 0:M.filter(({structureId:V})=>k.includes(V)).map(Qe),F=(x=w==null?void 0:w.drawMatchUps)==null?void 0:x.filter(({matchUpId:V})=>_==null?void 0:_.includes(V));if(F!=null&&F.length){const V=(q=hn({drawDefinition:g,event:d}))==null?void 0:q.tieFormat;V&&F.forEach(Y=>{const{tieMatchUps:z}=Jl({tieFormat:V,isMock:h});Object.assign(Y,{tieMatchUps:z,matchUpType:Jt})})}const L=M==null?void 0:M.filter(V=>Qo({matchUp:V})&&V.structureId===r);L==null||L.forEach(V=>{const{matchUpId:Y,score:z,winningSide:J}=V,Q=gn({inContextDrawMatchUps:M,drawDefinition:g,matchUpId:Y}),X=KT({inContextDrawMatchUps:M,tournamentRecord:a,drawDefinition:g,matchUpsMap:w,winningSide:J,targetData:Q,matchUpId:Y,structure:I,matchUp:V,score:z,event:d});X.error&&console.log(X.error)});const W=M==null?void 0:M.filter(V=>V.matchUpStatus===re&&V.structureId===r);W==null||W.forEach(V=>{const{matchUpId:Y}=V,z=gn({inContextDrawMatchUps:M,drawDefinition:g,matchUpId:Y}),{targetLinks:{loserTargetLink:J},targetMatchUps:{loserMatchUpDrawPositionIndex:Q,loserMatchUp:X}}=z,Z=J.target.structureId,nt=X.drawPositions[Q],rt=Vn({drawPosition:nt,structureId:Z,tournamentRecord:a,drawDefinition:g,event:d});rt.error&&console.log(rt.error)});const j=[],H=Ic({inContextDrawMatchUps:M,drawDefinition:g,matchUpsMap:w}).goesToMap,{structure:B}=Ot({drawDefinition:t.drawDefinition,structureId:r}),{matchUps:R}=Qt({structure:B});return R.forEach(V=>{var J,Q;const Y=H==null?void 0:H.loserMatchUpIds[V.matchUpId];if(Y&&V.loserMatchUpId!==Y){V.loserMatchUpId=Y;const X={tournamentId:a==null?void 0:a.tournamentId,eventId:(J=t.event)==null?void 0:J.eventId,context:e,matchUp:V};j.push(X)}const z=H==null?void 0:H.winnerMatchUpIds[V.matchUpId];if(z&&V.winnerMatchUpId!==z){V.winnerMatchUpId=z;const X={tournamentId:a==null?void 0:a.tournamentId,eventId:(Q=t.event)==null?void 0:Q.eventId,context:e,matchUp:V};j.push(X)}}),{structures:O,matchUpModifications:j,links:D,drawDefinition:g,...$}}function HE({drawDefinition:t,drawSize:e}){if(!t)return{error:lt};const n=au({stage:je,stageSequence:1,drawDefinition:t,drawSize:e});return n.error?n:(Zt({drawDefinition:t}),{...$})}function qE(t){var O,D,M,w,k;const{drawType:e=Ms,attachConsolation:n=!0,applyPositioning:r=!0,tournamentRecord:s,staggeredEntry:i,automated:o,placeByes:c,isMock:a,event:u}=t;let l=t==null?void 0:t.drawDefinition;if(!l)return{error:lt};const f=(O=dn({tournamentRecord:s,inContext:!0}))==null?void 0:O.tournamentParticipants,p=je,h=mo({stageSequence:1,drawDefinition:l,stage:p}),d=[Pr,va,Ds].includes(e)?h.length:Vo(h.length);if(!i&&e===ic&&h.length<2||e===Pr&&h.length<3)return{error:xd};let{tieFormat:m,matchUpType:g}=t;if(m){const _=vn({tieFormat:m});if(_.error)return _}m=Dr(m||((D=hn({drawDefinition:l}))==null?void 0:D.tieFormat)),g=g||l.matchUpType||_n.Singles;const{structures:I}=lr({stageSequence:1,drawDefinition:l,stage:p});if(I.length>1)return{error:Go};if((w=(M=I==null?void 0:I[0])==null?void 0:M.matchUps)!=null&&w.length)return{error:Go};const T=(k=I==null?void 0:I[0])==null?void 0:k.structureId;Object.assign(t,bt({structureName:t.structureName||je,structureId:T,matchUpType:g,tieFormat:m,drawSize:d,stage:p}));const E=FE(t);if(E.error)return E;const y=E.generators[e];if(!y)return{error:Ym};const b=y==null?void 0:y();if(b.error)return b;const{structures:N,links:A}=b,C=N.map(_=>Qt({structure:_}).matchUps).flat();m&&C.forEach(_=>{const{tieMatchUps:F}=Jl({tieFormat:m,isMock:a});Object.assign(_,{tieMatchUps:F,matchUpType:g})}),(!r||!n)&&(l=pt(l,!1,!0)),l.links||(l.links=[]),A.length&&l.links.push(...A);const v=N.map(({structureId:_})=>_);l.structures||(l.structures=[]);const P=l.structures.map(({structureId:_})=>_);l.structures=l.structures.map(_=>v.includes(_.structureId)?N.find(({structureId:F})=>F===_.structureId):_);const U=N.filter(({structureId:_})=>!P.includes(_));return U.length&&l.structures.push(...U),o&&lu({seedingProfile:t.seedingProfile,participants:f,applyPositioning:r,tournamentRecord:s,drawDefinition:l,structureId:T,placeByes:c,drawSize:d,event:u}),n&&Zt({drawDefinition:l}),{links:A,structures:N,...$}}function Fh(t){var M,w,k;if(!t.drawDefinition)return{error:lt};const e="generateQualifyingStructure";let n=t.drawSize||_d(t.participantsCount);const{qualifyingRoundNumber:r,qualifyingPositions:s,targetStructureId:i,structureOptions:o,appliedPolicies:c,drawDefinition:a,structureName:u,structureId:l,roundTarget:f,drawType:p,idPrefix:h,isMock:d,uuids:m}=t;let g,I,S,T,E=0,y,b=1;if(!oe(n))return G({result:{error:Eu},stack:e});const N=Ot({structureId:i,drawDefinition:a});if(N.error)return G({context:{targetStructureId:i},result:N,stack:e});if(!N.structure)return{error:Te};const A=N.structure,C=A.matchUpType;if(A.stage===Pt)if(A.stageSequence&&A.stageSequence>1)b=A.stageSequence-1;else{let _=i,F=2,L;for(;!L&&_;){A.stageSequence=F;const W=(w=(M=a.links.find(j=>j.source.structureId===_))==null?void 0:M.target)==null?void 0:w.structureId;if(_=W,F+=1,!W)L=!0;else{const j=Ot({structureId:W,drawDefinition:a});if(!j.structure)return{error:Te};if(j.error)return G({context:{targetTargetStructureId:W},result:j,stack:e});j.structure.stage!==Pt&&(L=!0)}}}const v=f?`${f}-`:"",P=`${b}`,U=u||(v||P?`${Pt} ${v}${P}`:Pt);if(p===Pr){const{maxRoundNumber:_,structures:F,groupCount:L}=za({structureName:u||U,structureId:l||(m==null?void 0:m.pop()),stage:Pt,structureOptions:o,appliedPolicies:c,stageSequence:b,matchUpType:C,roundTarget:f,idPrefix:h,drawSize:n,isMock:d,uuids:m});E=L,g=_,S=F[0],y=[1]}else({drawSize:n,matchUps:T,roundLimit:g,roundsCount:I}=rs({qualifyingRoundNumber:r,qualifyingPositions:s,matchUpType:C,idPrefix:h,drawSize:n,isMock:d,uuids:m})),g||(g=I),S=Ze({structureName:u||U,structureId:l||(m==null?void 0:m.pop()),qualifyingRoundNumber:g,stage:Pt,stageSequence:b,matchUpType:C,roundLimit:g,matchUps:T}),f&&ae({element:S,extension:{name:Hr,value:f}}),E=(k=T==null?void 0:T.filter(_=>_.roundNumber===g))==null?void 0:k.length;const O=p===Pr?js.Position:js.Winner,{link:D}=kc({sourceStructureId:S.structureId,sourceRoundNumber:g,targetStructureId:i,finishingPositions:y,linkType:O});return{qualifyingDrawPositionsCount:n,qualifiersCount:E,...$,structure:S,link:D}}function Lh({drawDefinition:t,tournamentId:e,structure:n,eventId:r,link:s}){var a;if(!t)return{error:lt};if(!n)return{error:Wi};if(!s)return{error:Km};const i=s.target.structureId,o=Ot({drawDefinition:t,structureId:i});if(o.error)return G({stack:"attachQualifyingStructure",context:{targetStructureId:i},result:o});t.structures||(t.structures=[]),t.links||(t.links=[]),t.structures.push(n),t.links.push(s);const c=((a=Qt({structure:n}))==null?void 0:a.matchUps)||[];return Oi({drawDefinition:t,tournamentId:e,matchUps:c,eventId:r}),Zt({drawDefinition:t,structureIds:[n.structureId]}),{...$}}function p_({matchUps:t,matchUpType:e}){var D;if(!t)return{error:$s};let n=[],r=[],s=0;e&&(t=t.filter(M=>M.matchUpType===e));const i=Vt(t.map(({matchUpType:M})=>M));if(i.length>1)if(i.includes(Jt))t=t.filter(M=>M.matchUpType===Jt);else if(i.includes(Oe))t=t.filter(M=>M.matchUpType===Oe);else if(i.includes(me))t=t.filter(M=>M.matchUpType===me);else return{};if(!cr(t)||!t.length)return{};const o=(M,w)=>vt(M)-vt(w),c=Vt(t.map(M=>M.drawPositions).flat().filter(Boolean)).sort(o),u=ht(1,Math.max(...c)+1).filter(M=>!c.includes(M)).sort(o),{roundMatchUps:l}=Cn({matchUps:t}),f=l==null?void 0:l[1],p=(l==null?void 0:l[2])||[],h=(f==null?void 0:f[0])||{},d=h.drawId,m=h.structureId,g=l?Object.keys(l).map(M=>vt(M)):[],I=Math.max(...g),S=((D=l==null?void 0:l[I])==null?void 0:D.length)||0,T=Math.ceil(Math.log(S)/Math.log(2)),E=ht(1,T+1).map(M=>{const w=Math.pow(2,M-1),k=I+T-M+1;return ht(1,w+1).map(_=>({drawId:d,structureId:m,matchUpId:Yt(),drawPositions:[],sides:[],roundNumber:k,roundPosition:_,finishingRound:M}))});T&&(t=t.concat(...E.flat()));const b=(f==null?void 0:f.map(M=>M.drawPositions)).flat(1/0),A=p.map(M=>M.drawPositions).flat(1/0).filter(M=>!b.includes(M)).sort(o),C=p.filter(M=>{var w;return(w=M.drawPositions)==null?void 0:w.reduce((k,_)=>A.includes(_)||k,void 0)}).map(M=>{var F,L;const w=(F=M.drawPositions)==null?void 0:F.reduce((W,j)=>A.includes(j)?j:W,void 0),k=(L=M.drawPositions)==null?void 0:L.indexOf(w),_=M.sides[k];return{[w]:_}});if(u!=null&&u.length&&(A==null?void 0:A.length)===(u==null?void 0:u.length)){const M=A.map((F,L)=>[F,u[L]].sort(o)),w=Object.assign({},...C),k=pt(f==null?void 0:f[0].finishingRound,!1,!0),_=pt(f==null?void 0:f[0].finishingPositionRange,!1,!0);r=M.map((F,L)=>{const W=Math.max(...F||[])/2;return{sides:F==null?void 0:F.map(H=>w[H]||{bye:!0,drawPosition:H}),drawId:d,structureId:m,roundPosition:W,drawPositions:F,roundNumber:1,finishingRound:k,matchUpId:Yt(),matchUpStatus:"BYE",sideNumber:L+1,finishingPositionRange:_}}),t=t.concat(...r)}const v=I+T;return ht(1,v+1).forEach(M=>{const w=[],k=O({matchUps:t,roundNumber:M}),F=O({matchUps:t,roundNumber:M-1}).map(h_).filter(Boolean),L=(k==null?void 0:k.length)===(n==null?void 0:n.length),W=(k==null?void 0:k.length)===(n==null?void 0:n.length)/2;M===1&&k.forEach(j=>{const H=j.drawPositions||[],{matchUpId:B,structureId:R}=j,x=[{...j.sides[0],drawPosition:H[0],matchUpId:B,structureId:R},{...j.sides[1],drawPosition:H[1],matchUpId:B,structureId:R}],q={...j,children:x};w.push(q)}),L?(s++,k.forEach((j,H)=>{const B=j.drawPositions||[],{matchUpId:R,structureId:x}=j,q=B.filter(Boolean).reduce((J,Q)=>b.includes(Q)?J:Q,void 0),Y=[{...j.sides.filter(Boolean).reduce((J,Q)=>Q.participantId&&!F.includes(Q.participantId)?Q:J,void 0),drawPosition:q,feedRoundNumber:s,sides:j.sides,matchUpId:R,structureId:x},n[H]],z={...j,children:Y};w.push(z)})):W&&k.forEach((j,H)=>{const B=[n[H*2],n[H*2+1]],R={...j,children:B};w.push(R)}),n=w}),{hierarchy:n[0],missingMatchUps:r,maxRound:I,finalRound:v,matchUps:t};function O({matchUps:M,roundNumber:w}){return M.filter(k=>k.roundNumber===w).sort((k,_)=>k.roundPosition-_.roundPosition)}}function h_(t){if(t.matchUpStatus===re)return t.sides.reduce((e,n)=>n.participantId||e,void 0);if(t.winningSide)return t.sides.reduce((e,n)=>n.sideNumber===t.winningSide?n.participantId:e,void 0)}function YE(t){var s,i;const e=Fh(t);if(e.error)return e;const{structure:n,link:r}=e;return!n||!r?{error:tt}:Lh({tournamentId:(s=t.tournamentRecord)==null?void 0:s.tournamentId,eventId:((i=t.event)==null?void 0:i.eventId)||t.eventId,drawDefinition:t.drawDefinition,structure:n,link:r})}function zE(t){return KE(t)}function KE({matchUpModifications:t,tournamentRecord:e,drawDefinition:n,structures:r,links:s=[],event:i}){var g,I,S;if(!n)return{error:lt};if(!Array.isArray(r)||!Array.isArray(s))return G({result:{error:tt}});const o="attachStructures",c=T=>{var E;return[T.source.structureId,T.source.roundNumber||((E=T.source.finishingPositions)==null?void 0:E.join("|")),T.target.roundNumber].join("|")},a=(g=n.links)==null?void 0:g.map(c);if(s.some(T=>{const E=c(T);return a==null?void 0:a.includes(E)}))return G({result:{error:Lv},info:"playoff structure exists",stack:o});s.length&&((I=n.links)==null||I.push(...s));const l=r.map(({structureId:T})=>T),f=(S=n.structures)==null?void 0:S.map(({structureId:T})=>T);n.structures=(n.structures||[]).map(T=>l.includes(T.structureId)?r.find(({structureId:E})=>E===T.structureId):T);const p=r==null?void 0:r.filter(({structureId:T})=>!(f!=null&&f.includes(T)));p.length&&n.structures.push(...p),Ic({drawDefinition:n});const h=r.map(T=>{var E;return((E=Qt({structure:T}))==null?void 0:E.matchUps)||[]}).flat();Oi({tournamentId:e==null?void 0:e.tournamentId,eventId:i==null?void 0:i.eventId,drawDefinition:n,matchUps:h});const d=r.map(({structureId:T})=>T);if(Zt({drawDefinition:n,structureIds:d}),t!=null&&t.length){const T={};t.forEach(y=>{var N;const b=(N=y.matchUp)==null?void 0:N.matchUpId;b&&(T[b]=y)});const E=y=>{y.matchUps.forEach(b=>{if(T[b.matchUpId]){const{tieMatchUps:N,...A}=T[b.matchUpId].matchUp;if(Object.assign(b,A),N!=null&&N.length){const C={};N.forEach(v=>T[v.matchUpId]=v),b.tieMatchUps.forEach(v=>Object.assign(v,C[v.matchUpId]))}T[b.matchUpId].matchUp=b,qt(T[b.matchUpId])}})};n.structures.forEach(y=>{if(f!=null&&f.includes(y.structureId))if(y.structures)for(const b of y.structures)E(b);else E(y)})}const m=p.map(kn("structureId"));return{...$,addedStructureIds:m}}function hd(t){var o,c;const{structures:e,links:n,matchUpModifications:r,error:s}=_h(t);if(s)return{error:s};const i=t.drawDefinition;return zE({tournamentId:(o=t.tournamentRecord)==null?void 0:o.tournamentId,eventId:((c=t.event)==null?void 0:c.eventId)||t.eventId,matchUpModifications:r,drawDefinition:i,structures:e,links:n})}function JE({tournamentRecord:t,matchUpIds:e=[],drawDefinition:n,structureId:r,event:s}){var f;if(typeof n!="object")return{error:lt};if(typeof r!="string")return{error:En};if(!Array.isArray(e))return{error:tt};const i=(f=n.structures)==null?void 0:f.find(p=>p.structureId===r);if(!i)return{error:Te};const o=i==null?void 0:i.matchUps,c=o==null?void 0:o.find(p=>!!p.roundPosition);if(i.structures||c||i.finishingPosition===fo)return{error:Go};const a=[],l=((o==null?void 0:o.filter(({matchUpId:p,score:h})=>(Be({score:h})&&a.push(p),e.includes(p))))??[]).map(kn("matchUpId"));if(l.length){i.matchUps=(i.matchUps??[]).filter(({matchUpId:d})=>!l.includes(d)),ei({tournamentId:t==null?void 0:t.tournamentId,matchUpIds:l,action:"deleteAdHocMatchUps",eventId:s==null?void 0:s.eventId,drawDefinition:n});const p=Vt(i.matchUps.map(kn("roundNumber"))),h=O1(p);if(h.length){h.reverse();for(const d of h)i.matchUps.forEach(m=>{m.roundNumber&&m.roundNumber>d&&(m.roundNumber-=1,qt({tournamentId:t==null?void 0:t.tournamentId,context:["adHoc round deletion"],eventId:s==null?void 0:s.eventId,drawDefinition:n,matchUp:m}))})}if(a.length){i.positionAssignments=Vt(i.matchUps.flatMap(g=>(g.sides??[]).map(I=>I.participantId)).filter(Boolean)).map(g=>({participantId:g}));const d=(i==null?void 0:i.matchUpFormat)??(n==null?void 0:n.matchUpFormat)??(s==null?void 0:s.matchUpFormat),m=Jf({positionAssignments:i.positionAssignments,matchUps:i.matchUps,tournamentRecord:t,drawDefinition:n,matchUpFormat:d,event:s});m.error&&console.log(m)}Zt({structureIds:[r],eventId:s==null?void 0:s.eventId,drawDefinition:n})}return{...$}}function QE({drawDefinition:t,orderMap:e}){return t?((typeof e!="object"||!Object.values(e).every(n=>oe(n)))&&G({result:{error:tt},context:{orderMap:e}}),t.structures||(t.structures=[]),t.structures.forEach(n=>{const r=e[n.structureId];r&&(n.structureOrder=r)}),t.structures.sort((n,r)=>jo(n.structureOrder)-jo(r.structureOrder)),{...$}):{error:lt}}function ZE({drawDefinition:t,structureDetails:e}){if(!or(e))return{error:tt};if(!t)return{error:lt};const n=Object.assign({},...e.map(s=>{if(!or(s))return;const{structureId:i,structureName:o}=s||{};if(!(!i||!o))return{[i]:o}}).filter(Boolean));if(!Object.values(n).length)return{error:Tt};let r=0;for(const s of t.structures||[]){const i=n[s.structureId];i&&(s.structureName=i,r+=1)}return{...$,modificationsApplied:r}}function XE({tournamentRecord:t,drawDefinition:e,structureId:n,event:r}){var m;if(typeof n!="string")return{error:tt};if(!e)return{error:lt};if(!n)return{error:En};const s=e.structures||[],i=[],o=s.find(({stage:g,stageSequence:I})=>g===It&&I===1),c=n===o.structureId,a=s.find(({stage:g})=>g===Pt);if(c&&!a)return{error:M1};const u=[],l=[n],f=g=>{var I;return(I=e.links)==null?void 0:I.map(S=>S.source.structureId===g&&S.target.structureId!==o.structureId&&S.target.structureId).filter(Boolean)},p=s.map(({structureId:g})=>g),h=Object.assign({},...p.map(g=>({[g]:f(g)})));for(;l.length;){const g=l.pop(),{structure:I}=Ot({structureId:g,drawDefinition:e}),{matchUps:S}=Qt({structure:I}),T=Xf(S);u.push(...T),e.links=((m=e.links)==null?void 0:m.filter(y=>y.source.structureId!==g&&y.target.structureId!==g))||[],(!c||g!==n)&&(e.structures=(e.structures??[]).filter(y=>(g&&g===y.structureId&&i.push(g),y.structureId!==g)));const E=g&&h[g].filter(y=>y!==o.structureId||n===o.structureId);E!=null&&E.length&&l.push(...E)}const{matchUps:d}=xe({drawDefinition:e});return d==null||d.forEach(g=>{g.winnerMatchUpId&&u.includes(g.winnerMatchUpId)&&delete g.winnerMatchUpId,g.loserMatchUpId&&u.includes(g.loserMatchUpId)&&delete g.loserMatchUpId}),c&&(o.positionAssignments=[],o.seedAssignments=[],o.matchUps=[],o.extensions&&(o.extensions=[])),ei({tournamentId:t==null?void 0:t.tournamentId,matchUpIds:u,action:"removeStructure",eventId:r==null?void 0:r.eventId,drawDefinition:e}),Zt({drawDefinition:e,eventId:r==null?void 0:r.eventId}),{...$,removedMatchUpIds:u,removedStructureIds:i}}function md({participantIdPairings:t,addToStructure:e=!0,tournamentRecord:n,matchUpIds:r=[],drawDefinition:s,matchUpsCount:i,roundNumber:o,structureId:c,newRound:a}){var m,g,I,S,T,E;if(typeof s!="object")return{error:lt};if(!c&&((m=s.structures)==null?void 0:m.length)===1&&(c=(I=(g=s.structures)==null?void 0:g[0])==null?void 0:I.structureId),typeof c!="string")return{error:En};const u=(S=s.structures)==null?void 0:S.find(y=>y.structureId===c);if(!u)return{error:Te};if(!i){const y=((T=s==null?void 0:s.entries)==null?void 0:T.filter(N=>{const A=N.entryStatus;return ps.includes(A)}))??[],b=Math.floor((y==null?void 0:y.length)/2)||1;if(a)i=b;else{const N=b-(((E=u.matchUps)==null?void 0:E.length)||0);N>0&&(i=N)}}if(t&&!Array.isArray(t)||i&&!oe(i)||r&&!Array.isArray(r)||!t&&!i)return{error:tt,info:"matchUpsCount or pairings error"};let l;const f=u.matchUps??[],p=f==null?void 0:f.reduce((y,b)=>(b.roundPosition&&(l=!0),((b==null?void 0:b.roundNumber)||0)>y?b.roundNumber:y),0);if(u.structures||l||u.finishingPosition===fo)return{error:Go};if(o&&o-1>(p||0))return{error:tt,info:"roundNumber error"};const h=o??(a&&(p??0)+1||p||1);t=t??ht(0,i).map(()=>({participantIds:[void 0,void 0]}));const d=t==null?void 0:t.map(y=>{const b=(y==null?void 0:y.participantIds)??[void 0,void 0];b.push(void 0,void 0);const A=b.slice(0,2).map((C,v)=>bt({sideNumber:v+1,participantId:C}));return{matchUpStatus:pe.ToBePlayed,matchUpId:r.pop()??Yt(),roundNumber:h,sides:A}});if(e){const y=Rh({tournamentRecord:n,drawDefinition:s,structureId:c,matchUps:d});if(y.error)return y}return{matchUpsCount:d.length,matchUps:d,...$}}function Rh({tournamentRecord:t,drawDefinition:e,structureId:n,matchUps:r}){var u,l,f,p,h,d;if(typeof e!="object")return{error:lt};if(!n&&((u=e.structures)==null?void 0:u.length)===1&&(n=(f=(l=e.structures)==null?void 0:l[0])==null?void 0:f.structureId),typeof n!="string")return{error:En};if(!cr(r))return{error:tt,info:sn("matchUps")};const s=(p=e.structures)==null?void 0:p.find(m=>m.structureId===n);if(!s)return{error:Te};const o=(s==null?void 0:s.matchUps).find(m=>!!m.roundPosition);if(s.structures||o||s.finishingPosition===fo)return{error:Go};const c=((d=(h=He({tournamentRecord:t,inContext:!1}))==null?void 0:h.matchUps)==null?void 0:d.map(Qe))??[],a=r.map(Qe);return tn(c,a)?{error:Fv,info:"One or more matchUpIds already present in tournamentRecord"}:(s.matchUps.push(...r),Oi({tournamentId:t==null?void 0:t.tournamentId,drawDefinition:e,matchUps:r}),Zt({drawDefinition:e,structureIds:[n]}),{...$})}const m_={generateAndPopulatePlayoffStructures:_h,attachPlayoffStructures:zE,addPlayoffStructures:hd,setStructureOrder:QE,renameStructures:ZE,generateQualifyingStructure:Fh,attachQualifyingStructure:Lh,addQualifyingStructure:YE,getAvailablePlayoffRounds:ou,getAvailablePlayoffProfiles:ou,getSourceRounds:Oh,getDrawStructures:lr,getPositionsPlayedOff:ld,getQualifiersCount:Li,removeStructure:XE,generateAdHocMatchUps:md,deleteAdHocMatchUps:JE,addAdHocMatchUps:Rh,addVoluntaryConsolationStage:HE,addVoluntaryConsolationStructure:Ch,generateVoluntaryConsolation:qE,buildDrawHierarchy:p_,generateDrawTypeAndModifyDrawDefinition:wh,generateDrawStructuresAndLinks:Mh};function Bh({participantsCount:t,participantCount:e}){if(t=t||e,!t)return{error:tt};const n=Vo(t);return n?{drawSize:n}:G({result:{error:tt},stack:"getEliminationDrawSize",context:{participantsCount:t}})}function xh(t){let{drawSizeProgression:e=!1,policyDefinitions:n,drawSize:r}=t||{};const{requireParticipantCount:s=!0,tournamentRecord:i,drawDefinition:o,event:c}=t||{},a="getSeedsCount",u=(t==null?void 0:t.participantsCount)||(t==null?void 0:t.participantCount);if(!n){const g=Zi({tournamentRecord:i,drawDefinition:o,event:c});if(g.error)return G({result:g,stack:a});n=g.policyDefinitions}const l=oe(u);if(u&&!l)return G({result:{error:tt},context:{participantsCount:u},stack:a});if(s&&!l)return G({result:{error:dv},stack:a});if(isNaN(r))if(u)({drawSize:r}=Bh({participantsCount:u}));else return G({result:{error:Eu},stack:a});if((s&&u||r)>r)return{error:lg};const p=n[tc];if(!p)return{error:Z1};const h=p.seedsCountThresholds;return h?(p.drawSizeProgression!==void 0&&(e=p.drawSizeProgression),{seedsCount:h.filter(g=>e?g.drawSize<=r:r===g.drawSize).reduce((g,I)=>u>=I.minimumParticipantCount?I.seedsCount:g,0)}):{error:R1}}function tb({requireParticipantCount:t=!0,enforcePolicyLimits:e=!0,drawSizeProgression:n,participantsCount:r,participantCount:s,appliedPolicies:i,drawDefinition:o,seedingProfile:c,structureId:a,seedsCount:u}){var S,T;r=r??s;const l=Ot({drawDefinition:o,structureId:a});if(l.error)return l;const f=l.structure;if(!f)return{error:Te};const{positionAssignments:p}=ke({structure:f}),h=(p==null?void 0:p.length)||0;if(u>h)return{error:L1};const d=(S=f.structures)==null?void 0:S.length,m=oe(c==null?void 0:c.groupSeedingThreshold)&&c.groupSeedingThreshold,g=(T=$l({roundRobinGroupsCount:d,drawSize:h}))==null?void 0:T.seedGroups,{seedsCount:I}=xh({policyDefinitions:i,requireParticipantCount:t,drawSizeProgression:n,participantsCount:r,drawSize:h});return I&&(i!=null&&i[tc])&&u>I&&e&&(u=I),f.seedLimit=u,f.seedAssignments=ht(1,u+1).map(E=>{const y=g==null?void 0:g.find(A=>A.includes(E)),b=y&&Math.min(...y),N=m&&E>=m?b:E;return{participantId:void 0,seedNumber:E,seedValue:N}}),Zt({drawDefinition:o,structureIds:[a]}),{...$,seedLimit:u}}function g_({positionAssignments:t,participantFactors:e}){if(!e||!t)return{error:Tt};let n=pt(e,!1,!0);const r=t.map(({drawPosition:d})=>d),s=t.filter(d=>!d.participantId&&!d.bye&&!d.qualifier).map(cU);let i,o=!0;for(;o;)({drawPositionResolutions:i,remainingPreferences:o,participantPreferences:n}=I_({participantPreferences:n,drawPositionResolutions:i}));const c=Object.keys(i).map(d=>vt(d));let a=s.filter(d=>!c.includes(d)),u=Object.keys(n);const f=ht(1,((d,m)=>Math.log(m)/Math.log(d))(2,(r==null?void 0:r.length)||0)+1).map(d=>Math.pow(2,d)),p={};for(const d of f){const m=Ge(r,d).filter(S=>tn(S,a)),g={};if(u.forEach(S=>{m.forEach(T=>{const E=T.join("|");tn(T,e[S].preferences)&&(g[E]||(g[E]=[]),g[E].push(S))})}),on(Object.keys(g)).forEach(S=>{const T=g[S].filter(E=>u.includes(E));for(;T.length;){const E=cn(T),y=S.split("|").map(b=>vt(b)).filter(b=>a.includes(vt(b)));if(y.length){const b=cn(y);a=a.filter(A=>A!==b),u=u.filter(A=>A!==E),i[b]=E;const N=S.split("|").length;p[N]||(p[N]=0),p[N]+=1}}}),!a.length)break}const h={chunkResolution:p};return u.length&&(u.forEach(d=>{const m=cn(a);m&&(i[m]=d)}),h.randomAssignment=u.length),{drawPositionResolutions:i,report:h}}function I_({participantPreferences:t,drawPositionResolutions:e={}}){const n=Object.keys(t).reduce((o,c)=>{const u=t[c].preferences[0];return u&&(o[u]||(o[u]=[]),o[u].push(c)),o},{}),r=Math.min(...Object.values(n).filter(o=>o.length).map(o=>o.length)),s=Object.keys(n).filter(o=>n[o].length&&r&&n[o].length===r);s.forEach(o=>{const c=n[o],a=cn(c);e[o]=a,delete t[a]});let i;return Object.values(t).forEach(o=>{o.preferences=o.preferences.filter(c=>{const a=!s.includes(c.toString());return a&&(i=!0),a})}),{drawPositionResolutions:e,remainingPreferences:i,participantPreferences:t}}function $h({drawPositions:t,structure:e}){if([Pt,It].includes(e.stage)&&e.stageSequence===1)return;const{positionAssignments:n}=ee({structure:e}),r=n==null?void 0:n.filter(({drawPosition:s})=>t==null?void 0:t.includes(s));r==null||r.forEach(s=>{ae({element:s,extension:{name:Vu,value:!0}})})}function Vh(t){const{participantIdAttributeName:e="participantId",isQualifierPosition:n,positionActionName:r,tournamentRecord:s,drawDefinition:i,participantId:o,drawPosition:c,structureId:a,event:u}=t,l="positionParticipantAction";if(!i)return{error:lt};let{inContextDrawMatchUps:f,matchUpsMap:p}=t;p||(p=ln({drawDefinition:i}),Object.assign(t,{matchUpsMap:p})),f||({matchUps:f}=xe({inContext:!0,drawDefinition:i,matchUpsMap:p}),Object.assign(t,{inContextDrawMatchUps:f}));const{positionAssignments:h}=ee({drawDefinition:i,structureId:a}),d=h==null?void 0:h.find(T=>T.drawPosition===c);if(d!=null&&d.participantId){const T=d.participantId,E=_r({inContextDrawMatchUps:f,tournamentRecord:s,drawDefinition:i,participantId:o,drawPosition:c,structureId:a,matchUpsMap:p,event:u});return E.success?S({removedParticipantId:T}):G({result:E,stack:l})}const m=Ac({inContextDrawMatchUps:f,tournamentRecord:s,drawDefinition:i,drawPosition:c,structureId:a,matchUpsMap:p,event:u});if(m.error)return G({result:m,stack:l});const g=m.participantId,I=_r({inContextDrawMatchUps:f,isQualifierPosition:n,tournamentRecord:s,drawDefinition:i,participantId:o,drawPosition:c,structureId:a,matchUpsMap:p,event:u});if(!I.success)return G({result:I,stack:l});return S({removedParticipantId:g});function S({removedParticipantId:T}){const{structure:E}=Ot({drawDefinition:i,structureId:a});$h({drawPositions:[c],structure:E});const y={[e]:o,name:r,drawPosition:c,structureId:a};return Ll({drawDefinition:i,positionAction:y}),G({result:{...$,context:{removedParticipantId:T},stack:l}})}}function eb({alternateParticipantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:s}){return Vh({positionActionName:"alternateDrawPositionAssignment",participantIdAttributeName:"alternateParticipantid",participantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:s})}function nb({structurePositionAssignments:t,provisionalPositioning:e,tournamentRecord:n,drawDefinition:r,event:s}){var c;if(!r)return{error:lt};if(!Array.isArray(t))return{error:tt};const i="setPositionAssignments";for(const a of t){const{structureId:u,positionAssignments:l}=a;if(!l)continue;const f=Ot({drawDefinition:r,structureId:u});if(f.error)return f;const p=f.structure;if(!p)return{error:Te};const h=(c=ee({structure:p}).positionAssignments)==null?void 0:c.map(({drawPosition:I})=>I),d=l==null?void 0:l.map(({drawPosition:I})=>I);if(qe(h,d).length!==(h==null?void 0:h.length))return G({result:{error:tt},info:"drawPositions do not match",stack:i});const m=ln({drawDefinition:r}),{matchUps:g}=xe({inContext:!0,drawDefinition:r,matchUpsMap:m});for(const I of l||[]){const{drawPosition:S,participantId:T,bye:E,qualifier:y}=I;if(E){const b=Vn({tournamentRecord:n,drawDefinition:r,drawPosition:S,matchUpsMap:m,structureId:u,structure:p,event:s});if(b!=null&&b.error)return b}else if(y)l.forEach(b=>{b.drawPosition===S&&(b.qualifier=!0,delete b.participantId,delete b.bye)});else if(T){const b=_r({provisionalPositioning:e,inContextDrawMatchUps:g,tournamentRecord:n,drawDefinition:r,participantId:T,drawPosition:S,matchUpsMap:m,structureId:u,event:s});if(b!=null&&b.error)return b}}ni({tournamentId:n==null?void 0:n.tournamentId,drawDefinition:r,structure:p,event:s})}const o=t.map(({structureId:a})=>a);return Zt({tournamentId:n==null?void 0:n.tournamentId,eventId:s==null?void 0:s.eventId,drawDefinition:r,structureIds:o}),{...$}}function gd({drawDefinition:t,stages:e}){return((t==null?void 0:t.structures)||[]).filter(r=>!(e!=null&&e.length)||e.includes(r.stage)).map(r=>{const{positionAssignments:s}=ee({structure:r});return s?s.map(kn("participantId")):[]}).flat()}function pr(t){const e=((t==null?void 0:t.entries)??[]).filter(Boolean).reduce((r,s)=>{const{entryStage:i,entryStatus:o}=s,c=`_${i||It}${o||""}`;return r[c]||(r[c]=[]),r[c].push(s),r},{}),n=r=>isNaN(r)?1/0:r;return Object.keys(e).map(r=>e[r].sort((s,i)=>n(s.entryPosition)-n(i.entryPosition)).map((s,i)=>{const o=i+1;return{...s,entryPosition:o}})).flat()}function Ri(t){return[po,Or].includes(t)}function jh({autoEntryPositions:t=!0,ignoreAssignment:e,tournamentRecord:n,drawDefinition:r,participantIds:s,entryStatus:i,entryStage:o,extension:c,eventSync:a,drawId:u,stage:l,event:f}){var v,P,U,O,D,M,w,k,_,F,L,W;if(!s||!Array.isArray(s))return{error:bs,method:"modifyEntriesStatus",participantIds:s};if(!r&&!f)return{error:Wt};if(i&&!GP.includes(i))return{error:zd};if(o&&!Ff.includes(o))return{error:xs};const p="modifyEntriesStatus",h=[];if(!i&&!c)return G({result:{error:Tt},info:"Missing entryStatus",stack:p});if(c&&!ur({extension:c,requiredAttributes:["name"]}))return G({result:{error:tt},info:"Invalid extension",context:{extension:c},stack:p});const d=[];(v=f==null?void 0:f.drawDefinitions)==null||v.forEach(j=>{const H=gd({stages:l&&[l],drawDefinition:j});d.push(...H)});const m=(n==null?void 0:n.participants)||[];if(!s.every(j=>{var B;const H=(B=Ps({tournamentParticipants:m,participantId:j}))==null?void 0:B.participantType;return!(H&&[jr.Pair,jr.Team].includes(H)&&Ri(i))&&!(i&&(f!=null&&f.eventType)&&H===xt&&[$n,ds].includes(f.eventType)&&[dr,...Gf].includes(i))}))return{error:zd};const I=f&&be({event:f}).flightProfile,S=(P=I==null?void 0:I.flights)==null?void 0:P.find(j=>j.drawId===u),T=j=>{const H=(j||[]).filter(x=>!l||!x.entryStage||l===x.entryStage).filter(({participantId:x})=>s.includes(x)),B=x=>i&&d.includes(x.participantId)&&!(Gf.includes(x.entryStatus)&&Gf.includes(i));return H.every(x=>B(x)&&!e?!1:(i&&(x.entryStatus=i,delete x.entryPosition),o&&(x.entryStage=o,delete x.entryPosition),c&&(c.value?ae({element:x,extension:c}):Ar({element:x,name:c.name})),!0))?{...$}:{error:Yo}},E=({flight:j,drawDefinition:H})=>{f&&(f.entries=pr({entries:f.entries||[]})),j&&(j.drawEntries=pr({entries:j.drawEntries})),H&&(H.entries=pr({entries:H.entries}))},y=j=>{const{flight:H,drawDefinition:B}=j,R="updateDrawEntries";if(H){const x=T(H.drawEntries);if(x.error)return G({result:x,stack:R})}if(B){const x=T(B.entries);if(x.error)return G({result:x,stack:R});h.includes(B.drawId)||h.push(B.drawId)}return{...$}},b=((U=f==null?void 0:f.entries)==null?void 0:U.find(({entryPosition:j})=>j))||((O=S==null?void 0:S.drawEntries)==null?void 0:O.find(({entryPosition:j})=>j))||((D=r==null?void 0:r.entries)==null?void 0:D.find(({entryPosition:j})=>j));if(t&&!b&&E({flight:S,drawDefinition:r}),S||r){const j=y({flight:S,drawDefinition:r});if(j.error)return G({result:j,stack:p})}const N=((M=f==null?void 0:f.drawDefinitions)==null?void 0:M.map(({drawId:j})=>j))||[],A=((w=I==null?void 0:I.flights)==null?void 0:w.filter(j=>!N.includes(j.drawId)))||[];for(const j of A){const H=j&&y({flight:j});if(H!=null&&H.error)return G({result:H,stack:p})}const C=((k=I==null?void 0:I.flights)==null?void 0:k.length)===1&&(((_=f==null?void 0:f.drawDefinitions)==null?void 0:_.length)||0)<=((F=I==null?void 0:I.flights)==null?void 0:F.length);if(!S&&!r&&i&&jP.includes(i))return{error:Iv};if(!S&&!r||i===ti||a&&C){const j=T(f==null?void 0:f.entries);if(j!=null&&j.error)return G({result:j,stack:p});let H;if(i===ti&&((L=I==null?void 0:I.flights)==null||L.every(B=>{const R=T(B.drawEntries);return R.error?(H=R.error,!1):(B.drawEntries=B.drawEntries.filter(({participantId:x})=>!s.includes(x)),!0)}),(W=f==null?void 0:f.drawDefinitions)==null||W.every(B=>{var x;const R=T(B.entries);return R.error?(H=R.error,!1):(B.entries=(x=B.entries)==null?void 0:x.filter(({participantId:q})=>!s.includes(q)),!0)})),H)return G({result:{error:H},stack:p})}t&&E({flight:S,drawDefinition:r});for(const j of(f==null?void 0:f.drawDefinitions)||[])h.length&&!h.includes(j.drawId)||Zt({tournamentId:n.tournamentId,eventId:f==null?void 0:f.eventId,drawDefinition:j});return{...$}}function rb({stage:t,drawDefinition:e}){return!!(t===je||_a({stage:t,drawDefinition:e})&&cu({stage:t,drawDefinition:e}))}function sb({entryStatus:t=Ur,drawDefinition:e,stageSequence:n,stage:r}){if(t===dr)return WP({stage:r,drawDefinition:e})?{positionsAvailable:1/0,...$}:{error:gv};const s=xk({drawDefinition:e,stageSequence:n,stage:r}),i=HP({drawDefinition:e,stage:r}),o=al({entryStatus:lc,drawDefinition:e,stage:r}),c=al({entryStatus:Ur,drawDefinition:e,stage:r}),a=o+c,u=a>=s,l=s-a;return r!==je&&u?{error:fg}:t===lc?o<i?{...$}:{error:fg}:{positionsAvailable:l,...$}}function Gh(t){const{entryStatus:e=un.DirectAcceptance,entryStageSequence:n,entryStage:r=It,ignoreStageSpace:s,drawDefinition:i,entryPosition:o,participant:c,roundTarget:a,extensions:u,extension:l,drawType:f}=t,p="addDrawEntry";if(!i)return{error:lt};if(!r)return{error:Qm};if(f!==Xn&&!rb({stage:r,drawDefinition:i}))return G({result:{error:xs},stack:p});const h=sb({stageSequence:n,stage:r,drawDefinition:i,entryStatus:e});if(!s&&!h.success)return{error:h.error};if(l&&!ur({extension:l}))return G({result:{error:tt},info:"Invalid extension",context:{extension:l},stack:p});const d=t.participantId||(c==null?void 0:c.participantId);if(!d)return G({result:{error:Ce},stack:p});const m=e===un.LuckyLoser&&Mo({participantId:d,drawDefinition:i,entryStatus:e}),g=r===je&&Mo({participantId:d,drawDefinition:i,entryStage:r}),I=e!==un.LuckyLoser&&r!==je&&Mo({drawDefinition:i,participantId:d});if(I||m||g)return G({context:{invalidEntry:I,invalidLuckyLoser:m,invalidVoluntaryConsolation:g},result:{error:Yd},stack:p});const S=bt({entryStageSequence:n,participantId:d,entryPosition:o,entryStatus:e,entryStage:r,extensions:u});return l&&ae({element:S,extension:l}),a&&ae({extension:{name:"roundEntry",value:a},element:S}),i.entries||(i.entries=[]),i.entries.push(S),Zt({drawDefinition:i}),{...$}}function ib(t){const e="addDrawEntries",{entryStatus:n=un.DirectAcceptance,stage:r=As.Main,autoEntryPositions:s=!0,ignoreStageSpace:i,drawDefinition:o,participantIds:c,stageSequence:a,roundTarget:u,extension:l}=t;if(!r)return{error:Qm};if(!o)return{error:lt};if(!Array.isArray(c))return{error:gr};if(!rb({stage:r,drawDefinition:o}))return{error:xs};if(l&&!ur({extension:l}))return G({result:{error:tt},info:"Invalid extension",context:{extension:l},stack:e});const f=sb({drawDefinition:o,stageSequence:a,entryStatus:n,stage:r});if(!i&&!f.success)return{error:f.error};const p=f.positionsAvailable??0;if(!i&&r!==je&&p<c.length)return{error:lg};const h=c.reduce((d,m)=>{const g=n===un.LuckyLoser&&Mo({participantId:m,drawDefinition:o,entryStatus:n}),I=r===je&&Mo({entryStage:r,drawDefinition:o,participantId:m});return n!==un.LuckyLoser&&r!==je&&Mo({drawDefinition:o,participantId:m})||g||I?d.concat(m):d},[]);return c.filter(d=>d&&!h.includes(d)).forEach(d=>{const m={entryStageSequence:a,entryStage:r,participantId:d,entryStatus:n};l&&ae({element:m,extension:l}),u&&ae({extension:{name:Hr,value:u},element:m}),o.entries||(o.entries=[]),o.entries.push(m)}),s&&(o.entries=pr({entries:o.entries})),Zt({drawDefinition:o}),h!=null&&h.length?{info:"some participantIds could not be added",participantIdsNotAdded:h,...$}:{...$}}function ob({autoEntryPositions:t=!0,entryStageSequence:e,ignoreStageSpace:n,drawDefinition:r,participantIds:s,entryStatus:i,roundTarget:o,entryStage:c,extension:a,drawId:u,event:l}){if(!(s!=null&&s.length))return{error:Ns};if(!l)return{error:wn};if(!u)return{error:Hn};const f=(l.entries||[]).map(fe);if(s.filter(m=>!f.includes(m)).length)return{error:q1};if(r){const m=ib({stageSequence:e,autoEntryPositions:t,stage:c,ignoreStageSpace:n,drawDefinition:r,participantIds:s,entryStatus:i,roundTarget:o,extension:a});if(m.error)return m}const{flightProfile:h}=be({event:l}),d=h==null?void 0:h.flights.find(m=>m.drawId===u);return d!=null&&d.drawEntries&&(s.forEach(m=>{const g=i===ka&&Wh({participantId:m,entryStatus:i,flight:d}),I=c===je&&Wh({participantId:m,entryStage:c,flight:d});!(i!==ka&&c!==je&&Wh({flight:d,participantId:m}))&&!g&&!I&&d.drawEntries.push({participantId:m,entryStatus:i,entryStage:c})}),t&&(d.drawEntries=pr({entries:d.drawEntries}))),{...$}}function Wh({participantId:t,entryStatus:e,entryStage:n,flight:r}){var i;const s=(i=r.drawEntries)==null?void 0:i.find(o=>o.participantId===t&&(!e||e===o.entryStatus)&&(!n||n===o.entryStage));return t&&s}function Id({autoEntryPositions:t=!0,tournamentParticipants:e,tournamentRecord:n,participantIds:r,event:s}){var l,f;const i="removeEventEntries";if(!(s!=null&&s.eventId))return{error:Wt};if(!Array.isArray(r))return G({result:{error:Ns},stack:i});if(r=r==null?void 0:r.filter(Boolean),!(r!=null&&r.length))return G({result:{error:Ns},stack:i});const{eventId:o}=s;if(e||(e=dn({participantFilters:{participantIds:r},tournamentRecord:n,withEvents:!0,withDraws:!0}).tournamentParticipants),e==null?void 0:e.every(p=>{const h=p.events.find(m=>m.eventId===o),d=(h==null?void 0:h.drawIds)||[];return p.draws.filter(m=>d.includes(m.drawId)&&m.positionAssignments).length}))return G({result:{error:Yo},stack:i});const a=[];s.entries=(s.entries||[]).filter(p=>{const h=!r.includes(p==null?void 0:p.participantId);return h||a.push(p.participantId),h}),t&&(s.entries=pr({entries:s.entries}));const{flightProfile:u}=be({event:s});return(l=u==null?void 0:u.flights)==null||l.forEach(p=>{p.drawEntries=(p.drawEntries||[]).filter(h=>!r.includes(h.participantId))}),(f=s.drawDefinitions)==null||f.forEach(p=>{p.entries=(p.entries||[]).filter(h=>!r.includes(h.participantId))}),{...$,participantIdsRemoved:a}}function Fs(t){var v;const{entryStatus:e=Ur,autoEntryPositions:n=!0,participantIds:r=[],entryStageSequence:s,ignoreEventGender:i,entryStage:o=It,tournamentRecord:c,ignoreStageSpace:a,drawDefinition:u,roundTarget:l,extensions:f,extension:p,drawId:h,event:d}=t,m="addEventEntries";if(!d)return{error:Wt};if(!(r!=null&&r.length))return G({result:{error:Ns},stack:m});if(!(d!=null&&d.eventId))return{error:wn};const g=[],I=[];if(f&&(!Array.isArray(f)||!f.every(ur))||p&&!ur({extension:p}))return G({result:{error:tt},context:bt({extension:p,extensions:f}),info:"Invalid extension(s)",stack:m});const S=!!c,T=[];let E;const y=((v=c==null?void 0:c.participants)==null?void 0:v.filter(P=>{var D,M,w;if(!r.includes(P.participantId))return!1;const U=d.eventType===Oe&&P.participantType===xt&&!Ri(e),O=d.eventType===me&&P.participantType===_t;return U&&(!d.gender||i||[hs,Io].includes(d.gender)||d.gender===((D=P.person)==null?void 0:D.sex))||O&&!Ri(e)||d.eventType===me&&P.participantType===xt&&Ri(e)?!0:U&&d.gender&&!i&&![hs,Io].includes(d.gender)&&d.gender!==((M=P.person)==null?void 0:M.sex)?(T.push({participantId:P.participantId,sex:(w=P.person)==null?void 0:w.sex}),!1):d.eventType===se&&(P.participantType===se||Ri(e)&&P.participantType===xt)}).map(P=>P.participantId))||[],b=r.filter(P=>!S||y.includes(P));d.entries||(d.entries=[]);const N=d.entries.map(P=>{var U;return P.participantId||((U=P.participant)==null?void 0:U.participantId)});if(b.forEach(P=>{if(!N.includes(P)){const U=bt({participantId:P,entryStatus:e,entryStage:o,extensions:f});p&&ae({element:U,extension:p}),l&&ae({extension:{name:Hr,value:l},element:U}),s&&(U.entryStageSequence=s),g.push(U.participantId),d.entries.push(U)}}),h&&!Ri(o)){const P=ob({participantIds:b,autoEntryPositions:n,entryStageSequence:s,ignoreStageSpace:a,drawDefinition:u,entryStatus:e,roundTarget:l,entryStage:o,extension:p,drawId:h,event:d});P.error&&(E=P.error)}if([me,se].includes(d.eventType)){const P=(d.entries||[]).map(w=>w.participantId),U=(d.entries||[]).filter(w=>Ri(w.entryStatus)).map(w=>w.participantId),D=((c==null?void 0:c.participants)||[]).filter(w=>P.includes(w.participantId)&&[_t,se].includes(w.participantType)).map(w=>w.individualParticipantIds).flat(1/0),M=U.filter(w=>D.includes(w));M.length&&(I.push(...M),Id({participantIds:M,autoEntryPositions:!1,tournamentRecord:c,event:d}))}if(b.length!==r.length)return G({result:{error:gr},context:{misMatchedGender:T,gender:d.gender},stack:m});n&&(d.entries=pr({entries:d.entries||[]}));const C=g.length-I.length;return G({result:{...$,addedEntriesCount:C},stack:m,info:E})}function cb({addIndividualParticipantsToEvents:t,individualParticipantIds:e,groupingParticipantId:n,tournamentRecord:r,suppressErrors:s}){const i="removeIndividualParticipantIds";if(!r)return G({result:{error:et},stack:i});if(!n||!e)return G({result:{error:Tt},stack:i});const c=(r.participants||[]).find(f=>f.participantId===n);if(!c)return G({result:{error:_e},stack:i});if(![se,Fn].includes(c.participantType))return G({result:{participantType:c.participantType,error:xr},stack:i});const a=ab({individualParticipantIds:e,groupingParticipant:c,tournamentRecord:r,suppressErrors:s}),{removed:u,error:l}=a;if(l)return G({result:a,stack:i});if(t)for(const f of r.events||[]){const p=(f.entries||[]).map(({participantId:h})=>h).filter(Boolean);if(p.includes(n)){const h=u==null?void 0:u.filter(d=>!p.includes(d));Fs({participantIds:h,entryStatus:Or,tournamentRecord:r,event:f})}}return u&&Ht({topic:nn,payload:{tournamentId:r.tournamentId,participants:[c]}}),{...$,...a}}function ab({individualParticipantIds:t=[],groupingParticipant:e,tournamentRecord:n,suppressErrors:r,mappedMatchUps:s,participants:i}){var h;const o=[];if(!e)return{removed:o};const c=[],a=[];i||({participants:i,mappedMatchUps:s}=Fi({withMatchUps:!0,tournamentRecord:n,withEvents:!0}));const u=i==null?void 0:i.find(({participantId:d})=>d===e.participantId),l=(h=u==null?void 0:u.events)==null?void 0:h.map(({eventId:d})=>d),f=(e.individualParticipantIds||[]).filter(d=>{var S;const m=t==null?void 0:t.includes(d),g=m&&((S=i==null?void 0:i.find(T=>T.participantId===d))==null?void 0:S.matchUps.filter(({eventId:T})=>l.includes(T)).map(({matchUpId:T})=>s==null?void 0:s[T]).filter(({winningSide:T,score:E})=>T||Be({score:E}))),I=m&&!(g!=null&&g.length);if(m&&!I&&a.push(d),I){o.push(d);for(const T of n.events||[])for(const E of T.drawDefinitions||[]){const{extension:y}=Ke({element:E,name:Wr});let b=y==null?void 0:y.value[e.participantId];y&&b&&(b=b.filter(A=>A.participantId!==d),ae({element:E,extension:y}),Ba({drawDefinition:E}));const N=tr({drawDefinition:E,inContext:!1}).matchUps||[];for(const A of N){const C=A.sides||[];for(const v of C){const P=v.lineUp||[];P.find(O=>O.participantId===d)&&(v.lineUp=P.filter(O=>O.participantId!==d),qt({tournamentId:n==null?void 0:n.tournamentId,drawDefinition:E,matchUp:A}))}}}}else c.push(d);return!I});e.individualParticipantIds=f;const p={groupingParticipantId:e.participantId,cannotRemove:a,notRemoved:c,removed:o};return a.length&&!r&&{...p,cannotRemove:a,error:qd}||p}function Hh({participantRole:t=Rg.Competitor,individualParticipantIds:e=[],groupingTypes:n=[jr.Team,jr.Group],tournamentRecord:r}){if(!r)return{error:et};const s=r.participants||[],{participants:i,mappedMatchUps:o}=Fi({withMatchUps:!0,tournamentRecord:r,withEvents:!0});let c=0;return s.filter(a=>(a.participantRole===t||!a.participantRole)&&a.participantType&&n.includes(a.participantType)).forEach(a=>{const{removed:u}=ab({groupingParticipant:a,individualParticipantIds:e,tournamentRecord:r,mappedMatchUps:o,participants:i});u&&c++}),c?$:{error:lv}}function Fc(t){var h,d,m;if(!(t!=null&&t.tournamentRecord))return{error:et};if(!((h=t==null?void 0:t.participantIds)!=null&&h.length))return{error:Ns};const{addIndividualParticipantsToEvents:e,tournamentRecord:n,participantIds:r}=t,s=((d=n.participants)==null?void 0:d.length)||0;if(!s)return{...$};const i=(m=n.events||[])==null?void 0:m.filter(({eventType:g})=>g===we).map(g=>{var I;return(I=g==null?void 0:g.drawDefinitions)==null?void 0:I.map(({drawId:S})=>S)}).flat(1/0),{tournamentParticipants:o}=dn({participantFilters:{participantIds:r},tournamentRecord:n,withDraws:!0}),c=()=>{const I=(He({matchUpFilters:{drawIds:i,matchUpTypes:[me]},tournamentRecord:n}).matchUps||[]).map(({sides:S})=>S==null?void 0:S.map(({participantId:T})=>T)).flat().filter(Boolean);return qe(I,r)},a=(i==null?void 0:i.length)&&c(),u=o.filter(g=>{var I;return(I=g.draws)==null?void 0:I.filter(S=>(!(i!=null&&i.length)||!(i!=null&&i.includes(S.drawId)))&&S.positionAssignments).length});if(a!=null&&a.length||u.length)return{error:Yo};const l={},f={};for(const g of n.events||[]){const I=Id({tournamentParticipants:o,tournamentRecord:n,participantIds:r,event:g});if(I.error)return I;l[g.eventId]=I.participantIdsRemoved}n.participants=n.participants.filter(g=>{const I=r.includes(g.participantId)||g.participantType===_t&&g.individualParticipantIds.some(S=>r.includes(S));if(!I&&g.participantType===we&&g.individualParticipantIds.some(S=>r.includes(S))&&(g.individualParticipantIds=g.individualParticipantIds.filter(S=>!r.includes(S))),I&&e&&[_t,se].includes(g.participantType))for(const S of g.individualParticipantIds||[])r.includes(S)||(f[g.participantId]||(f[g.participantId]=[]),f[g.participantId].push(S));return!I});const p=s-n.participants.length;if(Hh({individualParticipantIds:r,tournamentRecord:n}),e)for(const g of n.events||[]){const S=l[g.eventId].map(T=>f[T]||[]).flat();Fs({participantIds:S,entryStatus:Or,tournamentRecord:n,event:g})}return p&&Ht({payload:{participantIds:r,tournamentId:n.tournamentId},topic:NI}),p?{...$,participantsRemovedCount:p}:{error:qd}}function ub({selected:t=!0,drawDefinition:e,entryStatuses:n,drawId:r,event:s,stage:i}){var a;let o=s.entries??[];if(r){const{flightProfile:u}=be({event:s}),l=(a=u==null?void 0:u.flights)==null?void 0:a.find(f=>f.drawId===r);l?o=l.drawEntries:e.entries&&(o=e==null?void 0:e.entries)}const c=o.filter(u=>(!(n!=null&&n.length)||!u.entryStatus||n.includes(u.entryStatus))&&(!i||!u.entryStage||u.entryStage===i)&&(!t||u.entryStatus&&ps.includes(u.entryStatus)));return{entries:o,stageEntries:c}}function lb({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:n,participantId:r,drawId:s,stage:i,event:o}){var S;const c="destroyGroupEntry";if(!e)return{error:et};if(!r)return G({result:{error:Ce},stack:c});if(!o)return{error:Wt};if(!o.eventType||![_n.Doubles,_n.Team].includes(o.eventType))return G({result:{error:ui},stack:c});const a=e.participants||[],u=a.find(T=>T.participantId===r);if(!u)return G({result:{error:_e},stack:c});if(!u.participantType||![jr.Pair,jr.Team].includes(u.participantType)||u.participantType===we&&o.eventType!==we||u.participantType===_t&&o.eventType!==$n)return{error:xr};const f=(o.entries||[]).find(T=>T.participantId===r);if(!f)return{error:dg};const{stageEntries:p}=ub({selected:!1,drawDefinition:n,drawId:s,event:o,stage:i}),h=p.map(fe),d=a.filter(({participantId:T})=>h.includes(T)).map(({individualParticipantIds:T})=>T).flat().filter(Boolean),m=(S=u.individualParticipantIds)==null?void 0:S.filter(T=>Br(T,d).length===1);let g=Id({participantIds:[r],tournamentRecord:e,event:o});if(g.error||m!=null&&m.length&&(g=Fs({participantIds:m,entryStatus:Or,entryStage:f.entryStage,tournamentRecord:e,drawDefinition:n,drawId:s,event:o}),g.error))return g;let I;return t&&Fc({participantIds:[r],tournamentRecord:e}).success&&(I=!0),{...$,participantRemoved:I}}function db({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:n,participantId:r,drawId:s,event:i}){return lb({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:n,participantId:r,drawId:s,event:i})}function S_(t){if(!t.tournamentRecord)return{error:et};const{participantIds:e,...n}=t;let r=0;const s=[];for(const i of e){const o=lb({participantId:i,...n});o.success&&(r+=1),o.error&&s.push(o.error)}return r?{destroyedCount:r,...$}:{error:s}}function Sd(t){const{tournamentRecord:e,replaceWithBye:n,drawDefinition:r,destroyPair:s,entryStatus:i,matchUpsMap:o,drawId:c}=t,a="removeDrawPositionAssignment",u=Ac(t);if(u.error)return G({result:u,stack:a});const{participantId:l}=u,{drawPosition:f,event:p,structureId:h}=t;if([dr,ti].includes(i)&&l){const{tournamentRecord:g}=t,{participant:I}=zs({tournamentRecord:g,participantId:l}),{participantType:S,individualParticipantIds:T}=I||{};if(s&&S===_t){const E=db({tournamentRecord:g,drawDefinition:r,participantId:l,event:p});if(E.error)return G({result:E,stack:a});T&&jh({participantIds:T,tournamentRecord:g,drawDefinition:r,entryStatus:i,drawId:c,event:p})}else jh({participantIds:[l],tournamentRecord:g,drawDefinition:r,entryStatus:i,drawId:c,event:p})}if(n){const g=Vn({tournamentRecord:e,drawDefinition:r,drawPosition:f,structureId:h,matchUpsMap:o,event:p});if(g.error)return G({result:g,stack:a})}const{structure:d}=Ot({drawDefinition:r,structureId:h});return $h({structure:d,drawPositions:[f]}),Ll({drawDefinition:r,positionAction:{name:"removeDrawPositionAssignment",replaceWithBye:n,drawPosition:f,entryStatus:i,structureId:h}}),u}function fb({tournamentRecord:t,drawDefinition:e,drawPositions:n,structureId:r,event:s}){if(!e)return{error:lt};if(!r)return{error:En};if((n==null?void 0:n.length)!==2)return{error:tt,drawPositions:n};const i=ln({drawDefinition:e}),{matchUps:o}=xe({inContext:!0,drawDefinition:e,matchUpsMap:i}),{structure:c}=Ot({drawDefinition:e,structureId:r});if(!c)return{error:Te};let a;if(c.structureType===mn?a=E_({inContextDrawMatchUps:o,tournamentRecord:t,drawDefinition:e,drawPositions:n,matchUpsMap:i,structure:c,event:s}):a=T_({inContextDrawMatchUps:o,tournamentRecord:t,drawDefinition:e,drawPositions:n,matchUpsMap:i,structure:c,event:s}),a.error)return a;if($h({structure:c,drawPositions:n}),Ll({drawDefinition:e,positionAction:{name:"swapDrawPositionAssignments",drawPositions:n,structureId:r}}),ni({tournamentId:t==null?void 0:t.tournamentId,drawDefinition:e,structure:c,event:s}),s.eventType===ds){const l=Qt({matchUpFilters:{matchUpTypes:[yr]},inContext:!0,structure:c}).matchUps.filter(p=>{var h;return(h=p.drawPositions)==null?void 0:h.some(d=>n.includes(d))}),f=Qt({structure:c,matchUpFilters:{matchUpTypes:[yr]}}).matchUps;l.forEach(p=>{(p.sides||[]).forEach(h=>{var m;const d=h==null?void 0:h.drawPosition;if(n.includes(d)){const g=h.participantId,I=f.find(({matchUpId:T})=>T===p.matchUpId),S=(m=p==null?void 0:p.sides)==null?void 0:m.reduce((T,E,y)=>E.drawPosition===d?y:T,void 0);Fp({inContextTargetMatchUp:p,drawPositionSideIndex:S,teamParticipantId:g,tournamentRecord:t,drawDefinition:e,matchUp:I,event:s})}})})}return Zt({drawDefinition:e,structureIds:[r]}),{...$}}function T_({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,drawPositions:r,matchUpsMap:s,structure:i,event:o}){const c=i==null?void 0:i.positionAssignments.filter(l=>r==null?void 0:r.includes(l.drawPosition));if(!c)return{error:tt,structure:i,info:"Missing positionAssignments"};if(c.filter(({bye:l})=>l).length===2)return{...$};if(c.filter(({qualifier:l})=>l).length===2)return{...$};const a=c.some(({qualifier:l})=>l);return c.some(({bye:l})=>l)&&!a?pb({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,assignments:c,matchUpsMap:s,structure:i,event:o}):y_({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,assignments:c,matchUpsMap:s,structure:i,event:o})}function pb({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,assignments:r,matchUpsMap:s,structure:i,event:o}){const c=r.find(({bye:d})=>d),a=r.find(({participantId:d})=>d),u=c.drawPosition,{participantId:l,drawPosition:f}=a,{structureId:p}=i;let h=Sd({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,structureId:p,matchUpsMap:s});return h.error||(h=Sd({drawPosition:f,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,structureId:p,matchUpsMap:s}),h.error)||(Vn({drawPosition:f,tournamentRecord:e,drawDefinition:n,structureId:p,matchUpsMap:s,event:o}),h=_r({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,structureId:p,participantId:l,matchUpsMap:s,event:o}),h.error)?h:{...$}}function y_({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,assignments:r,matchUpsMap:s,structure:i,event:o}){const c=Object.assign({},...r.map((a,u)=>{const{drawPosition:l}=a,f={...r[1-u],drawPosition:l};return{[l]:f}}));return i.positionAssignments=i.positionAssignments.map(a=>c[a.drawPosition]||a),$p({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,matchUpsMap:s,assignments:r,structure:i,event:o}),{...$}}function E_({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,drawPositions:r,matchUpsMap:s,structure:i,event:o}){var l;const c=(l=i.structures)==null?void 0:l.reduce((f,p)=>{const h=p==null?void 0:p.positionAssignments.filter(d=>r==null?void 0:r.includes(d.drawPosition));return h&&f.push(...h),f},[]);if(c.filter(({bye:f})=>f).length===2)return{...$};if(c.filter(({qualifier:f})=>f).length===2)return{...$};$p({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,matchUpsMap:s,assignments:c,structure:i,event:o});const a=c.some(({qualifier:f})=>f);if(c.some(({bye:f})=>f)&&!a)pb({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,assignments:c,matchUpsMap:s,structure:i,event:o});else{const f=pt(c,!1,!0);c.forEach((p,h)=>{const d=f[1-h].participantId;p.qualifier=f[1-h].qualifier,p.participantId=d})}return{...$}}function hb({inheritance:t=!0,tournamentRecord:e,drawDefinition:n,matchUpId:r,event:s}){var a,u;if(!n)return{error:lt};const i=(a=ie({drawDefinition:n,matchUpId:r}))==null?void 0:a.matchUp;if(!(i!=null&&i.tieMatchUps))return{error:qn};const o=(u=ie({inContext:!0,drawDefinition:n,matchUpId:r,event:s}))==null?void 0:u.matchUp;let c=0;return((i==null?void 0:i.sides)||[]).forEach(l=>{l.lineUp&&delete l.lineUp}),((o==null?void 0:o.sides)||[]).forEach(l=>{if(c+=1,t===!1){const f=o==null?void 0:o.tieFormat,p=l.participantId;f&&p&&Uc({drawDefinition:n,participantId:p,lineUp:[],tieFormat:f})}qt({tournamentId:e==null?void 0:e.tournamentId,context:"resetMatchUpLineUps",eventId:s==null?void 0:s.eventId,drawDefinition:n,matchUp:i})}),{...$,modificationsCount:c}}function mb({tournamentRecord:t,drawDefinition:e,drawPosition:n,structureId:r,subOrder:s,event:i}){var m;if(!e)return{error:lt};if(!r)return{error:En};if(!n)return{error:Wc};const{structure:o}=Ot({drawDefinition:e,structureId:r});if(!o)return{error:Te};let c=o;o.structures&&o.structureType===mn&&(c=(m=o.structures)==null?void 0:m.find(g=>{var I;return(I=g.positionAssignments)==null?void 0:I.find(S=>S.drawPosition===n)}));const a=c==null?void 0:c.positionAssignments,u=a==null?void 0:a.find(g=>g.drawPosition===n);u&&ae({element:u,extension:{name:rc,value:s}});const p=((i==null?void 0:i.eventType)===Jt||e.matchUpType===Jt||(i==null?void 0:i.tieFormat)||(e==null?void 0:e.tieFormat)||(o==null?void 0:o.tieFormat))&&{matchUpTypes:[Jt]},{matchUps:h}=Qt({structure:c,afterRecoveryTimes:!1,inContext:!0,matchUpFilters:p,event:i}),d=(o==null?void 0:o.matchUpFormat)||e.matchUpFormat;return Jf({positionAssignments:a,tournamentRecord:t,drawDefinition:e,matchUpFormat:d,matchUps:h,event:i}),Zt({drawDefinition:e,structureIds:[r]}),{...$}}const b_={setSubOrder:mb,clearDrawPosition:Ac,assignDrawPosition:_r,setPositionAssignments:nb,automatedPositioning:lu,assignDrawPositionBye:Vn,swapDrawPositionAssignments:fb,alternateDrawPositionAssignment:eb,resolveDrawPositions:g_,resetMatchUpLineUps:hb,initializeStructureSeedAssignments:tb,getNextSeedBlock:jl};function gb({drawDefinition:t,event:e,matchUpId:n}){if(!t)return{error:lt};if(!n)return{error:$e};const{matchUp:r}=ie({drawDefinition:t,event:e,matchUpId:n});return r?Ar({element:r,name:$u}):{error:Ye}}function N_(t,e){return(t||"").localeCompare(e||"")}function A_({maxIterations:t=4e3,valueSortedPairings:e,pairingValues:n,valueObjects:r,deltaObjects:s}){const i=Object.assign({},...e.map(S=>({[S.pairing]:S.value}))),o=Object.keys(n);let c=[];const a=Ib({actorsCount:o.length,valueSortedPairings:e,pairingValueMap:i,deltaObjects:s,valueObjects:r}),u=[qh(a)];c.push(a);let l=a.value,f=a,p=0,h=0,d=o.length,m;do d-=1,m=o.length*n[o[0]].length;while(m>t&&d>5);const g=[];o.forEach(S=>{n[S].slice(0,d).forEach(E=>{h+=1;const y=_o(S,E.opponent);if(!g.includes(y)){const b=Ib({stipulated:[[S,E.opponent]],actorsCount:o.length,valueSortedPairings:e,pairingValueMap:i,deltaObjects:s,valueObjects:r});if(!u.includes(qh(b))){u.push(qh(b)),c.push(b);const{maxDelta:N,value:A}=b;N<f.maxDelta&&(f=b),(A<l||A===l&&Math.round(Math.random()))&&(l=A),g.push(y),p+=1}}}),c=c.filter(E=>Math.abs(E.value-l)<5)}),c.sort((S,T)=>S.maxDiff-T.maxDiff);const I=cn(c);return{candidatesCount:p,deltaCandidate:f,maxIterations:t,iterations:h,candidate:I}}function qh(t){return t.participantIdPairings.map(({participantIds:e})=>e.sort().join("|")).sort().join("/")}function Ib({valueSortedPairings:t,stipulated:e=[],pairingValueMap:n,deltaObjects:r,valueObjects:s,actorsCount:i}){const o=[].concat(...e),c=[];let a=0;e.filter(Boolean).forEach(p=>{const[h,d]=p,m=_o(h,d),g=n[m];c.push({participantIds:p,value:g}),a+=n[m]}),Ge(t,i).map(p=>on(p).map(h=>({...h,value:h.value+Math.random()*Math.round(Math.random())}))).flat().forEach(p=>{const h=p.pairing.split("|");if(!h.reduce((m,g)=>o.includes(g)||m,!1)){o.push(...h);const m=p.value;a+=m,c.push({participantIds:h,value:m})}}),c.sort((p,h)=>p.value-h.value);const l=c.reduce((p,h)=>{const[d,m]=h.participantIds,g=_o(d,m),I=r[g];return I>p?I:p},0),f=c.reduce((p,h)=>{const[d,m]=h.participantIds,g=_o(d,m),I=s[g];return I>p?I:p},0);return{value:a,participantIdPairings:c,maxDelta:l,maxDiff:f}}function _o(t,e){return[t,e].sort(N_).join("|")}function Sb({participantIds:t}){const e={},n=[];t.forEach(s=>{e[s]=t.filter(i=>i!==s),e[s].forEach(i=>{const o=_o(i,s);n.includes(o)||n.push(o)})});const r=Object.assign({},...n.map(s=>({[s]:0})));return{uniquePairings:n,possiblePairings:e,deltaObjects:r}}function v_({matchUps:t}){const e=[];for(const n of t){const r=n.sides.map(kn("participantId"));if(r.length===2){const[s,i]=r,o=_o(s,i);e.includes(o)||e.push(o)}}return{encounters:e}}function C_({possiblePairings:t,valueObjects:e}){const n={};for(const s of Object.keys(t)){const i=t[s].map(o=>r(s,o));n[s]=i.sort((o,c)=>o.value-c.value)}function r(s,i){const o=_o(s,i);return{opponent:i,value:e[o]}}return{pairingValues:n}}const P_=0;function U_({tournamentParticipants:t,adHocRatings:e,eventType:n,scaleName:r,pairing:s}){var o;const i=((o=wr[r])==null?void 0:o.defaultInitialization)??P_;return s.split("|").map(c=>{var a;if(n===$n){const u=(a=t==null?void 0:t.find(l=>l.participantId===c))==null?void 0:a.individualParticipantIds;return u?u==null?void 0:u.map(l=>e[l]||i):i*2}else return e[c]||i})}function O_({tournamentParticipants:t,adHocRatings:e={},possiblePairings:n,uniquePairings:r,maxIterations:s,deltaObjects:i,valueObjects:o,eventType:c,scaleName:a,salted:u}){r.forEach(I=>{const S=U_({tournamentParticipants:t,adHocRatings:e,scaleName:a,eventType:c,pairing:I}),T=typeof u=="number"&&u||.5,E=u&&(Math.round(Math.random())?T:T*-1)||0,y=Math.abs(S[0]-S[1])+E,b=Math.abs(S[0]-S[1]);i[I]=b,o[I]||(o[I]=0),o[I]+=y?Math.pow(y,2):0});const l=r.map(I=>({pairing:I,value:o[I]})).sort((I,S)=>I.value-S.value),{pairingValues:f}=C_({possiblePairings:n,valueObjects:o}),{candidate:p,candidatesCount:h,deltaCandidate:d,iterations:m}=A_({valueSortedPairings:l,maxIterations:s,pairingValues:f,deltaObjects:i,valueObjects:o}),{participantIdPairings:g}=p;return{participantIdPairings:g,candidatesCount:h,deltaCandidate:d,iterations:m,candidate:p}}const M_=100,D_=100,w_=4e3;function Tb({encounterValue:t=M_,sameTeamValue:e=D_,maxIterations:n=w_,generateMatchUps:r=!0,tournamentParticipants:s,tournamentRecord:i,participantIds:o,addToStructure:c,drawDefinition:a,adHocRatings:u,structureId:l,salted:f=.5,matchUpIds:p,eventType:h,structure:d,scaleName:m}){if(!a)return{error:lt};if(!d&&!l)return{error:Te};if(d||(d=Ot({drawDefinition:a,structureId:l}).structure),!or(d))return{error:Wi};if(!(o!=null&&o.length))return{error:Ns};const{encounters:g}=v_({matchUps:(d==null?void 0:d.matchUps)??[]}),I={};for(const D of g)I[D]||(I[D]=0),I[D]+=t;const S=s==null?void 0:s.filter(({participantType:D})=>D===se);if(S)for(const D of S){const M=D.individualParticipantIds??[],{uniquePairings:w}=Sb({participantIds:M});for(const k of w)I[k]||(I[k]=0),I[k]+=e}const{uniquePairings:T,possiblePairings:E,deltaObjects:y}=Sb({participantIds:o}),b={tournamentParticipants:s,possiblePairings:E,drawDefinition:a,participantIds:o,uniquePairings:T,maxIterations:n,adHocRatings:u,deltaObjects:y,valueObjects:I,eventType:h,scaleName:m,structure:d,salted:f},{candidatesCount:N,participantIdPairings:A,iterations:C,candidate:v}=O_(b);if(!N)return{error:Jd};let P;if(r){const D=md({structureId:d==null?void 0:d.structureId,participantIdPairings:A,tournamentRecord:i,addToStructure:c,newRound:!0,drawDefinition:a,matchUpIds:p});if(D.error)return D;P=D.matchUps}const{maxDelta:U,maxDiff:O}=v;return{...$,participantIdPairings:A,candidatesCount:N,iterations:C,matchUps:P,maxDelta:U,maxDiff:O}}function Yh({tournamentParticipants:t,restrictEntryStatus:e,adHocRatings:n={},generateMatchUps:r,tournamentRecord:s,addToStructure:i,participantIds:o,encounterValue:c,sameTeamValue:a,drawDefinition:u,scaleAccessor:l,maxIterations:f,structureId:p,matchUpIds:h,scaleName:d,eventType:m,salted:g,event:I}){var y,b,N,A;if(typeof u!="object"||u.drawType&&u.drawType!==Xn)return{error:Gi};if(!Array.isArray(u==null?void 0:u.entries)&&o&&!Array.isArray(o))return{error:tt,info:"Missing Entries"};m=m??(I==null?void 0:I.eventType);const S=(y=u==null?void 0:u.entries)==null?void 0:y.filter(C=>{const v=C.entryStatus;return!e||ps.includes(v)}).map(fe);if(o){const C=o.filter(v=>!(S!=null&&S.includes(v)));if(C!=null&&C.length)return{error:bs,invalidParticipantIds:C}}else o=S;if(!p){const C=(N=(b=u==null?void 0:u.structures)==null?void 0:b.filter(v=>v.stageSequence===1))==null?void 0:N.reduce((v,P)=>{const U=P.stage&&ao[P.stage];return Qr({drawDefinition:u,structure:P})&&U>(ao[v==null?void 0:v.stage]||1)?P:v},void 0);p=C==null?void 0:C.structureId}const T=(A=u==null?void 0:u.structures)==null?void 0:A.find(C=>C.structureId===p);if(!T)return{error:Te};if(!Qr({drawDefinition:u,structure:T}))return{error:Gi};t=t??s.participants??[];for(const C of o??[]){const v=t==null?void 0:t.find(U=>U.participantId===C);let P=yb({scaleName:`${d}.${pI}`,scaleAccessor:l,participant:v,eventType:m});!P&&d&&(P=yb({scaleAccessor:l,participant:v,scaleName:d,eventType:m})),P&&!n[C]&&(n[C]=P)}return Tb({tournamentParticipants:t,generateMatchUps:r,tournamentRecord:s,addToStructure:i,participantIds:o,encounterValue:c,sameTeamValue:a,drawDefinition:u,maxIterations:f,adHocRatings:n,matchUpIds:h,structure:T,eventType:m,salted:g})}function yb({scaleType:t=to,scaleAccessor:e,participant:n,scaleName:r,eventType:s}){var a;const i={eventType:s||_n.Singles,scaleType:t,scaleName:r},o=n&&Ts({scaleAttributes:i,participant:n}),c=(a=o==null?void 0:o.scaleItem)==null?void 0:a.scaleValue;return e&&or(c)?c[e]:c}function Eb({drawDefinition:t,matchUpId:e,outcome:n,matchUp:r}){var i,o;if(!r&&!t)return{error:lt};if(!n)return{error:Tt,info:"missing outcome"};if(!r&&!e)return{error:Rn};if(!r){const c=ie({drawDefinition:t,matchUpId:e});if(c.error)return c;r=c.matchUp}return typeof n!="object"||!((i=n.score)!=null&&i.scoreStringSide1)||!((o=n.score)!=null&&o.scoreStringSide2)?{error:tt}:ae({element:r,extension:{name:$u,value:n}})}function k_({matchUps:t}){if(!t)return{error:$s};const e=t.map(s=>s.drawPositions).flat();ze()&&t.forEach(s=>{var i;if(!Array.isArray(s.drawPositions)){console.log("drawPositions not an array",s);return}(i=s.drawPositions)==null||i.forEach(o=>{bb(o)||console.log("invalid drawPosition",s)})});const n=e==null?void 0:e.every(bb),r=t.find(s=>!Array.isArray(s.drawPositions));return n&&!r}function bb(t){return t!==null&&(t===void 0||!isNaN(t))}function Nb({drawDefinition:t,matchUpId:e,event:n}){if(!t)return{error:lt};const{matchUp:r}=ie({drawDefinition:t,matchUpId:e,event:n});return ae({extension:{name:ec,value:!0},element:r})}function Ab({tournamentRecord:t,drawDefinition:e,matchUpId:n,event:r}){if(!e)return{error:lt};const{matchUp:s}=ie({drawDefinition:e,matchUpId:n,event:r});return(s==null?void 0:s.matchUpType)!==yr?{error:qn}:Ja({enableAutoCalc:!0,tournamentRecord:t,drawDefinition:e,matchUpId:n,event:r})}function vb({drawDefinition:t,finishingOrder:e}){var S;if(!t)return{error:lt};const n="setOrderOfFinish";if(!Array.isArray(e))return G({result:{error:tt},info:sn("finishingOrder"),stack:n});const{completedMatchUps:r,matchUpsMap:s}=To({inContext:!0,drawDefinition:t}),i=(r==null?void 0:r.map(Qe))||[],o=e.map(Qe),{matchUpTypes:c,roundNumbers:a,structureIds:u,matchUpTieIds:l}=(r||[]).filter(({matchUpId:T})=>o.includes(T)).reduce((T,E)=>{const{matchUpTieId:y,matchUpType:b,roundNumber:N,structureId:A}=E;return T.matchUpTypes.includes(b)||T.matchUpTypes.push(b),T.roundNumbers.includes(N)||T.roundNumbers.push(N),T.structureIds.includes(A)||T.structureIds.push(A),T.matchUpTieIds.includes(y)||T.matchUpTieIds.push(y),T},{matchUpTypes:[],roundNumbers:[],structureIds:[],matchUpTieIds:[]});if(c.length>1||l.length>1||a.length>1||u.length>1)return G({result:{error:tt},info:"matchUpType, structureId and roundNumber must be equivalent",stack:n});let f,p;const h={},d=[],m=[];if(!e.every(({orderOfFinish:T,matchUpId:E})=>(d.push(E),T&&m.push(T),h[E]=T,f=i.includes(E),p=T===void 0||oe(T)&&Math.floor(T)>0,f&&p)))return G({result:{error:f?tt:Hc},info:!f&&"matchUps must be completed"||!p&&"orderOfFinish must be integer > 0 or undefined"||void 0,stack:n});const I=r==null?void 0:r.filter(T=>T.structureId===u[0]&&T.roundNumber===a[0]&&T.matchUpType===c[0]&&T.matchUpTieId===l[0]&&!d.includes(T.matchUpId));for(const T of I||[]){const{orderOfFinish:E}=T||{};if(E){if(!oe(E))return G({context:{orderOfFinish:E,matchUp:T},result:{error:tt},stack:n});m.push(E)}}if($m(m).length!==m.length||Math.max(...m)>m.length)return G({result:{error:tt},info:"Values not unique or greater than expected number of values",stack:n});if(u.length){const T=Va({matchUpFilters:{matchUpIds:o},structureId:u[0],drawDefinition:t,matchUpsMap:s});if(T.error)return G({result:T,stack:n});(S=T.completedMatchUps)==null||S.forEach(E=>E.orderOfFinish=h[E.matchUpId])}return{...$}}const __={resetScorecard:Xp,setMatchUpStatus:Ja,setMatchUpFormat:Gl,updateTieMatchUpScore:ms,isValidMatchUpFormat:nr,disableTieAutoCalc:Nb,enableTieAutoCalc:Ab,addFinishingRounds:ja,addMatchUpTimeItem:Ln,resetMatchUpTimeItems:IM,checkInParticipant:fh,checkOutParticipant:ph,getCheckedInParticipantIds:Fa,addMatchUpScheduleItems:kl,addMatchUpScheduledDate:Cp,addMatchUpScheduledTime:wi,addMatchUpStartTime:Up,addMatchUpEndTime:Op,addMatchUpStopTime:Mp,addMatchUpResumeTime:Dp,addMatchUpTimeModifiers:vp,addGoesTo:Ic,setOrderOfFinish:vb,setDelegatedOutcome:Eb,removeDelegatedOutcome:gb,drawMatic:Yh,addMatchUpOfficial:UT,findMatchUp:eU,getRoundMatchUps:Cn,validDrawPositions:k_,validateScore:rp};function Td({drawDefinition:t,policyDefinitions:e}){var i;if(!t)return{error:lt};if(!e||typeof e!="object")return{error:Au};t.extensions||(t.extensions=[]);const n=((i=ge({drawDefinition:t}))==null?void 0:i.appliedPolicies)??{},r=[Lu,HC],s=Object.keys(e).every(o=>!n[o]||r.includes(o)?(n[o]=e[o],!0):!1);if(s){const c=ae({element:t,extension:{name:zi,value:n}});if(c.error)return c}return Zt({drawDefinition:t}),s?{...$}:{error:ng}}const F_={attachPolicies:Td};function Cb({excludedMatchUpStatuses:t=[],includeEventParticipants:e,includeQualifyingStage:n,finishingRoundLimit:r,policyDefinitions:s,roundNumberLimit:i,tournamentRecord:o,drawDefinition:c,matchUpsLimit:a,requirePlay:u,requireLoss:l,allEntries:f,winsLimit:p,event:h}){var F,L,W,j,H;if(!c)return{error:lt};const d=[As.Main,As.PlayOff];n&&d.push(As.Qualifying);const m=h!=null&&h.eventType?{matchUpTypes:[h.eventType]}:void 0,g=c!=null&&c.matchUpType?{matchUpTypes:[c.matchUpType]}:void 0,I=e&&h?((F=si({contextFilters:{stages:d},matchUpFilters:m,tournamentRecord:o,inContext:!0,event:h}))==null?void 0:F.matchUps)||[]:((L=tr({contextFilters:{stages:d},matchUpFilters:g,tournamentRecord:o,inContext:!0,drawDefinition:c}))==null?void 0:L.matchUps)||[],T=mo({stage:je,drawDefinition:c}).map(({participantId:B})=>B),E={},y={},b={},N={};s||(s=Zi({policyTypes:[Xg],tournamentRecord:o,drawDefinition:c,event:h}).policyDefinitions);const A=s==null?void 0:s[Xg];t=t.length&&t||(A==null?void 0:A.excludedMatchUpStatuses)||[],e=e!==void 0?e:A==null?void 0:A.includeEventParticipants,f=f!==void 0?f:A==null?void 0:A.allEntries,r=r||(A==null?void 0:A.finishingRoundLimit),i=i||(A==null?void 0:A.roundNumberLimit),a=a||(A==null?void 0:A.matchUpsLimit),u===void 0&&(u=(A==null?void 0:A.requirePlay)!==void 0?A.requirePlay:!0),l===void 0&&(l=(A==null?void 0:A.requireLoss)!==void 0?A.requireLoss:!0),p=p||(A==null?void 0:A.winsLimit);for(const B of I){if(u&&B.winningSide&&![1,2].includes(B.winningSide)&&B.matchUpStatus!==Fe||B.finishingRound&&r&&B.finishingRound>=r||B.finishingRound&&i&&B.finishingRound<=i)continue;const R=(W=B.sides)==null?void 0:W.find(({sideNumber:q})=>B.winningSide&&q===3-B.winningSide),x=(j=B.sides)==null?void 0:j.find(({sideNumber:q})=>B.winningSide&&q===B.winningSide);if((H=B.sides)==null||H.forEach(q=>{var Y;const V=(Y=q==null?void 0:q.participant)==null?void 0:Y.participantId;V&&(b[V]=q.participant,B.matchUpStatus===Fe&&!u&&(y[V]=q.participant,E[V]||(E[V]=0),t.includes(B.matchUpStatus)||(E[V]+=1)))}),R!=null&&R.participant){const q=R.participant.participantId;y[q]=R.participant,E[q]||(E[q]=0),B.matchUpStatus&&!t.includes(B.matchUpStatus)&&(E[q]+=1)}if(x!=null&&x.participant){const q=x.participant.participantId;N[q]||(N[q]=0),N[q]+=1,E[q]||(E[q]=0),B.matchUpStatus&&!t.includes(B.matchUpStatus)&&(E[q]+=1)}}const C=(o==null?void 0:o.participants)&&!u&&!l&&f,v=C?((e&&h?h.entries:c.entries)||[]).filter(B=>![ti,Or].includes(B.entryStatus)).map(({participantId:B})=>B):[],P=Object.keys(y),U=C?((o==null?void 0:o.participants)||[]).filter(({participantId:B})=>v.includes(B)):l&&Object.values(y)||Object.values(b),O=B=>!l||P.includes(B),D=B=>!u||(E[B]||0)>=0,M=B=>!p||(N[B]||0)<=p,w=B=>!a||E[B]<=a,k=B=>!T.includes(B);return{eligibleParticipants:U.filter(B=>O(B.participantId)&&D(B.participantId)&&M(B.participantId)&&w(B.participantId)&&k(B.participantId)).map(B=>{var R;return{...B,individualParticipants:(R=B.individualParticipantIds)==null?void 0:R.map(x=>{var q;return(q=o==null?void 0:o.participants)==null?void 0:q.find(V=>V.participantId===x)})}}),losingParticipantIds:P,...$}}function L_({provisionalPositioning:t,drawDefinition:e,seedBlockInfo:n,structureId:r,event:s}){if(!e)return{error:lt,nextUnfilledDrawPositions:[]};if(!r)return{error:En,nextUnfilledDrawPositions:[]};const i=Ot({drawDefinition:e,structureId:r});if(i.error)return i;const{positionAssignments:o=[]}=ke({structure:i.structure}),{unfilledPositions:c}=jl({provisionalPositioning:t,randomize:!0,drawDefinition:e,seedBlockInfo:n,structureId:r,event:s}),a=o.filter(u=>!u.participantId&&!u.bye&&!u.qualifier).map(u=>u.drawPosition);return c!=null&&c.length?{nextUnfilledDrawPositions:c}:{nextUnfilledDrawPositions:a}}function Pb({tournamentParticipants:t,drawDefinition:e,event:n}){if(!e)return{error:lt};const r=xe({tournamentParticipants:t,inContext:!0,drawDefinition:e,event:n}),s=pt(r.matchUps,!1,!0),i=Vt(s.reduce((c,a)=>c.concat(...a.sides.map(u=>u.participantId).filter(Boolean)),[])),o=Object.assign({},...i.map(c=>{const a=s.filter(u=>u.sides.map(f=>f.participantId).filter(Boolean).includes(c));return{[c]:a}}));return{participantIds:i,participantIdMatchUps:o}}function Ub({byeAdvancements:t=!1,tournamentParticipants:e,drawDefinition:n}){if(!n)return{error:lt};const{participantIds:r,participantIdMatchUps:s}=Pb({tournamentParticipants:e,drawDefinition:n}),i=r.map(o=>{const a=s[o].filter(p=>[De,re].includes(p.matchUpStatus)||p.winningSide),u=a.map(p=>{const h=p.sides.find(g=>g.bye),d=p.sides.find(g=>g.participantId===o).sideNumber;return(p.winningSide||t&&h&&d)===d?p.finishingPositionRange.winner:p.finishingPositionRange.loser}),l=p=>Math.abs(p[0]-p[1]),f=u.reduce((p,h)=>p&&l(p)<l(h)?p:h,void 0);return{[o]:{relevantMatchUps:a,finishingPositionRanges:u,finishingPositionRange:f}}});return Object.assign({},...i)}function zh({targetRoundNumber:t,finishingPosition:e,drawDefinition:n,structureId:r,linkType:s}){const{links:i}=$a({drawDefinition:n,structureId:r})||{},c=((i==null?void 0:i.target)||[]).filter(({linkType:u})=>u===s).filter(({target:u})=>!t||t===u.roundNumber).map(u=>{const l=u.source.structureId,{structure:f}=Ot({structureId:l,drawDefinition:n});if(!(e&&(f==null?void 0:f.finishingPosition)!==e))return u}).filter(Boolean);return{sourceStructureIds:c.map(({source:u})=>u.structureId),relevantLinks:c}}function R_({tournamentParticipants:t,returnParticipants:e,drawPosition:n,participant:r,drawId:s,event:i}){var c;const o=((c=i==null?void 0:i.entries)==null?void 0:c.filter(({entryStatus:a})=>[Or,po].includes(a)).map(({participantId:a})=>a))||[];if(o.length){const a=r.individualParticipantIds,u=e?t.filter(({participantId:p})=>o.includes(p)):void 0,l=e?t.filter(({participantId:p})=>a.includes(p)):void 0;return{validModifyAssignedPairAction:bt({payload:{participantId:r.participantId,replacementIndividualParticipantId:void 0,existingIndividualParticipantId:void 0,drawPosition:n,drawId:s},method:rO,availableIndividualParticipantIds:o,availableIndividualParticipants:u,existingIndividualParticipantIds:a,existingIndividualParticipants:l,type:sT},!1,!1,!0)}}return{}}function B_({tournamentParticipants:t=[],sourceStructuresComplete:e,possiblyDisablingAction:n,isWinRatioFedStructure:r,activeDrawPositions:s,positionAssignments:i,drawDefinition:o,drawPosition:c,structureId:a,structure:u,drawId:l,event:f}){var I,S,T,E,y;if(s.includes(c)||r&&!e)return{};const{sourceStructureIds:p,targetStructureIds:h}=((I=o.links)==null?void 0:I.reduce((b,N)=>{var v,P;const A=(v=N.source)==null?void 0:v.structureId,C=(P=N.target)==null?void 0:P.structureId;return b.sourceStructureIds.includes(A)||b.sourceStructureIds.push(A),b.targetStructureIds.includes(C)||b.targetStructureIds.push(C),b},{sourceStructureIds:[],targetStructureIds:[]}))||{},d=[],m=((S=o.links)==null?void 0:S.filter(b=>{var N;return((N=b.target)==null?void 0:N.structureId)===u.structureId}))||[];for(const b of m){const N=(T=b==null?void 0:b.source)==null?void 0:T.structureId,{structure:A}=Ot({structureId:N,drawDefinition:o}),C=(A==null?void 0:A.finishingPosition)===fo&&((p==null?void 0:p.length)!==1||(h==null?void 0:h.length)!==1),v={};if(C){const{matchUps:D}=Qt({drawDefinition:o,structure:u,event:f}),{initialRoundNumber:M}=Uo({drawPosition:c,matchUps:D}),w=(E=o.links)==null?void 0:E.find(_=>{var F;return((F=_.target)==null?void 0:F.structureId)===(u==null?void 0:u.structureId)&&_.target.roundNumber===M}),k=(y=w==null?void 0:w.source)==null?void 0:y.roundNumber;v.roundNumbers=[k]}const{completedMatchUps:P}=Va({structureId:N,inContext:!0,matchUpFilters:v,drawDefinition:o}),U=i.map(D=>D.participantId).filter(Boolean),O=P==null?void 0:P.filter(({matchUpType:D,winningSide:M})=>M&&((f==null?void 0:f.eventType)!==we||D===we)).map(({winningSide:D,sides:M})=>D&&(M==null?void 0:M[1-(D-1)])).map(kn("participantId")).filter(D=>D&&!U.includes(D));O==null||O.forEach(D=>{d.includes(D)||d.push(D)})}const g=t==null?void 0:t.filter(b=>d==null?void 0:d.includes(b.participantId));return g==null||g.forEach(b=>{const N=(o.entries||[]).find(A=>A.participantId===b.participantId);b.entryPosition=N==null?void 0:N.entryPosition}),d!=null&&d.length?{validLuckyLosersAction:{type:aT,method:eO,availableLuckyLosers:g,availableLuckyLoserParticipantIds:d,willDisableLinks:n,payload:{drawId:l,structureId:a,drawPosition:c}}}:{}}function x_({positionSourceStructureIds:t,unassignedParticipantIds:e,possiblyDisablingAction:n,provisionalPositioning:r,tournamentParticipants:s,isWinRatioFedStructure:i,positionAssignments:o,returnParticipants:c,appliedPolicies:a,drawDefinition:u,isByePosition:l,drawPosition:f,structureId:p,event:h}){var E,y,b;const{drawId:d}=u,m=[];let g,I,S=[];const T=(y=(E=a==null?void 0:a[tc])==null?void 0:E.validSeedPositions)==null?void 0:y.ignore;if(T||({unplacedSeedParticipantIds:g,unplacedSeedAssignments:I,unfilledPositions:S}=jl({provisionalPositioning:r,randomize:!0,drawDefinition:u,structureId:p,event:h})),S!=null&&S.length||(S=o.filter(N=>!N.participantId&&!N.bye&&!N.qualifier).map(N=>N.drawPosition)),l||m.push({payload:{drawId:d,structureId:p,drawPosition:f,isPositionAction:!0},willDisableLinks:n,method:oO,type:pp}),i&&T){const N=o.map(U=>U.participantId).filter(Boolean),A={structureIds:t},{completedMatchUps:C}=To({inContext:!0,matchUpFilters:A,drawDefinition:u}),v=Vt((b=(C??[]).filter(({matchUpType:U})=>(h==null?void 0:h.eventType)!==we||U===we))==null?void 0:b.map(({sides:U})=>U==null?void 0:U.map(kn("participantId"))).flat().filter(U=>U&&!N.includes(U))),P=c?s==null?void 0:s.filter(U=>v==null?void 0:v.includes(U.participantId)).map(U=>pt(U,void 0,!0)):void 0;return P==null||P.forEach(U=>{const O=(u.entries??[]).find(D=>D.participantId===U.participantId);U.entryPosition=O==null?void 0:O.entryPosition}),P!=null&&P.length&&m.push(bt({payload:{drawId:d,structureId:p,drawPosition:f},willDisableLinks:n,method:nT,type:pc,availableParticipantIds:v,participantsAvailable:P})),{validAssignmentActions:m}}if(S.includes(f)||l){let N;if(I!=null&&I.length){const C=I.filter(v=>g==null?void 0:g.includes(v.participantId));C.sort($_),N=C.map(v=>v.participantId)}else N=e;const A=c?s==null?void 0:s.filter(C=>N.includes(C.participantId)).map(C=>pt(C,void 0,!0)):void 0;A!=null&&A.length&&m.push(bt({payload:{drawId:d,structureId:p,drawPosition:f},willDisableLinks:n,method:nT,type:pc,availableParticipantIds:N,participantsAvailable:A}))}return{validAssignmentActions:m}}function $_(t,e){return t.bye||Pc(t.seedValue)<Pc(e.seedValue)||t.seedValue&&!e.seedValue?-1:(t.seedNumber||0)-(e.seedNumber||0)}function V_({drawPositionInitialRounds:t,tournamentParticipants:e,positionAssignments:n,returnParticipants:r,appliedPolicies:s,drawDefinition:i,drawPosition:o,structureId:c,drawId:a}){var y,b,N;const u=[],l=[],f=[],p=[],h=n.map(A=>A.participantId).filter(Boolean),d=s==null?void 0:s[vs],m=!(d!=null&&d.disableRoundRestrictions)&&t[o],g=d==null?void 0:d.requireCompletedStructures,{sourceStructureIds:I,relevantLinks:S}=zh({targetRoundNumber:m,linkType:vi,drawDefinition:i,structureId:c})||{};I!=null&&I.length&&p.push(...I);const{sourceStructureIds:T,relevantLinks:E}=zh({targetRoundNumber:m,linkType:Ai,drawDefinition:i,structureId:c})||{};T!=null&&T.length&&p.push(...T);for(const A of S){const C=(y=i.structures)==null?void 0:y.find(P=>P.structureId===A.source.structureId);if((C==null?void 0:C.stage)!==Pt)continue;const v=ki({structureId:A.source.structureId,drawDefinition:i});if(!g||v){const P=C.qualifyingRoundNumber,{matchUps:U}=Qt({matchUpFilters:{roundNumbers:[P],hasWinningSide:!0},afterRecoveryTimes:!1,tournamentParticipants:e,inContext:!0,structure:C});for(const O of U){const D=O.sides.find(w=>(w==null?void 0:w.sideNumber)===O.winningSide),M=O.matchUpStatus===re&&((b=O.sides)==null?void 0:b.find(({participantId:w})=>w));if(D||M){const{participantId:w,participant:k}=D||M||{};w&&!h.includes(w)&&(k&&r&&u.push(k),l.push(w))}}}}for(const A of E){const C=(N=i.structures)==null?void 0:N.find(P=>P.structureId===A.source.structureId);if((C==null?void 0:C.stage)!==Pt)continue;const v=ki({structureId:A.source.structureId,drawDefinition:i});if(!g||v){const{positionAssignments:P}=ee({structure:C}),U=(P==null?void 0:P.map(O=>{var w;const D=O.participantId,M=(w=Ke({element:O,name:Ys}).extension)==null?void 0:w.value;return M?{participantId:D,groupOrder:M==null?void 0:M.groupOrder}:{}}).filter(({groupOrder:O,participantId:D})=>O===1&&!h.includes(D)).map(({participantId:O})=>O))??[];if(U&&l.push(...U),r){const O=e.filter(({participantId:D})=>U.includes(D));u.push(...O)}}}return l.length&&f.push(bt({payload:{qualifyingParticipantId:void 0,drawPosition:o,structureId:c,drawId:a},method:Z0,type:fp,qualifyingParticipantIds:l,qualifyingParticipants:r?u:void 0})),{validAssignmentActions:f,sourceStructureIds:p}}function j_({onlyAssignedPositions:t=!0,possiblyDisablingAction:e,tournamentParticipants:n,inactiveDrawPositions:r,activeDrawPositions:s,positionAssignments:i,returnParticipants:o,byeDrawPositions:c,drawDefinition:a,isByePosition:u,drawPosition:l,structureId:f,structure:p,drawId:h,event:d}){if(s.includes(l))return{};const m=v=>!t||v.participantId||v.qualifier||v.bye,g=r==null?void 0:r.filter(v=>v!==l&&!(u&&c.includes(v))),I=(i==null?void 0:i.filter(v=>m(v)&&(g==null?void 0:g.includes(v.drawPosition))))||[],S=I.map(({drawPosition:v})=>v),{matchUps:T}=Qt({afterRecoveryTimes:!1,inContext:!0,drawDefinition:a,structure:p,event:d}),E=T.filter(({drawPositions:v})=>tn(v,S)),y=Object.assign({},...E.map(v=>{var P;return(P=v.sides)==null?void 0:P.filter(({sourceDrawPositionRange:U})=>U).map(({drawPosition:U,sourceDrawPositionRange:O})=>({[U]:O}))}).flat()),b=I.map(v=>v.participantId).filter(Boolean),N=(n||[]).filter(v=>b.includes(v.participantId)),A=Object.assign({},...N.map(v=>({[v.participantId]:v}))),C=I.map(v=>{const P=A==null?void 0:A[v.participantId],U=y[v.drawPosition];return bt({...v,participant:o?pt(P,!1,!0):void 0,sourceDrawPositionRange:U})});return C.length?{validSwapAction:{payload:{drawId:h,structureId:f,drawPositions:[l]},willDisableLinks:e,method:nO,type:uT,availableAssignments:C}}:{}}function Ob(t){const{policyDefinitions:e,tournamentParticipants:n=[],returnParticipants:r=!0,provisionalPositioning:s,tournamentRecord:i,drawDefinition:o,drawPosition:c,event:a}=t;if(!a)return{error:Wt};if(!o)return{error:lt};if(!t.structureId)return{error:En};let u=Ot({structureId:t.structureId,drawDefinition:o});if(u.error)return u;const l=u.containingStructure||u.structure;if(!l)return{error:Te};const f=l.structureId;if(u=qa({drawDefinition:o,structureId:f}),c===void 0&&!u.isAdHoc)return{error:Wc};if(u.isAdHoc)return Sh(t);if(u.error)return u;const{drawPositionInitialRounds:p,inactiveDrawPositions:h,activeDrawPositions:d,byeDrawPositions:m}=u,g=ge({tournamentRecord:i,drawDefinition:o,structure:l,event:a}).appliedPolicies??{};Object.assign(g,e||{});const{actionsPolicy:I,enabledStructures:S,actionsDisabled:T}=sE({actionType:id,appliedPolicies:g,drawDefinition:o,structure:l}),E=(I==null?void 0:I.activePositionOverrides)||[],{sourceStructureIds:y}=zh({finishingPosition:uc,targetRoundNumber:1,linkType:Ai,drawDefinition:o,structureId:f})||{};let b;y!=null&&y.length&&(b=y.reduce((q,V)=>ki({structureId:V,drawDefinition:o})&&q,!0));const N=y.length,A=y.length&&!b,{policyActions:C}=oE({enabledStructures:S,drawDefinition:o,structure:l}),v=![Pt,It].includes(l.stage)||l.stageSequence!==1,{drawId:P}=o,U=[],{assignedPositions:O,positionAssignments:D}=ke({structure:l}),M=O==null?void 0:O.find(q=>q.drawPosition===c),w=D==null?void 0:D.map(q=>q.drawPosition);if(!(w!=null&&w.includes(c)))return{error:Wo};const{stage:k,stageSequence:_}=l,F=[k];k===Re&&F.push(It),k===It&&F.push(Re);const L=mo({entryStatuses:ho,provisionalPositioning:s,drawDefinition:o,stageSequence:_,structureId:f,stages:F}),W=gd({drawDefinition:o,stages:F}),j=L.filter(q=>!W.includes(q.participantId)).map(q=>q.participantId),H=m.includes(c),B=d.includes(c);if(T)return{info:"Actions Disabled for structure",isByePosition:H,isActiveDrawPosition:B,isDrawPosition:!0,hasPositionAssigned:!!M,validActions:[]};if(Pn({policyActions:C,action:pc})&&!B&&D&&!A&&(!M||H)){const{validAssignmentActions:q}=x_({positionSourceStructureIds:y,unassignedParticipantIds:j,possiblyDisablingAction:v,isWinRatioFedStructure:N,tournamentParticipants:n,positionAssignments:D,returnParticipants:r,appliedPolicies:g,drawDefinition:o,isByePosition:H,drawPosition:c,structureId:f,event:a});q==null||q.forEach(V=>U.push(V))}if(Pn({policyActions:C,action:fp})){const{validAssignmentActions:q}=V_({drawPositionInitialRounds:p,tournamentParticipants:n,positionAssignments:D,returnParticipants:r,appliedPolicies:g,drawDefinition:o,drawPosition:c,structureId:f,drawId:P});q==null||q.forEach(V=>U.push(V))}const{participantId:R}=M||{},x=R&&n.find(q=>q.participantId===R);if(M){Pn({policyActions:C,action:cT})&&!B&&(U.push({type:cT,method:eT,payload:{drawId:P,structureId:f,drawPosition:c},willDisableLinks:v}),H||U.push({type:oT,method:X0,payload:{drawId:P,structureId:f,drawPosition:c},willDisableLinks:v}),Pn({policyActions:C,action:pp})&&!H&&U.push({type:pp,method:eT,payload:{drawId:P,structureId:f,drawPosition:c,replaceWithBye:!0},willDisableLinks:v}));const q=l.stage===Pt||l.stage===It&&l.stageSequence===1;if(!H&&iE({activePositionOverrides:E,activeDrawPositions:d,action:hc})&&Pn({policyActions:C,action:hc})&&Vl({drawDefinition:o,structureId:f,drawPosition:c})&&q){const{seedAssignments:V}=Mr({drawDefinition:o,structure:l}),{seedNumber:Y,seedValue:z}=(V==null?void 0:V.find(J=>J.participantId===R))||{};U.push({type:hc,method:cO,participant:x,seedNumber:Y,payload:{drawId:P,structureId:f,participantId:R,seedValue:z}})}if(!H&&iE({activePositionOverrides:E,activeDrawPositions:d,action:Il})&&Pn({policyActions:C,action:Il})&&Vl({drawDefinition:o,structureId:f,drawPosition:c})&&q){const{seedAssignments:V}=Mr({drawDefinition:o,structure:l}),{seedNumber:Y}=(V==null?void 0:V.find(z=>z.participantId===R))||{};U.push({type:Il,method:iO,participant:x,seedNumber:Y,payload:{drawId:P,structureId:f,participantId:R}})}if(!H&&R){if(Pn({policyActions:C,action:mc})){const V={type:mc,method:rT,participant:x,payload:{drawId:P,penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0}};U.push(V)}if(Pn({policyActions:C,action:Sl})){const V={type:Sl,method:sO,participant:x,payload:{participantId:R,otherName:void 0}};U.push(V)}}if(Pn({policyActions:C,action:uT})){const{validSwapAction:V}=j_({possiblyDisablingAction:v,tournamentParticipants:n,inactiveDrawPositions:h,activeDrawPositions:d,positionAssignments:D,returnParticipants:r,byeDrawPositions:m,drawDefinition:o,isByePosition:H,drawPosition:c,structureId:f,structure:l,drawId:P});V&&U.push(V)}}if(Pn({policyActions:C,action:iT})&&!A){const{validAlternatesAction:q}=Gw({possiblyDisablingAction:v,tournamentParticipants:n,positionAssignments:D,activeDrawPositions:d,returnParticipants:r,appliedPolicies:g,drawDefinition:o,drawPosition:c,validActions:U,structureId:f,structure:l,drawId:P,event:a});q&&U.push(q)}if(Pn({policyActions:C,action:aT})&&!A&&D){const{validLuckyLosersAction:q}=B_({sourceStructuresComplete:b,possiblyDisablingAction:v,isWinRatioFedStructure:N,tournamentParticipants:n,activeDrawPositions:d,positionAssignments:D,drawDefinition:o,drawPosition:c,structureId:f,structure:l,drawId:P});q&&U.push(q)}if((x==null?void 0:x.participantType)===_t&&Pn({policyActions:C,action:sT})){const{validModifyAssignedPairAction:q}=R_({tournamentParticipants:n,returnParticipants:r,drawPosition:c,participant:x,drawId:P,event:a});q&&U.push(q)}return{hasPositionAssigned:!!M,isActiveDrawPosition:B,isDrawPosition:!0,isByePosition:H,validActions:U}}function G_(t){return Object.assign(t,{inContext:!0}),To(t)}function W_(t){const{structure:e}=Ot(t);return Object.assign(t,{structure:e,inContext:!0}),Qt(t)}function H_(t){return Object.assign(t,{inContext:!0}),xe(t)}const q_={allPlayoffPositionsFilled:WT,isCompletedStructure:ki,getAllStructureMatchUps:Qt,getStructureMatchUps:Va,allStructureMatchUps:W_,allDrawMatchUps:H_,drawMatchUps:G_,getEliminationDrawSize:Bh,getParticipantIdMatchUps:Pb,getParticipantIdFinishingPositions:Ub,getEligibleVoluntaryConsolationParticipants:Cb,structureActions:RM,matchUpActions:Sh,positionActions:Ob,getStructureSeedAssignments:Mr,getNextUnfilledDrawPositions:L_,getExitProfiles:Wf,getValidGroupSizes:xp,getSeedingThresholds:jM,getSeedBlocks:xl,getSeedGroups:$l,getMatchUpContextIds:SM,getMatchUpParticipantIds:Hf,getMatchUpScheduleDetails:_f,generateTieMatchUpScore:La,matchUpDuration:GI,credits:sd};function Mb({validation:t=!0,tournamentRecord:e,drawDefinition:n,participantId:r,structureId:s,seedValue:i,event:o}){if(!n)return{error:lt};if(!s)return{error:En};const{structure:c}=Ot({drawDefinition:n,structureId:s});if(!c)return{error:Te};if(!(!t||Me(i)||i===void 0||i===""||typeof i=="string"&&i.split("-").every(p=>Me(p)&&vt(p)>0)))return{error:tt};const{seedAssignments:u}=Mr({drawDefinition:n,structure:c}),l=u==null?void 0:u.map(p=>p.seedNumber),f=u==null?void 0:u.find(p=>p.participantId===r);if(f){const p=typeof i=="string"?i.includes("-")&&i.split("-").map(h=>parseInt(h)).join("-")||parseInt(i)>0&&parseInt(i)||"":i&&i>0&&i||"";f.seedValue=p}else{const h={seedNumber:Math.max(0,...l||[])+1,participantId:r};i&&(h.seedValue=i),c.seedAssignments||(c.seedAssignments=[]),c.seedAssignments.push(h)}return cS({tournamentId:e==null?void 0:e.tournamentId,eventId:o==null?void 0:o.eventId,drawDefinition:n,structure:c}),{...$}}function Y_({autoEntryPositions:t=!0,drawDefinition:e,participantId:n,stages:r}){return e?n?gd({drawDefinition:e,stages:r}).includes(n)?{error:Yo}:(e!=null&&e.entries&&(e.entries=e.entries.filter(o=>o.participantId!==n)),t&&(e.entries=pr({entries:e.entries})),Zt({drawDefinition:e}),{...$}):{error:Ce}:{error:lt}}const z_={setStageAlternatesCount:$k,setStageWildcardsCount:Vk,setStageQualifiersCount:Dh,modifySeedAssignment:Mb,setStageDrawSize:au,addDrawEntries:ib,addDrawEntry:Gh,removeEntry:Y_,assignSeed:Do},K_={generateQualifyingLink:kc},J_=()=>({matchUpType:void 0,drawName:void 0,drawId:void 0,structures:[],entries:[],links:[]}),Q_=["drawId","structures"];function Db(t,e=!0){return t?typeof t!="object"?{error:Ir}:t.drawId?Z_(t)?e?pt(t):t:{error:Gi}:{error:Hn,method:"setState"}:{error:lt}}function Z_(t){const e=Object.keys(t);return Q_.reduce((n,r)=>e.includes(r)?n:!1,!0)}function wb({drawId:t=Yt(),matchUpType:e,drawType:n}){const r=J_();return Object.assign(r,{drawId:t,drawType:n,matchUpType:e})}let ss,kb=[];const X_=function(){const t={getState:s=>({drawDefinition:pt(ss,s==null?void 0:s.convertExtensions,!1,s==null?void 0:s.removeExtensions)}),version:()=>Es(),reset:()=>(ss=void 0,{...$}),newDrawDefinition:s=>(ss=wb({drawId:s==null?void 0:s.drawId,drawType:s==null?void 0:s.drawType}),{drawDefinition:pt(ss),drawId:ss.drawId,...$}),setDrawDescription:s=>ss?(ss.description=s==null?void 0:s.description,Zt({drawDefinition:ss}),{drawId:ss.drawId,...$}):{error:lt}};function e(s){return s!=null&&s.error?(t.error=s.error,t.success=!1):(t.error=void 0,t.success=!0,ss=s,t.drawId=s.drawId),t}return n([K_,q_,LS,z_,F_,__,b_,m_]),t.devContext=s=>(zo(s),t),t.setParticipants=(s=[])=>(kb=s,t),t.setState=(s,i,o)=>{Hi(i,o);const c=Db(s);return e(c)},t;function n(s){s.forEach(i=>{Object.keys(i).forEach(o=>{t[o]=c=>{if(ze())return r({params:c,governor:i,methodName:o});try{return r({params:c,governor:i,methodName:o})}catch(a){Xc({engineName:"drawEngine",methodName:o,params:c,err:a})}}})})}function r({params:s,governor:i,methodName:o}){delete t.success,delete t.error;const c=(s==null?void 0:s.rollbackOnError)&&pt(ss,!1,!0);s={...s,...{},tournamentParticipants:kb,drawDefinition:ss};const u=i[o](s);if(u!=null&&u.error)return c&&Db(c),{...u,rolledBack:!!c};const l=(u==null?void 0:u.success)&&(s==null?void 0:s.delayNotify)!==!0&&(s==null?void 0:s.doNotNotify)!==!0;return l&&Di(),(l||!(u!=null&&u.success)||s!=null&&s.doNotNotify)&&fi(),u}}(),tF={modifyCollectionDefinition:zl,orderCollectionDefinitions:qp,removeCollectionDefinition:Kl,addCollectionDefinition:Zl,removeCollectionGroup:Kp,calculateWinCriteria:gc,addCollectionGroup:Jp,modifyTieFormat:Qp};function Bi({matchUp:t}){const{extension:e}=xn({name:Wu,element:t});if(!e)return{error:an};const{history:n=[],undoHistory:r=[]}=e.value;return{history:n,undoHistory:r,...$}}function eF({matchUp:t,updateScore:e}){var C;const n=((C=Bi({matchUp:t}))==null?void 0:C.history)||[];if(!Array.isArray(n))return{error:tt,info:"history is not an array"};const{matchUpFormat:r}=t;if(!r)return{error:Vd};if(!nr(r))return{error:Xm};const s=yn(r),{bestOf:i,finalSetFormat:o,setFormat:c}=s,a=["0","15","30","40","A","G"],u={sets:[]};let l=[],f,p=[0,0],h=1,d=0,m,g=0;const I=v=>[1,2].includes(v),S=()=>(d+=1,{winningSide:void 0,side1Score:0,side2Score:0,setNumber:d,games:[]}),T=()=>({winningSide:void 0,points:[]}),E=()=>({winningSide:void 0,side1Score:"",side2Score:"",shots:[]});let y=E(),b=T(),N=S(),A=0;for(const v of n){A+=1,m=u.sets.length+1===i;const P=m&&o?o:c,{tiebreakAt:U,setTo:O,NoAD:D,tiebbreakFormat:M}=P,w=N.side1Score===U&&N.side1Score===N.side2Score,k=!!P.tiebreakSet,_=k?P.tiebreakSet:M,{tiebreakTo:F,NoAD:L}=_||{},W=()=>{f=void 0,p=[0,0],h=3-h,N.side1TiebreakScore=0,N.side2TiebreakScore=0,N.side1PointScore="",N.side2PointScore="",g=0},j=R=>{N.winningSide=R;const{s:x,...q}=N;u.sets.push(q),y=E(),b=T(),N=S(),W()},H=R=>{b.winningSide=R;const{g:x,...q}=b;N.games.push(q),y=E(),b=T(),W();const V=`side${R}Score`;N[V]+=1},B=R=>{y.winningSide=R;const{p:x,...q}=y;b.points.push(q),y=E(),g=0;const V=()=>p.reduce((Q,X)=>Q+X)%4/4>.5?h:3-h,Y=R-1;if(w||k){p[Y]+=1,f=V(),N[`side${R}TiebreakScore`]=p[Y],N[`side${3-R}TiebreakScore`]=p[1-Y];const z=L?1:2;if(p[Y]>=F&&p[Y]>=p[1-Y]+z)return H(R),{gameCompleted:!0}}else if(p[1-Y]===4&&p[Y]===3?p[1-Y]-=1:p[Y]+=1,N.side1PointScore=a[p[0]],N.side2PointScore=a[p[1]],p[Y]===5||p[Y]===4&&p[1-Y]<3||D&&p[Y]===4)return H(R),{gameCompleted:!0}};if(I(v.srv)&&(h=v.srv),["p","s","g","o"].includes(v.u)&&l.push(v.u),v.shotOutcome&&(y.shots.push(v),v.shotType==="SERVE"&&["OUT","NET"].includes(v.shotOutcome)&&(g+=1),g===2)){const x=3-h;B(x)}if(I(v.p)||oe(v.pointNumber)){const R=v.winningSide||v.p,x=B(R);if(x!=null&&x.gameCompleted)continue}if(I(v.g)||oe(v.gameNumber)){const R=v.winningSide||v.g;b.winningSide=R;const x=`side${R}Score`,q=`side${3-R}Score`;if(l.length&&(l.includes("p"),l=[]),H(R),N[x]===O&&N[x]-N[q]>=(D?1:2)&&(j(R),m))break}if(I(v.s)||oe(v.setNumber)){const R=v.winningSide||v.s;if(j(R),l.length&&(l.includes("p"),l.includes("g"),l=[]),m)break}}return A!==n.length&&console.log({error:"Match completed with excess history"}),(N.side1Score||N.side2Score||N.games.length||N.side1TiebreakScore||N.side2TiebreakScore)&&u.sets.push(N),u.scoreStringSide1=gs({...u,matchUpFormat:r}),u.scoreStringSide2=gs({...u,matchUpFormat:r,reversed:!0}),h=f||h,e&&(t.score=u),{...$,servingSide:h,score:u}}function xi({undoHistory:t,history:e,matchUp:n}){return ae({element:n,extension:{value:{history:e,undoHistory:t},name:Wu}})}function nF({matchUp:t,sideNumber:e}){if(![1,2].includes(e))return{error:rg};const{history:n=[]}=Bi({matchUp:t});return n.push({srv:e}),xi({matchUp:t,history:n})}function rF({matchUp:t}){return xi({matchUp:t})}function sF({matchUp:t,point:e}){if(!e)return{error:Tt};if(typeof e!="object")return{error:tt,context:{point:e}};const{history:n=[]}=Bi({matchUp:t});return n.push(e),xi({matchUp:t,history:n})}function iF({matchUp:t,game:e}){if(typeof e!="object")return{error:tt,context:{game:e}};const{history:n=[]}=Bi({matchUp:t});return n.push(e),xi({matchUp:t,history:n})}function oF({matchUp:t,shot:e}){if(typeof e!="object")return{error:Tt};const{history:n=[]}=Bi({matchUp:t});return n.push(e),xi({matchUp:t,history:n})}function cF({matchUp:t,set:e}){if(typeof e!="object")return{error:Tt};const{history:n=[]}=Bi({matchUp:t});return n.push(e),xi({matchUp:t,history:n})}function aF({matchUp:t}){const{history:e=[],undoHistory:n=[]}=Bi({matchUp:t});return n.length&&e.push(n.pop()),xi({matchUp:t,history:e,undoHistory:n})}function uF({matchUp:t}){const{history:e=[],undoHistory:n=[]}=Bi({matchUp:t});return n.push(e.pop()),xi({matchUp:t,history:e,undoHistory:n})}const lF={calculateHistoryScore:eF,setServingSide:nF,clearHistory:rF,addPoint:sF,addGame:iF,addShot:oF,addSet:cF,redo:aF,undo:uF,umo:{scoreboard:()=>{},addPoints:()=>{},addPoint:()=>{}}};function Kh(t){var R;const{matchUp:e,sideNumber:n,setNumber:r,isTiebreakValue:s,isPointValue:i}=t||{};let{matchUpFormat:o}=t||{};if(!e)return{error:Rn};o=o||(e==null?void 0:e.matchUpFormat);const c=yn(o),a=!!(e!=null&&e.winningSide),u=(R=e.score)==null?void 0:R.sets,l=u==null?void 0:u.length,f=r&&r-1,p=!!(u!=null&&u.find((x,q)=>x.setNumber===r&&q===f)),h=(u==null?void 0:u.filter(x=>x==null?void 0:x.winningSide))||[],d=(h==null?void 0:h.length)||0,m=r&&(u==null?void 0:u.slice(r))||[],g=!!(l&&r&&(m!=null&&m.reduce((x,q)=>(!q||!q.side1Score&&!q.side2Score&&!q.side1TiebreakScore&&!q.side2TiebreakScore&&!q.side1PointScore&&!q.side2PointScore)&&x,!0))),I=r<=l&&u.find(x=>x.setNumber===r),S=I&&gl({setObject:I,matchUpScoringFormat:c}),{isCompletedSet:T,sideGameScores:E,sideTiebreakScores:y}=S||{},b=!!(I&&!T&&g||r&&r===l+1&&!a),N=[1,2].includes(n),A=N?n-1:0,C=I&&N&&(!s&&!i&&E[A]!==void 0&&E[A]||s&&y[A]!==void 0&&y[A]),v=!!C,P=h==null?void 0:h.map(x=>gl({setObject:x,matchUpScoringFormat:c}).isValidSetOutcome).reduce((x,q)=>x&&q,!0),U=h.reduce((x,q)=>{const{winningSide:V}=q,Y=V-1;return x[Y]++,x},[0,0]),O=e==null?void 0:e.winningSide,D=O&&O-1,M=1-D,w=U[D],k=U[M],_=Math.max(...U),F=Mn(U)[_],{bestOf:L}=c||{},W=L&&Math.ceil(L/2)||1,j=_===W&&F===1&&U.indexOf(_)+1||void 0,H=w>k&&O===j;return{completedSetsHaveValidOutcomes:P,validMatchUpWinningSide:H,calculatedWinningSide:j,matchUpScoringFormat:c,validMatchUpOutcome:j&&P&&H,isLastSetWithValues:g,completedSetsCount:d,isCompletedMatchUp:a,isValidSideNumber:N,hasExistingValue:v,existingValue:C,isExistingSet:p,isActiveSet:b,...S}}const dF={tallyParticipantResults:hf,matchUpIsComplete:Qo,analyzeMatchUp:Kh,getMatchUpType:HI,scoreHasValue:Be,validMatchUps:cr,validMatchUp:$g};let Fo={},ai;function _b(t,e=!0){if(!t)return{error:Tt};if(typeof t!="object")return{error:Ir};if(t.matchUpId)ai=t.matchUpId,Fo[ai]=e?pt(t):t;else if(Array.isArray(t))for(const n of t.reverse())n.matchUpId&&(Fo[n.matchUpId]=e?pt(n):n,ai||(ai=n.matchUpId));else for(const n of Object.values(t))n.matchUpId&&(Fo[n.matchUpId]=e?pt(n):n,ai||(ai=n.matchUpId));return e?pt(t):t}function fF(){return Fo[ai]}function pF(){return Object.values(Fo)}function hF(){ai=void 0,Fo={}}function mF(t){return pt(Fo[ai],t==null?void 0:t.convertExtensions,!1,t==null?void 0:t.removeExtensions)}(()=>{const t={getState:s=>mF(s),version:()=>Es(),reset:()=>(hF(),{...$}),drawId:void 0,error:void 0,success:!1,devContext:s=>(zo(s),t),setState:(s,i,o)=>{Hi(i,o);const c=_b(s);return e(c)}};function e(s){return s!=null&&s.error?(t.error=s.error,t.success=!1):(t.error=void 0,t.success=!0,t.drawId=s.drawId),t}return n([tF,lF,dF,LS]),t;function n(s){s.forEach(i=>{Object.keys(i).forEach(o=>{t[o]=c=>{if(ze())return r({params:c,governor:i,methodName:o});try{return r({params:c,governor:i,methodName:o})}catch(a){Xc({engineName:"matchUpEngine",methodName:o,params:c,err:a})}}})})}function r({params:s,governor:i,methodName:o}){t.error=void 0,t.success=!1;const c=(s==null?void 0:s.matchUp)||fF(),a=(s==null?void 0:s.matchUps)||pF(),u=(s==null?void 0:s.rollbackOnError)&&pt(c,!1,!0);s={...s,matchUpId:c==null?void 0:c.matchUpId,matchUps:a,matchUp:c};const l=i[o](s);if(l!=null&&l.error)return u&&_b(u),{...l,rolledBack:!!u};const f=(l==null?void 0:l.success)&&(s==null?void 0:s.delayNotify)!==!0&&(s==null?void 0:s.doNotNotify)!==!0;return f&&Di(),(f||!(l!=null&&l.success)||s!=null&&s.doNotNotify)&&fi(),l}})();function Jh(t){const e=t||{};return e.tournamentId||(e.tournamentId=Yt()),e.startDate&&!hi(e.startDate)&&!Mu.test(e.startDate)?{error:bn}:e.endDate&&!hi(e.endDate)&&!Mu.test(e.endDate)?{error:bn}:(e.extensions&&(e.extensions=e.extensions.filter(ur)),{...e})}function Qh(t,e){var s;if(typeof t!="object")return{error:Ir};const n=((s=t.unifiedTournamentId)==null?void 0:s.tournamentId)||t.tournamentId;if(!n)return{error:is};const r=e!==!1?pt(t):t;return Qc({[n]:r}),Zc(n),r}function gF({convertExtensions:t=!1,removeExtensions:e=!1,tournamentId:n}){if(typeof n!="string")return{};const r=Jc(n);return{tournamentRecord:pt(r,t,!1,e)}}function IF(t,e,n){var r;if(e){const s=e.drawId||((r=e.matchUp)==null?void 0:r.drawId);if(s){const{event:i,drawDefinition:o}=Je({tournamentRecord:t,drawId:s});if(e={...e,event:i,drawDefinition:o},n){const c=ln({drawDefinition:o}),{matchUps:a}=xe({inContext:!0,drawDefinition:o,matchUpsMap:c});e.matchUpsMap=c,e.inContextDrawMatchUps=a}}if(e.eventId&&!e.event){const{event:i}=Je({eventId:e.eventId,tournamentRecord:t});i&&(e={...e,event:i})}}return e}function SF(t){return t.tournamentRecord?Cb(t):{error:et}}function TF({tournamentRecord:t,participantId:e}){if(!t)return{error:et};if(!e)return{error:Ce};const n=[e].concat((t.participants||[]).filter(s=>{var i;return(s==null?void 0:s.participantType)&&[se,_t].includes(s.participantType)&&((i=s.individualParticipantIds)==null?void 0:i.includes(e))}).map(s=>s.participantId));return{eventDetails:(t.events||[]).filter(s=>{const i=((s==null?void 0:s.entries)||[]).map(o=>o.participantId);return tn(i,n)}).map(s=>({eventName:s.eventName,eventId:s.eventId}))}}function yF({tournamentRecord:t,participantId:e}){if(!t)return{error:et};if(!e)return{error:Ce};const{tournamentParticipants:n}=dn({participantFilters:{participantTypes:[se,_t,Fn]},tournamentRecord:t});return(n||[]).filter(s=>{var i;return(i=s.individualParticipantIds)==null?void 0:i.includes(e)}).reduce((s,i)=>{const{participantType:o}=i;return s[o]||(s[o]=[]),s[o].push(i),s},{})}function EF({participantFilters:t={},tournamentRecord:e}){if(!e)return{error:et};if(typeof t!="object")return{error:Ir,context:{participantFilters:t}};const n={eventIds:t.eventIds},r=He({tournamentRecord:e,contextFilters:n}).matchUps||[],s=Object.assign({},...r.map(l=>({[l.matchUpId]:l}))),i=r.filter(({schedule:l})=>l&&Object.keys(l).length),o=fr({tournamentRecord:e,matchUps:r}).sourceMatchUpIds||[],c={};for(const l of i){const{sides:f}=l;let p;const h=(f==null?void 0:f.map(m=>{if(m.participant)return[m.participant].concat(...m.participant.individualParticipants||[]);o[l.matchUpId]&&!p&&(p=(o[l.matchUpId]||[]).map(g=>s[g]).filter(({winningSide:g,bye:I})=>!g&&!I))}).filter(Boolean).flat())||[];for(const m of h){const{participantId:g}=m;c[g]||(c[g]={potentialMatchUps:[],participant:m,matchUps:[]}),c[g].matchUps.push(l)}const d=(p==null?void 0:p.map(({sides:m})=>m).flat().map(({participant:m})=>m&&[m].concat(...m.individualParticipants||[])).filter(Boolean).flat())||[];for(const m of d){const{participantId:g}=m;c[g]||(c[g]={potentialMatchUps:[],participant:m,matchUps:[]}),c[g].potentialMatchUps.push(l)}}return{participantSchedules:Object.values(c).filter(({participant:l})=>!(t.participantIds&&!t.participantIds.includes(l.participantId)||t.participantTypes&&!t.participantTypes.includes(l.participantType))),...$}}function bF({tournamentRecord:t,drawDefinition:e,byeAdvancements:n=!1}){if(!t)return{error:et};const r=t.participants;return Ub({tournamentParticipants:r,byeAdvancements:n,drawDefinition:e})}function NF({participantRole:t=fn,tournamentRecord:e,persons:n}){var d;if(!e)return{error:et};if(!Array.isArray(n))return{error:tt};if(!Object.keys(ly).includes(t))return{error:cv};const r=(e.participants||[]).map(({person:m})=>m==null?void 0:m.personId).filter(Boolean),s=[],i=n.filter(m=>m&&(!m.personId||!r.includes(m.personId))).map(m=>(m.personId||(m.personId=Yt()),s.push(m.personId),m)),o=(m,g)=>Object.assign({},...Object.keys(m).filter(I=>!g.includes(I)).map(I=>({[I]:m[I]}))),c=i.map(m=>bt({extensions:m.participantExtensions,timeItems:m.participantTimeItems,participantType:xt,participantRole:t,person:o(m,["participantExtensions","participantTimeItems","pairedPersons"])}));let a=0,u=0,l=Ss({participants:c,tournamentRecord:e});if(l.error)return l;u=l.addedCount||0;const f=[],p=((d=dn({participantFilters:{participantTypes:[xt]},tournamentRecord:e}))==null?void 0:d.tournamentParticipants)||[];if(t===fn&&n.filter(({pairedPersons:m})=>m).forEach(({personId:m,pairedPersons:g})=>{Array.isArray(g)&&g.forEach(I=>{const S=[m,I.personId].map(T=>Ps({tournamentParticipants:p,personId:T})).filter(Boolean);if(S.length===2){const T=S.map(fe);f.push(bt({extensions:I.participantExtensions,timeItems:I.timeItems,participantRole:fn,individualParticipantIds:T,participantType:_t}))}})}),f.length){if(l=Ss({participants:f,tournamentRecord:e}),l.error)return l;a=l.addedCount||0}const h=u+a;return{...$,addedCount:h,newPersonIds:s}}function AF({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:n}){var i,o;const r=(n.events||[]).filter(c=>{var a;return(c==null?void 0:c.eventType)===we&&((a=c==null?void 0:c.entries)==null?void 0:a.some(u=>u.participantId===e))}),s=c=>!t.includes(c.participantId);for(const c of r){c.entries=(c.entries||[]).filter(s);const{flightProfile:a}=be({event:c});(i=a==null?void 0:a.flights)==null||i.forEach(u=>{u.drawEntries=(u.drawEntries||[]).filter(s)}),(o=c==null?void 0:c.drawDefinitions)==null||o.forEach(u=>{u.entries=(u.entries||[]).filter(s)})}return{...$}}function Zh({individualParticipantIds:t,groupingParticipantId:e,removeFromOtherTeams:n,tournamentRecord:r}){const s="addIndividualParticipantIds";if(!r)return G({result:{error:et},stack:s});if(!e||!t)return G({result:{error:Tt},stack:s});const i=r.participants||[],o=i.find(f=>f.participantId===e);if(!o)return G({result:{error:_e},stack:s});if(o!=null&&o.participantType&&![se,Fn].includes(o.participantType))return G({result:{error:xr},context:{participantType:o.participantType},stack:s});const c=t.filter(f=>{const p=i.find(h=>h.participantId===f);return(p==null?void 0:p.participantType)!==xt});if(c.length)return G({result:{error:gr,invalidParticipantIds:c},stack:s});o.individualParticipantIds||(o.individualParticipantIds=[]);const a=o.individualParticipantIds,u=t.filter(f=>!a.includes(f));u.length&&(n&&Hh({individualParticipantIds:u,tournamentRecord:r}),o.individualParticipantIds=o.individualParticipantIds.concat(...u));const{topics:l}=$r();if(l.includes(nn)){const f=i.find(({participantId:p})=>p===e);Ht({topic:nn,payload:{participants:[f]}})}return AF({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:r}),{groupingParticipant:pt(o,!1,!0),added:u.length,...$}}function vF({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:n}){const r="modifyIndividualParticipantIds";if(!n)return G({result:{error:et},stack:r});if(!e||!t)return G({result:{error:Tt},stack:r});const s=n.participants||[],i=s.find(h=>h.participantId===e);if(!i)return G({result:{error:_e},stack:r});if(![se,Fn].includes(i.participantType))return G({result:{error:xr},context:{participantType:i.participantType},stack:r});const o=t.filter(h=>{const d=s.find(m=>m.participantId===h);return(d==null?void 0:d.participantType)!==xt});if(o.length)return G({result:{error:gr,invalidParticipantIds:o},stack:r});const c=i.individualParticipantIds||[],a=t.filter(h=>!c.includes(h)),u=c.filter(h=>!t.includes(h)),l=Zh({individualParticipantIds:a,groupingParticipantId:e,tournamentRecord:n});if(l.error)return G({result:l,stack:r});const f=cb({individualParticipantIds:u,groupingParticipantId:e,tournamentRecord:n});if(f.error)return G({result:f,stack:r});const{topics:p}=$r();if(p.includes(nn)){const h=s.find(({participantId:d})=>d===e);Ht({topic:nn,payload:{tournamentId:n.tournamentId,participants:[h]}})}return{...l,...f}}function Fb({addParticipants:t=!0,participantAttribute:e,tournamentRecord:n,personAttribute:r,teamNames:s,accessor:i,uuids:o}){var d,m;if(!n)return{error:et};const c={},a=(n.participants||[]).filter(({participantType:g,participantRole:I})=>g===xt&&I===fn);let u=0;for(const g of a){const S=i&&((d=Yi({element:g,accessor:i}))==null?void 0:d.value)||r&&((m=g.person)==null?void 0:m[r])||e&&g[e];if(S){if(!Object.keys(c).includes(S)){c[S]={participantName:(s==null?void 0:s[u])||S,participantId:(o==null?void 0:o.pop())||Yt(),individualParticipantIds:[],participantRole:fn,participantType:se};const T={name:mf,value:r||e};ae({element:c[S],extension:T}),u+=1}c[S].individualParticipantIds.push(g.participantId)}}const l=Object.keys(c),f=(n.participants||[]).map(g=>{if(g.participantType!==se||g.participantRole!==fn)return;const{extension:I}=xn({name:mf,element:g}),S=I==null?void 0:I.value;if(l.includes(S))return g.participantId}).filter(Boolean);let p=0;const h=[];return Object.keys(c).forEach(g=>{const I=c[g],{participantId:S}=I;f.includes(S)||(n.participants||(n.participants=[]),t&&n.participants.push(I),h.push(I),p++)}),t&&p?(Ht({payload:{tournamentId:n.tournamentId,participants:h},topic:yi}),{...$,participantsAdded:p}):h.length?{...$,newParticipants:h}:{error:iv}}function CF({tournamentRecord:t,participantIds:e,signInState:n}){if(!t)return{error:et};if(!Array.isArray(e))return{error:Tt};if(![ya,_P].includes(n))return{error:tt,signInState:n};const s=t.participants||[];if(!s.length)return{error:Yc};const i=s.map(fe),o=e.filter(l=>!i.includes(l));if(o.length)return{error:tt,context:{invalidParticipantIds:o}};const c=[],a=new Date().toISOString();for(const l of s){const{participantId:f}=l;if(e.includes(f)){const h=PT({duplicateValues:!1,tournamentRecord:t,participantId:f,timeItem:{itemType:Ta,itemValue:n,createdAt:a}});if(h.error)return h;c.push(l)}}const{topics:u}=$r();return c.length&&u.includes(nn)&&Ht({topic:nn,payload:{tournamentId:t.tournamentId,participants:c}}),{...$}}function PF({clearExistingAssignments:t=!0,individualParticipantIds:e,reverseAssignmentOrder:n,initialTeamIndex:r=0,scaledParticipants:s=[],teamParticipantIds:i,tournamentRecord:o,scaleAttributes:c,teamNameBase:a,teamsCount:u,eventId:l,event:f}){var I,S,T,E;if(!o)return{error:et};if(!Array.isArray(i)&&!oe(u)&&!l||!oe(r)||s&&!Array.isArray(s)||c&&(typeof c!="object"||!Object.keys(c).length))return{error:tt};if(!c&&!s.length||!s&&!(e&&c))return{error:Tt,info:"Missing scaling details"};if(l&&!i){if((f==null?void 0:f.eventType)!==ds)return{error:ui};i=(I=f==null?void 0:f.entries)==null?void 0:I.filter(({entryStatus:y})=>y===Ur).map(fe)}if(!(i!=null&&i.length)&&!u)return{info:"Missing teamParticipantIds or teamsCount",error:Tt};let p=e||s.map(({participantId:y})=>y);n&&(i==null||i.reverse(),r+=1),r>((i==null?void 0:i.length)||0)-1&&(r=0);const h=(i==null?void 0:i.slice(r).concat(...i.slice(0,r)))||[],d=[];for(const y of o.participants||[]){const{participantId:b,participantType:N}=y;if(h.includes(b)){if(N!==vr)return{error:xr,participant:y};d.push(y)}}if(u&&d.length<u){const y=u-((d==null?void 0:d.length)||0),b=a||"Team",N=ht(0,y).map(P=>({participantName:`${b} ${P+1}`,participantType:vr,participantRole:fn})),{participants:A=[]}=Ss({participants:N,returnParticipants:!0,tournamentRecord:o}),C=A.map(fe),v=((S=o.participants)==null?void 0:S.filter(({participantId:P})=>C.includes(P)))??[];d.push(...v)}if(!d.length)return{error:yg};if(t)for(const y of d)y.individualParticipantIds=[];else{const y=d.map(b=>b).flat();e!=null&&e.length?p=p.filter(b=>!y.includes(b)):s=s==null?void 0:s.filter(({participantId:b})=>!y.includes(b))}if(!(e!=null&&e.length)&&!(s!=null&&s.length))return{error:Jd,info:"Nothing to be done"};if(!s.length){for(const y of o.participants||[]){const{participantId:b,participantType:N}=y;if(!p.includes(b))continue;if(N!==xt)return{error:xr,participant:y};const A=(T=Ts({scaleAttributes:c,participant:y}))==null?void 0:T.scaleItem,C=c!=null&&c.accessor?(E=A==null?void 0:A.scaleValue)==null?void 0:E[c==null?void 0:c.accessor]:A==null?void 0:A.scaleValue,v={participantId:b,scaleValue:C};s.push(v)}if(!s.length)return{error:_e}}s.sort((y,b)=>c!=null&&c.sortOrder?((b==null?void 0:b.scaleValue)||0)-((y==null?void 0:y.scaleValue)||0):((y==null?void 0:y.scaleValue)||1/0)-((b==null?void 0:b.scaleValue)||1/0));for(const y of s)if(!y.participantId)return{error:tt,scaledParticipant:y};let m=0;for(;m<s.length;){for(const y of d){if(m+1>s.length)break;const b=s[m];y.individualParticipantIds.push(b.participantId),m++}d.reverse()}const g=d.map(fe);for(const y of o.events||[]){if(y.eventType!==ds)continue;const b=(y.entries||[]).filter(N=>g.includes(N.participantId));for(const N of b){const A=N.participantId,C=d.find(U=>U.participantId===A),v=C==null?void 0:C.individualParticipantIds;y.entries=(y.entries||[]).filter(U=>!v.includes(U.participantId)),(y.drawDefinitions||[]).forEach(U=>{U.entries=(U.entries||[]).filter(O=>!v.includes(O.participantId))});const{flightProfile:P}=be({event:y});((P==null?void 0:P.flights)||[]).forEach(U=>{U.drawEntries=(U.drawEntries||[]).filter(O=>!v.includes(O.participantId))})}}return{...$,scaledParticipants:s}}function UF({individualParticipantIds:t=[],participantRoleResponsibilities:e,participantRole:n=uy,tournamentRecord:r,participantId:s,groupName:i}){if(!r)return{error:et};if(!i)return{error:Tt,info:"Missing groupName"};if(!Array.isArray(t))return{info:"Invalid individualParticipantIds",error:tt};const{tournamentParticipants:o}=dn({participantFilters:{participantTypes:[xt]},tournamentRecord:r}),c=o.map(f=>f.participantId);for(const f of t)if(!c.includes(f))return{error:xr,participantId:f};const a=bt({participantId:s||Yt(),participantRoleResponsibilities:e,participantName:i,individualParticipantIds:t,participantType:Fn,participantRole:n}),u=es({participant:a,tournamentRecord:r});if(u.error)return u;const{topics:l}=$r();return l.includes(yi)&&Ht({topic:yi,payload:{tournamentId:r.tournamentId,participants:[a]}}),{...$,participant:pt(a)}}function OF({tournamentRecord:t,participantId:e,participantOtherName:n}){if(!t)return{error:et};if(!e)return{error:Ce};const{participant:r}=zs({tournamentRecord:t,participantId:e});if(!r)return{error:_e};r.participantOtherName=n;const{topics:s}=$r();return s.includes(nn)&&Ht({topic:nn,payload:{tournamentId:t.tournamentId,participants:[r]}}),{...$}}function Lb({personFormat:t,person:e}){const n=g=>g.replace(/\W/g,""),r=g=>/^[a-z]*$/.test(n(g)),s=g=>/^[A-Z]*$/.test(n(g)),i=g=>/^[LAST]{4}/.test(n(g)),o=g=>g.toLowerCase().indexOf("l")<g.toLowerCase().indexOf("f"),c=g=>g.indexOf(",")>=0,a=g=>g.toLowerCase().indexOf("f.")>=0,u=g=>g.toLowerCase().indexOf("f")<0,l=g=>g.indexOf(" ")>0;if(!e)return;const f=l(t)?" ":"",p=g=>g.split(" ").map(I=>I.split("").map((S,T)=>T?S.toLowerCase():S.toUpperCase()).join("")).join(" ");let h=p((e==null?void 0:e.standardGivenName)??""),d=p((e==null?void 0:e.standardFamilyName)??"");if(!t)return`${h}${f}${d}`;a(t)&&!c(t)&&!o(t)&&(h=`${h[0]}.`),r(t)?(h=h.toLowerCase(),d=d.toLowerCase()):s(t)?(h=h.toUpperCase(),d=d.toUpperCase()):i(t)&&(d=d.toUpperCase());let m=`${h}${f}${d}`;return u(t)?m=d:o(t)&&(c(t)?m=`${d},${f}${h}`:m=`${d}${f}${h}`),m}function MF({participantMap:t,participant:e,formats:n}){const{participantType:r,individualParticipantIds:s,person:i}=e,o=r&&n[r];if(r!==vr&&o){const{personFormat:c,doublesJoiner:a}=o;r===xt&&(e.participantName=Lb({person:i,personFormat:c})),r===_t&&(e.participantName=s==null?void 0:s.map(u=>{var f;const l=(f=t[u])==null?void 0:f.person;return Lb({person:l,personFormat:c})}).filter(Boolean).join(a??"/"))}}function DF({tournamentRecord:t,formats:e}){if(!t)return{error:et};if(!or(e))return{error:Tt};const n=t.participants??[],r=yC(n,"participantId");for(const s of n)MF({participant:s,participantMap:r,formats:e});return{...$}}function wF({tournamentRecord:t,participantFilters:e}){if(!t)return{error:et};let n=t.participants||[];e&&(n=Hl({participants:n,participantFilters:e,tournamentRecord:t}));const r={},s=i=>{if(i.person){const{personId:o}=i.person;r[o]?r[o].participantIds.push(i.participantId):r[o]={...i.person,participantIds:[i.participantId]}}};return n.forEach(i=>{i.person&&s(i),i.individualParticipants&&i.individualParticipants.forEach(s)}),{tournamentPersons:Object.values(r)}}function kF({tournamentRecord:t,participantName:e,participantId:n}){if(!t)return{error:et};if(!n)return{error:Ce};if(!e)return{error:Tt,info:"Missing participantName"};const{participant:r}=zs({tournamentRecord:t,participantId:n});if(!r)return{error:_e};r.participantName=e;const{topics:s}=$r();return s.includes(nn)&&Ht({topic:nn,payload:{tournamentId:t.tournamentId,participants:[r]}}),{...$}}function _F({participants:t=[],tournamentRecord:e,arraysToMerge:n}){if(!e)return{error:et};e.participants||(e.participants=[]);const r=t.filter(dl).map(u=>({[u.participantId]:u})),s=Object.assign({},...r),i=[];e.participants=e.participants.map(u=>{if(s[u.participantId]){const l=Wp(u,s[u.participantId],n);return i.push(l),l}return u});const o=e.participants.map(fe),c=t.filter(({participantId:u})=>!o.includes(u)),{topics:a}=$r();return c.length&&(e.participants=e.participants.concat(...c),a.includes(yi)&&Ht({topic:yi,payload:{participants:c}})),i.length&&a.includes(nn)&&Ht({topic:nn,payload:{tournamentId:e.tournamentId,participants:i}}),{modifiedParticipantsCount:i.length,newParticipantsCount:c.length,...$}}function Xh(t){const{updateParticipantName:e=!0,groupingParticipantId:n,removeFromOtherTeams:r,tournamentRecord:s,pairOverride:i,participant:o}=t;if(!s)return{error:et};if(!o)return{error:qo};if(!o.participantId)return es({tournamentRecord:s,participant:o});const{participant:c}=zs({participantId:o.participantId,tournamentRecord:s});if(!c)return es({tournamentRecord:s,participant:o});const{participantRoleResponsibilties:a,individualParticipantIds:u,participantOtherName:l,participantName:f,participantRole:p,participantType:h,onlineResources:d,contacts:m,person:g}=o;if(h&&c.participantType!==h)return{error:ov};const I={};if(m&&(I.contacts=m),d&&(I.onlineResources=d),f&&typeof f=="string"&&(I.participantName=f),l&&typeof l=="string"&&(I.participantOtherName=l),Array.isArray(u)){const{tournamentParticipants:S}=dn({participantFilters:{participantTypes:[Ea.INDIVIDUAL]},tournamentRecord:s}),T=S==null?void 0:S.map(fe);if(T){const E=u.filter(y=>typeof y=="string"&&T.includes(y));([Fn,Jt].includes(h||c.participantType)||h===_t&&(E.length===2||i))&&(I.individualParticipantIds=E),c.participantType===Ea.PAIR&&e&&(I.participantName=FF({individualParticipants:S,newValues:I}))}}return Object.keys(ly).includes(p)&&(I.participantRole=p),Object.keys(Ea).includes(h)&&(I.participantType=h),Array.isArray(a)&&(I.participantRoleResponsibilties=a),c.participantType===Ea.INDIVIDUAL&&g&&LF({updateParticipantName:e,existingParticipant:c,newValues:I,person:g}),Object.assign(c,bt(I)),n&&Zh({individualParticipantIds:[c.participantId],groupingParticipantId:n,removeFromOtherTeams:r,tournamentRecord:s}),Ht({topic:nn,payload:{tournamentId:s.tournamentId,participants:[c]}}),{participant:pt(c),...$}}function FF({individualParticipants:t,newValues:e}){const n=e.individualParticipantIds;let r=t.filter(({participantId:s})=>n.includes(s)).map(({person:s})=>s==null?void 0:s.standardFamilyName).filter(Boolean).sort().join("/");return n.length===1&&(r+="/Unknown"),r}function LF({updateParticipantName:t,existingParticipant:e,newValues:n,person:r}){const s={},{standardFamilyName:i,standardGivenName:o,nationalityCode:c,personId:a,sex:u}=r;u&&Object.keys(iS).includes(u)&&(s.sex=u);let l;if(a&&typeof a=="string"&&(s.personId=a),c&&typeof c=="string"&&(RF(c)||c==="")&&(s.nationalityCode=c),i&&typeof i=="string"&&i.length>1&&(s.standardFamilyName=i,l=!0),o&&typeof o=="string"&&o.length>1&&(s.standardGivenName=o,l=!0),l&&t){const f=`${s.standardGivenName} ${s.standardFamilyName}`;n.participantName=f}Object.assign(e.person,s)}function RF(t){return ri.flatMap(({iso:e,ioc:n})=>[e,n]).filter(Boolean).includes(t)}function Rb({drawDefinition:t,timeItem:e}){if(!t)return{error:rr};if(!e)return{error:Sg};const n=e&&Object.keys(e),r=["itemType","itemValue"];if(!(r.filter(o=>n.includes(o)).length===r.length))return{error:Ig};t.timeItems||(t.timeItems=[]);const i=new Date().toISOString();return Object.assign(e,{createdAt:i}),t.timeItems.push(e),Ba({drawDefinition:t}),{...$}}function du(t){const{removePriorValues:e,tournamentRecord:n,participantId:r,scaleItem:s}=t;let i,o;if(!Bb({scaleItem:s}))return{error:Uu};if(r&&Array.isArray(n.participants)&&(o=n.participants.find(c=>c.participantId===r),o)){const c=xb({removePriorValues:e,participant:o,scaleItem:s});if(c.error)return c;i=!c.valueChanged;const{topics:a}=$r();a.includes(nn)&&Ht({topic:nn,payload:{tournamentId:n.tournamentId,participants:[o]}})}return i&&{...$,info:Eg,existingValue:s.scaleValue}||o&&{...$,newValue:s.scaleValue}||{error:_e}}function BF(t){var f;const{scaleItemsWithParticipantIds:e=[],removePriorValues:n,tournamentRecord:r,auditData:s,context:i}=t;if(!r)return{error:et};if(!r.participants)return{error:Yc};let o=0;const c={},a=[];for(const p of e){const h=p==null?void 0:p.participantId;if(Array.isArray(p==null?void 0:p.scaleItems))for(const d of p.scaleItems)if(Bb({scaleItem:d}))Array.isArray(c[h])||(c[h]=[]),c[h].push(d);else return{error:Uu}}r.participants.forEach(p=>{const{participantId:h}=p||{};Array.isArray(c[h])&&c[h].forEach(d=>{xb({participant:p,scaleItem:d,removePriorValues:n}),a.push(p),o++})});const u=o?void 0:zc,{topics:l}=$r();if(l.includes(nn)&&o&&Ht({topic:nn,payload:{tournamentId:r.tournamentId,participants:a}}),i){const{eventId:p,drawId:h,...d}=i,m=((f=d.scaleAttributes)==null?void 0:f.scaleType)&&[d.scaleAttributes.scaleType];if(Object.keys(d).length){const g={itemType:EI,itemValue:d};if(m&&(g.itemSubTypes=m),h||p){const{drawDefinition:I,event:S}=Je({tournamentRecord:r,eventId:p,drawId:h});h&&Rb({drawDefinition:I,timeItem:g}),p&&ii({event:S,timeItem:g})}else _s({tournamentRecord:r,timeItem:g})}}return s&&l.includes(ha)&&Ht({topic:ha,payload:s}),bt({...$,modificationsApplied:o,info:u})}function Bb({scaleItem:t}){const e=t&&Object.keys(t),n=["scaleType","eventType","scaleName"];return!!(n.filter(s=>e==null?void 0:e.includes(s)).length===n.length)}function xb({removePriorValues:t,participant:e,scaleItem:n}){if(!e)return{error:qo};const r=n&&Object.keys(n),s=["scaleType","eventType","scaleName"];if(!(s.filter(l=>r.includes(l)&&n[l]).length===s.length))return{error:Uu};const o=new Date().toISOString();e.timeItems||(e.timeItems=[]);const{scaleItem:c}=Ts({scaleAttributes:n,participant:e}),a=l=>[void 0,null,""].includes(l),u=!(a(c==null?void 0:c.scaleValue)&&a(n.scaleValue))&&JSON.stringify(c==null?void 0:c.scaleValue)!==JSON.stringify(n.scaleValue);if(u){const{scaleType:l,eventType:f,scaleName:p}=n,h=[eo,l,f,p].join("."),d=bt({itemValue:n.scaleValue,itemDate:n.scaleDate,createdAt:o,itemType:h});n.scaleId&&(d.itemSubTypes=[n.scaleId]),t&&(e.timeItems=e.timeItems.filter(m=>m.itemType!==h)),e.timeItems.push(d)}return{...$,valueChanged:u,newValue:n.scaleValue}}const xF={getTournamentPenalties:vy,modifyPenalty:Cy,removePenalty:Ay,addPenalty:Ny,createGroupParticipant:UF,scaledTeamAssignment:PF,deleteParticipants:Fc,addParticipants:Ss,addParticipant:es,addPersons:NF,addIndividualParticipantIds:Zh,removeIndividualParticipantIds:cb,modifyIndividualParticipantIds:vF,removeParticipantIdsFromAllTeams:Hh,getParticipantMembership:yF,generateTeamsFromParticipantAttribute:Fb,regenerateParticipantNames:DF,getParticipantIdFinishingPositions:bF,modifyParticipant:Xh,modifyParticipantName:kF,modifyParticipantOtherName:OF,mergeParticipants:_F,getPairedParticipant:Jr,filterParticipants:Hl,setParticipantScaleItem:du,setParticipantScaleItems:BF,modifyParticipantsSignInStatus:CF,getParticipantEventDetails:TF,getEligibleVoluntaryConsolationParticipants:SF,findParticipant:rP,getTournamentParticipants:dn,getParticipantSchedules:EF,getTournamentPersons:wF,getParticipants:Fi};function $F({removePriorValues:t=!0,stageSeedingScaleNames:e,seedingScaleNames:n,tournamentRecord:r,status:s=Kr,drawIds:i=[],event:o}){var h,d,m,g;if(!r)return{error:et};if(!o)return{error:Wt};const c=`${Qn}.${Zn}`,{timeItem:a}=ws({itemType:c,event:o}),u=(a==null?void 0:a.itemValue)||{[s]:{}},l=(((h=u[s].seeding)==null?void 0:h.seedingScaleNames)||n)&&{...(d=u[s].seeding)==null?void 0:d.seedingScaleNames,...n},f=(((m=u[s].seeding)==null?void 0:m.stageSeedingScaleNames)||e)&&{...(g=u[s].seeding)==null?void 0:g.stageSeedingScaleNames,...e};return u[s].seeding=bt({stageSeedingScaleNames:f,seedingScaleNames:l,published:!0,drawIds:i}),ii({event:o,timeItem:{itemValue:u,itemType:c},removePriorValues:t}),Ht({topic:EP,payload:{tournamentId:r.tournamentId,eventId:o.eventId,drawIds:i}}),{...$}}function VF({removePriorValues:t=!0,seedingScaleNames:e,tournamentRecord:n,status:r=Kr,stages:s,event:i}){var l,f;if(!n)return{error:et};if(!i)return{error:Wt};const o=`${Qn}.${Zn}`,{timeItem:c}=ws({itemType:o,event:i}),a=(c==null?void 0:c.itemValue)||{[r]:{}};if(a[r]){if(Array.isArray(s)&&((l=a[r].seeding)!=null&&l.stageSeedingScaleNames))for(const p of s)a[r].seeding.stageSeedingScaleNames[p]&&delete a[r].seeding.stageSeedingScaleNames[p];Array.isArray(e)&&((f=a[r].seeding)!=null&&f.seedingScaleNames)&&(a[r].seeding.seedingScaleNames=a[r].seeding.seedingScaleNames.filter(p=>!e.includes(p))),!s&&!e&&delete a[r].seeding}return ii({event:i,timeItem:{itemValue:a,itemType:o},removePriorValues:t}),Ht({topic:kI,payload:{tournamentId:n.tournamentId,eventId:i.eventId}}),{...$}}function jF({tournamentRecord:t,policyDefinitions:e}){if(!t)return{error:et};const n=t.events||[],r=(t==null?void 0:t.participants)||[],{tournamentInfo:s}=tu({tournamentRecord:t}),{venues:i}=Of({tournamentRecord:t}),o=n.map(a=>{const{eventId:u}=a,l=(({eventId:d,eventName:m,eventType:g,eventLevel:I,surfaceCategory:S,matchUpFormat:T,category:E,gender:y,startDate:b,endDate:N,ballType:A,discipline:C})=>({eventId:d,eventName:m,eventType:g,eventLevel:I,surfaceCategory:S,matchUpFormat:T,category:E,gender:y,startDate:b,endDate:N,ballType:A,discipline:C}))(a),f=pa({tournamentRecord:t,event:a}).scheduleTiming,p=(a.drawDefinitions||[]).map(d=>{const m=(({drawId:E,drawName:y,matchUpFormat:b,updatedAt:N})=>({matchUpFormat:b,updatedAt:N,drawName:y,drawId:E}))(d),{abandonedMatchUps:g,completedMatchUps:I,upcomingMatchUps:S,pendingMatchUps:T}=To({requireParticipants:!0,tournamentParticipants:r,context:{eventId:u},policyDefinitions:e,tournamentRecord:t,inContext:!0,scheduleTiming:f,drawDefinition:d,event:a});return{drawInfo:m,matchUps:{abandonedMatchUps:g,completedMatchUps:I,upcomingMatchUps:S,pendingMatchUps:T}}}),{timeItem:h}=ws({itemType:`${Qn}.${Zn}`,event:a});return Object.assign(l,{publish:h==null?void 0:h.itemValue,drawsData:p}),l});return{allEventData:{tournamentInfo:s,venuesData:i,eventsData:o}}}function GF({removePriorValues:t=!0,tournamentRecord:e,status:n=Kr,event:r}){if(!e)return{error:et};if(!r)return{error:Wt};const s=`${Qn}.${Zn}`,{timeItem:i}=ws({itemType:s,event:r}),o=(i==null?void 0:i.itemValue)||{[n]:{}};return delete o[n].structureIds,delete o[n].drawIds,ii({event:r,timeItem:{itemValue:o,itemType:s},removePriorValues:t}),Ht({topic:wI,payload:{tournamentId:e.tournamentId,eventId:r.eventId}}),{eventId:r.eventId,...$}}function $b({drawDefinition:t}){const e=t.links||[],n={},r={};let s=e.map(h=>{const d=h.source.structureId,m=h.target.structureId;return r[m]=r[m]||h.target.feedProfile===Cr,n[m]=Vt([...n[m]||[],d]).filter(Boolean),[h.source.structureId,h.target.structureId]});const i=s.length;ht(0,Math.ceil(i/2)).forEach(()=>{s=ht(0,i).map(h=>{const d=s[h],m=s.reduce((g,I)=>tn(d,I)?g.concat(...I):g,[])||[];return Vt(d.concat(...m))})});const o=s[0],c=(h,d)=>qe(h,d).length===h.length,a=s.slice(1).reduce((h,d)=>h&&c(d,o),!0),u=[o].filter(Boolean),l=[o].filter(Boolean);return(t.structures||[]).forEach(h=>{const{structureId:d,stage:m}=h;u.find(I=>I.includes(d))||(u.push([d]),m!==je&&l.push(d))}),{allStructuresLinked:a&&l.length===1,sourceStructureIds:n,hasDrawFeedProfile:r,structureGroups:u}}function Vb(t){const{tournamentParticipants:e=[],includePositionAssignments:n,policyDefinitions:r,tournamentRecord:s,inContext:i=!0,drawDefinition:o,noDeepCopy:c,sortConfig:a,context:u,event:l}=t;if(!o)return{error:lt};const f=(({matchUpFormat:b,updatedAt:N,drawType:A,drawName:C,drawId:v})=>({matchUpFormat:b,updatedAt:N,drawName:C,drawType:A,drawId:v}))(o);let p,h;const{allStructuresLinked:d,sourceStructureIds:m,hasDrawFeedProfile:g,structureGroups:I}=$b({drawDefinition:o});if(!d)return{error:W1};let S=!1,T=!1;const y=I.map(b=>{const N={},A=b.map(C=>{const{structure:v}=Ot({drawDefinition:o,structureId:C}),{seedAssignments:P}=Mr({drawDefinition:o,structure:v});return(v==null?void 0:v.stage)===It&&v.stageSequence===1&&(p=P),(v==null?void 0:v.stage)===Pt&&v.stageSequence===1&&(h=P),v}).sort((C,v)=>Pi(C,v,a)).map(C=>{var F;const{structureId:v}=C;let P=[];[It,Re,Ie].includes(C.stage)&&(P=p),C.stage===Pt&&(P=h);const{matchUps:U,roundMatchUps:O,roundProfile:D}=Qt({seedAssignments:(F=C==null?void 0:C.seedAssignments)!=null&&F.length?void 0:P,context:{drawId:f.drawId,...u},tournamentParticipants:e,policyDefinitions:r,tournamentRecord:s,drawDefinition:o,inContext:i,structure:C,event:l}),{positionAssignments:M}=ee({structure:C}),w=M==null?void 0:M.filter(dl).map(L=>{T=!0;const{drawPosition:W,participantId:j}=L,{extension:H}=Ke({element:L,name:Ys});return H&&{drawPosition:W,participantId:j,participantResult:H.value}}).filter(L=>L==null?void 0:L.participantResult),k=(({stageSequence:L,structureName:W,structureType:j,matchUpFormat:H,stage:B})=>({stageSequence:L,structureName:W,structureType:j,matchUpFormat:H,stage:B}))(C);k.sourceStructureIds=m[v],k.hasDrawFeedProfile=g[v],k.positionAssignments=M,k.structureActive=U.reduce((L,W)=>{var H;const j=[De,Gs,te,In,ce,Gr,en,Fe].includes(W.matchUpStatus);return L||j||!!W.winningSide||!!((H=W.score)!=null&&H.scoreStringSide1)},!1);const _=U.reduce((L,W)=>L&&[re,De,In,ce,te,zn].includes(W.matchUpStatus),!!U.length);return k.structureCompleted=_,N[v]=_,k.structureActive&&(S=!0),{...k,participantResults:w,seedAssignments:P,roundMatchUps:O,roundProfile:D,structureId:v}});return A.forEach(C=>{var v;n||delete C.positionAssignments,C.sourceStructuresComplete=(v=C.sourceStructureIds)==null?void 0:v.every(P=>N[P])}),A}).flat();return f.drawActive=S,f.participantPlacements=T,f.drawGenerated=y==null?void 0:y.reduce((b,N)=>b||!!(N!=null&&N.roundMatchUps),!1),f.drawCompleted=y==null?void 0:y.reduce((b,N)=>b&&N.structureCompleted,!0),{structures:c?y:pt(y,!1,!0),drawInfo:c?f:pt(f,!1,!0),...$}}function jb(t){var P;const{includePositionAssignments:e,tournamentRecord:n,participantsProfile:r,policyDefinitions:s,usePublishState:i,status:o=Kr,sortConfig:c,event:a}=t,u=pt(n,!1,!0),l=pt(a,!1,!0);if(!u)return{error:et};if(!l)return{error:Wt};const{eventId:f}=l,{tournamentId:p,endDate:h}=u,{timeItem:d}=ws({itemType:`${Qn}.${Zn}`,event:l}),m=(P=d==null?void 0:d.itemValue)==null?void 0:P[o],{tournamentParticipants:g}=dn({withGroupings:!0,withEvents:!1,withDraws:!1,...r,tournamentRecord:u}),I=({stage:U})=>{var O;return!i||!((O=m==null?void 0:m.stages)!=null&&O.length)||m.stages.includes(U)},S=({structureId:U})=>{var O;return!i||!((O=m==null?void 0:m.structureIds)!=null&&O.length)||m.structureIds.includes(U)},T=({drawId:U})=>{var O;return!i||!((O=m==null?void 0:m.drawIds)!=null&&O.length)||m.drawIds.includes(U)},y=(l.drawDefinitions||[]).filter(T).map(U=>(({drawInfo:O,structures:D})=>({...O,structures:D}))(Vb({context:{eventId:f,tournamentId:p,endDate:h},includePositionAssignments:e,tournamentParticipants:g,noDeepCopy:!0,policyDefinitions:s,tournamentRecord:u,drawDefinition:U,sortConfig:c,event:l}))).map(({structures:U,...O})=>{var D;return{...O,structures:(D=U==null?void 0:U.filter(S))==null?void 0:D.filter(I)}}).filter(U=>{var O;return(O=U.structures)==null?void 0:O.length}),{tournamentInfo:b}=tu({tournamentRecord:u}),A=(u.venues||[]).map(U=>(({venueData:O})=>({...O}))(Ju({tournamentRecord:u,venueId:U.venueId}))),C=(({eventId:U,eventName:O,eventType:D,eventLevel:M,surfaceCategory:w,matchUpFormat:k,category:_,gender:F,startDate:L,endDate:W,ballType:j,discipline:H})=>({eventId:U,eventName:O,eventType:D,eventLevel:M,surfaceCategory:w,matchUpFormat:k,category:_,gender:F,startDate:L,endDate:W,ballType:j,discipline:H}))(l),v={tournamentInfo:b,venuesData:A,eventInfo:C,drawsData:y};return v.eventInfo.publish={createdAt:d==null?void 0:d.createdAt,state:d==null?void 0:d.itemValue},{...$,eventData:v}}function fu(t){var N,A,C,v,P,U,O,D,M,w;let{policyDefinitions:e,drawIds:n,structureIds:r,stages:s}=t;const{includePositionAssignments:i,removePriorValues:o,tournamentRecord:c,status:a=Kr,event:u,drawIdsToRemove:l,drawIdsToAdd:f,stagesToRemove:p,stagesToAdd:h,structureIdsToRemove:d,structureIdsToAdd:m}=t;if(!c)return{error:et};if(!u)return{error:Wt};if(!e){const{appliedPolicies:k}=ge({tournamentRecord:c,event:u});e=k}const g=`${Qn}.${Zn}`,I=((N=u.drawDefinitions)==null?void 0:N.map(({drawId:k})=>k))||[],{timeItem:S}=ws({itemType:g,event:u});!n&&!f&&!l?n=I:!n&&(f!=null&&f.length||l!=null&&l.length)&&(n=((C=(A=S==null?void 0:S.itemValue)==null?void 0:A.PUBLIC)==null?void 0:C.drawIds)||[]),n=(n||[]).filter(k=>!(l!=null&&l.length)||!l.includes(k)),f!=null&&f.length&&(n=Vt(n.concat(...f.filter(k=>I.includes(k))))),!r&&(m!=null&&m.length||d!=null&&d.length)&&(r=((P=(v=S==null?void 0:S.itemValue)==null?void 0:v.PUBLIC)==null?void 0:P.structureIds)||[]),r=(r||[]).filter(k=>!(d!=null&&d.length)||!d.includes(k)),m!=null&&m.length&&(r=Vt(r.concat(...m))),!s&&(h!=null&&h.length||p!=null&&p.length)&&(s=((O=(U=S==null?void 0:S.itemValue)==null?void 0:U.PUBLIC)==null?void 0:O.stages)||[]),s=(s||[]).filter(k=>!(p!=null&&p.length)||!p.includes(k)),h!=null&&h.length&&(s=Vt(s.concat(...h)));const T=(D=S==null?void 0:S.itemValue)==null?void 0:D[a],E={itemValue:{[a]:{...T,drawIds:n,structureIds:r,stages:s}},itemType:g};ii({event:u,timeItem:E,removePriorValues:o});const{eventData:y}=jb({includePositionAssignments:i,usePublishState:!0,tournamentRecord:c,policyDefinitions:e,event:u}),b=(w=(M=y==null?void 0:y.eventInfo)==null?void 0:M.publish)==null?void 0:w.state;return y.drawsData=y.drawsData.filter(({drawId:k})=>{var _;return(_=b==null?void 0:b.PUBLIC)==null?void 0:_.drawIds.includes(k)}),Ht({payload:{eventData:y,tournamentId:c.tournamentId},topic:yP}),{...$,eventData:y}}const WF={getTournamentInfo:tu,getVenueData:Ju,getCourtInfo:FI,getAllEventData:jF,getEventData:jb,getDrawData:Vb,unPublishEventSeeding:VF,publishEventSeeding:$F,unPublishEvent:GF,publishEvent:fu,unPublishOrderOfPlay:Dy,publishOrderOfPlay:wy};function Gb({collectionPosition:t,teamParticipantId:e,dualMatchUpSide:n,drawDefinition:r,participantIds:s,collectionId:i}){var l;if(!i||!t||!Array.isArray(s))return{modifiedLineUp:(n==null?void 0:n.lineUp)||[],error:tt};const o=(n==null?void 0:n.lineUp)||((l=ba({participantId:e,drawDefinition:r}))==null?void 0:l.lineUp),c=[],a=[];return{modifiedLineUp:(o==null?void 0:o.map(f=>{var h;if(!s.includes(f.participantId))return f;const p=(h=f.collectionAssignments)==null?void 0:h.filter(d=>{const m=d.collectionId===i&&d.collectionPosition===t;return m&&(d.previousParticipantId&&c.push(d.previousParticipantId),a.push({participantId:f.participantId,...d})),!m});return{participantId:f.participantId,collectionAssignments:p}}).filter(Boolean))||[],assignmentsRemoved:a,previousParticipantIds:c}}function tm({tournamentRecord:t,drawDefinition:e,tieMatchUpId:n,event:r}){var E;if(!t)return{error:et};if(!e)return{error:Hn};if(!r)return{error:wn};const s=ln({drawDefinition:e}),{matchUp:i}=ie({matchUpId:n,drawDefinition:e,matchUpsMap:s});if(!i)return{error:Ye};const{matchUp:o,structure:c}=ie({tournamentParticipants:t.participants,matchUpId:n,inContext:!0,drawDefinition:e,matchUpsMap:s,event:r});if(!o)return{error:Ye};const{collectionPosition:a,drawPositions:u,collectionId:l,matchUpTieId:f,matchUpType:p}=o;if(p&&![Oe,me].includes(p))return{error:qn};const{positionAssignments:h}=ee({structure:c}),d=h==null?void 0:h.filter(y=>u==null?void 0:u.includes(y.drawPosition)),m=d==null?void 0:d.map(kn("participantId")),{tournamentParticipants:g}=dn({tournamentRecord:t,participantFilters:{participantTypes:[se],participantIds:m}}),{matchUp:I}=ie({matchUpId:f,drawDefinition:e,matchUpsMap:s}),{matchUp:S}=ie({matchUpId:f,inContext:!0,drawDefinition:e,matchUpsMap:s}),T=(E=hn({matchUp:I,drawDefinition:e,structure:c,event:r}))==null?void 0:E.tieFormat;return{inContextDualMatchUp:S,inContextTieMatchUp:o,relevantAssignments:d,collectionPosition:a,teamParticipants:g,collectionId:l,matchUpType:p,dualMatchUp:I,tieMatchUp:i,tieFormat:T,structure:c,...$}}function em(t){var B,R,x,q,V,Y,z,J,Q,X,Z,nt,rt;const e=tm(t);if(e.error)return e;const n="assignTieMatchUpParticipantId";let r=t.teamParticipantId;const{tournamentRecord:s,drawDefinition:i,participantId:o,event:c}=t;if(!o)return G({result:{error:Ce},stack:n});if(t.sideNumber&&![1,2].includes(t.sideNumber))return G({result:{error:rg},stack:n});const{inContextDualMatchUp:a,inContextTieMatchUp:u,relevantAssignments:l,collectionPosition:f,teamParticipants:p,collectionId:h,matchUpType:d,dualMatchUp:m,tieFormat:g}=e,I=(B=u==null?void 0:u.sides)==null?void 0:B.flatMap(K=>{var it,st;return((it=K.participant)==null?void 0:it.individualParticipantIds)||((st=K.participant)==null?void 0:st.participantId)||[]});if(I!=null&&I.includes(o))return G({result:{...$},stack:n});r=r||t.sideNumber&&((x=(R=a==null?void 0:a.sides)==null?void 0:R.find(K=>K.sideNumber===t.sideNumber))==null?void 0:x.participantId);const{tournamentParticipants:[S]}=dn({tournamentRecord:s,participantFilters:{participantIds:[o]}});if(!S)return G({result:{error:_e},stack:n});const{appliedPolicies:T}=ge({tournamentRecord:s,drawDefinition:i,event:c}),E=((q=t.policyDefinitions)==null?void 0:q[Jn])||(T==null?void 0:T[Jn])||iu[Jn];if((V=E==null?void 0:E.participants)!=null&&V.enforceGender&&[Se,Ne].includes(u==null?void 0:u.gender)&&(u==null?void 0:u.gender)!==((Y=S.person)==null?void 0:Y.sex))return{error:vu,info:"Gender mismatch"};const{individualParticipantIds:y,participantType:b}=S;if(d===Oe&&b!==xt)return{error:xr};const N=b===xt?[o]:y,A=r&&(p==null?void 0:p.find(({participantId:K})=>K===r))||(p==null?void 0:p.find(({individualParticipantIds:K})=>tn(N,K)));if(!A)return{error:yg};if(r||(r=A.participantId),!r)return{error:_e};const C=l==null?void 0:l.find(K=>K.participantId===(A==null?void 0:A.participantId)),v=C==null?void 0:C.drawPosition,P=(z=u==null?void 0:u.sides)==null?void 0:z.find(K=>K.drawPosition===v),U=t.sideNumber||(P==null?void 0:P.sideNumber);if(!g)return{error:Nu};if(!((J=g.collectionDefinitions)==null?void 0:J.find(K=>K.collectionId===h)))return{error:J1};if(!((Q=m==null?void 0:m.sides)!=null&&Q.length)){const{extension:K}=Ke({element:i,name:Wr}),it=pt((K==null?void 0:K.value)||{},!1,!0),st=({displaySideNumber:dt,drawPosition:mt,sideNumber:Mt})=>({drawPosition:mt,sideNumber:Mt,displaySideNumber:dt});m&&(m.sides=(X=a==null?void 0:a.sides)==null?void 0:X.map(dt=>{const mt=dt.participantId;return{...st(dt),lineUp:mt&&it[mt]||[]}}))}const D=(Z=m==null?void 0:m.sides)==null?void 0:Z.find(K=>K.sideNumber===U),M=(nt=u==null?void 0:u.sides)==null?void 0:nt.find(K=>K.sideNumber===U),w=(D==null?void 0:D.lineUp)||((rt=ba({participantId:r,drawDefinition:i}))==null?void 0:rt.lineUp),k=w==null?void 0:w.filter(K=>{var it;return(it=K.collectionAssignments)==null?void 0:it.find(st=>st.collectionPosition===f&&st.collectionId===h&&!st.previousParticipantId)}),_=k==null?void 0:k.map(K=>K==null?void 0:K.participantId),F=(_==null?void 0:_.length)>1&&_||(b===_t?S.individualParticipantIds:[o]),L=Gb({collectionPosition:f,teamParticipantId:r,dualMatchUpSide:D,drawDefinition:i,participantIds:F,collectionId:h});if(L.error)return G({result:L,stack:n});const{modifiedLineUp:W}=L;let j;if(d===me){if(b!==_t){let K=nm({collectionPosition:f,teamParticipantId:r,drawDefinition:i,modifiedLineUp:W,participantId:o,collectionId:h,tieFormat:g});if(K!=null&&K.error)return G({result:K,stack:n});if(K=H({side:M}),K.error)return K;j=K.deleteParticipantId,D&&(D.lineUp=W),m&&qt({tournamentId:s==null?void 0:s.tournamentId,matchUp:m,context:n,drawDefinition:i})}else if(b===_t)for(const K of F)nm({collectionPosition:f,teamParticipantId:r,drawDefinition:i,modifiedLineUp:W,participantId:K,collectionId:h,tieFormat:g})}else{const K=nm({collectionPosition:f,teamParticipantId:r,drawDefinition:i,modifiedLineUp:W,participantId:o,collectionId:h,tieFormat:g});if(K!=null&&K.error)return K}if(D&&(D.lineUp=W),m&&qt({tournamentId:s==null?void 0:s.tournamentId,matchUp:m,context:n,drawDefinition:i}),j){const{error:K}=Fc({participantIds:[j],tournamentRecord:s});K&&console.log("cleanup")}return{...$,modifiedLineUp:W};function H({side:K}){let it;if(K.participant){const st=K.participant.individualParticipantIds||[];if(st.filter(Boolean).length===1){const{participant:mt}=Jr({participantIds:st,tournamentRecord:s});st.push(o);const{participant:Mt}=Jr({participantIds:st,tournamentRecord:s});if(!Mt&&mt){mt.individualParticipantIds=st;const Nt=Xh({pairOverride:!0,tournamentRecord:s,participant:mt});if(Nt.error)return Nt}else it=mt==null?void 0:mt.participantId}}else{const dt=es({participant:{individualParticipantIds:[o],participantRole:fn,participantType:_t},pairOverride:!0,tournamentRecord:s});if(dt.error)return dt}return{...$,deleteParticipantId:it}}}function nm({collectionPosition:t,teamParticipantId:e,drawDefinition:n,modifiedLineUp:r,participantId:s,collectionId:i,tieFormat:o}){var l,f;const c=(l=ba({participantId:e,drawDefinition:n}))==null?void 0:l.lineUp,a=(f=r||c)==null?void 0:f.find(p=>(p==null?void 0:p.participantId)===s),u={collectionId:i,collectionPosition:t};if(a)a.collectionAssignments.push(u);else{const p={collectionAssignments:[u],participantId:s};r.push(p)}return Uc({participantId:e,lineUp:r,drawDefinition:n,tieFormat:o})}const HF="ASC",Wb="DESC";function Hb(t){var U,O,D;let{tieFormat:e}=t;const{useDefaultEventRanking:n,tournamentRecord:r,drawDefinition:s,scaleAccessor:i,singlesOnly:o,attach:c,event:a}=t;if((a==null?void 0:a.eventType)!==ds)return{error:ui};if(!r)return{error:et};if(!e&&!s)return{error:rr};if(e=e||((U=hn({drawDefinition:s,event:a}))==null?void 0:U.tieFormat),vn({tieFormat:e}).error)return{error:li};if(typeof i!="object"&&!n)return{error:tt,context:{scaleAccessor:i}};const u={},f=((s==null?void 0:s.entries)||a.entries).filter(M=>(M==null?void 0:M.entryStatus)===Ur).map(fe),{participants:p=[]}=Fi({withIndividualParticipants:!0,withScaleValues:!0,tournamentRecord:r}),h=p.filter(({participantId:M})=>f.includes(M)),d=M=>M===Ii?"rankings":"ratings",m=((O=a==null?void 0:a.category)==null?void 0:O.categoryName)||((D=a==null?void 0:a.category)==null?void 0:D.ageCategoryCode),{scaleName:g=m,scaleType:I=Ii,sortOrder:S,accessor:T}=i||{},E=d(I),y=(M,w)=>{var _,F,L;let k=(_=M[E])==null?void 0:_[w];if(!k&&n&&(k=(F=M[E])==null?void 0:F[gi]),Array.isArray(k)){const W=(L=k.find(j=>j.scaleName===g))==null?void 0:L.scaleValue;if(Me(W))return W;if(T&&typeof W=="object")return W[T]}return 0},b=(M,w,k)=>{const _=S===Wb?w:M,F=S===Wb?M:w;return y(_,k)-y(F,k)},N=(M,w)=>b(M,w,gi),A=(M,w)=>b(M,w,Tr),C=[],v=e.collectionDefinitions||[];for(const M of h){const w=M.individualParticipants.sort(N),k=o?w:M.individualParticipants.sort(A),_={};for(const L of v){const W=[],{collectionId:j,matchUpCount:H,matchUpType:B,gender:R}=L,x=B===gi;ht(0,H).forEach(q=>{const V=x?w:k,Y=q+1,z=[];ht(0,x?1:2).forEach(J=>{const Q=V.find(X=>{const Z=[Se,Ne].includes(R)&&R||R===hs&&[Se,Ne][J];return(!Z||Z===X.person.sex)&&!W.includes(X.participantId)}).participantId;Q&&(z.push(Q),W.push(Q),_[Q]||(_[Q]=[]),_[Q].push({collectionPosition:Y,collectionId:j}))}),x||C.push(z)})}const F=Object.keys(_).map(L=>({collectionAssignments:_[L],participantId:L}));u[M.participantId]=F}const P=[];for(const M of C){const{participant:w}=Jr({tournamentParticipants:p,participantIds:M});if(!w){const k={individualParticipantIds:M,participantRole:fn,participantType:_t};P.push(k)}}if(c){for(;P.length;)es({participant:P.pop(),tournamentRecord:r});ae({element:s,extension:{name:Wr,value:u}})}return{...$,lineUps:u,participantsToAdd:P}}function qb(t){const{matchUpFormat:e,matchUpStatus:n,winningSide:r,scoreString:s}=t;if(!s)return{outcome:{...fl,winningSide:r,matchUpStatus:n}};if(r&&![1,2,void 0].includes(r))return{error:tt,winningSide:r};const i=s&&vl({scoreString:s}),o={},c=gs({sets:i,matchUpFormat:e}),a=gs({sets:i,reversed:!0,matchUpFormat:e});return r===2?(o.scoreStringSide1=a,o.scoreStringSide2=c):(o.scoreStringSide1=c,o.scoreStringSide2=a),o.sets=vl({scoreString:o.scoreStringSide1}),bt({outcome:{matchUpStatus:n,winningSide:r,score:o}})}const qF={[ce]:2,[Fe]:1,[en]:1,[In]:1,[te]:4};function Yb(t){let{defaultWithScorePercent:e=2,winningSide:n}=t;const{matchUpStatusProfile:r=qF,matchUpFormat:s=Kn,pointsPerMinute:i=1,sideWeight:o=4}=t;if(!nr(s))return{error:Xm};if(typeof r!="object")return{error:tt};if(e>100&&(e=100),isNaN(e)||isNaN(i)||isNaN(o))return{error:tt};const c=Object.keys(r).filter(P=>Object.keys(DC).includes(P)&&P!==De);if(Object.keys(c).reduce((P,U)=>P+r[U],0)>100)return{error:tt,matchUpStatusProfile:r};const u=c.reduce((P,U)=>(P.pointer=P.pointer+r[U],P.valueMap.push([P.pointer,U]),P),{pointer:0,valueMap:[]}),l=Wn(1,100),f=(u.valueMap.find(P=>l<=P[0])||[100,De])[1],p={sets:[],scoreStringSide1:"",side2ScoreString:""};if([ce,te].includes(f)){n=n||Wn(1,2);const P={score:p,winningSide:n,matchUpStatus:f};if(!(f===te&&Wn(1,100)>100-e))return{outcome:P}}else if([Fe,en].includes(f))return{outcome:{score:p,matchUpStatus:f}};const h=yn(s),{bestOf:d,setFormat:m,finalSetFormat:g}=h||{},I=[],S=Wn(0,1),T=n?[n-1]:[...ht(0,o).map(()=>S),1-S],y=[In,te,us,mi].includes(f)&&(cn(ht(1,d))||1);let b;for(const P of ht(1,(d||0)+1)){const U=P===d,{set:O,incomplete:D,winningSideNumber:M}=YF({incomplete:y===P,matchUpStatus:f,pointsPerMinute:i,setFormat:U&&g||m,setNumber:P,weightedRange:T});if(I.push(O),D){b=M;break}if(Kh({matchUp:{score:{sets:I},matchUpFormat:s}}).calculatedWinningSide)break}const N=Kh({matchUp:{score:{sets:I},matchUpFormat:s}}),A=b?n||b:N.calculatedWinningSide,{score:C}=ty({score:{sets:I},winningSide:A,matchUpStatus:f});return{outcome:{score:C,winningSide:A,matchUpStatus:f}}}function YF({weightedRange:t=[0,1],pointsPerMinute:e,matchUpStatus:n,incomplete:r,setFormat:s,setNumber:i}){const o={setNumber:i},{setTo:c,tiebreakFormat:a,tiebreakAt:u,tiebreakSet:l,timed:f,minutes:p}=s,h=Wn(0,t.length-1),d=t[h];let m;if(f){const g=p*e,I=Math.round(g*.2),S=g+cn([1,-1])*I,T=T1(S,2),E=[T,S-T];d&&E.reverse(),m=t[h]+1;let y=E[0]>E[1]&&1||E[1]>E[0]&&2||0;if(r){const[A,C]=E;return Object.assign(o,{side1Score:A,side2Score:C}),We.includes(n)?{set:o,incomplete:r,winningSideNumber:m}:{set:o,incomplete:r}}y||(E[Wn(0,1)]+=1),y=E[0]>E[1]?1:2,y!==m&&E.reverse();const[b,N]=E;return Object.assign(o,{side1Score:b,side2Score:N,winningSide:m}),{set:o}}else{if(r)return o.side1Score=Wn(0,u),o.side2Score=Wn(0,u),We.includes(n)&&(m=t[h]+1),{set:o,incomplete:r,winningSideNumber:m};{const g=ht(1,c+1).map(N=>ht(0,c+2-N).map(()=>N)).flat(),I=g[Wn(0,g.length-1)],S=c&&FS({isSide1:!0,tiebreakAt:u,lowValue:I,setTo:c}),T=!S,E=t.length===1&&t[h]+1;if(!T){E?(S[0]>S[1]?1:2)!==E&&S.reverse():d&&S.reverse();const[N,A]=S;Object.assign(o,{side1Score:N,side2Score:A})}const y=gl({matchUpScoringFormat:{setFormat:s},setObject:o});let b;if(y.hasTiebreakCondition||T){const{NoAD:N,tiebreakTo:A}=a||l||{},C=ht(1,A+1).map(U=>ht(0,A+2-U).map(()=>U)).flat(),v=C[Wn(0,C.length-1)],P=dp({isSide1:!0,tiebreakNoAd:N,tiebreakTo:A,lowValue:v});if(P)if(T){const U=P[0]>P[1]?1:2;E?U!==E&&P.reverse():d&&P.reverse(),[o.side1TiebreakScore,o.side2TiebreakScore]=P,b=P[0]>P[1]&&1||P[1]>P[0]&&2||void 0}else y.leadingSide===2?[o.side1TiebreakScore,o.side2TiebreakScore]=P:[o.side2TiebreakScore,o.side1TiebreakScore]=P}o.winningSide=y.winningSide||y.leadingSide||E||b}}return{set:o}}function pu(t){var m,g,I;const{matchUpStatusProfile:e,completeAllMatchUps:n,randomWinningSide:r,tournamentRecord:s,completionGoal:i,drawDefinition:o,event:c}=t;if(!o)return{error:lt};const a=t.matchUpFormat||o.matchUpFormat||(c==null?void 0:c.matchUpFormat),u=o.structures.slice().sort(Pi);let l=0;const{matchUps:f,matchUpsMap:p}=xe({contextFilters:{stages:[It,Pt]},matchUpFilters:{matchUpTypes:[Jt],roundNumbers:[1]},inContext:!0,drawDefinition:o});if(f!=null&&f.length){const S=((m=c==null?void 0:c.category)==null?void 0:m.ageCategoryCode)||((g=c==null?void 0:c.category)==null?void 0:g.categoryName);if(S)Hb({singlesOnly:!0,tournamentRecord:s,drawDefinition:o,scaleAccessor:{scaleName:S,sortOrder:HF,scaleType:Ii},attach:!0,event:c});else{const T=(I=f[0])==null?void 0:I.structureId,{positionAssignments:E}=ee({drawDefinition:o,structureId:T});if(E!=null&&E.length){const{tournamentParticipants:y}=dn({participantFilters:{participantTypes:[Jt]},tournamentRecord:s}),b=N=>{const A=N.tieMatchUps.filter(({matchUpType:v})=>v===Oe),C=N.tieMatchUps.filter(({matchUpType:v})=>v===me);A.forEach((v,P)=>{const U=v.matchUpId;v.sides.forEach(O=>{const{drawPosition:D}=O,M=y==null?void 0:y.find(w=>{const{participantId:k}=w,_=E.find(F=>F.participantId===k);return(_==null?void 0:_.drawPosition)===D});if(M){const w=M.individualParticipantIds[P];em({teamParticipantId:M.participantId,participantId:w,tournamentRecord:s,drawDefinition:o,tieMatchUpId:U,event:c})}})}),C.forEach((v,P)=>{const U=v.matchUpId;v.sides.forEach(O=>{const{drawPosition:D}=O,M=y==null?void 0:y.find(w=>{const{participantId:k}=w,_=E.find(F=>F.participantId===k);return(_==null?void 0:_.drawPosition)===D});M&&M.individualParticipantIds.slice(P*2,P*2+2).forEach(k=>{em({teamParticipantId:M.participantId,participantId:k,tournamentRecord:s,drawDefinition:o,tieMatchUpId:U,event:c})})})})};f.forEach(b)}}}const h=typeof n=="string"&&n,d=h&&De;for(const S of u){if(l>=i)break;const{matchUps:T}=Qt({matchUpFilters:{matchUpTypes:[me,Oe]},afterRecoveryTimes:!1,tournamentRecord:s,inContext:!0,drawDefinition:o,matchUpsMap:p,structure:S,event:c}),E=T.filter(({winningSide:y})=>!y).sort(vo).map(Qe);for(const y of E){if(!isNaN(i)&&l>=i)break;const{matchUps:b}=Qt({matchUpFilters:{matchUpTypes:[me,Oe]},afterRecoveryTimes:!1,tournamentRecord:s,inContext:!0,drawDefinition:o,matchUpsMap:p,structure:S,event:c}),N=b.find(C=>C.matchUpId===y),A=[Fe,en].includes(N.matchUpStatus);if(N!=null&&N.readyToScore&&!A){const C=zF({winningSide:!r&&1,matchUpStatusProfile:e,tournamentRecord:s,drawDefinition:o,targetMatchUp:N,matchUpFormat:a,matchUpStatus:d,scoreString:h,event:c});if(C!=null&&C.error)return C;l+=1}}}return{...$,completedCount:l}}function zb(t){const{matchUpStatusCodes:e,policyDefinitions:n,tournamentRecord:r,drawDefinition:s,targetMatchUp:i,matchUpStatus:o,matchUpFormat:c,scoreString:a,winningSide:u,event:l}=t;if(!i||i.matchUpStatus===re)return;const{matchUpId:f}=i||{},{outcome:p}=qb({matchUpFormat:c,matchUpStatus:o,scoreString:a,winningSide:u});return e&&(p.matchUpStatusCodes=e),Qa({tournamentRecord:r,policyDefinitions:n,drawDefinition:s,matchUpFormat:c,matchUpId:f,outcome:p,event:l})}function zF(t){const{matchUpStatusProfile:e={},tournamentRecord:n,policyDefinitions:r,drawDefinition:s,matchUpStatus:i,matchUpFormat:o,targetMatchUp:c,scoreString:a,winningSide:u,event:l}=t;if(a||i)return zb(t);const{matchUpId:f}=c||{},{outcome:p}=Yb({matchUpStatusProfile:e,matchUpFormat:o,winningSide:u});return Qa({policyDefinitions:r,tournamentRecord:n,drawDefinition:s,matchUpFormat:o,matchUpId:f,outcome:p,event:l})}function KF({tournament:t}){if(!t)return{error:et};const{providerTournamentID:e,hostCountryCode:n,tournamentLevel:r,totalPrizeMoney:s,tournamentName:i,extensions:o,startDate:c,endDate:a}=t,u=Jh({hostCountryCode:n,tournamentLevel:r,totalPrizeMoney:s,tournamentName:i,tournamentId:e,extensions:o,startDate:c,endDate:a});u.events=[];for(const l of t.events||[]){const{extensions:f,ageCategory:p,discipline:h,eventType:d,eventId:m,gender:g,stages:I}=l,S={drawDefinitions:JF(I),category:{ageCategory:p},gender:["M",Se].includes(g)&&Se||["F",Ne].includes(g)&&Ne||void 0,eventType:["D",$n].includes(d)&&$n||["T",we].includes(d)?we:ls,extensions:f,discipline:h,eventId:m};u.events.push(S)}return{...$,tournamentRecord:u}}function JF(t){const e=[];for(const n of t||[]){const{stageType:r}=n,s=["M",It].includes(r)&&It||["Q",Pt].includes(r)&&Pt||["C",Re].includes(r)&&Re||["P",Ie].includes(r)&&Ie||void 0;for(const i of n.draws||[]){const{drawId:o,drawSize:c,matchUps:a}=i,u={stage:s,drawId:o,drawSize:c};e.push(u),console.log(a.map(({roundNumber:l,roundPosition:f})=>({roundNumber:l,roundPosition:f})),{draw:i,drawDefinition:u})}}return e}const QF={ABANDONED:"ABANDONED",ACTIVE:"ACTIVE",CANCELLED:"CANCELLED",COMPLETED:"COMPLETED",IN_PROGRESS:"IN_PROGRESS"};function ZF({tournamentRecord:t,status:e}){return t?e&&!Object.keys(QF).includes(e)?{error:tt,info:"Unknown status"}:(t.tournamentStatus=e,{...$}):{error:et}}function XF({tournamentRecord:t,onlineResource:e}){return t?e?(t.onlineResources||(t.onlineResources=[]),t.onlineResources.push(e),{...$}):{error:Tt}:{error:et}}function rm({tournamentRecord:t}){var s;if(!t)return{error:et};const e={positionsNoOutcomes:[],canBePruned:[],matchPlay:[],inactive:[],drawAnalysis:{}},n={};return((s=t.events)==null?void 0:s.map(i=>{const o=i.eventId;return n[o]=i,((i==null?void 0:i.drawDefinitions)||[]).map(c=>({drawDefinition:c,eventId:o}))}).flat().filter(Boolean)).forEach(({drawDefinition:i,eventId:o})=>{let c=0,a=0,u=0;const{allStructuresLinked:l}=$b({drawDefinition:i}),f=n[o],h=((i==null?void 0:i.structures)||[]).map(b=>{const{stage:N,stageSequence:A,structureId:C}=b,v=ao[N],{inContextStructureMatchUps:P}=qa({drawDefinition:i,structure:b,event:f}),U=P==null?void 0:P.filter(({winningSide:R})=>R),O=U.filter(Boolean).length||0;a+=O,u+=P.length-a;const D=Math.max(U.filter(({roundNumber:R})=>R===1).map(({roundPosition:R})=>R)),{positionAssignments:M}=ee({structure:b}),w=M==null?void 0:M.filter(({participantId:R})=>R);c+=(w==null?void 0:w.length)||0;const k=((M==null?void 0:M.length)||0)-((w==null?void 0:w.length)||0),{roundMatchUps:_,roundProfile:F,roundNumbers:L,maxMatchUpsCount:W}=Cn({matchUps:P}),j=F&&Object.keys(F).filter(R=>!F[R].inactiveRound).map(R=>parseInt(R)),H=F&&Object.keys(F).filter(R=>F[R].inactiveRound).map(R=>parseInt(R)),B=F&&Object.values(F).every(R=>R.inactiveRound);return{positionsAssignedCount:(w==null?void 0:w.length)||0,maxWinningSideFirstRoundPosition:D,unassignedPositionsCount:k,inactiveStructure:B,maxMatchUpsCount:W,inactiveRounds:H,roundMatchUps:_,activeRounds:j,roundNumbers:L,roundProfile:F,structureId:C,stageSequence:A,orderNumber:v,stage:N}}),d=h.find(b=>b.orderNumber===2&&b.stageSequence===1),m=h.filter(({inactiveStructure:b})=>!b).length,{links:g}=$a({drawDefinition:i,structureId:d.structureId}),I=vt(d.activeRounds[0])===1&&d.activeRounds.length===1&&m===1,S=h==null?void 0:h.every(({inactiveStructure:b})=>b),T=!g.length&&d.activeRounds.length&&(d.roundProfile[1].inactiveCount||d.inactiveRounds.length),E=i.drawId;c&&!a&&e.positionsNoOutcomes.push(E),S&&e.inactive.push(E),I&&e.matchPlay.push(E),T&&e.canBePruned.push(E);const y={matchUpsWithWinningSideCount:a,matchUpsNoOutcomeCount:u,positionsAssignedCount:c,allStructuresLinked:l,structuresData:h,inactiveDraw:S,isMatchPlay:I,drawId:E};e.drawAnalysis[E]=y}),{...$,drawsAnalysis:e}}function tL(t){var c,a,u,l,f;const e=(c=t.participants)==null?void 0:c.filter(({participantType:p})=>p===se),n=(e==null?void 0:e.length)===2,r=((a=t.events)==null?void 0:a.length)===1&&t.events[0],s=((u=r==null?void 0:r.drawDefinitions)==null?void 0:u.length)===1&&r.drawDefinitions[0],i=((l=s==null?void 0:s.structures)==null?void 0:l.length)===1&&s.structures[0],o=((f=i==null?void 0:i.positionAssignments)==null?void 0:f.length)===2;return!!(r.tieFormat&&n&&o)}function eL({tournamentRecord:t}){if(!t)return{error:et};const{drawsAnalysis:e}=rm({tournamentRecord:t}),n={isDual:tL(t),drawsAnalysis:e};return{...$,analysis:n}}function nL({tournamentRecord:t,promotionalName:e,tournamentName:n,formalName:r}){return t?(n&&(t.tournamentName=n),e&&(t.promotionalName=e),r&&(t.formalName=r),t.promotionalName===t.tournamentName&&delete t.promotionalName,t.formalName===t.tournamentName&&delete t.formalName,{...$}):{error:et}}function rL({tournamentRecord:t,notes:e}){return t?Kf({element:t,notes:e}):{error:et}}function sL({tournamentRecord:t,categories:e}){return t?(e=(e||[]).filter(n=>n.categoryName&&n.type),t.tournamentCategories=e,{...$}):{error:et}}function iL({tournamentRecord:t}){var i;if(!t)return{error:et};const{startDate:e,endDate:n}=t,r=ef(e,n),s=[];for(const o of t.venues||[])(i=o==null?void 0:o.courts)!=null&&i.length&&s.push(...o.courts);for(const o of s){const{startTime:c,endTime:a}=(o.dateAvailability||[]).reduce((l,f)=>{const p=jt(l.startTime),h=jt(l.endTime);return f.startTime&&jt(f.startTime)<p&&(l.startTime=f.startTime),f.endTime&&jt(f.endTime)>h&&(l.endTime=f.endTime),l},{startTime:"08:00",endTime:"18:00"}),u=r.map(l=>{var p;return((p=o.dateAvailability)==null?void 0:p.find(h=>h.date===l))||{date:l,startTime:c,endTime:a}});o.dateAvailability=u}return{...$}}function sm({tournamentRecord:t,startDate:e,endDate:n}){var i;if(!t)return{error:et};if(e&&!Vr.test(e)||n&&!Vr.test(n))return{error:bn};if(!e&&!n)return{error:sg};if(n&&e&&new Date(n)<new Date(e))return{error:tt};let r;(e&&t.startDate&&new Date(e)>new Date(t.startDate)||n&&t.endDate&&new Date(n)<new Date(t.endDate))&&(r=!0),e&&(t.startDate=e),n&&(t.endDate=n),e&&t.endDate&&new Date(e)>new Date(t.endDate)&&(t.endDate=e),n&&t.startDate&&new Date(n)<new Date(t.startDate)&&(t.startDate=n);const s=r&&((i=aL({tournamentRecord:t}))==null?void 0:i.unscheduledMatchUpIds);return iL({tournamentRecord:t}),Ht({topic:TP,payload:{startDate:e,endDate:n}}),{...$,unscheduledMatchUpIds:s}}function oL({tournamentRecord:t,startDate:e}){return sm({tournamentRecord:t,startDate:e})}function cL({tournamentRecord:t,endDate:e}){return sm({tournamentRecord:t,endDate:e})}function aL({tournamentRecord:t}){const e=He({tournamentRecord:t}).matchUps??[],n=t.startDate&&new Date(t.startDate),r=t.endDate&&new Date(t.endDate),s=[],i=[];for(const o of e){const{schedule:c,matchUpId:a}=o;if(c&&c.scheduledDate){const u=new Date(c.scheduledDate);(n&&u<n||r&&u>r)&&(i.push(a),s.includes(c.scheduledDate)||s.push(c.scheduledDate))}}return s.length&&!lh({scheduledDates:s,tournamentRecord:t}).clearedScheduleCount?{error:w1}:{unscheduledMatchUpIds:i}}const uL={analyzeTournament:eL,analyzeDraws:rm,addOnlineResource:XF,removeNotes:rU,addNotes:Kf,completeDrawMatchUps:pu,getRounds:tE,getProfileRounds:hh,setTournamentName:nL,setTournamentNotes:rL,setTournamentDates:sm,setTournamentEndDate:cL,setTournamentStartDate:oL,setTournamentCategories:sL,addTimeItem:Ha,addEventTimeItem:ii,addTournamentTimeItem:_s,addParticipantTimeItem:PT,addExtension:ae,addEventExtension:Yr,removeEventExtension:Yu,addTournamentExtension:Ti,removeTournamentExtension:Af,addParticipantExtension:lP,removeParticipantExtension:fP,addDrawDefinitionExtension:Nf,removeDrawDefinitionExtension:dP,setTournamentStatus:ZF,convertPointEight:KF};function lL({tournamentRecord:t}){if(!t)return{error:et};const e=[],{extension:n}=Bn({tournamentRecord:t,name:qr});n&&e.push({method:"addTournamentExtension",params:{extension:n}});const r=t.events||[];for(const s of r){const{eventId:i}=s,{extension:o}=Us({event:s,name:qr});o&&e.push({method:"addEventExtension",params:{eventId:i,extension:o}})}return{methods:e}}function dL({drawDefinition:t,courtDayDate:e,matchUpId:n}){return Qy({drawDefinition:t,courtDayDate:e,matchUpId:n})}function fL({tournamentRecord:t}){if(!t)return{error:et};const e=[],{extension:n}=Bn({name:Ji,tournamentRecord:t});n&&e.push({method:"addTournamentExtension",params:{extension:n}});const r=t.events||[];for(const s of r){const{eventId:i}=s,{extension:o}=Us({name:Ji,event:s});o&&e.push({params:{eventId:i,extension:o},method:"addEventExtension"})}return{methods:e}}function pL({scheduleAttributes:t=[Qs,oo,ga,Ia,Sa,zr,Xs,Os,Zs],tournamentRecord:e,drawDefinition:n,matchUpId:r}){var c,a;const s="clearMatchUpSchedule",i=n?(c=tr({matchUpFilters:{matchUpIds:[r]},inContext:!1,drawDefinition:n}).matchUps)==null?void 0:c[0]:(a=He({matchUpFilters:{matchUpIds:[r]},tournamentRecord:e,inContext:!1}).matchUps)==null?void 0:a[0];if(!i)return{error:Ye};const o=(i.timeItems||[]).filter(u=>(u==null?void 0:u.itemType)&&!t.includes(u==null?void 0:u.itemType));return i.timeItems=o,qt({tournamentId:e.tournamentId,context:s,drawDefinition:n,matchUp:i}),{...$}}const hL={allocateTeamMatchUpCourts:wl,addMatchUpCourtOrder:Pp,assignMatchUpCourt:Po,assignMatchUpVenue:bc,clearMatchUpSchedule:pL,addMatchUpScheduleItems:dy,addMatchUpScheduledDate:jp,addMatchUpScheduledTime:Gp,addMatchUpStartTime:fy,addMatchUpEndTime:py,addMatchUpStopTime:hy,addMatchUpResumeTime:my,addMatchUpOfficial:gy,getMatchUpFormatTiming:yf,modifyMatchUpFormatTiming:Vp,getModifiedMatchUpFormatTiming:ry,getEventMatchUpFormatTiming:_y,modifyEventMatchUpFormatTiming:iy,removeEventMatchUpFormatTiming:Ky,getMatchUpFormatTimingUpdate:lL,getMatchUpDependencies:fr,getMatchUpDailyLimits:Yy,setMatchUpDailyLimits:Sy,getMatchUpDailyLimitsUpdate:fL,validateSchedulingProfile:td,setSchedulingProfile:lk,getSchedulingProfile:od,removeMatchUpCourtAssignment:dL,clearScheduledMatchUps:lh,bulkScheduleMatchUps:OT,bulkRescheduleMatchUps:Iy};function mL({tournamentRecord:t,categoryName:e,categoryType:n}){if(!t)return{error:et};const{appliedPolicies:r}=ge({tournamentRecord:t}),s=r==null?void 0:r[Xo];return((s==null?void 0:s.matchUpFormats)||[]).filter(({categoryNames:o,categoryTypes:c})=>!e&&!c||e&&(o==null?void 0:o.includes(e))||n&&(c==null?void 0:c.includes(n)))}function Kb({tournamentRecord:t,categoryName:e,categoryType:n}){if(!t)return{error:et};const{appliedPolicies:r}=ge({tournamentRecord:t}),s=r==null?void 0:r[pf];return((s==null?void 0:s.allowedDrawTypes)||[]).filter(({categoryNames:o,categoryTypes:c})=>!e&&!c||e&&(o==null?void 0:o.includes(e))||n&&(c==null?void 0:c.includes(n)))}function Jb({policyDefinitions:t,drawDefinition:e,drawSize:n,drawId:r,event:s,stage:i}){if(!s)return{error:Wt};const{entries:o,stageEntries:c}=ub({drawDefinition:e,drawId:r,stage:i,event:s}),a=c.length,{drawSize:u}=Bh({participantsCount:a}),l=xh({drawSize:n??u,participantsCount:a,policyDefinitions:t});if(l.error)return G({result:l,stack:"getEntriesAndSeedsCount"});const{seedsCount:f}=l;return{entries:o,seedsCount:f,stageEntries:c}}const gL={attachPolicies:gh,attachEventPolicies:nE,removeEventPolicy:Bw,findPolicy:Xi,getSeedsCount:xh,getEntriesAndSeedsCount:Jb,getAllowedDrawTypes:Kb,getAllowedMatchUpFormats:mL,getAppliedPolicies:ge};function yd({participant:t,eventType:e}){var u,l,f,p,h,d;const n=(u=t==null?void 0:t.person)==null?void 0:u.personId,r=(f=(l=t==null?void 0:t.person)==null?void 0:l.personOtherIds)==null?void 0:f[0],s=(p=t==null?void 0:t.person)==null?void 0:p.tennisId,i=(d=(h=t==null?void 0:t.ratings)==null?void 0:h[e])==null?void 0:d.find(({scaleName:m})=>m===BS),o=i==null?void 0:i.scaleValue,{wtnRating:c,confidence:a}=o||{};return{timeStamp:i==null?void 0:i.scaleDate,personOtherId:r,confidence:a,wtnRating:c,personId:n,tennisId:s}}function IL({tournamentRecord:t}){if(!t)return{error:et};const e=t.tournamentId,{participantMap:n}=Fi({withScaleValues:!0,withEvents:!0,withSeeding:!0,tournamentRecord:t,withDraws:!0}),s=(He({matchUpFilters:{matchUpTypes:[gi,Tr]},tournamentRecord:t}).matchUps??[]).flatMap(({sides:d,matchUpType:m})=>d==null?void 0:d.flatMap(g=>{var I,S;return m===Tr?(I=g.participant)==null?void 0:I.individualParticipantIds:((S=g.participant)==null?void 0:S.participantId)||g.participantId}).filter(Boolean)).filter(Boolean),i=[],o={},c={},a={};let u=0;const l=({id:d,entry:m,eventId:g,eventType:I})=>{var P;const{qualifyingSeeding:S,mainSeeding:T,entryStatus:E,entryStage:y,drawId:b}=m;o[d]||(o[d]=[]);const{participant:N,events:A}=(n==null?void 0:n[d])??{},C=yd({participant:N,eventType:I}),v=(P=A==null?void 0:A[g])==null?void 0:P.ranking;E===oT&&i.push(d),o[d].push({participantType:N==null?void 0:N.participantType,participantId:d,tournamentId:e,eventType:I,eventId:g,drawId:b,entryStatus:E,entryStage:y,...C,ranking:v,mainSeeding:T,qualifyingSeeding:S})};for(const d of t.events??[]){const m={},g=C=>{m[C]||(m[C]={count:0}),m[C].count+=1},{drawDefinitions:I=[],eventType:S,eventId:T}=d,E=I.flatMap(C=>{const{drawId:v,entries:P}=C;u+=1;const U=({stage:k,stageSequence:_})=>k===It&&_===1||k===Pt,D=(C.structures??[]).filter(U).flatMap(({positionAssignments:k})=>k).map(({participantId:k})=>k).filter(Boolean),M=({participantId:k})=>D.includes(k),w=k=>{var H,B,R,x,q,V,Y,z;const{participantId:_,entryStatus:F,entryStage:L}=k;g(F);const W=(x=(R=(B=(H=n==null?void 0:n[_])==null?void 0:H.draws)==null?void 0:B[v])==null?void 0:R.seedAssignments)==null?void 0:x[It];return{qualifyingSeeding:(z=(Y=(V=(q=n==null?void 0:n[_])==null?void 0:q.draws)==null?void 0:V[v])==null?void 0:Y.seedAssignments)==null?void 0:z[Pt],participantId:_,mainSeeding:W,entryStatus:F,entryStage:L,drawId:v}};return P==null?void 0:P.filter(M).map(w)}),y=C=>{var U;const v=C.participantId,P=(U=n==null?void 0:n[v].participant.individualParticipantIds)==null?void 0:U.filter(O=>s.includes(O));return v&&{[v]:{individualParticipantIds:P}}};S===Zu?(()=>{const C=Object.assign({},...E.map(y).filter(Boolean)),v=P=>{C[P.participantId].individualParticipantIds.forEach(U=>{l({id:U,eventType:S,eventId:T,entry:P})})};E.forEach(v)})():E.forEach(C=>{l({id:C==null?void 0:C.participantId,eventType:S,eventId:T,entry:C})});const N=Object.values(m).reduce((C,v)=>C+v.count,0);Object.keys(m).forEach(C=>{m[C].pct=m[C].count/N*100}),a[T]={tournamentId:e,eventId:T,entries:E,entryStatuses:m};const A=Object.assign({},...ps.flatMap(C=>{var v,P;return[{[C+"_count"]:(v=m[C])==null?void 0:v.count},{[C+"_pct"]:(P=m[C])==null?void 0:P.pct}]}));c[T]={tournamentId:e,eventId:T,...A}}const f=Object.values(n??{}).filter(({participant:{participantType:d,participantRole:m}})=>d===xt&&m===fn),h={nonParticipatingEntriesCount:f.filter(({participant:d})=>!s.includes(d.participantId)).map(({participant:d})=>d.participantId).length,individualParticipantsCount:f.length,eventsCount:Object.values(a).length,drawDefinitionsCount:u,tournamentId:e};return{entryStatusReports:Object.values(c).flat(),participantEntryReports:Object.values(o).flat(),eventReports:Object.values(a).flat(),withDrawnParticipantIds:i,tournamentEntryReport:h}}function SL({eventType:t,matchUps:e,eventId:n,drawId:r}){const s={},i=m=>{const g=m==null?void 0:m.matchUpFormat;g&&(s[g]||(s[g]=0),s[g]+=1)},o=e.filter(m=>n?m.eventId===n:m.drawId===r).reduce((m,g)=>(i(g),(g.sides??[]).flatMap(I=>{var S;return(((S=I==null?void 0:I.participant)==null?void 0:S.individualParticipants)||[I==null?void 0:I.participant]).filter(Boolean)}).forEach(I=>m[I.participantId]=I),m),{}),c=Object.values(o),a=c.map(m=>yd({participant:m,eventType:t})).filter(({wtnRating:m})=>m),u=(c.length-a.length)/c.length*100,l=a.reduce((m,g)=>{const{wtnRating:I,confidence:S}=g;return m.totalWTN+=I,m.totalConfidence+=S,m},{totalWTN:0,totalConfidence:0}),f=a!=null&&a.length?l.totalWTN/a.length:0,p=a!=null&&a.length?l.totalConfidence/a.length:0,d=Object.values(s).reduce((m,g)=>m+(g||0),0);return{matchUpFormatCounts:s,matchUpsCount:d,avgConfidence:p,pctNoRating:u,avgWTN:f}}function TL({firstFlightOnly:t=!0,extensionProfiles:e,tournamentRecord:n}){var l;if(!n)return{error:is};const r={},s=Object.assign({},...(e??[]).map(({name:f,label:p,accessor:h})=>{var g,I,S;const d=(I=(g=Bn({tournamentRecord:n,name:f}))==null?void 0:g.extension)==null?void 0:I.value,m=h?(S=Yi({element:d,accessor:h}))==null?void 0:S.value:d;return{[p||f]:m}})),i=n==null?void 0:n.tournamentId,c=He({participantsProfile:{withScaleValues:!0},tournamentRecord:n}).matchUps??[],a=f=>{var h,d;const p=(h=kr({itemType:EI,itemSubTypes:[br],element:{timeItems:f}}))==null?void 0:h.timeItem;return(d=p==null?void 0:p.itemValue)==null?void 0:d.scaleBasis},u=(l=n==null?void 0:n.events)==null?void 0:l.flatMap(({timeItems:f,drawDefinitions:p=[],extensions:h,eventType:d,eventId:m,category:g})=>{var A,C,v,P;const I=h==null?void 0:h.find(U=>U.name===ar),S=(C=(A=I==null?void 0:I.value)==null?void 0:A.flights)==null?void 0:C.map(U=>({[U.drawId]:U.flightNumber})),T=S&&Object.assign({},...S),E=((P=(v=h==null?void 0:h.find(U=>U.name===ju))==null?void 0:v.value)==null?void 0:P.length)||0,y=Object.values(T),b=T&&Math.min(...y),N=a(f);return r[m]={totalPositionManipulations:0,maxPositionManipulations:0,generatedDrawsCount:0,drawDeletionsCount:E,seedingBasis:N?JSON.stringify(N):void 0,tournamentId:i,eventId:m},p.filter(U=>!t||!S||T[U.drawId]===b).flatMap(U=>{const{matchUpFormat:O,tieFormat:D,timeItems:M,extensions:w,structures:k,drawType:_,drawId:F}=U,{matchUpFormatCounts:L,matchUpsCount:W,avgConfidence:j,pctNoRating:H,avgWTN:B}=SL({eventType:d,matchUps:c,drawId:F}),R=a(M)||N,x=yL({extensions:w}),q=(x==null?void 0:x.length)||0;return r[m].totalPositionManipulations+=q,r[m].generatedDrawsCount+=1,q>r[m].maxPositionManipulations&&(r[m].maxPositionManipulations=q),k==null?void 0:k.filter(V=>V.stageSequence===1&&[Pt,It,Re,Ie].includes(V.stage)).map(V=>{var Ut,Kt;const Y=[It,Ie].includes(V.stage)?c.find(ut=>ut.structureId===V.structureId&&ut.finishingRound===1&&ut.winningSide):void 0,z=(Ut=Y==null?void 0:Y.sides)==null?void 0:Ut.find(ut=>ut.sideNumber===Y.winningSide),J=z==null?void 0:z.participant,Q=(J==null?void 0:J.participantType)===vr&&J.participantId,X=(J==null?void 0:J.participantType)===_t?J.individualParticipants:[],Z=yd({participant:(X==null?void 0:X[0])||J,eventType:d}),{personId:nt,personOtherId:rt,tennisId:K,confidence:it,wtnRating:st}=Z||{},dt=yd({participant:X==null?void 0:X[1],eventType:d}),{personId:mt,personOtherId:Mt,tennisId:Nt,confidence:St,wtnRating:ct}=dt||{},{ageCategoryCode:Et,categoryName:gt,subType:Ft}=g??{},yt=V.matchUpFormat||O,Xt=(L[yt]||0)/W*100,{tieFormatName:$t,tieFormatDesc:At}=Nl(D),{tieFormatName:Dt,tieFormatDesc:at}=Nl(V.tieFormat),ot=At===at,Lt=!ot&&Dt,ft=V.tieFormat&&!ot&&at,Ct=((Kt=x==null?void 0:x.filter(ut=>ut.structureId===V.structureId))==null?void 0:Kt.length)||0;return{...s,tournamentId:i,eventId:m,structureId:V.structureId,drawId:F,eventType:d,category:Ft,categoryName:gt,ageCategoryCode:Et,flightNumber:T[F],drawType:_,stage:V.stage,seedingBasis:R?JSON.stringify(R):void 0,winningPersonId:nt,winningPersonOtherId:rt,winningPersonTennisId:K,winningPersonWTNrating:st,winningPersonWTNconfidence:it,winningPerson2Id:mt,winningPerson2OtherId:Mt,winningPerson2TennisId:Nt,winningPerson2WTNrating:ct,winningPerson2WTNconfidence:St,winningTeamId:Q,positionManipulations:Ct,pctNoRating:H,matchUpFormat:yt,pctInitialMatchUpFormat:Xt,matchUpsCount:W,drawTieFormatName:$t,drawTieFormatDesc:At,tieFormatName:Lt,tieFormatDesc:ft,avgConfidence:j,avgWTN:B}})})});return{eventStructureReports:Object.values(r),structureReports:u}}function yL({extensions:t}){var e,n;return(n=(e=t==null?void 0:t.find(({name:r})=>r===xu))==null?void 0:e.value)==null?void 0:n.slice(1)}const EL={getStructureReports:TL,getEntryStatusReports:IL};function bL({representativeParticipantIds:t,drawDefinition:e}){if(!e)return{error:rr};if(!Array.isArray(t))return{error:tt};const n=xa((e==null?void 0:e.entries)||[]);return t.length&&qe(t,n).length<t.length?{error:tt}:Nf({drawDefinition:e,extension:{name:gf,value:t}})}function NL({drawDefinition:t}){var r;const e=Hu({name:"participantRepresentatives",drawDefinition:t});return e.error?e:{representativeParticipantIds:((r=e.extension)==null?void 0:r.value)||[]}}function AL({tournamentRecord:t,drawDefinition:e,participantId:n,sideNumber:r,matchUpId:s,event:i}){var l,f;if(n&&typeof n!="string")return{error:bs};if(!e)return{error:lt};if(!s)return{error:$e};const o=r===void 0;if(o&&(r=1),![1,2].includes(r))return{error:tt,sideNumber:r};const{matchUp:c,structure:a}=ie({drawDefinition:e,matchUpId:s,event:i});if(!c)return{error:Ye};if(!(!(a!=null&&a.structures)&&!(e.drawType&&e.drawType!==Xn)&&!((l=a==null?void 0:a.matchUps)!=null&&l.find(({roundPosition:p})=>!!p))))return{error:Bd};if(!n&&((f=c==null?void 0:c.score)!=null&&f.scoreStringSide1||We.includes(c==null?void 0:c.matchUpstatus)||c!=null&&c.matchUpStatus&&[Fe,en].includes(c.matchUpStatus)))return{error:qd,info:"matchUp has completed status or score"};if(c){if(c.sides=[1,2].map(p=>{var d;const h=((d=c.sides)==null?void 0:d.find(m=>m.sideNumber===p))||{sideNumber:p};return r===p?{...h,participantId:n}:h}),o)for(const p of c.sides)p.sideNumber&&(p.sideNumber=3-p.sideNumber);qt({tournamentId:t==null?void 0:t.tournamentId,context:"assignSideParticipant",drawDefinition:e,matchUp:c})}return{...$,sidesSwapped:o}}function vL({tournamentRecord:t,drawDefinition:e,sideNumber:n,matchUpId:r,event:s}){var a,u;if(!t)return{error:et};if(!e)return{error:lt};if(!r)return{error:$e};if(!n)return{error:Tt};if(![1,2].includes(n))return{error:tt,sideNumber:n};const{matchUp:i,structure:o}=ie({drawDefinition:e,matchUpId:r,event:s});return i?!(o!=null&&o.structures)&&!(e.drawType&&e.drawType!==Xn)&&!((a=o==null?void 0:o.matchUps)!=null&&a.find(({roundPosition:l})=>!!l))?((u=i.sides)==null||u.forEach(l=>{l.sideNumber===n&&delete l.participantId}),qt({tournamentId:t==null?void 0:t.tournamentId,context:"assignSideParticipant",drawDefinition:e,matchUp:i}),{...$}):{error:Bd}:{error:Ye}}function Qb(t){var W,j,H,B,R,x,q,V,Y,z,J,Q,X,Z,nt;const e=tm(t);if(e.error)return e;const n="replaceTieMatchUpParticipantid",{existingParticipantId:r,tournamentRecord:s,newParticipantId:i,drawDefinition:o,substitution:c,event:a}=t;if(!r||!i)return G({result:{error:Ce},stack:n});if(r===i)return{...$};const{inContextDualMatchUp:u,inContextTieMatchUp:l,collectionPosition:f,collectionId:p,dualMatchUp:h,tieMatchUp:d,tieFormat:m}=e,g=l==null?void 0:l.matchUpType,I=(W=l==null?void 0:l.sides)==null?void 0:W.find(rt=>{var K,it,st;return((K=rt.participant)==null?void 0:K.participantId)===r||((st=(it=rt.participant)==null?void 0:it.individualParticipantIds)==null?void 0:st.includes(r))});if(!I)return{error:_e};const{tournamentParticipants:S}=dn({tournamentRecord:s,participantFilters:{participantIds:[r,i]}});if(S.length!==2)return G({result:{error:Ce},stack:n});if(S[0].participantType!==S[1].participantType)return G({result:{error:xr},stack:n});const{appliedPolicies:T}=ge({tournamentRecord:s,drawDefinition:o,event:a}),E=(T==null?void 0:T[Jn])||iu[Jn],y=S.find(({participantId:rt})=>rt===i);if((j=E==null?void 0:E.participants)!=null&&j.enforceGender&&[Se,Ne].includes(l==null?void 0:l.gender)&&(l==null?void 0:l.gender)!==((H=y.person)==null?void 0:H.sex))return{error:vu,info:"Gender mismatch"};const b=(B=E==null?void 0:E.processCodes)==null?void 0:B.substitution,{extension:N}=Ke({element:o,name:Wr}),A=(N==null?void 0:N.value)||{};if(!((R=h==null?void 0:h.sides)!=null&&R.length)){const rt=({displaySideNumber:K,drawPosition:it,sideNumber:st})=>({drawPosition:it,sideNumber:st,displaySideNumber:K});h&&(h.sides=(x=u==null?void 0:u.sides)==null?void 0:x.map(K=>{const it=K.participantId;return{...rt(K),lineUp:it&&A[it]||[]}}))}const C=(q=h==null?void 0:h.sides)==null?void 0:q.find(({sideNumber:rt})=>rt===I.sideNumber);if(!C)return G({result:{sideNumber:I.sideNumber,existingParticipantId:r,error:an},stack:n});const v=(V=l==null?void 0:l.sides)==null?void 0:V.flatMap(rt=>{var K,it;return((K=rt.participant)==null?void 0:K.individualParticipantIds)||((it=rt.participant)==null?void 0:it.participantId)||[]});if(v!=null&&v.includes(i))return G({result:{error:Yd},stack:n});const P=(z=(Y=u==null?void 0:u.sides)==null?void 0:Y.find(({sideNumber:rt})=>rt===I.sideNumber))==null?void 0:z.participantId,U=C.lineUp,O=U==null?void 0:U.find(({participantId:rt})=>i===rt),D=U==null?void 0:U.reduce((rt,K)=>K.substitutionOrder>rt?K.substitutionOrder:rt,0),M=(U==null?void 0:U.map(rt=>{var it;const K=pt(rt,!1,!0);if(![r,i].includes(K.participantId))return K;if(!c&&[r,i].includes(K.participantId)&&(K.collectionAssignments=(it=K.collectionAssignments)==null?void 0:it.filter(st=>!(st.collectionPosition===f&&st.collectionId===p))),c&&r===K.participantId&&(K.collectionAssignments=K.collectionAssignments.map(st=>st.collectionPosition===f&&st.collectionId===p&&st.substitutionOrder===void 0?{...st,substitutionOrder:D}:st)),K.participantId===i){K.collectionAssignments||(K.collectionAssignments=[]);const st={collectionId:p,collectionPosition:f};c&&(st.previousParticipantId=r,st.substitutionOrder=(D||0)+1),K.collectionAssignments.push(st)}return K}))||[];if(!O){const rt={collectionId:p,collectionPosition:f};c&&(rt.substitutionOrder=(D||0)+1,rt.previousParticipantId=r);const K={collectionAssignments:[rt],participantId:i};M.push(K)}const w=g===me,{assignedParticipantIds:k}=Xu({lineUp:U,collectionPosition:f,collectionId:p}),{assignedParticipantIds:_}=Xu({lineUp:M,collectionPosition:f,collectionId:p});if(C.lineUp=M,P&&m){const rt=Uc({participantId:P,lineUp:M,drawDefinition:o,tieFormat:m});if(rt.error)return G({result:rt,stack:n})}else console.log("team participantId not found");let F,L;if(w){const{tournamentRecord:rt}=t;let K=Jr({participantIds:_,tournamentRecord:rt});if(!K.participant){const dt=es({returnParticipant:!0,pairOverride:!0,tournamentRecord:rt,participant:{participantRole:fn,individualParticipantIds:_,participantType:_t}});if(dt.error)return G({result:dt,stack:n});F=(J=dt.participant)==null?void 0:J.participantId}K=Jr({participantIds:k,tournamentRecord:rt});const it=(Q=K.participant)==null?void 0:Q.participantId;it&&Fc({participantIds:[it],tournamentRecord:rt}).success&&(L=it)}if(c||((X=I.substitutions)==null?void 0:X.length)===1){if(c){const rt=(d==null?void 0:d.processCodes)||[];b&&rt.push(...b),d&&(d.processCodes=rt)}else for(const rt of b||[]){const K=(Z=d==null?void 0:d.processCodes)==null?void 0:Z.lastIndexOf(rt);K!==void 0&&((nt=d==null?void 0:d.processCodes)==null||nt.splice(K,1))}d&&qt({tournamentId:s==null?void 0:s.tournamentId,matchUp:d,context:n,drawDefinition:o})}return h&&qt({tournamentId:s==null?void 0:s.tournamentId,matchUp:h,context:n,drawDefinition:o}),{...$,modifiedLineUp:M,participantRemoved:L,participantAdded:F}}function CL(t){var P,U,O,D,M,w,k,_,F,L,W,j,H,B,R;const{tournamentRecord:e,drawDefinition:n,participantId:r,event:s}=t,i="removeTieMatchUpParticiapantId";if(!r)return G({result:{error:Ce},stack:i});const o=tm(t);if(o.error)return o;const{appliedPolicies:c}=ge({tournamentRecord:e,drawDefinition:n,event:s}),a=(c==null?void 0:c[Jn])||iu[Jn],u=(P=a==null?void 0:a.processCodes)==null?void 0:P.substitution,{inContextDualMatchUp:l,inContextTieMatchUp:f,relevantAssignments:p,collectionPosition:h,teamParticipants:d,collectionId:m,matchUpType:g,dualMatchUp:I,tieMatchUp:S,tieFormat:T}=o;if(!I)return{error:Rn};const E=(U=f==null?void 0:f.sides)==null?void 0:U.find(x=>{var q,V,Y;return((q=x.participant)==null?void 0:q.participantId)===r||((Y=(V=x.participant)==null?void 0:V.individualParticipantIds)==null?void 0:Y.includes(r))});if(!E)return{error:_e};if(!((O=E.substitutions)!=null&&O.length)&&(Be({score:f==null?void 0:f.score})||f!=null&&f.winningSide))return{error:_v};const y=(M=(D=l==null?void 0:l.sides)==null?void 0:D.find(({sideNumber:x})=>x===E.sideNumber))==null?void 0:M.participantId;if(!y)return{error:_e};const{tournamentParticipants:[b]}=dn({tournamentRecord:e,participantFilters:{participantIds:[r]}});if(!b)return{error:_e};if(g===Oe&&b.participantType===_t)return{error:vu};const N=b.participantType===xt?[r]:b.individualParticipantIds;if(!((w=I==null?void 0:I.sides)!=null&&w.length)){const{extension:x}=Ke({element:n,name:Wr}),q=(x==null?void 0:x.value)||{},V=({displaySideNumber:Y,drawPosition:z,sideNumber:J})=>({drawPosition:z,sideNumber:J,displaySideNumber:Y});I.sides=(k=l==null?void 0:l.sides)==null?void 0:k.map(Y=>{const z=Y.participantId;return{...V(Y),lineUp:z&&q[z]||[]}})}let A=(_=I.sides)==null?void 0:_.find(({sideNumber:x})=>x===E.sideNumber);if(!A&&(((F=I.sides)==null?void 0:F.filter(({lineUp:x})=>!x).length)||0)<2){const x=d==null?void 0:d.map(({participantId:q})=>{var V;return{drawPosition:(V=p==null?void 0:p.find(Y=>Y.participantId===q))==null?void 0:V.drawPosition,teamParticipantId:q}});A=(L=I.sides)==null?void 0:L.find(q=>{var V;return((V=x==null?void 0:x.find(({drawPosition:Y})=>Y===q.drawPosition))==null?void 0:V.teamParticipantId)===y})}if(!A)return console.log({teamParticipantId:y,teamParticipants:d}),{error:_e,participantId:r};const{modifiedLineUp:C,previousParticipantIds:v}=Gb({collectionPosition:h,teamParticipantId:y,dualMatchUpSide:A,participantIds:N,drawDefinition:n,collectionId:m});if(A.lineUp=C,y&&T&&Uc({participantId:y,lineUp:C,drawDefinition:n,tieFormat:T}),g===me&&b.participantType===xt){const x=(W=f==null?void 0:f.sides)==null?void 0:W.find(Y=>Y.sideNumber===(A==null?void 0:A.sideNumber)),{participantId:q}=x||{},{tournamentParticipants:[V]}=dn({tournamentRecord:e,participantFilters:{participantIds:[q]},withEvents:!0});if(V){const Y=V==null?void 0:V.individualParticipantIds.filter(z=>z!==r);if(v&&Y.push(...v),Y.length>2)return{error:gr};if(V.draws.length){if(Y.length===1){const{participant:z}=Jr({participantIds:Y,tournamentRecord:e});if(!z){const Q=es({participant:{participantRole:fn,individualParticipantIds:Y,participantType:_t},pairOverride:!0,tournamentRecord:e});if(Q.error)return Q}}}else if(Y.length){V.individualParticipantIds=Y;const z=Xh({participant:V,pairOverride:!0,tournamentRecord:e});if(z.error)return z}else{const z=Fc({participantIds:[q],tournamentRecord:e});z.error&&console.log("cleanup",{result:z})}}else return{error:_e}}if(((j=E.substitutions)==null?void 0:j.length)===1){const x=(H=f==null?void 0:f.sides)==null?void 0:H.find(q=>q.sideNumber!==E.sideNumber);if(!((B=x==null?void 0:x.substitutions)!=null&&B.length)&&((R=S==null?void 0:S.processCodes)!=null&&R.length)){for(const q of u||[]){const V=S.processCodes.lastIndexOf(q);S.processCodes.splice(V,1)}qt({tournamentId:e==null?void 0:e.tournamentId,matchUp:S,context:i,drawDefinition:n})}}return qt({tournamentId:e==null?void 0:e.tournamentId,matchUp:I,context:i,drawDefinition:n}),{...$,modifiedLineUp:C}}function im({tournamentRecord:t,drawDefinition:e,stage:n=It,structureId:r,structure:s}){var c;if(!t)return{error:et};if(!s&&!e)return{error:lt};if(!s&&!r&&((c=e==null?void 0:e.structures)==null?void 0:c.filter(a=>a.stage===n).length)===1&&(s=e.structures.find(a=>a.stage===n)),!s&&!r)return{error:En};const{error:i,positionAssignments:o}=ee({drawDefinition:e,structureId:r,structure:s});return{error:i,positionAssignments:o||[],structureId:s==null?void 0:s.structureId}}function om({autoPublish:t=!0,policyDefinitions:e,tournamentRecord:n,drawIds:r=[],auditData:s,eventId:i,event:o}){var E,y,b;if(!n)return{error:et};const c="deleteDrawDefinitions";if(!e){const{appliedPolicies:N}=ge({tournamentRecord:n,event:o});e=N}const a=Array.isArray(r)?r[0]:void 0;if(!o){const N=Je({tournamentRecord:n,eventId:i,drawId:a});if(N.error)return N;o=N.event}const u=[],l=[],f=[];if(!(o!=null&&o.drawDefinitions))return G({result:{...$},info:"event has no drawDefinition",stack:c});const p=o.drawDefinitions.map(({drawId:N})=>N);if(r.length||(r=p),r=r.filter(N=>p.includes(N)),!r.length)return G({result:{...$},info:"nothing to do; no matching drawIds in event.",stack:c});const h=pt(be({event:o}).flightProfile,!1,!0),d=({participantId:N,drawPosition:A,qualifier:C,bye:v})=>({bye:v,qualifier:C,drawPosition:A,participantId:N}),m=o.drawDefinitions.filter(N=>{var A,C,v,P,U,O;if(r.includes(N.drawId)){const{drawId:D,drawType:M,drawName:w}=N,k=(A=h==null?void 0:h.flights)==null?void 0:A.find(R=>R.drawId===N.drawId);k&&(k.drawEntries=(C=k.drawEntries)==null?void 0:C.filter(R=>tS.includes(R.entryStatus)));const _=(P=(v=lr({stageSequence:1,drawDefinition:N,stage:It}))==null?void 0:v.structures)==null?void 0:P[0],F=_?im({structureId:_.structureId,tournamentRecord:n,drawDefinition:N}):void 0,L=(U=F==null?void 0:F.positionAssignments)==null?void 0:U.map(d),W=(O=lr({stage:Pt,drawDefinition:N}))==null?void 0:O.structures,j=W!=null&&W.length?W.map(R=>{const x=R.stageSequence,q=im({structureId:R.structureId,tournamentRecord:n,drawDefinition:N});return{positionAssignments:q==null?void 0:q.positionAssignments.map(d),stageSequence:x}}):void 0,H={action:aw,payload:{drawDefinitions:[N],eventId:i||(o==null?void 0:o.eventId),auditData:s}};f.push(H),u.push(bt({tournamentId:n.tournamentId,eventId:i||(o==null?void 0:o.eventId),qualifyingPositionAssignments:j,positionAssignments:L,auditData:s,drawType:M,drawName:w,drawId:D}));const{matchUps:B}=tr({event:o,drawDefinition:N});B==null||B.forEach(({matchUpId:R})=>l.push(R))}return!r.includes(N.drawId)});o.drawDefinitions=m,h&&Yr({event:o,extension:{name:ar,value:h}}),cd({tournamentRecord:n});const g=`${Qn}.${Zn}`,{timeItem:I}=kr({element:o,itemType:g}),S=(E=I==null?void 0:I.itemValue)==null?void 0:E[Kr];let T;for(const N of r)if((y=S==null?void 0:S.drawIds)==null?void 0:y.includes(N)){T=!0;const C=((b=S.drawIds)==null?void 0:b.filter(U=>U!==N))||[],v={itemType:`${Qn}.${Zn}`,itemValue:{[Kr]:{drawIds:C}}},P=ii({event:o,timeItem:v});if(P.error)return{error:P.error}}if(f.length&&Ht({topic:ha,payload:f}),l.length&&ei({tournamentId:n==null?void 0:n.tournamentId,matchUpIds:l}),r.forEach(N=>{iU({drawId:N})}),PL({event:o,deletedDrawsDetail:u,auditData:s}),t&&T){const N=fu({tournamentRecord:n,event:o,policyDefinitions:e});N.error&&console.log("publish error",N)}return{...$}}function PL({event:t,deletedDrawsDetail:e,auditData:n}){const{extension:r}=xn({name:ju,element:t}),s={...n,deletedDrawsDetail:e},i={name:ju,value:Array.isArray(r==null?void 0:r.value)?r==null?void 0:r.value.concat(s):[s]};ae({element:t,extension:i})}function UL({removeCompletedMatchUps:t,tournamentRecord:e,drawDefinition:n,structureId:r,roundNumber:s,event:i}){if(!e)return{error:et};if(!n)return{error:lt};if(!s)return G({result:{error:Tt},info:"roundNumber required"});const o=Ot({drawDefinition:n,structureId:r});if(o.error)return o;const c=o.structure;return c!=null&&c.structures?{error:Go}:Qr({drawDefinition:n,structure:c})?OL({tournamentId:e.tournamentId,removeCompletedMatchUps:t,eventId:i.eventId,drawDefinition:n,roundNumber:s,structure:c}):(console.log("not implemented"),{...$})}function OL({removeCompletedMatchUps:t,drawDefinition:e,tournamentId:n,roundNumber:r,structure:s,eventId:i}){const o=(s==null?void 0:s.matchUps)??[],c=[];let a=!1;if(o.reduce((l,f)=>{const p=f==null?void 0:f.roundNumber;return p?l.includes(p)?l:l.concat(p):l},[]).sort(Ve).includes(r)){const l=o.filter(f=>{const p=f.roundNumber===r&&(!We.includes(f.matchUpStatus)||t);return p&&c.push(f.matchUpId),!p});c.length&&(ei({matchUpIds:c,drawDefinition:e,tournamentId:n,eventId:i}),l.some(p=>p.roundNumber===r)||(l.forEach(p=>{p.roundNumber>r&&(p.roundNumber-=1,qt({drawDefinition:e,tournamentId:n,eventId:i,matchUp:p}))}),a=!0),s.matchUps=l)}return{deletedMatchUpsCount:c.length,roundRemoved:a,...$}}function ML({tournamentRecord:t,drawDefinition:e,participantId:n,drawPosition:r,structureId:s,qualifier:i,event:o,bye:c}){if(!e)return{error:lt};if(!r)return{error:Wc};if(!s)return{error:En};if(c){const a=Vn({tournamentRecord:t,drawDefinition:e,drawPosition:r,structureId:s,event:o});if(a.error)return a}else{if(i)return{error:bg};{const a=_r({tournamentRecord:t,drawDefinition:e,participantId:n,drawPosition:r,structureId:s,event:o});if(a.error)return a}}return{...$}}function DL({allowDuplicateParticipantIdPairs:t,entryStage:e=As.Main,entryStatus:n=dr,participantIdPairs:r=[],tournamentRecord:s,drawDefinition:i,event:o,uuids:c}){if(!s)return{error:et};if(!o)return{error:Wt};if(o.eventType!==me)return{error:ui};const a=s.participants||[],u=a.filter(E=>E.participantType===xt).map(E=>E.participantId),l=u.filter(E=>!u.includes(E));if(l.length)return{error:gr,invalidParticipantIds:l};const f=r.filter(E=>E.length!==2);if(f.length)return{error:gr,invalidParticipantIdPairs:f};const p=a.filter(E=>E.participantType===_t).map(E=>E.individualParticipantIds),h=r.map(E=>({participantId:(c==null?void 0:c.pop())||Yt(),participantRole:fn,individualParticipantIds:E,participantType:_t})),d=t?h:h.filter(E=>!p.find(y=>qe(y,E.individualParticipantIds).length===2));let m,g=[];if(d){const E=Ss({allowDuplicateParticipantIdPairs:t,participants:d,returnParticipants:!0,tournamentRecord:s});if(E.error)return E;g=E.participants||[],m=E.info}const I=r.map(E=>{const y=g.find(N=>qe(N.individualParticipantIds,E).length===2);if(y)return y;const{participant:b}=Jr({tournamentRecord:s,participantIds:E});return b}).map(E=>E.participantId),S=Fs({participantIds:I,tournamentRecord:s,drawDefinition:i,entryStatus:n,entryStage:e,event:o});d.length&&Ht({payload:{participants:d},topic:yi});const T=d.map(fe);return{...S,info:m,newParticipantIds:T}}function Zb({enforceGender:t=!0,consideredEntries:e,tournamentRecord:n,participants:r,event:s}){if(r=r||(n==null?void 0:n.participants),!r)return{error:Yc};if(!Array.isArray(r))return{error:tt};if(!s)return{error:Wt};const{eventType:i,gender:o}=s,c=i===ds&&se||i===Zu&&_t||xt,a=Object.assign({},...(e||s.entries||[]).map(p=>({[p.participantId]:p.entryStatus}))),u=Object.keys(a),f=r.filter(p=>u.includes(p.participantId)).filter(p=>{var S;const h=a[p.participantId],d=i&&[_n.Doubles,_n.Team].includes(i)&&p.participantType===xt&&(Ri(h)||h===ti),m=p.participantType!==c&&!d,g=(S=p==null?void 0:p.person)==null?void 0:S.sex,I=t&&o&&i===_n.Singles&&[sa.Male,sa.Female].includes(o)&&g!==o;return m||I});if(f.length){const p=f.map(h=>h.participantId);return{error:Y1,invalidParticipantIds:p}}return{...$}}function wL(t){const{provisionalPositioning:e,useExistingSeedLimit:n,tournamentRecord:r,drawDefinition:s,seedingProfile:i,structureId:o,assignments:c,drawId:a,event:u}=t;let l=0;if(!(c!=null&&c.length))return{error:Jm};if(!r)return{error:et};if(!a)return{error:Hn};const f=Mr({provisionalPositioning:e,drawDefinition:s,structureId:o});if(f.error)return f;const{seedAssignments:p,seedLimit:h}=f,d=Object.assign({},...(p||[]).filter(I=>I.seedNumber).map(I=>({[I.seedNumber]:I})));c.forEach(I=>{const{seedNumber:S}=I;h&&S<=h&&(!n||d[S])&&(d[S]=I)});const m=Object.values(d),g=m.map(I=>I==null?void 0:I.participantId).filter(Boolean);if(g.length!==$m(g).length)return{error:F1};for(const I of m){const S=Do({...I,provisionalPositioning:e,tournamentRecord:r,drawDefinition:s,seedingProfile:i,structureId:o,event:u});if(S!=null&&S.error)return S;S!=null&&S.success&&l++}return l?{...$,modifications:l}:{error:zc}}function kL({removePairParticipants:t,tournamentRecord:e,eventIds:n}){if(!e)return{error:et};if(!e.events)return{error:wn};if(!Array.isArray(n))return{error:Tt,info:sn("drawIds")};const r=[],s=[],i=[],o=[];if(e.events=(e.events||[]).filter(c=>{if(n.includes(c.eventId)){const l={action:jy,payload:{events:[c]}};r.push(l),s.push({tournamentId:e.tournamentId,eventName:c.eventName,eventType:c.eventType,category:c.category,eventId:c.eventId,gender:c.gender})}const a=c.eventType===$n?(c.entries||[]).map(({entryStatus:l,participantId:f})=>l!==Or&&f).filter(Boolean):[],u=n.includes(c.eventId);return u?o.push(...a):i.push(...a),!u}),t){const c=o.filter(a=>!i.includes(a));e.participants=e.participants.filter(({participantId:a})=>!c.includes(a))}return cd({tournamentRecord:e}),r.length&&(Ht({topic:ha,payload:r}),_s({tournamentRecord:e,timeItem:{itemType:jy,itemValue:s}})),{...$}}const Xb="COLLEGE_DEFAULT",tN="COLLEGE_JUCO",eN="COLLEGE_D3",_L="DOMINANT_DUO",FL="DOMINANT_DUO_MIXED",LL="LAVER_CUP",RL="TEAM_DOUBLES_3_AGGREGATION",BL="USTA_BREWER_CUP",xL="USTA_OZAKI_CUP",$L="USTA_COLLEGE",VL="USTA_GOLD_TEAM_CHALLENGE",jL="USTA_LEVEL_1",GL="USTA_INTERSECTIONAL",WL="USTA_SECTION_BATTLE",HL="USTA_SOUTHERN_LEVEL_5",qL="USTA_TOC",YL="USTA_WTT_ITT",zL="USTA_ZONAL",nN="STANDARD",rN={[nN]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1},singles:{matchUpCount:6,matchUpValue:1},valueGoal:5},[eN]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1,matchUpFormat:"SET1-S:8/TB7@7"},singles:{matchUpFormat:Kn,matchUpCount:6,matchUpValue:1},tieFormatName:eN,valueGoal:5},[Xb]:{hydrate:!0,doubles:{matchUpCount:3,collectionValue:1,matchUpFormat:Kn},singles:{matchUpCount:6,matchUpValue:1,matchUpFormat:Kn},tieFormatName:Xb,valueGoal:4},[tN]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1,matchUpFormat:"SET1-S:8/TB7"},singles:{matchUpCount:6,matchUpValue:1,matchUpFormat:Kn},tieFormatName:tN,valueGoal:5},[LL]:VS,[_L]:xS,[FL]:$S,[RL]:jS,[BL]:GS,[xL]:WS,[$L]:HS,[VL]:qS,[GL]:YS,[jL]:zS,[WL]:KS,[HL]:JS,[YL]:ZS,[qL]:QS,[zL]:XS},Lo=t=>{const e=t!=null&&t.namedFormat&&Object.keys(rN).includes(t.namedFormat)?t.namedFormat:nN,n=Array.isArray(t==null?void 0:t.uuids)?t==null?void 0:t.uuids:[];let r;const{category:s,gender:i}=(t==null?void 0:t.event)||{},o=pt(rN[e],!1,!0);return o.hydrate?(r={winCriteria:{valueGoal:o.valueGoal},collectionDefinitions:[{collectionId:(n==null?void 0:n.pop())||Yt(),matchUpFormat:Vg,matchUpType:_n.Doubles,collectionName:"Doubles",...o.doubles},{collectionId:(n==null?void 0:n.pop())||Yt(),matchUpType:_n.Singles,matchUpFormat:Kn,collectionName:"Singles",...o.singles}]},o.tieFormatName&&(r.tieFormatName=o.tieFormatName)):(o.collectionDefinitions.forEach(c=>c.collectionId=Yt()),r=o),t!=null&&t.hydrateCollections&&r.collectionDefinitions.forEach(c=>{s&&!c.category&&(c.category=s),i&&!c.gender&&(c.gender=i)}),r};function Ed({suppressNotifications:t,tournamentRecord:e,internalUse:n,event:r}){var a,u,l,f;if(!e)return{error:et};if(e.events||(e.events=[]),!r)return{error:Wt};const{startDate:s,endDate:i}=e;if(!n&&((a=r.entries)!=null&&a.length||(u=r.drawDefinitions)!=null&&u.length)){const p=bt({drawDefinitions:!!((l=r.drawDefinitions)!=null&&l.length),entries:!!((f=r.entries)!=null&&f.length)});return{info:"entries/drawDefinitions cannot exist",error:tt,context:p}}const o=Object.assign({},{drawDefinitions:[],eventType:_n.Singles,entries:[],startDate:s,endDate:i},r);if(r.eventType===_n.Team){if(r.tieFormat){const p=vn({tieFormat:r.tieFormat});if(p.error)return p}else if(r.tieFormatName){if(!tT[r.tieFormatName])return{context:{tieFormatName:r.tieFormatName},error:tt};const p=Lo({namedFormat:r.tieFormatName});o.tieFormat=p}}if(o.eventId||(o.eventId=Yt()),e.events.reduce((p,h)=>p||h.eventId===o.eventId,void 0))return{error:H1};{const p=o;if(e.events.push(p),!t){const{topics:h}=$r();if(h.includes(Pf)){const d=si({event:r}).matchUps||[];Oi({tournamentId:e==null?void 0:e.tournamentId,eventId:r.eventId,matchUps:d})}for(const d of r.drawDefinitions||[])Ba({drawDefinition:d})}return{...$,event:o}}}function KL({tournamentRecord:t,participantId:e,matchUpId:n,matchUp:r,drawId:s}){r&&!s&&({drawId:s}=r),r&&!n&&({matchUpId:n}=r);const{drawDefinition:i}=Je({tournamentRecord:t,drawId:s});if(i){const o=t.participants,c=fh({tournamentParticipants:o,drawDefinition:i,participantId:e,matchUpId:n});if(c.error&&c.error!==ug)return c}else return{error:wn};return{...$}}function JL({tournamentRecord:t,participantId:e,matchUpId:n,matchUp:r,drawId:s}){r&&!s&&({drawId:s}=r),r&&!n&&({matchUpId:n}=r);const{drawDefinition:i}=Je({tournamentRecord:t,drawId:s});if(i){const o=t.participants,c=ph({tournamentParticipants:o,drawDefinition:i,participantId:e,matchUpId:n});if(c.error)return c}else return{error:wn};return{...$}}function QL(t){const{participantId:e}=t;return e&&typeof e!="string"?{error:tt,participantId:e}:sN({...t,participantIds:[e].filter(Boolean)})}function sN({tournamentRecord:t,drawDefinition:e,participantIds:n,stageSequence:r,stage:s=It,eventId:i,event:o}){if(!t)return{error:et};if(!Array.isArray(n))return{error:tt,participantIds:n};if(!o)return{error:Wt};const c="promoteAlternates";if(o){const a=iN({element:o,participantIds:n,stageSequence:r,stage:s});if(a.error)return a}if(e){const a=iN({element:e,participantIds:n,stageSequence:r,stage:s});if(a.error)return i?G({context:{drawPromotionError:a.error,drawId:e.drawId},result:{...$},stack:c}):a}return{...$}}function iN({participantIds:t,stageSequence:e,element:n,stage:r}){const s=(n.entries||[]).filter(f=>f.entryStatus===dr),i=(n.entries||[]).filter(f=>t.includes(f.participantId)),o=s.reduce((f,p)=>{const{entryPosition:h}=p;return isNaN(h)&&f||(!f||h<f.entryPosition)&&p||f},void 0),c=i.length?i:[o].filter(Boolean);if(!(c!=null&&c.length))return{error:dg};const a=c.filter(({entryStatus:f})=>f!==dr);if(a.length)return{error:zd,invalidEntryStatus:a};const u=c.filter(({entryStage:f})=>f&&f!==r);if(u.length)return{error:hv,invalidStage:u};const l=e&&c.filter(f=>f.stageSequence!==e);if(l!=null&&l.length)return{error:mv,invalidStageSequence:l};for(const f of c){f.entryStatus=Ur;const p=f==null?void 0:f.entryPosition;isNaN(p)||n.entries.forEach(d=>{d.entryStatus===dr&&d.entryPosition>p&&(d.entryPosition=d.entryPosition-1)});const h=Math.max(...n.entries.filter(d=>d.entryStatus===Ur&&!isNaN(d.entryPosition)).map(({entryPosition:d})=>vt(d||0)),0);f.entryPosition=h||0}return{...$}}function ZL(t){return Object.assign(t,{entryStatus:ti}),Sd(t)}function XL({luckyLoserParticipantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:s}){return Vh({positionActionName:"luckyLoserDrawPositionAssignment",participantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:s})}function tR(t){return XL(t)}function eR({qualifyingParticipantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:s}){return Vh({positionActionName:"qualifierDrawPositionAssignment",participantId:t,isQualifierPosition:!0,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:s})}function nR(t){return eR(t)}function rR(t){return eb(t)}function sR(t){return fb(t)}function oN(t){return ou(t)}function iR(t){return nb(t)}function oR({tournamentRecord:t,drawDefinition:e,drawPosition:n,structureId:r,event:s}){return Vn({tournamentRecord:t,drawDefinition:e,drawPosition:n,structureId:r,event:s})}function cR({replacementIndividualParticipantId:t,existingIndividualParticipantId:e,tournamentRecord:n,drawDefinition:r,participantId:s,event:i,uuids:o}){var m,g;if(!i)return{error:Wt};if((i==null?void 0:i.eventType)!==$n)return{error:ui};if(o&&!Array.isArray(o))return{error:tt};if(!n)return{error:et};if(![t,e,s].every(I=>typeof I=="string"))return{error:Ce};if(!(((m=i==null?void 0:i.entries)==null?void 0:m.filter(({entryStatus:I})=>[Or,po].includes(I)).map(({participantId:I})=>I))||[]).includes(t))return{error:bs};const a=(n.participants||[]).find(I=>I.participantId===s);if((a==null?void 0:a.participantType)!==_t)return{error:vu,participant:a};const u=a.individualParticipantIds,l=[t,...u.filter(I=>I!==e)],{participant:f}=Jr({participantIds:l,tournamentRecord:n});let p;if(f)p=f.participantId;else{const I={participantId:o==null?void 0:o.pop(),participantRole:fn,individualParticipantIds:l,participantType:_t},S=es({participant:I,returnParticipant:!0,tournamentRecord:n});if(S.error)return S;p=S.participant.participantId}const{flightProfile:h}=be({event:i});if(r){const I=(g=h==null?void 0:h.flights)==null?void 0:g.find(({drawId:S})=>S===r.drawId);I&&(I.drawEntries=I.drawEntries.map(S=>S.participantId===s?{...S,participantId:p}:S)),r.entries=r.entries.map(S=>S.participantId===s?{...S,participantId:p}:S);for(const S of r.structures||[])if(S.positionAssignments)S.positionAssignments=S.positionAssignments.map(T=>T.participantId===s?{...T,participantId:p}:T);else if(S.structures)for(const T of S.structures)T.positionAssignments=T.positionAssignments.map(E=>E.participantId===s?{...E,participantId:p}:E)}i.entries=i.entries.map(I=>I.participantId===s&&{...I,participantId:p}||I.participantId===t&&{...I,participantId:e}||I);const d=n.events.some(({entries:I,eventId:S,drawDefinitions:T})=>i.eventId===S?T.some(({drawId:E,entries:y})=>E===(r==null?void 0:r.drawId)?!1:y==null?void 0:y.find(b=>b.participantId===s)):I==null?void 0:I.find(E=>E.participantId===s));if(!d){const I=Fc({addIndividualParticipantsToEvents:!1,participantIds:[s],tournamentRecord:n});if(I.error)return I}return{...$,participantOtherEntries:d,newPairParticipantId:p}}function aR({autoEntryPositions:t=!0,participantIds:e,drawDefinition:n,drawId:r,stages:s,event:i}){var f;if(!i)return{error:Wt};if(!r)return{error:Hn};if(!(e!=null&&e.length))return{error:Ns};const o=gd({drawDefinition:n,stages:s});if(tn(o,e))return{error:Yo};const a=p=>{const h=p.participantId;return!e.includes(h)},{flightProfile:u}=be({event:i}),l=(f=u==null?void 0:u.flights)==null?void 0:f.find(p=>p.drawId===r);return l!=null&&l.drawEntries&&(l.drawEntries=l.drawEntries.filter(a),t&&(l.drawEntries=pr({entries:l.drawEntries}))),n!=null&&n.entries&&(n.entries=n.entries.filter(a),t&&(n.entries=pr({entries:n.entries}))),{...$}}function uR(t){const e=t.tournamentRecord;if(!e)return{error:et};const n=hd(t);if(n.error)return n;const{playoffStructureNameBase:r,playoffPositions:s,roundNumbers:i,structureId:o}=t,a={itemType:"addPlayoffStructures",itemValue:bt({playoffStructureNameBase:r,playoffPositions:s,roundNumbers:i,structureId:o})};return _s({tournamentRecord:e,timeItem:a}),n}function lR({tournamentRecord:t,drawDefinition:e,participantId:n,structureId:r,seedValue:s,event:i}){return t?(t.participants||[]).find(c=>c.participantId===n)?Mb({tournamentRecord:t,drawDefinition:e,participantId:n,structureId:r,seedValue:s,event:i}):{error:bs}:{error:et}}function dR({tournamentRecord:t,drawDefinition:e,scheduledDates:n,stageSequences:r,matchUpFormat:s,structureIds:i,structureId:o,eventType:c,matchUpId:a,eventIds:u,eventId:l,drawIds:f,stages:p,drawId:h,event:d,force:m}){const g="setMatchUpFormat";if(!t)return{error:et};if(!s)return{error:Vd};if(s&&!nr(s))return G({result:{error:bu,matchUpFormat:s},stack:g});if(n&&!Array.isArray(n))return G({result:{error:tt,scheduledDates:n},stack:g});if(c&&![ls,$n].includes(c))return G({result:{error:ui},stack:g});let I=0;if((o||i)&&!e)return G({result:{error:lt},stack:g});if(h&&a){const T=Gl({tournamentRecord:t,drawDefinition:e,matchUpFormat:s,structureIds:i,structureId:o,matchUpId:a});if(T.error)return T;I+=1}const S=T=>{const E=[];for(const y of T.structures||[]){if(Array.isArray(p)&&!p.includes(y.stage)||Array.isArray(r)&&!r.includes(y.stageSequence)||i.length&&!i.includes(y.structureId))continue;i.length&&y.matchUpFormat!==s&&(y.matchUpFormat=s,E.push(y.structureId),I+=1);const b=(m||n)&&Qt({matchUpFilters:{matchUpStatuses:[pe.ToBePlayed]},structure:y}),N=n&&Qt({matchUpFilters:{matchUpStatuses:[pe.ToBePlayed]},contextFilters:{scheduledDates:n},afterRecoveryTimes:!1,inContext:!0,structure:y});if(b!=null&&b.length){const A=N?N.map(Qe):b.map(Qe);for(const C of b)A.includes(C.matchUpId)&&(C.matchUpFormat=n!=null&&n.length?s:void 0,qt({tournamentId:t==null?void 0:t.tournamentId,eventId:d==null?void 0:d.eventId,context:g,drawDefinition:T,matchUp:C}))}}return!E.length&&T.matchUpFormat!==s&&(T.matchUpFormat=s,I+=1),E};i=i||[o].filter(Boolean),u=u||[l].filter(Boolean),f=f||[h].filter(Boolean);for(const T of t.events||[])if(!(u!=null&&u.length&&!u.includes(T.eventId)||c&&c!==T.eventType||c===we))if(Array.isArray(r)||Array.isArray(p)||i.length||f.length)for(const E of T.drawDefinitions||[]){if(Array.isArray(f)&&!f.includes(E.drawId))continue;const y=S(E);Zt({structureIds:y,drawDefinition:E})}else T.matchUpFormat!==s&&(T.matchUpFormat=s,I+=1);return I?{...$,modificationsCount:I}:{...$,info:zc}}function cN({tournamentRecord:t,drawDefinition:e,participantId:n,entryPosition:r,skipRefresh:s,event:i}){const o="setEntryPositions";if(!t)return{error:et};if(!n)return G({result:{error:Ce},stack:o});if(r!==void 0&&!Number.isSafeInteger(r))return{error:tt,entryPosition:r};((i==null?void 0:i.entries)||[]).forEach(a=>{a.participantId===n&&(a.entryPosition=r)}),((e==null?void 0:e.entries)||[]).forEach(a=>{a.participantId===n&&(a.entryPosition=r)});const c=a=>{a.entries.forEach(u=>{u.entryPosition===r&&u.participantId!==n&&(u.entryPosition+=.1)})};return s||(i!=null&&i.entries&&(c(i),i.entries=pr({entries:i.entries})),e!=null&&e.entries&&(c(e),e.entries=pr({entries:e.entries}))),{...$}}function fR({tournamentRecord:t,entryPositions:e,drawDefinition:n,event:r}){if(!t)return{error:et};if(!Array.isArray(e))return{error:tt};for(const s of e){const{participantId:i,entryPosition:o}=s,c=cN({skipRefresh:!0,tournamentRecord:t,drawDefinition:n,participantId:i,entryPosition:o,event:r});if(c.error)return c}return r!=null&&r.entries&&(r.entries=pr({entries:r.entries})),n!=null&&n.entries&&(n.entries=pr({entries:n.entries})),{...$}}function pR(t){return gb(t)}function aN({scaleAttributes:t,scaledEntries:e,stageEntries:n,seedsCount:r,scaleName:s}){if(!t)return{error:Tt,info:"missing scaleAttributes"};const i=Object.assign({},...(e||[]).slice(0,r).map(({participantId:a},u)=>({[a]:u+1})));s=s||t.scaleName;const o=new Date().toISOString();return{scaleItemsWithParticipantIds:n.map(({participantId:a})=>({scaleItems:[{scaleValue:i[a],eventType:t.eventType,scaleType:br,scaleName:s,scaleDate:o}],participantId:a}))}}function hR(t){return Eb(t)}function mR({tournamentRecord:t,scaleAttributes:e,participantIds:n}){var c;if(!t)return{error:et};if(!n)return{error:Ns};if(!e)return{error:Tt,info:"scaleAttributes required"};const{scaleType:r,eventType:s,scaleName:i}=e,o=[PP,r,s,i].join(".");return(c=t.participants)==null||c.forEach(a=>{n.includes(a.participantId)&&a.timeItems&&(a.timeItems=a.timeItems.filter(u=>u&&(u==null?void 0:u.itemType)!==o))}),{...$}}function uN({tournamentRecord:t,scaleAttributes:e,drawDefinition:n,entryStatuses:r,drawId:s,event:i,stage:o}){var l;if(!i)return{error:Wt};if(r&&!Array.isArray(r))return G({result:{error:tt},info:sn("entryStatus"),stack:"removeScaleValues"});let c=i.entries;if(s){const{flightProfile:f}=be({event:i}),p=(l=f==null?void 0:f.flights)==null?void 0:l.find(h=>h.drawId===s);p?c=p.drawEntries:c=n==null?void 0:n.entries}const u=(c||[]).filter(f=>(!o||!f.entryStage||f.entryStage===o)&&(!r||r.includes(f.entryStatus))).map(fe);return mR({tournamentRecord:t,scaleAttributes:e,participantIds:u})}function bd({tournamentRecord:t,scaleAttributes:e,participantId:n}){if(!t)return{error:et};if(!n)return{error:Ce};const{participant:r}=zs({tournamentRecord:t,participantId:n});return r?Ts({participant:r,scaleAttributes:e}):{error:_e}}function hu({sortDescending:t=!1,tournamentRecord:e,scaleAttributes:n,scaleSortMethod:r,stageSequence:s,entries:i,event:o,stage:c}){if(!e)return{error:et};return i=i||(o==null?void 0:o.entries)||[],{scaledEntries:i.filter(p=>(!c||!p.entryStage||p.entryStage===c)&&(!s||!p.entryStageSequence||p.entryStageSequence===s)&&ps.includes(p.entryStatus)).map(p=>{const{participantId:h}=p,{scaleItem:d}=bd({tournamentRecord:e,scaleAttributes:n,participantId:h});return{...p,...d}}).filter(p=>{const h=p.scaleValue;return!r&&(isNaN(h)||!parseFloat(h))?!1:h}).sort(r||l)};function l(p,h){return t?f(h)-f(p):f(p)-f(h)}function f(p){return parseFloat(p.scaleValue||(t?-1:1e5))}}function gR({tournamentRecord:t,drawDefinition:e,entryStatuses:n,scaleName:r,drawId:s,event:i,stage:o}){var a,u;if(!t)return{error:et};if(!i)return{error:Wt};r=r||((a=i.category)==null?void 0:a.categoryName)||((u=i.category)==null?void 0:u.ageCategoryCode);const c={eventType:i.eventType,scaleType:br,scaleName:r};return uN({tournamentRecord:t,scaleAttributes:c,drawDefinition:e,entryStatuses:n,drawId:s,event:i,stage:o})}function IR({tournamentRecord:t,drawDefinition:e,policyDefinitions:n,scaleAttributes:r,scaleName:s,drawSize:i,drawId:o,event:c,stage:a,sortDescending:u,scaleSortMethod:l}){const f=Jb({policyDefinitions:n,drawDefinition:e,drawSize:i,drawId:o,event:c,stage:a});if(f.error)return f;const{entries:p,seedsCount:h,stageEntries:d}=f;if(!d||!h)return{error:tt};const m=hu({tournamentRecord:t,scaleAttributes:r,scaleSortMethod:l,sortDescending:u,entries:p,stage:a}).scaledEntries??[],{scaleItemsWithParticipantIds:g}=aN({scaleAttributes:r,scaledEntries:m,stageEntries:d,seedsCount:h,scaleName:s});return{scaleItemsWithParticipantIds:g}}function SR({tournamentRecord:t,drawDefinition:e,resetEntries:n,event:r}){var o,c;if(!e)return{error:lt};const s=(o=e.structures)==null?void 0:o.find(a=>a.stage===je);if(!s)return{error:Te};const i=((c=s.matchUps)==null?void 0:c.map(({matchUpId:a})=>a))||[];return s.positionAssignments=[],s.seedAssignments=[],s.matchUps=[],ei({tournamentId:t==null?void 0:t.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:i,drawDefinition:e}),n&&(e.entries=e.entries.filter(a=>a.entryStage!==je)),Zt({tournamentId:t==null?void 0:t.tournamentId,eventId:r==null?void 0:r.eventId,drawDefinition:e,structureIds:[s.structureId]}),{...$}}function TR({autoPublish:t=!0,tournamentRecord:e,auditData:n,event:r}){var i;if(!e)return{error:et};if(!r)return{error:Wt};const{flightProfile:s}=be({event:r});if(s){const o=(i=s.flights)==null?void 0:i.map(({drawId:a})=>a).filter(Boolean),c=om({eventId:r.eventId,tournamentRecord:e,autoPublish:t,auditData:n,drawIds:o,event:r});return c.error?c:Yu({event:r,name:ar})}return{...$}}function lN({event:t,orderedDrawIdsMap:e}){var i,o;if(typeof t!="object")return{error:Wt};if(!e)return{error:Tt,info:"Missing drawIdsOrderMap"};if(typeof e!="object")return{error:tt,info:"orderedDrawIdsMap must be an object"};const n=Object.values(e);if(!n.every(c=>!isNaN(c)))return{error:tt,info:"drawOrder must be numeric"};if(Vt(n).length!==n.length)return{error:tt,info:"drawOrder values must be unique"};if((i=t.drawDefinitions)!=null&&i.length){const c=(t.drawDefinitions||[]).map(({drawId:u})=>u),a=Object.keys(e);if(a!=null&&a.length&&qe(c,a).length!==c.length)return{error:tt,info:"Missing drawIds"};t.drawDefinitions.forEach(u=>{u.drawOrder=e[u.drawId]})}const{flightProfile:s}=be({event:t});return(o=s==null?void 0:s.flights)==null||o.forEach(c=>{c.flightNumber=e[c.drawId]}),{...$}}function dN({tournamentRecord:t,event:e}){var s;if(!t)return{error:et};if(!e)return{error:Wt};const{flightProfile:n}=be({event:e}),r=(n==null?void 0:n.flights)&&Object.assign({},...n.flights.sort((i,o)=>i.flightNumber-o.flightNumber).map((i,o)=>({[i.drawId]:o+1})))||((s=e.drawDefinitions)==null?void 0:s.length)&&Object.assign({},...e.drawDefinitions.sort((i,o)=>i.drawOrder-o.drawOrder).map((i,o)=>({[i.drawId]:o+1})))||void 0;return r?lN({event:e,orderedDrawIdsMap:r}):{...$}}function yR({autoPublish:t=!0,tournamentRecord:e,auditData:n,drawId:r,event:s}){var c,a;if(!e)return{error:et};if(!r)return{error:Hn};if(!s)return{error:Wt};const{flightProfile:i}=be({event:s});if(i&&((c=i.flights)==null?void 0:c.find(l=>l.drawId===r))){const l=i.flights.filter(p=>p.drawId!==r),f={name:ar,value:{...i,flights:l}};Yr({event:s,extension:f})}if((a=s.drawDefinitions)==null?void 0:a.find(u=>u.drawId===r)){const u=om({drawIds:[r],eventId:s.eventId,tournamentRecord:e,autoPublish:t,auditData:n,event:s});if(u.error)return u}return dN({tournamentRecord:e,event:s})}function fN({deleteExisting:t,event:e,flightProfile:n}){var o;const r="attachFlightProfile";if(!n)return G({result:{error:Tt},stack:r});if(!e)return G({result:{error:Wt},stack:r});const{flightProfile:s}=be({event:e});return s&&!t?G({result:{error:Ng},stack:r}):(o=e.drawDefinitions)!=null&&o.length?G({result:{error:D1},stack:r}):(Yr({event:e,extension:{name:ar,value:n}}),{flightProfile:pt(n,!1,!0),...$})}const ER="splitWaterfall",bR="splitShuttle";function NR(t){const{drawNameRoot:e="Flight",attachFlightProfile:n,tournamentRecord:r,scaleAttributes:s,scaleSortMethod:i,deleteExisting:o,sortDescending:c,drawNames:a=[],flightsCount:u,splitMethod:l,uuids:f=[],event:p,stage:h}=t;if(!p)return{error:Wt};const d=p.entries||[],{flightProfile:m}=be({event:p});if(m&&n&&!o)return{error:Ng};const g=t.scaledEntries??hu({tournamentRecord:r,scaleAttributes:s,scaleSortMethod:i,sortDescending:c,event:p,stage:h}).scaledEntries,I=g.map(fe),S=on(d.filter(({participantId:v})=>!I.includes(v)).filter(v=>(!h||!v.entryStage||v.entryStage===h)&&(!v.entryStatus||ho.includes(v.entryStatus)))),T=g.concat(...S),E=T.length,y=Math.ceil(E/u);let b=Ge(T,y);l===ER?b=jm(T,u):l===bR&&(b=jm(T,u,!0));function N(v){return(v||[]).map(({participantId:P,scaleValue:U})=>{const O=d.find(D=>D.participantId===P);return O!=null&&O.scaleValue&&U&&(O.scaleValue=U),O}).sort((P,U)=>P.scaleValue-U.scaleValue).map((P,U)=>(P.scaleValue&&(P.seedNumber=U+1),P))}const A=ht(0,u).map(v=>{const P=v+1;return{flightNumber:P,drawId:(f==null?void 0:f.pop())||Yt(),drawEntries:N(b[v]),drawName:(a==null?void 0:a.length)&&a[v]||`${e} ${P}`}}),C={scaleAttributes:s,splitMethod:l,flights:A};if(n){const v=fN({flightProfile:C,deleteExisting:o,event:p});return{splitEntries:ze()&&b||void 0,...v}}else return{flightProfile:C,...$}}function AR(t){const{tournamentRecord:e}=t;if(!e)return{error:et};const n=e.participants;return qE({participants:n,...t})}function vR(t){return HE(t)}function CR({substituteParticipantId:t,existingParticipantId:e,tournamentRecord:n,drawDefinition:r,sideNumber:s,matchUpId:i,event:o}){var m,g,I;const c="substituteParticipant";if(!r)return{error:lt};if(!i)return{error:$e};if(!e||!t)return G({result:{error:Ce},stack:c});const{matchUp:a}=ie({drawDefinition:r,matchUpId:i,event:o});if(!a)return{error:Ye};if(!a.collectionId)return G({result:{error:qn},stack:c});const u=ln({drawDefinition:r}),{matchUps:l}=xe({tournamentParticipants:n==null?void 0:n.participants,inContext:!0,drawDefinition:r,matchUpsMap:u}),f=l==null?void 0:l.find(S=>S.matchUpId===i),p=l==null?void 0:l.find(S=>S.matchUpId===(f==null?void 0:f.matchUpTieId)),h=(m=p==null?void 0:p.sides)==null?void 0:m.find(S=>S.participant.individualParticipants.some(({participantId:T})=>T===e));return!h||s&&h.sideNumber!==s?{error:bs}:((I=(g=h.participant)==null?void 0:g.individualParticipants)==null?void 0:I.map(fe).filter(S=>S!==e)).includes(t)?Qb({newParticipantId:t,tieMatchUpId:i,existingParticipantId:e,substitution:!0,tournamentRecord:n,drawDefinition:r,event:o}):G({result:{error:bs},stack:c})}function PR(t){return CR(t)}function UR(t){return JE(t)}function pN({tournamentRecord:t,drawDefinition:e,flightProfile:n,drawName:r,drawId:s,event:i}){var c;if(!r||typeof r!="string")return G({result:{error:tt},context:{drawName:r}});n||(n=be({event:i}).flightProfile);const o=(c=n==null?void 0:n.flights)==null?void 0:c.find(a=>a.drawId===s);if(o){o.drawName=r;const a={name:ar,value:{...n,flights:n.flights}};Yr({event:i,extension:a})}return e&&(e.drawName=r,Zt({tournamentId:t==null?void 0:t.tournamentId,drawDefinition:e})),!o&&!e?{error:lt}:{...$,flight:o}}function OR({tournamentRecord:t,drawDefinition:e,drawUpdates:n,drawId:r,event:s}){var a;if(!or(n))return{error:mg};const i=be({event:s}).flightProfile,o=n.drawName&&pN({drawName:n.drawName,tournamentRecord:t,drawDefinition:e,flightProfile:i,drawId:r,event:s});if(o!=null&&o.error)return o==null?void 0:o.error;const c=(o==null?void 0:o.flight)||((a=i==null?void 0:i.flights)==null?void 0:a.find(u=>u.drawId===r));if(!c&&!e)return{error:lt};if(c){const u={name:ar,value:{...i,flights:i.flights}};Yr({event:s,extension:u})}return e&&(n.policyDefinitions&&Td({policyDefinitions:n.policyDefinitions,drawDefinition:e}),Zt({tournamentId:t==null?void 0:t.tournamentId,drawDefinition:e})),{...$}}function MR({tournamentRecord:t,removeScheduling:e,drawDefinition:n}){var o;if(!n)return{error:lt};const r=ln({drawDefinition:n}),s=c=>{var a;return(a=r==null?void 0:r.drawMatchUps)==null?void 0:a.find(u=>u.matchUpId===c)};for(const c of n.structures||[]){const{positionAssignments:a,stage:u,stageSequence:l}=c;a&&(l!==1||![Pt,It].includes(u))&&(c.positionAssignments=a.map(p=>(delete p.participantId,p)),c.seedAssignments=[]);const{matchUps:f}=Qt({afterRecoveryTimes:!1,inContext:!0,matchUpsMap:r,structure:c});for(const p of f){const{matchUpId:h,roundNumber:d,sides:m}=p,g=s(h);if(g){if(delete g.extensions,delete g.notes,g.matchUpStatus!==re&&Object.assign(g,fl),d&&d>1&&g.drawPositions){const I=m==null?void 0:m.map(({drawPosition:T,participantFed:E})=>!E&&T).filter(Boolean),S=g.drawPositions.map(T=>I.includes(T)?void 0:T);g.drawPositions=S}e?delete g.timeItems:(o=g.timeItems)!=null&&o.length&&(g.timeItems=g.timeItems.filter(I=>I.itemType&&![Qs,oo,ga,CP,Ia,Sa].includes(I.itemType))),qt({tournamentId:t==null?void 0:t.tournamentId,context:"resetDrawDefiniton",drawDefinition:n,matchUp:g})}}}const i=(n.structures||[]).map(({structureId:c})=>c);return Zt({drawDefinition:n,structureIds:i}),{...$}}function DR({matchPlayDrawPositions:t=!0,tournamentRecord:e,drawDefinition:n,drawId:r}){var o;if(!e)return{error:et};if(!n)return{error:lt};let s=[];const{drawsAnalysis:i}=rm({tournamentRecord:e});if(i.canBePruned.includes(r)){const c=i.matchPlay.includes(r),a=i.drawAnalysis[r],{structures:[u]}=lr({stageSequence:1,drawDefinition:n,stage:It}),l=a.structuresData.find(({structureId:d})=>u.structureId===d),f=u.matchUps||[];s=f.sort((d,m)=>d.roundPosition-m.roundPosition).filter(({roundNumber:d})=>!l.inactiveRounds.includes(d));const p=s.map(Qe),h=f.map(Qe).filter(d=>!p.includes(d));if(c){const d=s.sort((E,y)=>E.roundPosition-y.roundPosition).filter(({roundNumber:E})=>!l.inactiveRounds.includes(E)).filter(({winningSide:E})=>E),m=d.map(Qe),g=p.filter(E=>!m.includes(E));h.push(...g);const S=d.flatMap(E=>E.drawPositions||[]).filter(Boolean).flat(),T=Object.assign({},...S.map((E,y)=>({[E]:y+1})));if(d.forEach(E=>{t?E.drawPositions=E.drawPositions.map(y=>T[y]):delete E.drawPositions}),t){const E=(o=u==null?void 0:u.positionAssignments)==null?void 0:o.filter(y=>S.includes(y.drawPosition)).map(y=>(y.drawPosition=T[y.drawPosition],y));u.positionAssignments=E}else u.positionAssignments=[];u.matchUps=d,s=d}ei({tournamentId:e==null?void 0:e.tournamentId,matchUpIds:h,drawDefinition:n}),Zt({drawDefinition:n})}return{...$,matchUps:s}}function wR(t){return vb(t)}function kR({entryStatus:t=Ur,unpairedParticipantIds:e=[],participantIdPairs:n=[],entryStage:r=It,tournamentRecord:s,event:i}){if(!s)return{error:et};if(!i)return{error:Wt};const o=s.participants||[],c=o.filter(I=>I.participantType===xt).map(I=>I.participantId),u=e.concat(...n).flat(1/0).filter(I=>!c.includes(I));if(u.length)return{error:gr,invalidParticipantIds:u};const l=n.filter(I=>I.length!==2);if(l.length)return{error:gr,invalidParticipantIdPairs:l};const f=o.filter(I=>I.participantType===_t).map(I=>I.individualParticipantIds),h=n.filter(I=>!f.find(S=>qe(S,I).length===2)).map(I=>({participantType:_t,participantRole:fn,individualParticipantIds:I})),d=Ss({participants:h,tournamentRecord:s});if(d.error)return d;const m=n.map(I=>{const{participant:S}=Jr({tournamentRecord:s,participantIds:I});return S}).map(I=>({participantId:I,entryStatus:t,entryStage:r})),g=e.map(I=>({entryStatus:Or,participantId:I,entryStage:r}));return i.entries=(i.entries||[]).filter(I=>I.entryStage===r),i.entries=i.entries.concat(...m,...g),{...$}}function _R(t){var n;const e=(n=t.tournamentRecord)==null?void 0:n.participants;return Object.assign(t,{tournamentParticipants:e}),Yh(t)}function cm({qualifyingPositions:t,drawEntries:e=[],drawName:n,drawId:r,event:s,stage:i}){var m,g,I;const o="addFlight";if(!s)return G({result:{error:Wt},stack:o});if(!n)return G({result:{error:Tt},stack:o});if(e!=null&&e.length){const S=(s.entries||[]).map(kn("participantId")),T=e.map(kn("participantId"));if(qe(T,S).length!==T.length)return G({result:{error:tt},stack:o})}const c=(m=be({event:s}))==null?void 0:m.flightProfile,a=((I=(g=c==null?void 0:c.flights)==null?void 0:g.map(({flightNumber:S})=>!isNaN(S)&&vt(S)))==null?void 0:I.filter(Boolean))||[],u=Math.max(0,...a)+1,f={drawId:r||Yt(),flightNumber:u,drawEntries:e,drawName:n};if(i&&(f.stage=i),t&&(f.qualifyingPositions=t),((c==null?void 0:c.flights)||[]).find(({drawId:S})=>S===f.drawId))return G({result:{error:kv},stack:o});const h=((c==null?void 0:c.flights)||[]).concat(f),d={name:ar,value:{...c||{},flights:h}};return Yr({event:s,extension:d})}function FR(t){return md(t)}function LR(t){return Rh(t)}function RR(t){return am({...t,itemType:"attachConsolationStructures"})}function BR(t){return am({...t,itemType:"attachPlayoffStructures"})}function am({itemType:t="attachStructures",matchUpModifications:e,tournamentRecord:n,drawDefinition:r,structures:s,links:i}){if(!n)return{error:et};if(!r)return{error:lt};const o=KE({matchUpModifications:e,tournamentRecord:n,drawDefinition:r,structures:s,links:i});if(o.error)return o;const u={itemValue:{structureIds:s==null?void 0:s.map(({structureId:l})=>l),drawId:r.drawId},itemType:t};return _s({tournamentRecord:n,timeItem:u}),o}function hN({tournamentRecord:t,event:e,startDate:n}){if(!t)return{error:et};if(!e)return{error:Wt};if(!Vr.test(n))return{error:bn};const r=gN(t);if(r.error)return r;const{tournamentStartDate:s,tournamentEndDate:i}=r,o=new Date(Bt(n)).getTime();if(!s||!i||o<s||o>i)return{error:bn};const c=e.endDate&&new Date(Bt(e.endDate));return c&&o>c&&(e.endDate=n),e.startDate=n,{...$}}function mN({tournamentRecord:t,event:e,endDate:n}){if(!t)return{error:et};if(!e)return{error:Wt};if(!Vr.test(n))return{error:bn};const r=gN(t);if(r.error)return r;const{tournamentStartDate:s,tournamentEndDate:i}=r,o=new Date(Bt(n)).getTime();if(!s||!i||o<s||o>i)return{error:bn};const c=e.startDate&&new Date(Bt(e.startDate));return c&&o<c&&(e.startDate=n),e.endDate=n,{...$}}function xR({tournamentRecord:t,event:e,startDate:n,endDate:r}){if(!t)return{error:et};if(!e)return{error:Wt};if(!n&&!r)return{error:Tt,info:"missing date"};if(n&&!Vr.test(n))return{error:bn};if(r&&!Vr.test(r))return{error:bn};if(n&&r){const s=new Date(Bt(n)),i=new Date(Bt(r));if(s>i)return{error:tt}}if(n){const s=hN({tournamentRecord:t,event:e,startDate:n});if(s.error)return s}if(r){const s=mN({tournamentRecord:t,event:e,endDate:r});if(s.error)return s}return{...$}}function gN(t){const{startDate:e,endDate:n}=t;return!Vr.test(e)||!Vr.test(n)?G({result:{error:rv},context:{startDate:e,endDate:n}}):{tournamentStartDate:new Date(Bt(e)).getTime(),tournamentEndDate:new Date(Bt(n)).getTime()}}function $R({tournamentRecord:t,drawDefinition:e,drawPosition:n}){return t?e?oe(n)?{...$}:{error:Wo}:{error:lt}:{error:et}}function VR({tournamentRecord:t,drawDefinition:e,matchUpId:n,lineUps:r,event:s}){var m,g,I,S;if(!t)return{error:et};if(!e)return{error:rr};if(typeof n!="string")return{error:qn};if(!Array.isArray(r))return{error:tt,lineUps:r};const i="applyLineUps",o=t.participants||[];let c=ie({tournamentParticipants:o,inContext:!0,drawDefinition:e,matchUpId:n});if(c.error)return c;if(!c.matchUp)return{error:Ye};const{matchUp:a,structure:u}=c,{drawPositions:l,matchUpType:f}=a;if(f!==Jt)return{error:qn};if(!(l!=null&&l.length))return{error:Ld};const p=(m=hn({matchUp:a,drawDefinition:e,structure:u,event:s}))==null?void 0:m.tieFormat,h={};for(const T of r){if(!Array.isArray(T))return{error:tt,lineUp:T};const E={},y=[];for(const v of T){if(typeof v!="object")return{error:tt,lineUpAssignment:v};const{participantId:P,collectionAssignments:U=[]}=v;if(!Array.isArray(U))return{error:tt,collectionAssignments:U};const O=o.find(M=>M.participantId===P);if(!O)return{error:_e};if(O.participantType!==xt)return{error:xr};const D=(I=(g=a.sides)==null?void 0:g.find(M=>{var w,k;return(k=(w=M.participant)==null?void 0:w.individualParticipantIds)==null?void 0:k.includes(P)}))==null?void 0:I.sideNumber;D&&y.push(D);for(const M of U){if(typeof M!="object")return{error:tt,collectionAssignment:M};const{collectionId:w,collectionPosition:k}=M,_=(S=p==null?void 0:p.collectionDefinitions)==null?void 0:S.find(W=>W.collectionId===w);if(!_)return{error:tt,collectionId:w};const F=`${w}-${k}`;E[F]||(E[F]=[]);const L=E[F].length;if(_.matchUpType===Oe&&L||_.matchUpType===me&&L>1)return{info:"Excessive collectionPosition assignments",error:tt};E[F].push(P)}}const b=Object.values(E);for(const v of b)if(v.length===2){const{participant:P}=Jr({tournamentParticipants:o,participantIds:v});if(!P){const O=es({participant:{participantType:_t,participantRole:fn,individualParticipantIds:v},pairOverride:!0,tournamentRecord:t});if(O.error)return O}}const N=Mn(y),A=(N[1]||0)>(N[2]||0)&&1||(N[2]||0)>(N[1]||0)&&2||void 0,C=Object.keys(h).map(v=>parseInt(v));A&&!C.includes(A)&&(h[A]=T)}if(!Object.keys(h).length)return{error:Eg};if(c=ie({drawDefinition:e,matchUpId:n}),c.error)return c;if(!c.matchUp)return{error:Ye};const{matchUp:d}=c;d.sides||(d.sides=[]);for(const T of[1,2]){const E=d.sides.find(b=>b.sideNumber===T),y=h[T];if(y)E?E.lineUp=y:d.sides.push({lineUp:y,sideNumber:T});else continue}return qt({tournamentId:t==null?void 0:t.tournamentId,context:i,drawDefinition:e,matchUp:d}),{...$}}function jR(t){return Xp(t)}function GR(t){return wh(t)}function WR(t){return Mh(t)}function HR(t){const{tournamentRecord:e}=t;if(!e)return{error:et};const n=e.participants;return Fh({participants:n,...t})}function qR({tournamentRecord:t,drawDefinition:e,structure:n,link:r}){if(!t)return{error:et};if(!e)return{error:lt};const s=Lh({tournamentId:t.tournamentId,drawDefinition:e,structure:n,link:r});if(s.error)return s;const o={itemType:"attachQualifyingStructures",itemValue:{structureId:n.structureId,drawId:e.drawId}};return _s({tournamentRecord:t,timeItem:o}),s}function YR(t){const e=t.tournamentRecord;if(!e)return{error:et};const n=YE(t);if(n.error)return n;const{qualifyingRoundNumber:r,qualifyingPositions:s,targetStructureId:i,drawDefinition:o,structureName:c,matchUpType:a,drawSize:u,drawType:l}=t,p={itemType:"addQualifyingStructures",itemValue:bt({drawId:o.drawId,structureName:c,targetStructureId:i,qualifyingPositions:s,qualifyingRoundNumber:r,matchUpType:a,drawSize:u,drawType:l})};return _s({tournamentRecord:e,timeItem:p}),n}function zR(t){const{tournamentRecord:e}=t;if(!e)return{error:et};const n=e.participants;return Ch({participants:n,...t})}function IN(t){let{seedsCount:e}=t;const n=t.preparedStructureIds||[],{provisionalPositioning:r,inContextDrawMatchUps:s,tournamentRecord:i,appliedPolicies:o,qualifyingOnly:c,drawDefinition:a,seedingProfile:u,participants:l,matchUpsMap:f,automated:p,placeByes:h,drawType:d,drawSize:m,entries:g,event:I,enforcePolicyLimits:S=!0,seedAssignmentProfile:T,seedByRanking:E=!0,seededParticipants:y,assignSeedsCount:b,seedingScaleName:N,stageSequence:A=1,roundTarget:C,stage:v}=t,P=I==null?void 0:I.eventType,U=g.filter(H=>{var R,x;const B=(x=(R=Ke({name:Hr,element:H}))==null?void 0:R.extension)==null?void 0:x.value;return(!H.entryStage||H.entryStage===v)&&(!A||!H.entryStageSequence||H.entryStageSequence===A)&&(!C||!B||B===C)&&ho.includes(H.entryStatus)});y&&(e=y.length),e>m&&(e=m),e>U.length&&(e=U.length);const{structures:O}=lr({drawDefinition:a,stageSequence:A,roundTarget:C,stage:v}),D=((O==null?void 0:O.length)||0)>1,M=O==null?void 0:O.find(({structureId:H})=>!n.includes(H));if(!M)return G({result:{error:Te}});const w=M==null?void 0:M.structureId,k=M?Oo({provisionalPositioning:r,appliedPolicies:o,drawDefinition:a,structure:M}):void 0,{seedLimit:_}=tb({participantsCount:U.length,enforcePolicyLimits:S,appliedPolicies:o,drawDefinition:a,seedingProfile:u,structureId:w,seedsCount:e});_&&_<e&&(e=_);const F=g.map(fe);if(y)y.filter(({participantId:H})=>F.includes(H)).filter(H=>!H.seedNumber||H.seedNumber<=y.length).sort((H,B)=>H.seedNumber<B.seedNumber?-1:H.seedNumber<B.seedNumber?1:0).forEach(H=>{const{participantId:B,seedNumber:R,seedValue:x}=H;Do({provisionalPositioning:r,tournamentRecord:i,drawDefinition:a,seedingProfile:u,participantId:B,seedBlockInfo:k,structureId:w,seedNumber:R,seedValue:x,event:I})});else if(I||N){const{categoryName:H,ageCategoryCode:B}=(I==null?void 0:I.category)||{},R={scaleType:br,scaleName:N||H||B||I.eventId,eventType:P};let{scaledEntries:x}=hu({scaleAttributes:R,tournamentRecord:i,stageSequence:A,entries:g,stage:v});!(x!=null&&x.length)&&E&&({scaledEntries:x}=hu({scaleAttributes:{scaleType:Ii,scaleName:H||B,eventType:P},tournamentRecord:i,stageSequence:A,entries:g,stage:v}));const q=(x==null?void 0:x.length)??0;q<e&&(e=q),x==null||x.filter(({participantId:V})=>F.includes(V)).slice(0,b||e).forEach((V,Y)=>{const z=Y+1,{participantId:J,scaleValue:Q}=V,X=(T==null?void 0:T[z])||Q||z;Do({provisionalPositioning:r,tournamentRecord:i,drawDefinition:a,seedingProfile:u,participantId:J,structureId:w,seedNumber:z,seedValue:X,event:I})})}let L=[],W,j;if(p!==!1&&d!==Xn&&!(c&&v!==Pt)){const H=typeof p=="object"&&p.seedsOnly,B=lu({inContextDrawMatchUps:s,multipleStructures:D,tournamentRecord:i,appliedPolicies:o,drawDefinition:a,seedingProfile:u,participants:l,structureId:w,matchUpsMap:f,placeByes:h,seedLimit:_,seedsOnly:H,drawSize:m,drawType:d,event:I});if(B.conflicts&&(L=B==null?void 0:B.conflicts),W=B==null?void 0:B.positionAssignments,j=B==null?void 0:B.positioningReport,B.error)return G({result:B,stack:"prepareStage"})}return{positionAssignments:W,positioningReport:j,stageEntries:U,structureId:w,seedsCount:e,conflicts:L}}function um(t){var q,V,Y,z,J,Q,X,Z,nt,rt,K,it,st,dt,mt,Mt,Nt,St,ct,Et,gt,Ft,yt,wt,Xt,$t,At,Dt;const e="generateDrawDefinition",{considerEventEntries:n=!0,ignoreAllowedDrawTypes:r,voluntaryConsolation:s,hydrateCollections:i,policyDefinitions:o,ignoreStageSpace:c,tournamentRecord:a,qualifyingOnly:u,tieFormatName:l,drawEntries:f,addToEvent:p,placeByes:h,event:d}=t,m=ge({tournamentRecord:a,event:d}).appliedPolicies??{},I=(t.drawTypeCoercion??((q=m==null?void 0:m[pf])==null?void 0:q.drawTypeCoercion)??!0)&&t.drawSize===2&&na.SingleElimination||t.drawType||na.SingleElimination,{tournamentParticipants:S}=dn({tournamentRecord:a,inContext:!0}),T=t.enforceGender??((Y=(V=o==null?void 0:o[Jn])==null?void 0:V.participants)==null?void 0:Y.enforceGender)??((J=(z=m==null?void 0:m[Jn])==null?void 0:z.participants)==null?void 0:J.enforceGender),E=!r&&a&&Kb({tournamentRecord:a,categoryType:(Q=d==null?void 0:d.category)==null?void 0:Q.categoryType,categoryName:(X=d==null?void 0:d.category)==null?void 0:X.categoryName});if(E!=null&&E.length&&!E.includes(I))return G({result:{error:Bd},stack:e});const y=((Z=d==null?void 0:d.entries)==null?void 0:Z.filter(at=>at.entryStatus&&[...tS,ol].includes(at.entryStatus)))??[],b=(u&&[]||f||(n?y:[])).filter(({entryStage:at})=>!at||at===It),N=d&&S&&Zb({consideredEntries:b,enforceGender:T,participants:S,event:d});if(N!=null&&N.error)return G({result:N,stack:e});const C=!t.drawSize&&b.length&&![Xn,va,ic,Pr,Ds].includes(I)&&Vo(b.length)||t.drawSize&&oe(t.drawSize)&&vt(t.drawSize)||!1;if(isNaN(C)&&I!==Xn)return G({result:{error:Eu},stack:e});let v=typeof t.seedsCount!="number"?vt(t.seedsCount??0):t.seedsCount??0;const P=d==null?void 0:d.eventType,U=t.matchUpType??P,O=t.drawId?(nt=d==null?void 0:d.drawDefinitions)==null?void 0:nt.find(at=>at.drawId===t.drawId):void 0;let{tieFormat:D,matchUpFormat:M}=t;if(U===Jt&&P===Jt){const at=(K=(rt=O==null?void 0:O.structures)==null?void 0:rt.find(({stage:ot})=>ot===It))==null?void 0:K.tieFormat;D=D||at||l&&((it=d==null?void 0:d.tieFormat)==null?void 0:it.tieFormatName)===l&&d.tieFormat||l&&Lo({namedFormat:l,hydrateCollections:i,event:d})||(d==null?void 0:d.tieFormat)||Lo({event:d,hydrateCollections:i}),M=void 0}else M||(D=void 0,d!=null&&d.matchUpFormat||(M=Kn));if(D){const at=vn({gender:d==null?void 0:d.gender,enforceGender:T,tieFormat:D});if(at.error)return G({result:at,stack:e})}if(t.drawId&&typeof t.drawId!="string")return G({result:{error:tt},stack:e});O&&I!==O.drawType&&(O.drawType=I);let k=O??wb({drawType:I,drawId:t.drawId});if((M||D)&&!(M&&(d==null?void 0:d.matchUpFormat)===M||(d==null?void 0:d.tieFormat)&&D&&JSON.stringify(d.tieFormat)===JSON.stringify(D))){if(D){const ot=vC(D);if(ot.error)return G({result:ot,stack:e});k.tieFormat=ot.tieFormat??D}else if(M){const ot=Gl({tournamentRecord:a,drawDefinition:k,matchUpFormat:M,event:d});if(ot.error)return{error:ot.error,info:"matchUpFormat or tieFormat error"}}U&&(k.matchUpType=U)}if(o){if(typeof o!="object")return G({result:{info:"policyDefinitions must be an object",error:tt},stack:e});{const at={};for(const ot of Object.keys(o))JSON.stringify(m==null?void 0:m[ot])!==JSON.stringify(o[ot])&&(at[ot]=o[ot]);Object.keys(at).length&&(Td({drawDefinition:k,policyDefinitions:at}),Object.assign(m,at))}}m[tc]||(Td({drawDefinition:k,policyDefinitions:gp}),Object.assign(m,gp));let _=(dt=(st=O==null?void 0:O.structures)==null?void 0:st.find(at=>at.stage===It&&at.stageSequence===1))==null?void 0:dt.structureId;const F=f??y,L=[];let W,j=[];const H=t.qualifyingPlaceholder&&!((mt=t.qualifyingProfiles)!=null&&mt.length)&&!O,B=O?(Mt=O.structures)==null?void 0:Mt.filter(at=>at.stage===Pt):[],R=(B==null?void 0:B.length)===1&&!((Nt=B[0].matchUps)!=null&&Nt.length)&&B[0].structureId;if(R){const at=t.qualifyingProfiles,ot=at!=null&&at.length?UE({idPrefix:t.idPrefix,isMock:t.isMock,uuids:t.uuids,qualifyingProfiles:at,appliedPolicies:m}):void 0;if(ot!=null&&ot.error)return ot;k.structures=(St=k.structures)==null?void 0:St.filter(({structureId:ne})=>ne!==R),k.links=(ct=k.links)==null?void 0:ct.filter(({source:ne})=>ne.structureId!==R);const{qualifiersCount:Lt,qualifyingDrawPositionsCount:ft,qualifyingDetails:Ct}=ot??{};ft&&(ot!=null&&ot.structures&&((Et=k.structures)==null||Et.push(...ot.structures)),ot!=null&&ot.links&&((gt=k.links)==null||gt.push(...ot.links)));const Ut=(Ft=k.structures)==null?void 0:Ft.find(({stage:ne,stageSequence:Ae})=>ne===It&&Ae===1),{qualifiersCount:Kt}=Li({stageSequence:1,drawDefinition:k,structureId:_,stage:It}),ut=Math.max(Lt??0,Kt??0);let Rt=Dh({qualifiersCount:ut,drawDefinition:k,stage:It});if(Rt.error||(Rt=au({drawSize:ft,stage:Pt,drawDefinition:k}),Rt.error))return Rt;for(const ne of(f??[]).filter(({entryStage:Ae})=>Ae===As.Qualifying)){const Ae={...ne,entryStage:ne.entryStage??As.Main,drawDefinition:k};Gh(Ae)}for(const ne of Ct||[]){const{finalQualifyingRoundNumber:Ae,finalQualifyingStructureId:Ee,roundTarget:Un,finishingPositions:Xe,linkType:Lr}=ne,jn=Ut&&((yt=kc({targetStructureId:Ut.structureId,sourceStructureId:Ee,sourceRoundNumber:Ae,finishingPositions:Xe,targetEntryRound:Un,linkType:Lr}))==null?void 0:yt.link);if(jn!=null&&jn.error)return jn;jn&&(k.links||(k.links=[]),k.links.push(jn))}W={drawDefinition:k}}else{if(W=wh({...t,modifyOriginal:!1,tournamentRecord:a,appliedPolicies:m,drawDefinition:k,matchUpFormat:M,matchUpType:U,tieFormat:D,drawSize:C}),W.error)return G({result:W,stack:e});k=W.drawDefinition;for(const ot of F){if(f&&ot.entryStage&&ot.entryStage!==As.Main)continue;const Lt={...ot,ignoreStageSpace:c??I===Xn,entryStage:ot.entryStage??As.Main,drawDefinition:k,drawType:I},ft=Gh(Lt);if(f&&ft.error)return G({result:ft,stack:e})}I===Ci&&(v=0);const at=IN({...W,...t,qualifyingOnly:!C||u,appliedPolicies:m,drawDefinition:k,participants:S,stage:It,seedsCount:v,placeByes:h,drawSize:C,entries:F});if(at.error&&!at.conflicts)return at;if((wt=at.positioningReport)!=null&&wt.length&&L.push({[It]:at.positioningReport}),_=at.structureId,at.conflicts&&(j=at.conflicts),I===Xn&&t.roundsCount){const ot=(Xt=d==null?void 0:d.entries)==null?void 0:Xt.filter(({entryStage:Ct,entryStatus:Ut})=>(!Ct||Ct===It)&&Ut&&ps.includes(Ut)),Lt=ot==null?void 0:ot.map(kn("participantId")),ft=ot?Math.floor(ot.length/2):0;ht(1,t.roundsCount+1).forEach(()=>{var Ct;if(t.automated){const{restrictEntryStatus:Ut,generateMatchUps:Kt,addToStructure:ut,maxIterations:Rt,structureId:ne,matchUpIds:Ae,scaleName:Ee}=t.drawMatic??{};Yh({tournamentRecord:a,participantIds:Lt,drawDefinition:k,eventType:((Ct=t.drawMatic)==null?void 0:Ct.eventType)??U,generateMatchUps:Kt??!0,restrictEntryStatus:Ut,addToStructure:ut,maxIterations:Rt,structureId:ne,matchUpIds:Ae,scaleName:Ee})}else md({addToStructure:!0,tournamentRecord:a,newRound:!0,drawDefinition:k,matchUpsCount:ft})})}}const x=[];if(t.qualifyingProfiles){const at=(Ct,Ut)=>Ct.stageSequence-Ut.stageSequence,ot=(Ct,Ut)=>Ct.roundTarget-Ut.roundTarget,Lt=[];let ft=1;t.qualifyingProfiles.sort(ot);for(const Ct of t.qualifyingProfiles){if(!Array.isArray(Ct.structureProfiles))return G({result:{error:Tt},info:sn("structureProfiles")});ft=Ct.roundTarget||ft;const Ut=(($t=Ct.structureProfiles)==null?void 0:$t.sort(at))||[];let Kt=1;for(const ut of Ut){const{qualifyingRoundNumber:Rt,qualifyingPositions:ne,seededParticipants:Ae,seedingScaleName:Ee,seedsCount:Un=0,seedingProfile:Xe,seedByRanking:Lr,placeByes:jn,drawSize:ue}=ut,he=IN({...W,...t,stageSequence:Kt,qualifyingRoundNumber:Rt,preparedStructureIds:Lt,qualifyingPositions:ne,seededParticipants:Ae,stage:Pt,seedingScaleName:Ee,appliedPolicies:m,drawDefinition:k,qualifyingOnly:u,seedingProfile:Xe,seedByRanking:Lr,participants:S,roundTarget:ft,seedsCount:Un,placeByes:jn,drawSize:ue,entries:F});if(he.error)return he;he.structureId&&Lt.push(he.structureId),Kt+=1,(At=he.conflicts)!=null&&At.length&&x.push(...he.conflicts),(Dt=he.positioningReport)!=null&&Dt.length&&L.push({[Pt]:he.positioningReport})}ft+=1}}else if(_&&H){const at=Ze({structureName:Pt,stage:Pt}),{link:ot}=kc({sourceStructureId:at.structureId,targetStructureId:_,sourceRoundNumber:0,linkType:js.Position});k.structures||(k.structures=[]),k.structures.push(at),k.links||(k.links=[]),k.links.push(ot)}return k.drawName=t.drawName??I,typeof s=="object"&&zR({...s,tournamentRecord:a,appliedPolicies:m,drawDefinition:k,matchUpType:U}),p&&Za({tournamentRecord:a,drawDefinition:k,event:d}),{existingDrawDefinition:!!O,qualifyingConflicts:x,positioningReports:L,drawDefinition:k,structureId:_,...$,conflicts:j}}function KR(t){return ZE(t)}function JR(t){return t.tournamentRecord?hb(t):{error:et}}function QR({tournamentRecord:t}){if(!t)return{error:et};let e=0;for(const n of t.events??[]){const r=n.tieFormats??[],s=u=>{if(!u.tieFormat)return;let l;for(const f of r)Sc({descendant:u.tieFormat,ancestor:f}).different||(l=f.tieFormatId);if(l)u.tieFormatId=l,delete u.tieFormat;else{const f=pt(u.tieFormat,void 0,!0);f.tieFormatId||(f.tieFormatId=Yt()),u.tieFormatId=f.tieFormatId,delete u.tieFormat,r.push(f),e+=1}};s(n);for(const u of n.drawDefinitions??[]){s(u);for(const l of u.structures??[])s(l)}const i=(u,l)=>{var p;const f=(p=c.eventMatchUps)==null?void 0:p.find(h=>h.matchUpId===u);f&&(f.tieFormatId=l,delete f.tieFormat,qt({tournamentId:t==null?void 0:t.tournamentId,eventId:n.eventId,matchUp:f}))},o=u=>{const l=pt(u.tieFormat,void 0,!0);l.tieFormatId||(l.tieFormatId=Yt()),r.push(l),e+=1,i(u.matchUpId,l.tieFormatId)},c=si({matchUpFilters:{matchUpTypes:[yr]},event:n}),a=c.matchUps??[];for(const u of a){let l;for(const f of r)u.tieFormat&&Sc({descendant:u.tieFormat,ancestor:f}).different||(l=f.tieFormatId);l?i(u.matchUpId,l):o(u)}r.length&&(n.tieFormats=r)}return{...$,addedCount:e}}function ZR(t){return t.tournamentRecord?ms(t):{error:et}}function XR(t){return t.tournamentRecord?Nb(t):{error:et}}function tB(t){return t.tournamentRecord?Ab(t):{error:et}}function eB({tournamentRecord:t,eventUpdates:e,eventId:n,event:r}){var p;if(!t)return{error:et};if(!TC(n)||!or(e))return{error:tt};const s=((p=r==null?void 0:r.entries)==null?void 0:p.filter(({entryStatus:h})=>{const d=h;return[...ps,dr].includes(d)}).map(({participantId:h})=>h))||[],i=s?Fi({participantFilters:{participantIds:s},withIndividualParticipants:!0,tournamentRecord:t}).participants||[]:[],o=[],c=i.reduce((h,d)=>{var g,I;const m=(g=d.person)!=null&&g.sex?[d.person.sex]:((I=d.individualParticpants)==null?void 0:I.map(S=>{var T;return(T=S.person)==null?void 0:T.sex}))||[];return o.push(...m),h.includes(d.participantType)?h:h.concat(d.participantType)},[]),a=Vt(o),u=!a.length||[hs,Io].includes(e.gender||"")||a.length===1&&a[0]===e.gender;if(e.gender&&!u)return G({context:{gender:e.gender},result:{error:tt}});const f=(c.includes(we)&&[we]||c.includes(xt)&&[ls]||c.includes(_t)&&[$n]||[$n,ls,we]).includes(e.eventType||"");return e.eventType&&!f?G({context:{participantType:e.eventType},result:{error:tt}}):(e.eventType&&(r.eventType,e.eventType),e.eventName&&(r.eventName=e.eventName),e.gender&&(r.gender=e.gender),{...$})}const nB={generateQualifyingStructure:HR,attachQualifyingStructure:qR,attachPlayoffStructures:BR,addQualifyingStructure:YR,setStructureOrder:QE,attachStructures:am,renameStructures:KR,disableTieAutoCalc:XR,enableTieAutoCalc:tB,validateCollectionDefinition:cf,modifyCollectionDefinition:zl,orderCollectionDefinitions:qp,removeCollectionDefinition:Kl,addCollectionDefinition:Zl,removeCollectionGroup:Kp,addCollectionGroup:Jp,modifyTieFormat:Qp,resetScorecard:jR,resetTieFormat:Zp,setEventStartDate:hN,setEventEndDate:mN,setEventDates:xR,deleteEvents:kL,modifyEvent:eB,addEvent:Ed,removeSeededParticipant:$R,removeScaleValues:uN,checkValidEntries:Zb,addDrawEntries:ob,removeSeeding:gR,autoSeeding:IR,getAvailablePlayoffRounds:oN,getAvailablePlayoffProfiles:oN,deleteDrawDefinitions:om,addPlayoffStructures:uR,modifyDrawDefinition:OR,addDrawDefinition:Za,removeStructure:XE,modifyDrawName:pN,generateAndPopulatePlayoffStructures:_h,generateSeedingScaleItems:aN,setSubOrder:mb,addEventEntries:Fs,promoteAlternate:QL,promoteAlternates:sN,destroyPairEntry:db,destroyPairEntries:S_,setEntryPosition:cN,setEntryPositions:fR,addEventEntryPairs:DL,removeEventEntries:Id,removeDrawEntries:aR,modifyEventEntries:kR,modifyEntriesStatus:jh,modifySeedAssignment:lR,modifyPairAssignment:cR,resetVoluntaryConsolationStructure:SR,deleteFlightProfileAndFlightDraws:TR,deleteFlightAndFlightDraw:yR,generateFlightProfile:NR,refreshEventDrawOrder:dN,attachFlightProfile:fN,resetDrawDefinition:MR,pruneDrawDefinition:DR,updateDrawIdsOrder:lN,getFlightProfile:be,getScaledEntries:hu,generateLineUps:Hb,addFlight:cm,generateAdHocMatchUps:FR,deleteAdHocMatchUps:UR,addAdHocMatchUps:LR,drawMatic:_R,setOrderOfFinish:wR,setDelegatedOutcome:hR,removeDelegatedOutcome:pR,addVoluntaryConsolationStructure:Ch,addVoluntaryConsolationStage:vR,generateVoluntaryConsolation:AR,attachConsolationStructures:RR,bulkMatchUpStatusUpdate:ey,updateTieMatchUpScore:ZR,aggregateTieFormats:QR,setMatchUpFormat:dR,setMatchUpStatus:Qa,assignDrawPosition:ML,assignSeedPositions:wL,assignDrawPositionBye:oR,substituteParticipant:PR,removeRoundMatchUps:UL,swapDrawPositionAssignments:sR,assignMatchUpSideParticipant:AL,removeMatchUpSideParticipant:vL,removeDrawPositionAssignment:Sd,alternateDrawPositionAssignment:rR,withdrawParticipantAtDrawPosition:ZL,setDrawParticipantRepresentativeIds:bL,getDrawParticipantRepresentativeIds:NL,luckyLoserDrawPositionAssignment:tR,qualifierDrawPositionAssignment:nR,setPositionAssignments:iR,automatedPositioning:d_,automatedPlayoffPositioning:pd,checkInParticipant:KL,checkOutParticipant:JL,toggleParticipantCheckInState:Jy,addDrawDefinitionTimeItem:Rb,generateDrawTypeAndModifyDrawDefinition:GR,generateDrawStructuresAndLinks:WR,generateDrawMaticRound:Tb,generateDrawDefinition:um,applyLineUps:VR,assignTieMatchUpParticipantId:em,removeTieMatchUpParticipantId:CL,replaceTieMatchUpParticipantId:Qb,resetMatchUpLineUps:JR,updateTeamLineUp:Uc,validateLineUp:zT,getTeamLineUp:ba};function rB(t){const{entries:e=[],entryStatus:n,stage:r}=t;return Math.max(...e.filter(s=>(!r||r===s.entryStage)&&(!n||s.entryStatus===n)&&!isNaN(s.entryPosition)).map(({entryPosition:s})=>vt(s||0)),0)}function sB(t){var O,D,M,w;let{matchUps:e}=t;const{tournamentRecord:n,drawDefinition:r,excludeMargin:s,exclusionRule:i,zoneDoubling:o,matchUpType:c,scaleName:a,eventId:u,zonePct:l,drawId:f,event:p}=t;if(!n&&!e)return{error:et};if(c&&![Oe,me].includes(c))return{error:tt,info:{matchUpType:c}};if(e&&!cr(e))return{error:tt,context:{matchUps:e}};const h=wr[a],d=(h==null?void 0:h.ascending)??t.ascending??!1,m=(h==null?void 0:h.accessor)??t.valueAccessor,g=Array.isArray(h==null?void 0:h.range)?Math.abs(h.range[0]-h.range[1]):0,I=oe(l)&&g?(l||0/100)*g:t.zoneMargin||g,S={withScaleValues:!0,withCompetitiveness:!0},T={matchUpTypes:c?[c]:[Oe,me]},E=n==null?void 0:n.participants;(O=e==null?void 0:e[0])!=null&&O.hasContext?f?e=e.filter(k=>k.drawId===f):u&&(e=e.filter(k=>k.eventId===u)):e===void 0&&(e=f&&!r&&[]||!f&&u&&!p&&[]||f&&((D=tr({inContext:!0,drawDefinition:r,contextFilters:T,contextProfile:S,participants:E}))==null?void 0:D.matchUps)||!f&&u&&((M=si({inContext:!0,contextFilters:T,contextProfile:S,participants:E,event:p}))==null?void 0:M.matchUps)||((w=He({tournamentRecord:n,contextFilters:T,contextProfile:S}))==null?void 0:w.matchUps)||[]),c&&(e=e.filter(k=>k.matchUpType===c));const y=e.filter(({winningSide:k,score:_,sides:F,matchUpStatus:L})=>![In,te,ce,ia,zn].includes(L||"")&&Be({score:_})&&(F==null?void 0:F.length)===2&&k),b=oB({matchUps:y,excludeMargin:s,exclusionRule:i,valueAccessor:m,ascending:d,scaleName:a}),N=!o||c===Oe?I:(I||0)*2,A=I?y.map(({competitiveProfile:k,matchUpType:_,score:F,sides:L})=>{const W=SN({valueAccessor:m,matchUpType:_,scaleName:a,sides:L}),j=Math.abs(W[0].value-W[1].value);return{competitiveness:k==null?void 0:k.competitiveness,valuesGap:j,score:F}}).filter(({valuesGap:k})=>k<=N):[],C=iB({zoneData:A}),v=C&&[].concat(Object.values(C)).flat().length,P=v&&Object.assign({},...Object.keys(C).map(k=>({[k]:Math.round(1e4*C[k].length/v)/100}))),U=y.length-((A==null?void 0:A.length)||0);return{...$,relevantMatchUps:y,zoneDistribution:P,zoneData:A,accuracy:b,nonZone:U}}function iB({zoneData:t}){const e={[If]:[],[ca]:[],[aa]:[]};for(const n of t){const{competitiveness:r,score:s,valuesGap:i}=n;e[r]&&e[r].push({score:s,valuesGap:i})}return e}function SN({exclusionRule:t,valueAccessor:e,matchUpType:n,scaleName:r,sides:s}){const i=t==null?void 0:t.range.sort(),o=c=>{const a=c==null?void 0:c[t==null?void 0:t.valueAccessor];return{exclude:t&&a>=i[0]&&a<=i[1],exclusionValue:a}};return s.sort((c,a)=>c.sideNumber-a.sideNumber).map(({participant:c})=>{const a=[],u=c==null?void 0:c.individualParticipants;if(u!=null&&u.length){const l=[];let f=0;for(const p of u){const{scaleValue:h,value:d}=TN({valueAccessor:e,participant:p,matchUpType:n,scaleName:r}),{exclude:m,exclusionValue:g}=o(h);m&&a.push(g),l.push(h),d&&!isNaN(f)?f+=d:f=void 0}return{participantName:c.participantName,exclusionValues:a,scaleValues:l,value:f}}else if(c){const{scaleValue:l,value:f}=TN({valueAccessor:e,matchUpType:n,participant:c,scaleName:r}),{exclude:p,exclusionValue:h}=o(l);return p&&a.push(h),{participantName:c.participantName,exclusionValues:a,scaleValue:l,value:f}}else return{}})}function TN({participant:t,valueAccessor:e,matchUpType:n,scaleName:r}){var a,u,l,f,p;const s=(u=(a=t==null?void 0:t.rankings)==null?void 0:a[n])==null?void 0:u.find(h=>h.scaleName===r),o=(p=((f=(l=t==null?void 0:t.ratings)==null?void 0:l[n])==null?void 0:f.find(h=>h.scaleName===r))||s)==null?void 0:p.scaleValue,c=e?o==null?void 0:o[e]:o;return{scaleValue:o,value:c}}function oB({excludeMargin:t,exclusionRule:e,valueAccessor:n,ascending:r,scaleName:s,matchUps:i}){const o={affirmative:[],negative:[],excluded:[]};for(const u of i){const{matchUpType:l,sides:f,score:p,winningSide:h}=u;if(!h)continue;if(e&&(!e.valueAccessor||!e.range))return{info:"exclusionRule requires valueAccessor and range",error:Tt};const d=h-1,m=SN({exclusionRule:e,valueAccessor:n,matchUpType:l,scaleName:s,sides:f});if(e){const y=m.map(({exclusionValues:b})=>b).flat();if(y.length){o.excluded.push({scoreString:p==null?void 0:p.scoreStringSide1,exclusionValues:y,winningSide:h,sideValues:m});continue}}if(m.filter(y=>![void 0,"",null].includes(y.value)).length<2){o.excluded.push({scoreString:p==null?void 0:p.scoreStringSide1,missingValues:!0,winningSide:h,sideValues:m});continue}const g=m[d].value-m[1-d].value,I=parseFloat(t||0),S=I&&Math.abs(g)<I;if(S){o.excluded.push({scoreString:p==null?void 0:p.scoreStringSide1,excludeMargin:t,winningSide:h,excludeGap:S,sideValues:m,valuesGap:g});continue}const T=r?g:g*-1,E=h===1?p==null?void 0:p.scoreStringSide1:p==null?void 0:p.scoreStringSide2;T>0?o.affirmative.push({winningScoreString:E,winningSide:h,sideValues:m,valuesGap:g,score:p}):o.negative.push({winningScoreString:E,winningSide:h,sideValues:m,valuesGap:g,score:p})}const c=o.affirmative.length+o.negative.length,a=c&&o.affirmative.length/c*100;return o.percent=a?Math.round(100*a)/100:0,o}function cB({tournamentRecord:t,drawDefinition:e,structureId:n,matchUpId:r,drawId:s,event:i}){var p;if(!t)return{error:et};if(!s&&!i&&!n&&!r)return G({result:{error:Tt},stack:"getMatchUpFormat"});const o=eu({tournamentRecord:t,drawDefinition:e,matchUpId:r,drawId:s,event:i});if(r&&(o!=null&&o.error))return o;!e&&(o!=null&&o.drawDefinition)&&(e=o==null?void 0:o.drawDefinition);let c=o==null?void 0:o.structure;if(!c&&n&&!r){if(!e)return{error:Hn};const h=Ot({drawDefinition:e,structureId:n});if(h.error)return h;c=h.structure}const a=c==null?void 0:c.matchUpFormat,u=e==null?void 0:e.matchUpFormat,l=i==null?void 0:i.matchUpFormat,f=((p=o==null?void 0:o.matchUp)==null?void 0:p.matchUpFormat)||a||u||l;return{structureDefaultMatchUpFormat:a,eventDefaultMatchUpFormat:l,drawDefaultMatchUpFormat:u,matchUpFormat:f}}function aB({profileBands:t,tournamentRecord:e,matchUps:n}){if(!cr(n))return{error:$s};const r=!t&&Xi({policyType:Hs,tournamentRecord:e}).policy,s=t||(r==null?void 0:r.profileBands)||Sf[Hs].profileBands,i=n.filter(({winningSide:p})=>p),o=i.map(uI),c=(p,h)=>{const d=aI(h,s);return p[d]+=1,p},a=lI(o).reduce((p,h)=>c(p,h),{[If]:0,[ca]:0,[aa]:0,[iI]:0}),u=Object.keys(a).reduce((p,h)=>(a[h]||0)+p,0),l=Object.keys(a).map(p=>{const h=parseFloat((a[p]/u).toFixed(4));return{[p]:h*100}}),f=i.filter(({matchUpStatus:p})=>p===oI).length;return l.push({[oI]:parseFloat((f/u).toFixed(4))*100}),{competitiveBands:Object.assign({},...l),...$}}function uB({tournamentRecord:t,outcomes:e}){var o;if(!t)return{error:et};if(!(e!=null&&e.length))return{error:Tt,info:"Missing outcomes"};const n=e.reduce((c,a)=>{const{drawId:u,eventId:l}=a;return l&&u&&(c[l]?c[l].includes(u)||c[l].push(u):c[l]=[u]),c},{}),r=Object.keys(n);return{publishedEventIds:((o=t.events)==null?void 0:o.filter(c=>r.includes(c.eventId))).filter(c=>{const{timeItem:a}=ws({itemType:`${Qn}.${Zn}`,event:c}),u=a==null?void 0:a.itemValue,{eventId:l}=c;return n[l].filter(p=>{var h,d;return(d=(h=u==null?void 0:u[Kr])==null?void 0:h.drawIds)==null?void 0:d.includes(p)}).length}).map(c=>c.eventId),eventIdPublishedDrawIdsMap:n}}function lB({tournamentRecord:t,participantId:e}){if(!t)return{error:et};if(!e)return{error:Ce};const{participant:n}=zs({tournamentRecord:t,participantId:e});if(!n)return{error:_e};const{timeItem:r}=kr({itemType:Ta,element:n});return r&&r.itemValue===ya&&ya}function dB({tournamentRecord:t,event:e}){var p,h;if(!t)return{error:et};if(!e)return{error:Wt};const n=e.entries||[],r=t.participants||[],s=((p=e.category)==null?void 0:p.categoryName)||((h=e.category)==null?void 0:h.ageCategoryCode),{eventType:i}=e,o=n.map(d=>d.participantId),c=r.filter(d=>o.includes(d.participantId));let a,u,l;return{entryScaleAttributes:c.map(d=>{var b,N,A,C,v,P;const{participantId:m,participantName:g,name:I}=d;let S={scaleType:xI,eventType:i,scaleName:s};const T=(N=(b=Ts({participant:d,scaleAttributes:S}))==null?void 0:b.scaleItem)==null?void 0:N.scaleValue;S={scaleType:OP,eventType:i,scaleName:s};const E=(C=(A=Ts({participant:d,scaleAttributes:S}))==null?void 0:A.scaleItem)==null?void 0:C.scaleValue;S={scaleType:UP,eventType:i,scaleName:s};const y=(P=(v=Ts({participant:d,scaleAttributes:S}))==null?void 0:v.scaleItem)==null?void 0:P.scaleValue;return a=!!(a||T),u=!!(u||E),l=!!(l||y),{participantId:m,participantName:g||I,seed:T,ranking:E,rating:y}}),hasSeededParticipants:a,hasRankedParticipants:u,hasRatedParticipants:l}}function fB(t){return Cn(t)}function pB(t){const{tournamentRecord:e}=t;if(!e)return{error:et};const{tournamentParticipants:n}=dn({tournamentRecord:e,inContext:!0});return Ob({tournamentParticipants:n,...t})}function hB({tournamentRecord:t,drawDefinition:e}){return t?{drawDefinition:pt(e)}:{error:et}}const mB={allTournamentMatchUps:He,tournamentMatchUps:fT,allEventMatchUps:si,getRoundMatchUps:fB,allDrawMatchUps:tr,eventMatchUps:pT,drawMatchUps:vO,credits:sd,getTournamentStructures:LM,getEventStructures:GT,getEvents:uP,getEvent:aP,findDrawDefinitionExtension:Hu,findParticipantExtension:sP,findTournamentExtension:Bn,findEventExtension:Us,findExtension:xn,getTieFormat:Oy,getMatchUpFormat:cB,getDrawDefinition:hB,getEventProperties:dB,getPositionAssignments:im,isValidMatchUpFormat:nr,getMaxEntryPosition:rB,getMatchUpCompetitiveProfile:dI,findVenue:Js,getCourts:vP,getVenuesAndCourts:Of,findCourt:AP,getEventTimeItem:ws,getTournamentTimeItem:El,getParticipantTimeItem:SO,getDrawDefinitionTimeItem:IO,bulkUpdatePublishedEventIds:uB,matchUpActions:gE,positionActions:pB,findMatchUp:BD,participantScheduledMatchUps:cy,getPredictiveAccuracy:sB,getMatchUpsStats:aB,participantScaleItem:Ts,getParticipantScaleItem:bd,getParticipantSignInStatus:lB,getPolicyDefinitions:Zi,getMatchUpScheduleDetails:_f},gB={addVenue:ma,deleteVenue:yh,deleteVenues:ak,modifyVenue:PE,enableCourts:TE,enableVenues:yE,disableCourts:IE,disableVenues:SE,addCourt:Nh,addCourts:Ah,deleteCourt:bE,modifyCourt:bh,modifyCourtAvailability:vE,findVenue:NP};(()=>{const t={getState:o=>gF({convertExtensions:o==null?void 0:o.convertExtensions,removeExtensions:o==null?void 0:o.removeExtensions,tournamentId:os()}),newTournamentRecord:(o={})=>{const c=Jh(o),a=c.tournamentId;return c.error?c:(Dg(c),Zc(a),{...$,tournamentId:a})},setTournamentId:o=>Zc(o),version:()=>Es(),reset:()=>{const o=Xd(os());return e(o)},setState:(o,c,a)=>{Hi(c,a);const u=Qh(o,c);return e(u)},getDevContext:o=>ze(o),executionQueue:(o,c)=>i(o,c),devContext:o=>(zo(o),t)};function e(o){return o!=null&&o.error?(t.error=o.error,t.success=!1):(t.error=void 0,t.success=!0),t}return s([mB,nB,gB,gL,EL,hL,WF,uL,xF]),t;function n(o,c,a,u){var I,S;delete t.success,delete t.error;const l=Date.now(),f=IF(o,a),p=c({...f,tournamentRecord:o}),h=Date.now()-l,d=ze(),m={method:u},g=typeof d.result=="object"&&d.result.error;return![void 0,!1].includes(d.perf)&&(isNaN(d.perf)||h>d.perf)&&(m.elapsed=h),(g||d.params&&!Array.isArray(d.params)||Array.isArray(d.params)&&((I=d.params)!=null&&I.includes(u)))&&(m.params=a),(g||!g&&d.result&&!Array.isArray(d.result)||Array.isArray(d.result)&&((S=d.result)!=null&&S.includes(u)))&&(m.result=p),Object.keys(m).length>1&&console.log("te:",m),d.makeDeepCopy&&(p.deepCopyIterations=nC()),p}function r(o,c,a){const u=os(),l=(c==null?void 0:c.sandBoxRecord)||(c==null?void 0:c.sandboxRecord)||(c==null?void 0:c.sandboxTournament)||Jc(u),f=(c==null?void 0:c.rollbackOnError)&&pt(l,!1,!0),p=n(l,o,c,a);p!=null&&p.error&&f&&Qh(f);const h=(p==null?void 0:p.success)&&(c==null?void 0:c.delayNotify)!==!0&&(c==null?void 0:c.doNotNotify)!==!0,d=Kc(),m=Date.now();return d&&(Dl({tournamentRecord:l,value:{version:Es(),timeStamp:m}}),p.modificationsApplied=!0),h&&Di({directives:[{method:o,params:c}],mutationStatus:d,tournamentId:u,timeStamp:m}),(h||!(p!=null&&p.success)||c!=null&&c.doNotNotify)&&fi(),p}function s(o){o.forEach(c=>{Object.keys(c).forEach(a=>{t[a]=u=>{if(ze())return r(c[a],u,a);try{return r(c[a],u,a)}catch(l){Xc({engineName:"tournamentEngine",methodName:a,params:u,err:l})}}})})}function i(o,c){var m;if(!Array.isArray(o))return{error:tt};const a=os(),u=Jc(a),l=c&&pt(u,!1,!0),f=[];for(const g of o){if(typeof g!="object")return{error:tt};const{method:I,params:S}=g;if(!t[I]){const E={error:vg,methodName:I},y=ze();return(y.result&&!Array.isArray(y.result)||Array.isArray(y.result)&&((m=y.result)!=null&&m.includes(I)))&&console.log("te:",E),E}const T=n(u,t[I],S,I);if(T!=null&&T.error)return l&&Qh(l),{...T,rolledBack:!!l};f.push({...T,methodName:I})}const p=Kc(),h=Date.now();return p&&Dl({tournamentRecord:u,value:{version:Es(),timeStamp:h}}),Di({directives:o,mutationStatus:p,timeStamp:h,tournamentId:a}),fi(),{success:f.every(g=>g.success),results:f}}})();function yN(t,e){var s;if(typeof t!="object")return{error:Ir};const n=((s=t.unifiedTournamentId)==null?void 0:s.tournamentId)||t.tournamentId;if(!n)return{error:is};const r=e!==!1?pt(t):t;return Qc({[n]:r}),Zc(n),r}function IB(t){const{convertExtensions:e,removeExtensions:n,tournamentId:r}=t||{};if(typeof r!="string")return{};const s=Jc(r);return{tournamentRecord:pt(s,e,!1,n)}}function SB(t,e){return t&&e!=null&&e.someParam&&(e={...e}),e}function EN(t,e){return t&&e&&Array.isArray(e)&&e[t-1]||typeof e=="object"&&e[t]}function TB(t){const{participation:e={},awardProfiles:n,startDate:r,eventType:s,drawSize:i,drawType:o,category:c,endDate:a,level:u}=t,{participationOrder:l,flightNumber:f,rankingStage:p}=e,h=m=>!r&&!a||!m.dateRanges?!0:m.dateRanges.some(g=>{const I=!r||!g.startDate||new Date(r)>new Date(g.startDate),S=!a||!g.endDate||new Date(a)<=new Date(g.endDate);return I&&S});return{awardProfile:n.find(m=>{var g,I,S,T,E,y,b,N,A,C;return h(m)&&(!m.maxFlightNumber||f<=m.maxFlightNumber)&&(!((g=m.drawTypes)!=null&&g.length)||((I=m.drawTypes)==null?void 0:I.includes(o)))&&(!((S=m.drawSizes)!=null&&S.length)||m.drawSizes.includes(i))&&(!((T=m.stages)!=null&&T.length)||m.stages.includes(p))&&(!((E=m.levels)!=null&&E.length)||m.levels.includes(u))&&(!m.maxDrawSize||i<=m.maxDrawSize)&&(!m.drawSize||m.drawSize===i)&&(!m.maxLevel||u<=m.maxLevel)&&(!f||!((b=(y=m.flights)==null?void 0:y.flightNumbers)!=null&&b.length)||m.flights.flightNumbers.includes(f))&&(!m.participationOrder||m.participationOrder===l)&&(!((N=m.category)!=null&&N.ageCategoryCodes)||m.category.ageCategoryCodes.includes(c==null?void 0:c.ageCategoryCode))&&(!((A=m.eventTypes)!=null&&A.length)||((C=m.eventTypes)==null?void 0:C.includes(s)))})}}function bN({participantWon:t,flightNumber:e,valueObj:n,drawSize:r,flights:s,level:i}){var d,m;const o=(g,I)=>{if(g){if(Array.isArray(I)){const S=I.find(T=>T.flight===g||T.f===g);return S.value||S.v}if(typeof I=="object"){const S=I.flights||I.f;if(Array.isArray(S))return S[g-1]}}},c=(g,I)=>{const S=(g==null?void 0:g.value)||(g==null?void 0:g.v)||(oe(g)?g:0),T=EN(i,g==null?void 0:g.level);return{value:o(I,T)||oe(T)&&T||S}};let a=0,u,l,f,p;const h=t&&"won"||t===!1&&"lost"||void 0;if(Array.isArray(n)){let g=n.find(T=>{var E;return T.drawSize===r||((E=T.drawSizes)==null?void 0:E.includes(r))}),I=n.find(T=>T.drawSize&&T.threshold&&r>T.drawSize),S=n.find(T=>{var E;return!T.drawSize&&!((E=T.drawSizes)!=null&&E.length)});h!==void 0&&(g=g==null?void 0:g[h],I=I==null?void 0:I[h],S=S==null?void 0:S[h]),l=c(g,e).value,f=c(I,e).value,p=c(S,e).value,a=l||f||p,u=l&&g.requireWin||f&&I.requireWin||(S==null?void 0:S.requireWin)}else if(typeof n=="object"){let g=(d=n==null?void 0:n.drawSizes)==null?void 0:d[r],I=n;h!==void 0&&(g=g==null?void 0:g[h],I=I==null?void 0:I[h]),l=c(g,e).value,p=c(I,e).value,a=l||p,u=l?g.requireWin:I==null?void 0:I.requireWin}else oe(n)&&h===void 0&&(a=n);return e&&((m=s==null?void 0:s.pct)!=null&&m[e])&&(a=Math.round(a*s.pct[e])),{awardPoints:a,requireWin:u}}function yB({participantFilters:t,policyDefinitions:e,tournamentRecord:n,saveRankings:r,level:s}){var S;if(!n)return{error:et};const{policyDefinitions:i}=Zi({policyTypes:[df],tournamentRecord:n}),o=(e==null?void 0:e[df])||(i==null?void 0:i[df]);if(!o)return{error:Au};const c=o.awardProfiles;let a=o.requireWinFirstRound;const u=o.requireWinForPoints,{participants:l,derivedEventInfo:f,derivedDrawInfo:p,mappedMatchUps:h}=Fi({withRankingProfile:!0,participantFilters:t,tournamentRecord:n}),d=l==null?void 0:l.filter(T=>{var E;return(E=T.draws)==null?void 0:E.length}),m={},g={},I={};for(const T of d||[]){const{participantType:E,participantId:y,person:b,draws:N}=T;for(const A of N){const{drawId:C,structureParticipation:v,eventId:P}=A,U=f[P],O=p[C],D=O==null?void 0:O.drawType,{category:M,eventType:w}=U||{},k=A.startDate||U.startDate||n.startDate,_=A.endDate||U.endDate||n.endDate;if(w===ds&&y!==vr)continue;let F;if(c){let L=u,W=0,j=0,H=0,B;for(const R of v){const{finishingPositionRange:x,participationOrder:q,participantWon:V,flightNumber:Y,rankingStage:z,winCount:J}=R;W+=J||0;const Q=O==null?void 0:O.drawSize,{awardProfile:X}=TB({awardProfiles:c,participation:R,eventType:w,startDate:k,category:M,drawSize:Q,drawType:D,endDate:_,level:s});if(X){if(!Q)continue;const Z=Array.isArray(x)&&Math.max(...x),nt=Vt(x||[]).join("-"),rt=Z&&z!==Pt&&(x==null?void 0:x.includes(Q));X.requireWinForPoints!==void 0&&(L=X.requireWinForPoints),X.requireWinFirstRound!==void 0&&(a=X.requireWinFirstRound);const{finishingPositionPoints:K={},finishingPositionRanges:it,finishingRound:st,pointsPerWin:dt,flights:mt}=X,Mt=Array.isArray(X.perWinPoints)?(S=X.perWinPoints)==null?void 0:S.find(gt=>{var Ft;return(Ft=gt.participationOrders)==null?void 0:Ft.includes(q)}):X.perWinPoints,Nt=K.participationOrders;let St=0,ct;if((!Nt||Nt.includes(q))&&it&&Z){const gt=it[Z];gt&&({awardPoints:St,requireWin:ct}=bN({flightNumber:Y,valueObj:gt,drawSize:Q,flights:mt,level:s}))}if(!St&&st&&q===1&&Z){const gt=st[Z];gt&&({awardPoints:St,requireWin:ct}=bN({participantWon:V,flightNumber:Y,valueObj:gt,drawSize:Q,flights:mt,level:s}))}if(rt&&a!==void 0&&(L=a),ct!==void 0&&(L=ct),St>j&&(!L||J)&&(j=St,B=Z),!St&&dt&&J&&(H+=J*dt,B=nt),!St&&J&&Mt){const gt=EN(s,Mt==null?void 0:Mt.level);gt?H+=J*gt:Mt.value&&(H+=J*Mt.value)}}if(F=j+H,E===vr){const Z=(T.matchUps||[]).filter(({structureId:nt})=>nt===R.structureId);for(const{matchUpId:nt}of Z){const rt=h[nt],K=rt.sides.find(it=>it.participantId===y).sideNumber;if(rt.winningSice===K)for(const it of rt.tieMatchUps)it.winningSide}}}if(H||j){const R={winCount:W,positionPoints:j,rangeAccessor:B,perWinPoints:H,eventType:w,drawId:C,points:F},x=b==null?void 0:b.personId;x?(m[x]||(m[x]=[]),m[x].push(R)):E===_t?(I[y]||(I[y]=[]),I[y].push(R)):E===vr&&(g[y]||(g[y]=[]),g[y].push(R))}}}}return r&&ae({element:n,extension:{name:nI,value:{personPoints:m,teamPoints:g,pairPoints:I}}}),{participantsWithOutcomes:d,personPoints:m,pairPoints:I,teamPoints:g,...$}}const EB={getTournamentPoints:yB},bB=t=>250/Math.pow(t+5,.4),NB=()=>1;function AB(t=3,e=2){const n=t/e;return isNaN(n)?Lc.kDefault():n}const Lc={nSpread:400,diffThreshold:.125,kCalc:bB,kMultiplier:AB,kDefault:NB};function NN(t){let{winnerRating:e,loserRating:n,ratingRange:r}=t;const{ratings:s=wr,winnerCountables:i=1,loserCountables:o=0,ratingType:c=No,maxCountables:a,countables:u}=t||{},l=s==null?void 0:s[c];if(!l)return{error:Tt};r=l.range||r,e=e||l.defaultInitialization,n=n||l.defaultInitialization;const f=r[0]>r[1],p=l.decimalsCount||0,h=f?r.slice().reverse():r,d=(k,_)=>parseFloat(_)>=Math.min(...k)&&parseFloat(_)<=Math.max(...k);(!d(r,e)||!d(r,n))&&(d(r,e)||(e=l.defaultInitialization),d(r,n)||(n=l.defaultInitialization));const m=({value:k,sourceRange:_,targetRange:F})=>(k-_[0])*(F[1]-F[0])/(_[1]-_[0])+F[0],g=m({targetRange:wr[No].range,sourceRange:h,value:f?r[0]-e:e}),I=m({targetRange:wr[No].range,sourceRange:h,value:f?r[0]-n:n}),S=(k,_)=>1/(1+Math.pow(10,(_-k)/Lc.nSpread)),T=S(g,I),E=S(I,g),y=Lc.kCalc(i),b=Lc.kCalc(o),N=Lc.kMultiplier(a,u),A=g+N*y*(1-T),C=I+N*b*(0-E),v=m({sourceRange:wr[No].range,value:A,targetRange:h}),P=m({sourceRange:wr[No].range,value:C,targetRange:h}),U=f?r[0]-v:v;let O=parseFloat(parseFloat(U).toFixed(p));const D=f?r[0]-P:P;let M=parseFloat(parseFloat(D).toFixed(p));const w=Math.max(...r)?Math.abs(e-n)/Math.max(...r):0;return(v>P&&w>Lc.diffThreshold||O<0||M<0)&&(O=e,M=n),{newWinnerRating:O,newLoserRating:M}}const vB=t=>(t==null?void 0:t.reduce((e,n)=>(n.winningSide&&(e[n.winningSide-1]+=1),e),[0,0]))||[0,0];function CB({removePriorValues:t=!0,tournamentRecord:e,ratingType:n=No,considerGames:r,matchUpIds:s,asDynamic:i}){var f,p;if(!e)return{error:et};if(!Array.isArray(s))return{error:$s};if(typeof n!="string")return{error:tt,ratingType:n};if(!wr[n])return{error:tt};const o=wr[n],{accessor:c}=o,a={},u=He({matchUpFilters:{matchUpIds:s,matchUpStatuses:We},tournamentRecord:e,inContext:!0}).matchUps||[];for(const h of u.sort(vo)){const{endDate:d,matchUpFormat:m,score:g,sides:I,winningSide:S}=h,T=h.matchUpType,E={eventType:T,scaleName:n,scaleType:to},y=`${n}.${pI}`,b={scaleName:y,eventType:T,scaleType:to},N=Object.assign({},...(I||[]).map(k=>{const{sideNumber:_,participant:F}=k;return _&&{[_]:[F==null?void 0:F.participantId,...(F==null?void 0:F.individualParticipantIds)||[]].filter(Boolean).flat()}})),A=i?y:n,C=Object.assign({},...Object.values(N).flat().map(k=>{const{scaleItem:_}=bd({scaleAttributes:b,tournamentRecord:e,participantId:k}),{scaleItem:F}=bd({tournamentRecord:e,scaleAttributes:E,participantId:k}),L=c?{[c]:void 0}:void 0;return k&&{[k]:_??F??{scaleName:A,eventType:T,scaleDate:d,scaleType:to,scaleValue:L}}})),v=m?yn(m):{},P=(v==null?void 0:v.bestOf)||1,U=(v==null?void 0:v.setsTo)||1,O=r?P&U:P,D=(g==null?void 0:g.sets)&&vB(g.sets)||S===1&&[1,0]||[0,1],M=S?N[S]:[],w=S?N[3-S]:[];for(const k of M){const _=(f=C[k])==null?void 0:f.scaleValue,F=typeof _=="object"?_[c]:_;for(const L of w){const W=(p=C[L])==null?void 0:p.scaleValue,j=typeof W=="object"?W[c]:W,H=S?D[S]:[0,0],B=S?D[3-S]:[0,0],{newWinnerRating:R,newLoserRating:x}=NN({winnerCountables:H,loserCountables:B,maxCountables:O,winnerRating:F,loserRating:j,ratingType:n}),q=c?{..._,[c]:R}:R,V=c?{...W,[c]:x}:x;C[k].scaleValue=q,C[L].scaleValue=V;let Y=du({participantId:k,removePriorValues:t,tournamentRecord:e,scaleItem:{...C[k],scaleName:A}});if(Y.error||(Y=du({participantId:L,removePriorValues:t,tournamentRecord:e,scaleItem:{...C[L],scaleName:A}}),Y.error))return Y}}Object.assign(a,C)}const l=u.map(({matchUpId:h})=>h);return{...$,modifiedScaleValues:a,processedMatchUpIds:l}}const PB={calculateNewRatings:NN,generateDynamicRatings:CB};(()=>{const t={getState:i=>IB({convertExtensions:i==null?void 0:i.convertExtensions,removeExtensions:i==null?void 0:i.removeExtensions,tournamentId:os()}),setTournamentId:i=>Zc(i)};t.version=()=>Es(),t.reset=()=>{const i=Xd(os());return e(i)},t.setState=(i,o,c)=>{Hi(o,c);const a=yN(i,o);return e(a)};function e(i){return i!=null&&i.error?(t.error=i.error,t.success=!1):(t.error=void 0,t.success=!0),t}return s([EB,PB]),t;function n(i,o,c){delete t.success,delete t.error;const a=SB(i,c);return o({...a,tournamentRecord:i})}function r(i,o){const c=(o==null?void 0:o.sandBoxRecord)||(o==null?void 0:o.sandboxRecord)||(o==null?void 0:o.sandboxTournament)||Jc(os()),a=(o==null?void 0:o.rollbackOnError)&&pt(c,!1,!0),u=n(c,i,o);u!=null&&u.error&&a&&yN(a);const l=(u==null?void 0:u.success)&&(o==null?void 0:o.delayNotify)!==!0&&(o==null?void 0:o.doNotNotify)!==!0;return l&&Di(),(l||!(u!=null&&u.success)||o!=null&&o.doNotNotify)&&fi(),u}function s(i){i.forEach(o=>{Object.keys(o).forEach(c=>{t[c]=a=>{if(ze())return r(o[c],a);try{return r(o[c],a)}catch(u){Xc({engineName:"scaleEngine",methodName:c,params:a,err:u})}}})})}})();var UB=["Abbey","Assange","Ahern","Ampleforth","Atreides","Austen","Banks","Barrington","Batty","Bauers","Beals","Beer","Bennett","Berry","Bonaparte","Brockovich","Bukowski","Cassidy","Catton","Calvino","Carson","Chip","Constant","Crane","Crowne","Cummings","Curie","Dallas","Diamond","Deckard","Earhart","Eisenstein","Eldritch","Elliot","Eyre","Faulkner","Fukuoka","Godel","Goldstein","Greer","Hedges","Herbert","Holmgren","Humperdinck","Huxley","Illich","Jeffers","Jensen","Jevons","Johnson","Johnstone","Jovovich","Kingsnorth","Langer","Fernwright","Fuller","Le Guin","Lem","Lovelace","Midgely","Mond","Montoya","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","Wormwood"],OB=["Ada","Amelia","Amelie","America","Anne","Antoina","Aravis","Astrid","Beatrice","Brienne","Buttercup","Caitlin","Cimorene","Cordelia","Desdemona","Ellen","Elizabeth","Emily","Emmie","Erin","Eva","Evelyn","Hermia","Hypatia","Imogen","Jane","Jasmine","Juliana","Juliet","Heather","Helen","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"],MB=["Alan","Aldous","August","Axel","Barda","Bill","Charles","Chris","Darwin","David","Derrick","Edward","Emmanuel","Ernst","Estlin","Fezzik","Filby","Frank","Frito","George","Glen","Helmholtz","Inigo","Italo","Ivan","James","Jared","Joe","Julian","John Michael","Jonathan","Korben","Kirkpatrick","Kurt","Lief","Malachi","Mark","Masanobu","Michael","Mustapha","Neil","Octavio","Palmer","Paul","Pierre","Robinson","Rick","Rincewind","Roy","Sheldon","Stafford","Stanislaw","Stanley","Syme","Thorstein","Tyrone","Vizzini","Walton","Walker","Warren","Wendell","Westley","William","Winston"],DB={lastNames:UB,firstFemale:OB,firstMale:MB};function lm(t){const{count:e=100,sex:n}=t||{};if(!e||n&&![Se,Ne].includes(n))return{personData:[],error:tt};const r=Math.ceil(e*1.3),{lastNames:s,firstFemale:i,firstMale:o}=DB,c=ri.map(({iso:g})=>g).filter(Boolean),a=Math.ceil(r/s.length),u=Math.ceil(r/i.length),l=Math.ceil(r/o.length),f=ht(0,a).flatMap(()=>{const g=pt(s,!1,!0);return ht(0,s.length).map(()=>cn(g))}),p=ht(0,u).flatMap(()=>{const g=pt(i,!1,!0);return ht(0,i.length).map(()=>cn(g))}),h=ht(0,l).flatMap(()=>{const g=pt(o,!1,!0);return ht(0,o.length).map(()=>cn(g))}),d={};for(let g=0;g<r;g++){const I=f.pop(),S=n||Dn([Se,Ne]),T=S===Se?h.pop():p.pop(),E=Dn(c);d[`${T}${I}`]={nationalityCode:E,sex:S,firstName:T,lastName:I}}return{personData:Object.values(d).slice(0,e)}}function AN(t){let e=(t==null?void 0:t.count)||1;const{personExtensions:n,consideredDate:r,isMock:s=!0,gendersCount:i,personData:o,category:c,sex:a}=t||{};if(isNaN(e))return{error:tt};const u=(i==null?void 0:i[Se])||a===Se&&e||0,l=(i==null?void 0:i[Ne])||a===Ne&&e||0;e=Math.max(e,u+l);const f=e-(u+l),p=u&&lm({count:u,sex:Se}).personData||[],h=l&&lm({count:l,sex:Ne}).personData||[],d=[...p,...h,...f&&lm({count:f}).personData||[]];let m=d.filter(A=>!a||u&&l||A.sex===a);const g=[];if(Array.isArray(o)){const A=o.filter(C=>typeof C.firstName!="string"||typeof C.lastName!="string"||C.sex&&![Se,Ne].includes(C.sex)||C.nationalityCode&&(typeof C.nationalityCode!="string"||C.nationalityCode.length>3||!ri.find(({iso:v,ioc:P})=>[v,P].includes(C.nationalityCode)))?!1:(C.nationalityCode&&g.push(C.nationalityCode),!0));if(A.length)m=A;else return{error:tt}}const I=o?m:on(m);if(I.length<e){const{maleFirstNames:A,maleLastNames:C,femaleFirstNames:v,femaleLastNames:P,nationalityCodes:U}=d.reduce((O,D)=>{const{firstName:M,lastName:w,nationalityCode:k}=D;return D.sex===Se?(O.maleFirstNames.includes(M)||O.maleFirstNames.push(M),O.maleLastNames.includes(w)||O.maleLastNames.push(w)):(O.femaleFirstNames.includes(M)||O.femaleFirstNames.push(M),O.femaleLastNames.includes(w)||O.femaleLastNames.push(w)),O.nationalityCodes.includes(k)||O.nationalityCodes.push(k),O},{maleFirstNames:[],maleLastNames:[],femaleFirstNames:[],femaleLastNames:[],nationalityCodes:[]});ht(0,e-I.length).forEach(()=>{const O=a||Dn([Se,Ne]),D=Dn(U),M=Dn(O===Se?A:v),w=Dn(O===Se?C:P),k={firstName:M,lastName:w,sex:O,nationalityCode:D};I.push(k)})}const{ageMinDate:S,ageMaxDate:T}=ST({consideredDate:r,category:c}),E=vt((S==null?void 0:S.slice(0,4))||0)||vt((T==null?void 0:T.slice(0,4))||0)-3,y=vt((T==null?void 0:T.slice(0,4))||0)||vt((S==null?void 0:S.slice(0,4))||0)+3,b=(S||T)&&[E,y],N=I.slice(0,e).map((A,C)=>{const[v,P]=b||[],U=b&&cn(ht(v,P)),O=cn(ht(0,365)),D=U&&IC(U,O);return Object.assign(bt({extensions:n||[{name:"regionCode",value:C+1}],birthDate:D,isMock:s}),A)});return{persons:N.length&&N||I[0],nationalityCodes:g}}function vN(t){const{cities:e,states:n,postalCodes:r,nationalityCode:s,participantIndex:i}=t;return{postalCode:r==null?void 0:r[i],state:n==null?void 0:n[i],city:e==null?void 0:e[i],countryCode:s}}var wB=["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","Sparkle Soul Tribe","Stacked Deck","Cross Stringers","The Emergence","Total Demolition","Touch and Go","Upside Downers","Vertically Challenged","Visual Spectacle"];function dm({nameRoot:t="TEAM",count:e=1}={}){const r=on(wB).slice(0,e);return r.length<e&&ht(0,e-r.length).forEach(s=>r.push(`${t} ${s+1}`)),{names:r}}var kB=[{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"}],_B=["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 CN({count:t=1,participantsCount:e=32}={}){const n=on(_B),r=n.slice(0,t);return{cities:ht(0,e).map(i=>i<Math.min(t,n.length)?r[i]:Dn(r))}}function PN({count:t=1,participantsCount:e=32}={}){const n=on(kB),r=n.slice(0,t).map(i=>Object.keys(i)).flat();return{states:ht(0,e).map(i=>i<Math.min(t,n.length)?r[i]:Dn(r))}}function UN({count:t=1,participantsCount:e=32}={}){const n=ht(0,t).map(()=>ht(0,5).map(()=>Wn(0,9)).join(""));return{postalCodes:ht(0,e).map(s=>s<t?n[s]:Dn(n))}}function FB({keepExtensions:t=[],anonymizeParticipantNames:e=!0,tournamentRecord:n,tournamentName:r,personIds:s=[],tournamentId:i}){var F,L,W,j,H;if(!n)return{error:et};const o=Array.isArray(t)?sI.concat(...t):sI,c=B=>{var R;return Array.isArray(t)?(R=B==null?void 0:B.extensions)==null?void 0:R.filter(x=>o.includes(x.name)):B==null?void 0:B.extensions},a={};n.extensions=c(n);const u=i||Yt();a[n.tournamentId]=u,n.tournamentId=u,n.createdAt=new Date().toISOString(),n.tournamentName=r||`Anonymized: ${Sr(new Date)}`,delete n.parentOrganisation;for(const B of n.participants||[]){const R=Yt();a[B.participantId]=R,B.participantId=R}for(const B of n.participants||[])Array.isArray(B.individualParticipantIds)&&(B.individualParticipantIds=B.individualParticipantIds.map(R=>a[R]));let l=0;for(const B of n.venues||[]){B.extensions=c(B),B.venueName=`Venue #${l}`,B.venueAbbreviation=`V${l}`;const R=Yt();a[B.venueId]=R,l+=1}let f=1;for(const B of n.events||[]){B.extensions=c(B);const R=Yt();a[B.eventId]=R,B.eventId=R;const x=((F=B.category)==null?void 0:F.categoryName)||((L=B.category)==null?void 0:L.ageCategoryCode)||((W=B.category)==null?void 0:W.ratingType)||B.gender;if(B.eventName=`Event ${f} ${x}`,Array.isArray(B.entries))for(const V of B.entries)V.participantId=a[V.participantId];for(const V of B.drawDefinitions||[]){V.extensions=c(V);const Y=Yt();if(a[V.drawId]=Y,V.drawId=Y,Array.isArray(V.entries))for(const J of V.entries)J.participantId=a[J.participantId];const z=J=>{J.extensions=c(J);const Q=Yt();a[J.structureId]=Q,J.structureId=Q;for(const X of J.positionAssignments||[])X.participantId&&(X.participantId=a[X.participantId]);for(const X of J.seedAssignments||[])X.participantId&&(X.participantId=a[X.participantId]);for(const X of J.matchUps||[])for(const Z of X.sides||[])Z.lineUp&&(Z.lineUp=Z.lineUp.map(({participantId:nt,collectionAssignments:rt})=>({participantId:a[nt],collectionAssignments:rt})))};for(const J of V.structures||[])if(z(J),Array.isArray(J.structures))for(const Q of J.structures)z(Q);for(const J of V.links||[])J.source.structureId=a[J.source.structureId],J.target.structureId=a[J.target.structureId]}const{extension:q}=Us({name:ar,event:B});Array.isArray((j=q==null?void 0:q.value)==null?void 0:j.flights)&&((H=q==null?void 0:q.value.flights)==null||H.forEach(V=>{if(V.drawId=a[V.drawId],Array.isArray(V.drawEntries))for(const Y of V.drawEntries)Y.participantId=a[Y.participantId]})),f+=1}const p=n.startDate||Sr(new Date),h=(n.participants||[]).filter(({participantType:B})=>B===xt),d=h.reduce((B,R)=>{var q;const x=(q=R.person)==null?void 0:q.sex;return[Se,Ne].includes(x)?B[x]+=1:B[So]+=1,B},{[Se]:0,[Ne]:0,[So]:0}),m=Object.assign({},...Object.keys(d).map(B=>{var R;return{[B]:((R=AN({category:{ageCategoryCode:"O18"},count:d[B],addressProps:{citiesCount:10},personExtensions:[],consideredDate:p,sex:B}))==null?void 0:R.persons)||[]}})),g={[Se]:0,[Ne]:0,[So]:0},I=h.length,S=h.reduce((B,R)=>{var z,J;const x=((J=(z=R.person)==null?void 0:z.addresses)==null?void 0:J[0])||{},{city:q,state:V,postalCode:Y}=x;return B.cities.includes(q)||B.cities.push(q),B.states.includes(V)||B.states.push(V),B.postalCodes.includes(Y)||B.postalCodes.push(Y),B},{cities:[],postalCodes:[],states:[]}),T=S.postalCodes.length,E=S.cities.length,y=S.states.length,{cities:b}=CN({count:E||I,participantsCount:I}),{states:N}=PN({count:y||I,participantsCount:I}),{postalCodes:A}=UN({count:T||I,participantsCount:I}),C={cities:b,states:N,postalCodes:A};h.forEach((B,R)=>{var J,Q;const x=B==null?void 0:B.person,q=(x==null?void 0:x.sex)||So,V=(J=Bt(x==null?void 0:x.birthDate))==null?void 0:J.split("-")[0],Y=g[q],z=m[q][Y];if(g[q]+=1,V){const[,X,Z]=((Q=z==null?void 0:z.birthDate)==null?void 0:Q.split("-"))||[],nt=[V,X,Z].join("-");z.birthDate=nt}if(x!=null&&x.addresses){const X=vN({...C,participantIndex:R,nationalityCode:z.nationalityCode});z.addresses=[X]}z.personId=(s==null?void 0:s[R])||Yt(),e?(z.standardFamilyName=z.lastName,z.standardGivenName=z.firstName,B.participantName=`${z.standardGivenName} ${z.standardFamilyName}`):(z.standardFamilyName=x==null?void 0:x.standardFamilyName,z.standardGivenName=x==null?void 0:x.standardGivenName),delete z.firstName,delete z.lastName,z.extensions=c(x),B.person=z,a[x==null?void 0:x.personId]=z.personId}),(n.participants||[]).filter(({participantType:B})=>B===_t).forEach(B=>{const{individualParticipantIds:R}=B;B.participantName=LB({individualParticipantIds:R,individualParticipants:h})});const P=(n.participants||[]).filter(({participantType:B})=>B===se),U=P.length,O=dm({count:U}).names;P.forEach((B,R)=>{B.participantName=O[R]});const D=(n.participants||[]).filter(({participantType:B})=>B===Fn),M=D.length,w=dm({count:M,nameRoot:"Group"}).names;D.forEach((B,R)=>{B.participantName=w[R]});const{extension:k}=Bn({name:qs,tournamentRecord:n});Array.isArray(k==null?void 0:k.value)&&(k==null||k.value.forEach(B=>{B.tournamentId=a[B.tournamentId],B.structureId=a[B.structureId],B.eventId=a[B.eventId],B.drawId=a[B.drawId]}));const{extension:_}=Bn({name:nc,tournamentRecord:n});return Array.isArray(_==null?void 0:_.value)&&(_==null||_.value.forEach(B=>{B.personId=a[B.personId]})),{...$}}function LB({individualParticipantIds:t,individualParticipants:e}){let n=e.filter(({participantId:r})=>t.includes(r)).map(({person:r})=>r==null?void 0:r.standardFamilyName).filter(Boolean).sort().join("/");return t.length===1&&(n+="/Unknown"),n}function ON({matchUpStatusProfile:t,completeAllMatchUps:e,randomWinningSide:n,tournamentRecord:r,drawProfiles:s,event:i}){var d,m,g,I;const o=be({event:i}).flightProfile,{eventName:c,eventType:a,category:u}=i,{startDate:l}=r,f=[],p=(u==null?void 0:u.categoryName)||(u==null?void 0:u.ageCategoryCode)||(u==null?void 0:u.ratingType),h=(d=i.drawDefinitions)==null?void 0:d.map(({drawId:S})=>S);if(Array.isArray(o==null?void 0:o.flights))for(const[S,T]of o.flights.entries()){const{drawId:E,stage:y,drawName:b,drawEntries:N}=T;f.push(T.drawId);const A=s[S],{seedsCount:C,generate:v=!0}=A||{};if(v){const P=N.filter(dl).map(fe),U=p||c;if(r&&C&&C<=P.length&&ht(1,C+1).forEach((F,L)=>{const W={scaleValue:F,scaleName:U,scaleType:br,eventType:a,scaleDate:l},j=P[L];du({tournamentRecord:r,participantId:j,scaleItem:W})}),h!=null&&h.includes(E))break;let O=um({...A,matchUpType:a,seedingScaleName:U,tournamentRecord:r,isMock:!0,drawEntries:N,drawName:b,drawId:E,event:i,stage:y});if(O.error)return{error:O.error,drawIds:[]};const{drawDefinition:D}=O;if(!D)return{error:rr};const M=(m=s[S])==null?void 0:m.drawExtensions;if(Array.isArray(M)&&M.filter(ur).forEach(_=>ae({element:D,extension:_})),O=Za({suppressNotifications:!0,tournamentRecord:r,drawDefinition:D,event:i}),O.error)return{error:O.error,drawIds:[]};if(A!=null&&A.withPlayoffs){const _=(g=D.structures)==null?void 0:g[0].structureId,F=hd({idPrefix:A.idPrefix,...A.withPlayoffs,tournamentRecord:r,drawDefinition:D,isMock:!0,structureId:_,event:i});if(F!=null&&F.error)return F}const w=A==null?void 0:A.completionGoal;if(!((A==null?void 0:A.automated)===!1)&&(e||w)){const _=A==null?void 0:A.matchUpFormat,F=pu({completeAllMatchUps:!w&&e,matchUpStatusProfile:t,randomWinningSide:n,tournamentRecord:r,completionGoal:w,drawDefinition:D,matchUpFormat:_,event:i});if(F.error)return{error:F.error,drawIds:[]};const L=F.completedCount;if((A==null?void 0:A.drawType)===Ds){const W=(I=D.structures)==null?void 0:I.find(B=>B.stage===It);if(!W)return{error:Te};let j=pd({structureId:W.structureId,tournamentRecord:r,drawDefinition:D,event:i});if(j.error)return{error:j.error,drawIds:[]};const H=w?w-(L??0):void 0;if(j=pu({completeAllMatchUps:!w&&e,completionGoal:w?H:void 0,matchUpStatusProfile:t,randomWinningSide:n,tournamentRecord:r,drawDefinition:D,matchUpFormat:_,event:i}),j.error)return{error:j.error,drawIds:[]}}}}}return{...$,drawIds:f}}function Nd(t){let{rankingRange:e,scaledParticipantsCount:n}=t;const{ratingsParameters:r=wr,valuesInstanceLimit:s,consideredDate:i,category:o,nationalityCodesCount:c,nationalityCodeType:a,nationalityCodes:u,participantsCount:l=32,participantType:f,personIds:p,idPrefix:h,uuids:d,personExtensions:m,addressProps:g,gendersCount:I,matchUpType:S,personData:T,sex:E,inContext:y,withISO2:b,withIOC:N,scaleAllParticipants:A}=t,C=f===_t||S===Tr,v=f===se||S===se;e&&(!Array.isArray(e)||!e.every(dt=>Me(dt))||e.length!==2)&&(e=void 0),n=A?l:n;const P=1e3,U=n&&n>P?n:P;e=e||[1,U],e[1]+=1;const O=l*(C?2:v?8:1),D=AN({count:O,personExtensions:m,consideredDate:i,gendersCount:I,personData:T,category:o,sex:E});if(D.error)return D;const{nationalityCodes:M,persons:w}=D;let k=[],_=[],F=[],L=[];if(typeof o=="object"){const{categoryName:dt,ageCategoryCode:mt,ratingType:Mt}=o;if((dt||mt)&&!Mt){const[Nt,St]=e||[];if(_=on(ht(Nt,St)).slice(0,n||Wn(20,30)),[_t,se].includes(f)){const[ct,Et]=e||[];k=on(ht(ct,Et)).slice(0,n||Wn(20,30))}}if(Mt&&r[Mt]){const{ratingMax:Nt,ratingMin:St,ratingAttributes:ct}=o,Et=Object.assign({},r[Mt],ct||{}),{attributes:gt={},decimalsCount:Ft,accessors:yt,range:wt,step:Xt}=Et,$t=ft=>{const Ct={};for(const Ut of Object.keys(ft)||{}){const Kt=ft[Ut];if(typeof Kt=="object"&&Kt.generator){const{range:ut}=Kt,[Rt,ne]=ut.slice().sort();Ct[Ut]=Wn(Rt,ne)}else Ct[Ut]=Kt}return Ct},Dt=wt[0]>wt[1]?2:.5,[at,ot]=wt.slice().sort(),Lt=()=>ht(0,2e3).map(()=>_m(at,ot,Dt,Xt,Ft)).filter(ft=>(!Nt||ft<=Nt)&&(!St||ft>=St)).slice(0,n||Wn(20,30)).map(ft=>yt?Object.assign({},...yt.map(Ct=>({[Ct]:ft})),$t(gt)):ft);F=Lt(),[_t,se].includes(f)&&(L=Lt())}}const W=ri.filter(dt=>a==="IOC"&&dt.ioc||dt.iso);function j(dt){const mt=Math.ceil(O/dt);return s&&mt>s?Math.ceil(O/s):dt}const{postalCodesProfile:H,postalCodesCount:B,statesProfile:R,citiesProfile:x,citiesCount:q,statesCount:V}=g||{},Y=dt=>Object.keys(dt).map(mt=>ht(0,R[mt]).map(()=>mt)).flat(),z=x&&Y(x)||(g==null?void 0:g.cities)||CN({count:q||O,participantsCount:O}).cities,J=R&&Y(R)||(g==null?void 0:g.states)||PN({count:V||O,participantsCount:O}).states,Q=H&&Y(H)||(g==null?void 0:g.postalCodes)||UN({count:B||O,participantsCount:O}).postalCodes,X={cities:z,states:J,postalCodes:Q},Z=j(c),nt=Z?on(W).slice(0,c):u?W.filter(dt=>u.includes(dt.iso)):W,rt=on(ht(0,Math.ceil(O/(Z||1))).map(()=>nt).flat(1/0)),K=dm({count:l}).names;return{participants:ht(0,l).map(dt=>{const mt=C?2:v?8:1,Mt=ht(0,mt).map(gt=>{const Ft=dt*mt+gt;return st(Ft)}),Nt=Mt.map(gt=>gt.participantId),St=Mt.map(gt=>gt.person.standardFamilyName).join("/"),ct=C?_t:se,Et={participantId:MN({participantType:ct,idPrefix:h,index:dt,uuids:d}),participantRole:fn,participantName:C?St:K[dt],individualParticipantIds:Nt,participantType:ct};return y&&(Et.individualParticipants=Mt),C||v?[Et,...Mt]:Mt}).flat()};function st(dt){const mt=w[dt],{nationalityCode:Mt,participantExtensions:Nt,participantTimeItems:St,extensions:ct,firstName:Et,birthDate:gt,lastName:Ft,personId:yt,sex:wt}=mt||{},Xt=Et||"GivenName",$t=Ft||"FamilyName",At=`${Xt} ${$t}`,Dt=rt[dt],at=(M==null?void 0:M.length)&&Mt||Dt&&(a==="IOC"?Dt.ioc||Dt.iso:Dt.iso||Dt.ioc)||Mt;rt!=null&&rt.length&&!at&&!Mt&&console.log("%c Invalid Nationality Code",{participantIndex:dt,country:Dt});const ot=vN({...X,participantIndex:dt,nationalityCode:at}),Lt=bt({participantId:MN({participantType:xt,index:dt,idPrefix:h,uuids:d}),extensions:Nt,timeItems:St,participantRole:fn,participantType:xt,participantName:At,person:{addresses:[ot],personId:yt||(p==null?void 0:p.length)&&p[dt]||Yt(),standardFamilyName:$t,standardGivenName:Xt,nationalityCode:at,extensions:ct,birthDate:Yn(gt)?gt:void 0,sex:wt}});if(N&&at){const ft=ri.find(({iso:Ct})=>Ct===at);ft!=null&&ft.ioc&&(Lt.person.iocNationalityCode=ft.ioc),ft!=null&&ft.label&&(Lt.person.countryName=ft.label)}if(b&&at){const ft=ri.find(({iso:Ct})=>Ct===at);ft!=null&&ft.iso2&&(Lt.person.iso2NationalityCode=ft.iso2),ft!=null&&ft.label&&(Lt.person.countryName=ft.label)}if(o){const ft=_[dt],Ct=k[dt];Ad({scaleValue:ft,eventType:WI,scaleType:Ii,participant:Lt,category:o}),Ad({scaleValue:Ct,eventType:Zu,scaleType:Ii,participant:Lt,category:o});const Ut=F[dt],Kt=L[dt];Ad({scaleValue:Ut,eventType:WI,scaleType:to,participant:Lt,category:o}),Ad({scaleValue:Kt,eventType:Zu,scaleType:to,participant:Lt,category:o})}return Lt}}function Ad({scaleValue:t,participant:e,eventType:n,scaleType:r,category:s}){const i=s.categoryName||s.ratingType||s.ageCategoryCode,o=[eo,r,n,i].join("."),c={itemValue:t,itemType:o};i&&t&&(e.timeItems||(e.timeItems=[]),e.timeItems.push(c))}function MN({idPrefix:t,participantType:e,index:n,uuids:r}){return t?`${t}-${e===xt?"I":_t?"P":se?"T":Fn?"G":"X"}-${n}`:(r==null?void 0:r.pop())||Yt()}function DN({alternatesCount:t=0,tieFormatName:e,tieFormat:n,drawSize:r}){var h;let s=0,i=0,o=0,c=0;const a={},u={[Se]:0,[Ne]:0,[hs]:0,[So]:0,[Io]:0};n=typeof n=="object"?n:Lo({namedFormat:e}),(h=n==null?void 0:n.collectionDefinitions)==null||h.filter(Boolean).forEach(d=>{const{category:m,collectionId:g,matchUpType:I,matchUpCount:S,gender:T}=d;if([Se,Ne].includes(T)){const E=S*(I===me?2:1);u[T]<E&&(u[T]=E)}else T===hs&&(u[Se]<S&&(u[Se]=S),u[Ne]<S&&(u[Ne]=S));if(m){const E=JSON.stringify(m);a[E]=m}if(g||(d.collectionId=Yt()),I===me){const E=S;c+=S,s=Math.max(s,E)}if(I===Oe){const E=S;o+=S,i=Math.max(i,E)}});const l=Object.keys(a).length?Math.max(o,c*2):Math.max(i,s*2),f=s*(r+t),p=i*(r+t);return{maxDoublesDraw:f,maxSinglesDraw:p,teamSize:l,genders:u}}function RB({participantsProfile:t,eventProfiles:e,drawProfiles:n}){let{participantsCount:r,participantType:s=xt}=t||{};const i=r||0,o={[Ne]:0,[hs]:0,[So]:0,[Se]:0,[Io]:0};let c=0,a=0,u=0,l=0,f=0;const p=({alternatesCount:d=0,uniqueParticipants:m,tieFormatName:g,drawSize:I=0,eventType:S,tieFormat:T,category:E,gender:y,stage:b})=>{const N=S===$n,A=S===we,C=!!(m||b===Pt||E||y);if(A){l=Math.max(l,I+d),T=typeof T=="object"?T:Lo({namedFormat:g});const{teamSize:v,maxDoublesDraw:P,maxSinglesDraw:U,genders:O}=DN({alternatesCount:d,tieFormatName:g,tieFormat:T,drawSize:I});u=Math.max(u,v),a=Math.max(a,U),C||(c=Math.max(c,P)),Object.keys(O).forEach(D=>o[D]+=O[D])}else if(N)if(C){const v=(I+d)*2;f+=v,y&&(o[y]+=v)}else I+d&&I+d>c&&(c=I+d);else if(C){const v=I+d;y&&(o[y]+=v),f+=v}else I&&I>a&&(a=I+d)};if(e==null||e.forEach(d=>{const{tieFormatName:m,tieFormat:g,drawProfiles:I,eventType:S,category:T,gender:E}=d;if(I)for(const y of I){const{tieFormatName:b,tieFormat:N}=y;p({...y,tieFormatName:b||m,tieFormat:N||g,eventType:S,category:T,gender:E})}}),Array.isArray(n))for(const d of n)p(d);const h=Math.max(l*u,c*2,a);return c&&(s=_t),(r||i)<h&&(r=h),r&&c&&[_t,we].includes(s)&&(a&&Math.floor(a/2)>c?r=Math.floor(a/2):(!a||c*2>=a)&&(r=Math.ceil(r/2))),r===void 0&&(r=!(e!=null&&e.length)&&!(n!=null&&n.length)?32:0),r<i&&(r=i),{uniqueParticipantsCount:f,participantsCount:r,largestTeamDraw:l,largestTeamSize:u,participantType:s,gendersCount:o}}function wN({participantsProfile:t,tournamentRecord:e,eventProfiles:n,drawProfiles:r,startDate:s,uuids:i}){const{participantsCount:o,participantType:c,largestTeamDraw:a,largestTeamSize:u,gendersCount:l}=RB({participantsProfile:t,eventProfiles:n,drawProfiles:r}),f=t==null?void 0:t.teamKey,p=Nd({uuids:i,...t,consideredDate:s,participantsCount:o,participantType:c,gendersCount:l}).participants;let h=0,d=Ss({tournamentRecord:e,participants:p});if(d.error)return d;if(h+=d.addedCount,f){const I=Fb({tournamentRecord:e,...f});if(I.error)return I}const m=p.filter(({participantType:I})=>I===xt).map(fe),g=ht(0,a).map(I=>{const S=m.slice(I*u,(I+1)*u);return{participantName:`Team ${I+1}`,participantRole:fn,participantType:se,participantId:Yt(),individualParticipantIds:S}});return d=Ss({participants:g,tournamentRecord:e}),d.error?d:(h+=d.addedCount,{addedCount:h,...$})}function kN(t){var N,A;const{participantsProfile:e={},uniqueParticipantsCount:n,ratingsParameters:r,tournamentRecord:s,eventProfile:i,eventIndex:o,event:c,uuids:a}=t,{category:u,gender:l,eventType:f}=c,p=f===ls&&xt||f===$n&&_t||f,h=n[It]||0,d=n[Pt]||0,m=(N=i.drawProfiles)!=null&&N.length?h+d:((A=i.participantsProfile)==null?void 0:A.participantsCount)??0,g=[Se,Ne].includes(l)?l:void 0,I=e!=null&&e.idPrefix?`E-${o}-${e==null?void 0:e.idPrefix}`:void 0,{participants:S}=Nd({uuids:i.uuids||a,...e,scaledParticipantsCount:i.scaledParticipantsCount,consideredDate:s==null?void 0:s.startDate,rankingRange:i.rankingRange,participantType:p,participantsCount:m,ratingsParameters:r,category:u,idPrefix:I,sex:g}),E=Ss({tournamentRecord:s,participants:S});if(E.error)return E;const y=S==null?void 0:S.filter(({participantType:C})=>C===p),b=S==null?void 0:S.map(fe);return{uniqueDrawParticipants:y,uniqueParticipantIds:b}}function _N({drawProfiles:t,category:e,gender:n}){const r={},s=t==null?void 0:t.reduce((o,c)=>{const{qualifyingPositions:a=0,participantsCount:u=0,uniqueParticipants:l,stage:f=It,drawSize:p=0}=c||{};Object.keys(o).includes(f)||(o[f]=0);const h=(u||p)-a;return l||n||e||f===Pt?(Object.keys(r).includes(f)||(r[f]=0),r[f]+=h):o[f]=Math.max(o[f],h),o},{}),i=Object.keys(r);return i.forEach(o=>s[o]+=r[o]),{stageParticipantsCount:s,uniqueParticipantsCount:r,uniqueParticipantStages:i}}function FN({allUniqueParticipantIds:t,stageParticipantsCount:e,eventParticipantType:n,targetParticipants:r}){const s=e[It]||0,i=e[Pt]||0;return{stageParticipants:{QUALIFYING:r.filter(({participantType:c})=>c===n).filter(({participantId:c})=>!t.includes(c)).slice(0,i),MAIN:r.filter(({participantType:c})=>c===n).filter(({participantId:c})=>!t.includes(c)).slice(i,i+s)}}}function BB({autoEntryPositions:t,tournamentRecord:e,drawParticipants:n,drawProfile:r,event:s}){const{drawType:i=Ms,qualifyingPositions:o=0,stage:c=It,drawSize:a=0,drawName:u,drawId:l}=r,f=a-o,p=n.slice(0,f).map(fe);if(p.length){const m=Fs({participantIds:p,autoEntryPositions:t,tournamentRecord:e,stage:c,event:s});if(m.error)return m}const h=p.map(m=>({entryStatus:Ur,entryStage:c,participantId:m})),d=cm({drawName:u||i,qualifyingPositions:o,drawEntries:h,drawId:l,event:s,stage:c});return d.error?d:{...$}}function LN({uniqueDrawParticipants:t,autoEntryPositions:e,stageParticipants:n,tournamentRecord:r,drawProfiles:s,category:i,gender:o,event:c}){let a=0;for(const u of s){const{qualifyingPositions:l=0,uniqueParticipants:f,stage:p=It,drawSize:h=0}=u,d=h-l,m=f||o||i||p===Pt,g=m?t.slice(a,a+d):n[p||It]||[];m&&(a+=d);const I=BB({autoEntryPositions:e,drawParticipants:g,tournamentRecord:r,drawProfile:u,event:c});if(I.error)return I}return{...$}}function RN(t){var q;const{allUniqueParticipantIds:e,matchUpStatusProfile:n,participantsProfile:r,completeAllMatchUps:s,autoEntryPositions:i,hydrateCollections:o,randomWinningSide:c,ratingsParameters:a,tournamentRecord:u,eventProfile:l,eventIndex:f,publish:p,uuids:h}=t;let d=l.gender,m=l.eventName;const{eventType:g=ls,policyDefinitions:I,drawProfiles:S=[],eventExtensions:T,surfaceCategory:E,tieFormatName:y,discipline:b,eventLevel:N,timeItems:A,ballType:C,category:v}=l,P=l.eventId||Yt(),U=l.tieFormat||(g===we?Lo({namedFormat:y,event:{eventId:P,category:v,gender:d},hydrateCollections:o}):void 0),O=u.participants;for(const V of S)!d&&V.gender&&(d=V==null?void 0:V.gender);const{stageParticipantsCount:D,uniqueParticipantsCount:M,uniqueParticipantStages:w}=_N({drawProfiles:S,category:v,gender:d}),k=g===ls&&xt||g===$n&&_t||g,{uniqueDrawParticipants:_=[],uniqueParticipantIds:F=[]}=w?kN({event:{eventType:g,category:v,gender:d},uniqueParticipantsCount:M,participantsProfile:r,ratingsParameters:a,tournamentRecord:u,eventProfile:l,eventIndex:f,uuids:h}):{};let{eventAttributes:L}=l;typeof L!="object"&&(L={});const W=(v==null?void 0:v.categoryName)||(v==null?void 0:v.ageCategoryCode)||(v==null?void 0:v.ratingType);m=m||W||"Generated Event";const j={...L,surfaceCategory:E,discipline:b,eventLevel:N,eventName:m,eventType:g,tieFormat:U,ballType:C,category:v,eventId:P,gender:d};if(T!=null&&T.length&&Array.isArray(T)){const V=T.filter(ur);V!=null&&V.length&&Object.assign(j,{extensions:V})}if(Array.isArray(A)&&A.forEach(V=>ii({event:R,timeItem:V})),typeof I=="object")for(const V of Object.keys(I))nE({policyDefinitions:{[V]:I[V]},event:j});j.category&&(j.category.categoryName=W);let H;const B=Ed({suppressNotifications:!1,internalUse:!0,tournamentRecord:u,event:j});if(B.error)return B;const R=B==null?void 0:B.event,{stageParticipants:x}=FN({allUniqueParticipantIds:e,stageParticipantsCount:D,eventParticipantType:k,targetParticipants:O});if(S!=null&&S.length){const V=LN({uniqueDrawParticipants:_,autoEntryPositions:i,stageParticipants:x,tournamentRecord:u,drawProfiles:S,category:v,gender:d,event:R});if(V.error)return V;const Y=ON({matchUpStatusProfile:n,completeAllMatchUps:s,randomWinningSide:c,tournamentRecord:u,drawProfiles:S,event:R});if(Y.error)return Y;H=Y.drawIds}else if((q=l==null?void 0:l.participantsProfile)!=null&&q.participantsCount){const V=_.map(kn("participantId"));if(V.length){const Y=Fs({participantIds:V,autoEntryPositions:i,tournamentRecord:u,stage:It,event:R});if(Y.error)return Y}}return p&&fu({tournamentRecord:u,event:R}),{drawIds:H,eventId:P,uniqueParticipantIds:F}}function fm(t){var Nt,St;const{allUniqueParticipantIds:e=[],participantsProfile:n={},matchUpStatusProfile:r,completeAllMatchUps:s,autoEntryPositions:i,hydrateCollections:o,randomWinningSide:c,ratingsParameters:a,tournamentRecord:u,isMock:l=!0,drawProfile:f,startDate:p,drawIndex:h,uuids:d}=t,m=pt(f,!1,!0),{excessParticipantAlternates:g=!0,matchUpFormat:I=Kn,drawType:S=Ms,tournamentAlternates:T=0,alternatesCount:E=0,qualifyingPositions:y,qualifyingProfiles:b,generate:N=!0,eventExtensions:A,drawExtensions:C,completionGoal:v,tieFormatName:P,seedsCount:U,timeItems:O,drawName:D,category:M,idPrefix:w,publish:k,gender:_,stage:F}=m,L=m.drawSize||(m.ignoreDefaults?void 0:32),W=m.eventId||Yt(),j=f.eventType||f.matchUpType||ls,H=j===$n?_t:xt,B=typeof f.tieFormat=="object"&&f.tieFormat||j===se&&Lo({namedFormat:P,event:{eventId:W,category:M,gender:_},hydrateCollections:o})||void 0,R=(M==null?void 0:M.categoryName)||(M==null?void 0:M.ageCategoryCode)||(M==null?void 0:M.ratingType),x=f.eventName||R||`Generated ${j}`;let q=(u==null?void 0:u.participants)||[];const V=((b==null?void 0:b.map(ct=>ct.structureProfiles||[]).flat().reduce((ct,Et)=>{const gt=!Et.participantsCount||Et.participantsCount>Et.drawSize?Et.drawSize:Et.participantsCount||0;return ct+gt},0))||0)*(H===_t?2:1),Y=(!f.participantsCount||f.participantsCount>L?L:f.participantsCount)||0,z={eventName:x,eventType:j,tieFormat:B,category:M,eventId:W,gender:_};Array.isArray(O)&&O.forEach(ct=>ii({event:z,timeItem:ct}));let{eventAttributes:J}=f;if(typeof J!="object"&&(J={}),Object.assign(z,J),A!=null&&A.length&&Array.isArray(A)){const ct=A.filter(ur);ct!=null&&ct.length&&Object.assign(z,{extensions:ct})}const Q=[];if(V||f.uniqueParticipants||!u||_||M){const ct=(Y||0)+E+V;let Et=ct;const gt={[Se]:0,[Ne]:0};let Ft,yt;j===se&&({teamSize:Ft,genders:yt}=DN({alternatesCount:E,tieFormatName:P,tieFormat:B,drawSize:L}),Object.keys(yt).forEach(At=>{[Se,Ne].includes(At)&&yt[At]&&(gt[At]=L*yt[At])}),Et=Ft*((L||0)+V));const wt=n!=null&&n.idPrefix?`D-${h}-${n==null?void 0:n.idPrefix}`:void 0,$t=Nd({...n,scaledParticipantsCount:f.scaledParticipantsCount||n.scaledParticipantsCount,participantsCount:Et,consideredDate:u==null?void 0:u.startDate,sex:_||(n==null?void 0:n.sex),rankingRange:f.rankingRange,uuids:f.uuids||d,ratingsParameters:a,participantType:H,gendersCount:gt,idPrefix:wt,category:M}).participants;if(z.category&&(z.category.categoryName=R),u){const At=Ss({participants:$t,tournamentRecord:u});if(At.error)return At}if($t.forEach(({participantId:At})=>Q.push(At)),q=$t,j===se){const At=yt[Se]?$t.filter(({participantType:ut,person:Rt})=>ut===xt&&(Rt==null?void 0:Rt.sex)===Se).map(fe):[],Dt=yt[Ne]?$t.filter(({participantType:ut,person:Rt})=>ut===xt&&(Rt==null?void 0:Rt.sex)===Ne).map(fe):[],at=$t.filter(({participantType:ut})=>ut===xt).map(fe).filter(ut=>!At.includes(ut)&&!Dt.includes(ut)),ot=Ft-(yt[Se]+yt[Ne]);let Lt=0,ft=0,Ct=0;const Ut=ht(0,ct).map(ut=>{const Rt=Dt.slice(Lt,Lt+yt[Ne]),ne=At.slice(ft,ft+yt[Se]),Ae=at.slice(Ct,Ct+ot);return Lt+=yt[Ne],ft+=yt[Se],Ct+=ot,{individualParticipantIds:[...Rt,...ne,...Ae],participantOtherName:`TM${ut+1}`,participantName:`Team ${ut+1}`,participantRole:fn,participantType:se,participantId:Yt()}}),Kt=Ss({participants:Ut,tournamentRecord:u});if(!Kt.success)return Kt;q=Ut}}const X=ct=>{const{participantType:Et}=ct;return j===ls&&Et===xt||j===$n&&Et===_t?!0:j===se&&Et===se},Z=ct=>{var Et,gt;return!f.gender||((Et=ct.person)==null?void 0:Et.sex)===f.gender?!0:(gt=ct.individualParticipantIds)==null?void 0:gt.some(Ft=>{const yt=q.find(wt=>wt.participantId===Ft);return yt&&Z(yt)})},nt=q.filter(X).filter(Z).filter(({participantId:ct})=>!e.includes(ct)),rt=nt.slice(0,Y).map(ct=>ct.participantId);if(l&&(rt!=null&&rt.length)){const ct=Fs({autoEntryPositions:i,entryStage:F,tournamentRecord:u,participantIds:rt,event:z});if(ct.error)return ct}const K=V?nt.slice(Y,Y+V).map(ct=>ct.participantId):0;if(l&&(K!=null&&K.length)){let ct=0,Et=1;const gt=(yt,wt)=>yt.stageSequence-wt.stageSequence,Ft=(yt,wt)=>yt.roundTarget-wt.roundTarget;for(const yt of b.sort(Ft)){Et=yt.roundTarget||Et;let wt=1,Xt;for(const $t of yt.structureProfiles.sort(gt)){const Dt=($t.drawSize||_d($t.participantsCount))-(Xt||0),at=K.slice(ct,ct+Dt),ot=Fs({entryStage:Pt,entryStageSequence:wt,autoEntryPositions:i,tournamentRecord:u,participantIds:at,roundTarget:Et,event:z});if(ot.error)return ot;Xt=$t.qualifyingPositions,ct+=Dt,wt+=1}Et+=1}}const it=g&&((Nt=u==null?void 0:u.participants)==null?void 0:Nt.filter(({participantId:ct})=>!rt.includes(ct)).filter(X).filter(Z).slice(0,E||L-Y||T).map(ct=>ct.participantId));if(l&&(it!=null&&it.length)){const ct=Fs({participantIds:it,autoEntryPositions:!1,entryStatus:dr,tournamentRecord:u,event:z});if(ct.error)return ct.error}const st=R||x;u&&U&&U<=rt.length&&ht(1,U+1).forEach((Et,gt)=>{const Ft={scaleName:st,scaleDate:p,scaleType:xI,scaleValue:Et,eventType:j},yt=rt[gt];du({tournamentRecord:u,participantId:yt,scaleItem:Ft})});const dt=um({...pt(f,!1,!0),tournamentRecord:u,seedingScaleName:st,matchUpFormat:I,eventId:W,isMock:l,event:z});if(dt.error)return dt;if(!dt.drawDefinition)return{error:rr};const{drawDefinition:mt}=dt,Mt=mt.drawId;if(Array.isArray(C)&&C.filter(ur).forEach(ct=>ae({element:mt,extension:ct})),N){if(Za({drawDefinition:mt,event:z,suppressNotifications:!0}),f.withPlayoffs){const Et=(St=mt.structures)==null?void 0:St[0].structureId,gt=hd({...f.withPlayoffs,tournamentRecord:u,drawDefinition:mt,structureId:Et,idPrefix:w,isMock:l,event:z});if(gt!=null&&gt.error)return gt}const ct=f.automated===!1;if(l&&!ct){const Et=gt=>{var wt;const Ft=pu({completeAllMatchUps:gt.completeAllMatchUps,completionGoal:gt.completionGoal,matchUpStatusProfile:r,randomWinningSide:c,tournamentRecord:u,drawDefinition:mt,matchUpFormat:I,event:z});if(Ft.error)return Ft;const yt=Ft.completedCount;if(S===Ds){const Xt=(wt=mt.structures)==null?void 0:wt.find(Dt=>Dt.stage===It);if(!Xt)return{error:Te};pd({structureId:Xt.structureId,tournamentRecord:u,drawDefinition:mt,event:z});const $t=v?v-(yt??0):void 0,At=pu({completionGoal:v?$t:void 0,matchUpStatusProfile:r,completeAllMatchUps:s,randomWinningSide:c,tournamentRecord:u,drawDefinition:mt,matchUpFormat:I,event:z});if(At.error)return At}};if(v&&Et({completionGoal:v}),f.outcomes){const{matchUps:gt}=tr({inContext:!0,drawDefinition:mt,event:z});for(const Ft of f.outcomes){const{matchUpStatus:yt=De,matchUpStatusCodes:wt,stageSequence:Xt=1,matchUpIndex:$t=0,structureOrder:At,matchUpFormat:Dt,drawPositions:at,roundPosition:ot,stage:Lt=It,roundNumber:ft,winningSide:Ct,scoreString:Ut}=Ft,Kt=(gt==null?void 0:gt.reduce((Ee,Un)=>{const{structureId:Xe,matchUpId:Lr}=Un;return Ee[Xe]?Ee[Xe].push(Lr):Ee[Xe]=[Lr],Ee},{}))??[],ut=Object.assign({},...Object.keys(Kt).map((Ee,Un)=>({[Ee]:Un+1}))),Rt=gt==null?void 0:gt.filter(Ee=>(!Lt||Ee.stage===Lt)&&(!Xt||Ee.stageSequence===Xt)&&(!ft||Ee.roundNumber===ft)&&(!ot||Ee.roundPosition===ot)&&(!At||ut[Ee.structureId]===At)&&(!at||qe(at,Ee.drawPositions).length===2)),ne=Rt==null?void 0:Rt[$t],Ae=zb({matchUpStatusCodes:wt,tournamentRecord:u,drawDefinition:mt,targetMatchUp:ne,matchUpFormat:Dt,matchUpStatus:yt,scoreString:Ut,winningSide:Ct});if(Ae!=null&&Ae.error)return Ae}}s&&Et({completeAllMatchUps:s})}k&&fu({tournamentRecord:u,event:z})}else{const ct=cm({drawEntries:mt.entries,drawName:D||S,qualifyingPositions:y,drawId:Mt,event:z,stage:F});if(ct.error)return ct}return{...$,event:bt(z),uniqueParticipantIds:Q,targetParticipants:q,drawDefinition:mt,eventId:W,drawId:Mt}}function BN({tournamentRecord:t,venueProfiles:e,uuids:n}){const{startDate:r,endDate:s}=t,i=[];for(const[o,c]of e.entries()){const{venueAbbreviation:a,venueId:u=(n==null?void 0:n.pop())||Yt(),dateAvailability:l,startTime:f="07:00",endTime:p="19:00",courtTimings:h,courtsCount:d,courtNames:m,venueName:g,idPrefix:I,courtIds:S}=c,T={venueName:g||`Venue ${o+1}`,venueAbbreviation:a,venueId:u},E=ma({tournamentRecord:t,venue:T});if(E.error)return E;i.push(u);const y=ef(r,s),b=!Array.isArray(l)&&[{startTime:f,endTime:p}].concat(y.map(A=>({date:Sr(A),startTime:f,endTime:p}))),N=Ah({dateAvailability:l||b,tournamentRecord:t,courtTimings:h,courtsCount:d,courtNames:m,startTime:f,idPrefix:I,courtIds:S,endTime:p,venueId:u,dates:y});if(N.error)return N}return i}function xB(t){var A,C,v;const{ratingsParameters:e=wr,participantsProfile:n={},matchUpStatusProfile:r,completeAllMatchUps:s,autoEntryPositions:i,hydrateCollections:o,randomWinningSide:c,schedulingProfile:a,tournamentRecord:u,eventProfiles:l,venueProfiles:f,autoSchedule:p,drawProfiles:h,uuids:d}=t;if(!u)return{error:et};const m=[],g=[],I=[];l==null||l.forEach(P=>{var O;const U=(O=u.events)==null?void 0:O.find((D,M)=>P.eventIndex!==void 0&&M===P.eventIndex||P.eventName&&D.eventName===P.eventName||P.eventId&&D.eventId===P.eventId);U!=null&&U.gender&&(P.gender=U.gender)});const S=((A=u.participants)==null?void 0:A.length)||void 0;S&&(n!=null&&n.idPrefix)&&(n.idPrefix=`${n.idPrefix}-${S}`);const T=wN({startDate:u.startDate,participantsProfile:n,tournamentRecord:u,eventProfiles:l,drawProfiles:h,uuids:d});if(!T.success)return T;if(l){let P=((C=u.events)==null?void 0:C.length)||0;for(const U of l){const{ratingsParameters:O}=U,D=(v=u.events)==null?void 0:v.find((M,w)=>U.eventIndex!==void 0&&w===U.eventIndex||U.eventName&&M.eventName===U.eventName||U.eventId&&M.eventId===U.eventId);if(D){const{gender:M,category:w,eventType:k}=D,{drawProfiles:_,publish:F}=U,L=k===ls&&xt||k===$n&&_t||k;if(_){const{stageParticipantsCount:W,uniqueParticipantsCount:j,uniqueParticipantStages:H}=_N({drawProfiles:_,category:w,gender:M}),{uniqueDrawParticipants:B=[],uniqueParticipantIds:R=[]}=H?kN({event:{eventType:k,category:w,gender:M},uniqueParticipantsCount:j,participantsProfile:n,ratingsParameters:O,tournamentRecord:u,eventProfile:U,uuids:d}):{};m.push(...R);const{stageParticipants:x}=FN({targetParticipants:u.participants||[],allUniqueParticipantIds:m,stageParticipantsCount:W,eventParticipantType:L});let q=LN({uniqueDrawParticipants:B,autoEntryPositions:i,stageParticipants:x,tournamentRecord:u,drawProfiles:_,category:w,gender:M,event:D});if(q.error||(q=ON({matchUpStatusProfile:r,completeAllMatchUps:s,randomWinningSide:c,tournamentRecord:u,drawProfiles:_,event:D}),q.error))return q;I.push(...q.drawIds)}F&&fu({tournamentRecord:u,event:D})}else{const M=RN({startDate:u.startDate,allUniqueParticipantIds:m,matchUpStatusProfile:r,participantsProfile:n,completeAllMatchUps:s,autoEntryPositions:i,randomWinningSide:c,ratingsParameters:O,tournamentRecord:u,eventProfile:U,eventIndex:P,uuids:d});if(M.error)return M;const{eventId:w,drawIds:k,uniqueParticipantIds:_}=M;k&&I.push(...k),g.push(w),_!=null&&_.length&&m.push(..._),P+=1}}}if(h){let P=(u.events||[]).map(U=>{var O;return((O=U.drawDefinitions)==null?void 0:O.map(()=>1))||[]}).flat().reduce((U,O)=>U+O,0);for(const U of h){let O=fm({startDate:u.startDate,allUniqueParticipantIds:m,matchUpStatusProfile:r,participantsProfile:n,completeAllMatchUps:s,autoEntryPositions:i,hydrateCollections:o,randomWinningSide:c,ratingsParameters:e,tournamentRecord:u,drawProfile:U,drawIndex:P,uuids:d});if(O.error)return O;const{drawId:D,eventId:M,event:w,uniqueParticipantIds:k}=O;if(O=Ed({tournamentRecord:u,event:w,internalUse:!0}),O.error)return O;D&&I.push(D),g.push(M),k!=null&&k.length&&m.push(...k),P+=1}}const E=f!=null&&f.length?BN({tournamentRecord:u,venueProfiles:f}):[];let y,b={};if(a!=null&&a.length){const P={[u.tournamentId]:u},U=nu({tournamentRecords:P,schedulingProfile:a});if(U.error)return U;if(p){const{tournamentId:O}=u,D={[O]:u};b=dh({tournamentRecords:D})}}return{totalParticipantsCount:u.participants.length,scheduledRounds:y,schedulerResult:b,...$,eventIds:g,venueIds:E,drawIds:I}}const $B={anonymizeTournamentRecord:FB,modifyTournamentRecord:xB};function VB({schedulingProfile:t,tournamentRecord:e}){if(typeof t!="object")return{error:tt};const n=Nc({tournamentRecord:e}).containedStructures,r=He({tournamentRecord:e}).matchUps||[],{tournamentId:s}=e,i=[];for(const o of t){const{scheduleDate:c,venues:a=[]}=o;for(const u of a){const{rounds:l,venueId:f}=u;for(const p of l){const{drawId:h,winnerFinishingPositionRange:d,roundSegment:m}=p,I=r.filter(S=>{var y;const T=(d==null?void 0:d.indexOf("-"))>0&&d.split("-").map(b=>+b),E=(y=S.finishingPositionRange)==null?void 0:y.winner;return S.drawId===h&&(!p.roundNumber||S.roundNumber===p.roundNumber)&&(!E||!T||qe(E,T).length===2||Vt(E).length===Vt(T).length&&qe(E,T).length===Vt(E).length)})[0];if(I){const{eventId:S,roundNumber:T,drawName:E,structureName:y,roundName:b}=I;let N=I.structureId;T&&!d&&(N=Object.keys(n).find(v=>n[v].includes(N))||N);const A={tournamentId:s,structureId:N,roundNumber:T,roundSegment:m,eventId:S,drawId:h},C=Ry({tournamentRecords:{[s]:e},round:A,scheduleDate:c,venueId:f});if(C.error)return C;i.push({structureName:y,roundName:b,drawName:E,...A})}}}}return{scheduledRounds:i}}const jB=["Mock Tournament","CourtHive Challenge","Racket Rally","Generated Tournament","Factory Follies","Open Competition"];function GB(t){let{tournamentAttributes:e,startDate:n,endDate:r}=t;const{tournamentName:s=cn(jB),ratingsParameters:i=wr,scheduleCompletedMatchUps:o,tournamentExtensions:c,matchUpStatusProfile:a,completeAllMatchUps:u,participantsProfile:l,autoEntryPositions:f,hydrateCollections:p,randomWinningSide:h,policyDefinitions:d,schedulingProfile:m,autoSchedule:g,eventProfiles:I,venueProfiles:S,drawProfiles:T,uuids:E}=t;if(n&&!Yn(n)||r&&!Yn(r))return{error:bn};if(I&&!Array.isArray(I))return{error:tt};if(!n){const O=new Date;n=Sr(r??O),r=Sr(O.setDate(O.getDate()+7))}if(!r){const O=new Date(n);r=Sr(O.setDate(O.getDate()+7))}typeof e!="object"&&(e={});const y=Jh({...e,tournamentName:s,startDate:n,endDate:r});if(c!=null&&c.length&&Array.isArray(c)){const O=c.filter(D=>ur({extension:D}));O!=null&&O.length&&Object.assign(y,{extensions:O,isMock:!0})}if(typeof d=="object")for(const O of Object.keys(d))gh({policyDefinitions:{[O]:d[O]},tournamentRecord:y});const b=wN({participantsProfile:l,tournamentRecord:y,eventProfiles:I,drawProfiles:T,startDate:n,uuids:E});if(!b.success)return b;const N=[],A=[],C=[];if(Array.isArray(T)){let O=0;for(const D of T){let M=fm({allUniqueParticipantIds:N,matchUpStatusProfile:a,participantsProfile:l,completeAllMatchUps:u,autoEntryPositions:f,hydrateCollections:p,randomWinningSide:h,ratingsParameters:i,tournamentRecord:y,isMock:!0,drawProfile:D,startDate:n,drawIndex:O,uuids:E});if(M.error)return M;const{drawId:w,eventId:k,event:_,uniqueParticipantIds:F}=M;if(M=Ed({suppressNotifications:!1,internalUse:!0,tournamentRecord:y,event:_}),M.error)return M;w&&C.push(w),A.push(k),F!=null&&F.length&&N.push(...F),O+=1}}if(I){let O=0;for(const D of I){const M=RN({allUniqueParticipantIds:N,matchUpStatusProfile:a,participantsProfile:l,completeAllMatchUps:u,autoEntryPositions:f,hydrateCollections:p,randomWinningSide:h,ratingsParameters:i,tournamentRecord:y,eventProfile:D,eventIndex:O,startDate:n,uuids:E});if(M.error)return M;const{eventId:w,drawIds:k,uniqueParticipantIds:_}=M;k&&C.push(...k),A.push(w),_!=null&&_.length&&N.push(..._),O+=1}}const v=S!=null&&S.length?BN({tournamentRecord:y,venueProfiles:S,uuids:E}):[];let P,U={};if(m){const O=VB({schedulingProfile:m,tournamentRecord:y});if(O.error)return O;if(P=O.scheduledRounds,g){const{tournamentId:D}=y,M={[D]:y};U=dh({scheduleCompletedMatchUps:o,tournamentRecords:M})}}return Kc(),bt({...$,tournamentRecord:y,scheduledRounds:P,schedulerResult:U,eventIds:A,venueIds:v,drawIds:C})}const WB={generateOutcomeFromScoreString:qb,generateTournamentRecord:GB,generateEventWithDraw:fm,generateParticipants:Nd,parseScoreString:vl,generateOutcome:Yb,credits:sd};let pm=!1;(()=>{const t={version:()=>Es(),setDeepCopy:(r,s)=>(Hi(r,s),t),devContext:r=>(zo(r),pm=!0,t)};return n([$B,WB]),t;function e(r,s){const i=r({...s});return i!=null&&i.error||Di(),fi(),pm&&(zo(!1),pm=!1),i}function n(r){r.forEach(s=>{Object.keys(s).forEach(i=>{t[i]=o=>{try{return e(s[i],o)}catch(c){let a;typeof c=="string"?a=c.toUpperCase():c instanceof Error&&(a=c.message),console.log("ERROR",{params:JSON.stringify(o),method:i,error:a})}}})})}})();const hm={hasAttributeValues:EC,extractAttributes:kn,structureSort:Pi,matchUpSort:vo,tidyScore:mM,generateScoreString:gs,calculateWinCriteria:gc,compareTieFormats:Sc,parseScoreString:vl,scoreHasValue:Be,getScaleValues:sc,proConflicts:hT,addExtension:ae,chunkArray:Ge,countValues:N1,dateRange:ef,dateTime:SC,roundRobinGroups:RO,definedAttributes:bt,dehydrateMatchUps:PO,findExtension:Ke,garman:kO,getTimeItem:kr,generateHashCode:bC,generateRange:ht,generateTimeCode:Lg,instanceCount:Mn,intersection:qe,isNumeric:Me,isConvertableInteger:oe,isPowerOf2:mr,JSON2CSV:NC,flattenJSON:of,makeDeepCopy:pt,nearestPowerOf2:Fd,nextPowerOf2:Vo,numericSort:Ve,overlap:tn,parseAgeCategoryCode:ST,randomMember:Dn,randomPop:cn,shuffleArray:on,isAdHoc:Qr,unique:Vt,UUID:Yt,UUIDS:AC,validateTieFormat:vn},HB=zt({WebkitBoxSizing:"border-box",marginInlineEnd:".3em",display:"inline-block",boxSizing:"border-box",position:"relative",borderRadius:2,variants:{variant:{doubles:{width:".75rem"},singles:{width:"1rem"}}}});function qB({matchUp:t,individualParticipant:e,spacer:n}){var c,a,u;const r=((c=e==null?void 0:e.person)==null?void 0:c.iso2NationalityCode)||"",s=r?(a=gO.countryToFlag(r))==null?void 0:a.slice(0,4):"",i=document.createElement("span"),o=(u=t==null?void 0:t.matchUpType)==null?void 0:u.toLowerCase();return n||(i.className=HB({variant:o})),i.innerHTML=n?"":s,i}function mm({individualParticipant:t,composition:e,className:n,matchUp:r,spacer:s,side:i,type:o}){if(o==="scale")return f1({individualParticipant:t,composition:e,className:n,matchUp:r,spacer:s});const c=(e==null?void 0:e.configuration)||{},a=document.createElement("div");return o==="flag"&&c.flags&&qB({className:n,matchUp:r,individualParticipant:t,spacer:s})||o==="seeding"&&l1({className:n,composition:e,matchUp:r,side:i})||a}const YB=zt({willChange:"opacity",position:"fixed",zIndex:9998,bottom:0,right:0,left:0,top:0}),zB=zt({display:"block"}),KB=zt({position:"fixed",right:0,left:0}),JB=zt({paddingRight:"15px",alignItems:"center",margin:"30px auto",paddingLeft:"15px",position:"fixed",height:"100vh",display:"flex",width:"100%",zIndex:9999,bottom:0,right:0,left:0,top:0}),QB=zt({boxShadow:"0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23)",backgroundColor:"white",position:"relative",borderRadius:"3px",minHeight:"auto",width:"100%"}),ZB=zt({borderBottom:"1px solid rgba(0, 0, 0, 0.1)",alignItems:"center",position:"relative",display:"flex"}),XB=zt({fontWeight:"600",fontSize:"20px"}),xN=zt({borderTop:"1px solid rgba(0, 0, 0, 0.1)",justifyContent:"right",alignItems:"center",position:"relative",display:"flex"}),$N="Nothing to see here";function Fr(t){return typeof t=="function"}function vd(t){return typeof t=="string"}function VN(t){return Array.isArray(t)}function gm(t){return typeof t=="object"&&!Array.isArray(t)}function t2(t){if(t)for(;t.firstChild;)t.removeChild(t.firstChild)}const Im=(()=>{const t=KB(),e={},n=".5";let r=[],s,i=[],o=[],c;const a=I=>{if(I){let S;o=o.filter(T=>(T.id===I&&(S=T),T.id!==I)),S&&document.body.removeChild(S)}else{const S=o.pop();S&&document.body.removeChild(S)}},u=()=>{c&&(c.style.opacity=0,c.style.display="none")},l=I=>{const S=o.length;if(I&&e[S]===!1)return;const T=i.pop(),E=r.pop();Fr(T)&&T({content:E}),document.body.classList.remove(t),document.body.style.top=null,window.scrollTo({top:s,behavior:"instant"}),u(),a()},f=()=>{c=document.createElement("div"),c.className=YB(),c.id="cmdl-backdrop",c.onclick=()=>l(!0),document.body.appendChild(c)},p=({config:I})=>{s=window.scrollY,document.body.classList.add(t),document.body.style.top=`-${s}px`,c||f(),c.style.display="",(I==null?void 0:I.backdrop)!==!1&&(c.style.backgroundColor="rgba(0, 0, 0, 0.2)",c.style.transition="opacity 0.15s linear",c.style.opacity=1)},h=({config:I,attr:S})=>{if(!vd(S))return;const T=S.split(".");for(const E of T)if(I=I==null?void 0:I[E],!I)return;return I},d=({config:I,attr:S,attrs:T,unit:E="em",value:y})=>{var N;let b;return vd(S)?b=h({config:I,attr:S}):VN(T)&&(b=(N=T.map(A=>h({config:I,attr:A})).filter(Boolean))==null?void 0:N[0]),b!==void 0&&(y=b),isNaN(y)?y:`${y}${E}`},m=({buttons:I,config:S,modalNumber:T})=>{var b,N;const E=document.createElement("div");E.className=xN(),E.style.padding=d({config:S,attrs:["footer.padding","padding"],value:n});const y={label:((b=S==null?void 0:S.dictionary)==null?void 0:b.close)||"Close",onClick:Im.close,intent:"is-info"};for(const A of I){if(A.hide)continue;const C=Object.assign({},y);gm(A)&&Object.assign(C,A);const v=document.createElement("button");C.disabled!==void 0&&(v.disabled=C.disabled),C.id&&(v.id=C.id),v.className=((N=C==null?void 0:C.footer)==null?void 0:N.className)||"button font-medium",v.classList.add(C.intent),v.style="margin-right: .5em;",v.innerHTML=C.label||C.text,v.onclick=P=>{P.stopPropagation(),Fr(C.onClick)&&C.onClick({e:P,content:r[T]}),C.close!==!1&&(Fr(C.close)&&C.close(),Im.close())},E.appendChild(v)}return E};return{close:l,open:({title:I="",content:S,buttons:T,footer:E,config:y,onClose:b}={})=>{p({config:y}),i.push(b);const N=o.length+1;e[N]=y==null?void 0:y.clickAway;const A=document.createElement("section"),C=`cmdl-${N}`;A.className=zB(),A.role="dialog",A.tabIndex=-1,A.id=C;const v=document.createElement("div");v.className=JB(),v.style.maxWidth=`${(y==null?void 0:y.maxWidth)||450}px`,v.onclick=()=>l(!0);const P=document.createElement("div");P.className=QB(),P.onclick=W=>W.stopPropagation();const U=document.createElement("div"),O=document.createElement("div");U.appendChild(O),P.appendChild(U);const D=({title:W,config:j})=>{U.className=W?ZB():"",U.style.padding=d({config:j,attrs:["title.padding","padding"],value:n}),O.className=W?XB():"",O.innerHTML=W};I&&D({title:I});const M=document.createElement("div");P.appendChild(M);const w=({content:W,config:j})=>{M.style.fontSize=d({config:j,attr:"fontSize",value:"15px"}),M.style.position="relative",M.style.padding=d({config:j,attrs:["content.padding","padding"],value:n}),Fr(W)?r[N]=W(M):gm(W)?M.appendChild(W):vd(W)?M.innerHTML=W:M.innerHTML=$N};if(w({content:S,config:y}),VN(T))E=m({buttons:T,config:y,modalNumber:N}),P.appendChild(E);else if(E){const W=document.createElement("div");W.className=xN(),W.style.padding=d({config:y,attrs:["footer.padding","padding"]}),gm(E)?W.appendChild(E):vd(E)?W.innerHTML=E:W.innerHTML=$N,P.appendChild(W)}v.appendChild(P),A.appendChild(v),document.body.appendChild(A),o.push(A);const k=({content:W,config:j})=>{r[N]=void 0,t2(M),w({content:W,config:j})},_=({buttons:W,config:j})=>{P.removeChild(E),E=m({buttons:W,config:j,modalNumber:N}),P.appendChild(E)},F=({onClose:W})=>{i.length=0,i.push(W)};return{setContent:k,setButtons:_,update:({content:W,buttons:j,title:H,config:B,onClose:R})=>{y=B||y,W&&k({content:W,config:y}),j&&_({buttons:j,config:y}),R&&F({onClose:R}),H&&D({title:H,config:y})}}}}})(),e2="Qualifier",n2="BYE",r2="TBD";function jN(t){var T;const{isWinningSide:e,side:n,sideNumber:r,individualParticipant:s,matchUp:i,composition:o}=t||{},c=e?"winner":void 0,a=t.eventHandlers||{},u=o==null?void 0:o.configuration,l=s==null?void 0:s.participantName,f=E=>{Fr(a==null?void 0:a.participantClick)&&(E.stopPropagation(),a.participantClick({individualParticipant:s,pointerEvent:E,matchUp:i,side:n}))},p=document.createElement("div");p.classList.add("tmx-i"),p.setAttribute("sideNumber",r),s!=null&&s.participantId&&p.setAttribute("id",s.participantId),p.onclick=f;const h=document.createElement("div");h.className=XA({variant:c});const m=(u==null?void 0:u.flags)&&mm({...t,type:"flag"});if(m)h.appendChild(m);else{const E=mm({type:"scale",...t});E&&h.appendChild(E)}const g=document.createElement("div");if(g.className=t1({variant:c}),l){const E=document.createElement("span");if(e&&(u!=null&&u.winnerColor))E.style.color=typeof u.winnerColor=="string"?u.winnerColor:"green";else if(u!=null&&u.genderColor){const y=(T=s==null?void 0:s.person)==null?void 0:T.sex,b=y==="MALE"&&"#2E86C1"||y==="FEMALE"&&"#AA336A"||"";E.style.color=typeof u.genderColor=="string"?u.genderColor:b}E.innerHTML=l,g.appendChild(E)}else{const E=document.createElement("abbr");E.className=ZA({variant:u.showAddress?"showAddress":""}),E.innerHTML=(n==null?void 0:n.bye)&&n2||(n==null?void 0:n.qualifier)&&e2||r2,g.appendChild(E)}const I=mm({...t,className:u1(),type:"seeding"});I&&g.appendChild(I),h.appendChild(g),p.appendChild(h);const S=a1(t);return p.appendChild(S),{element:p}}const s2=zt({width:"auto",display:"inline-block",textTransform:"uppercase",fontFamily:"Sharp Sans, Arial, sans-serif",fontSize:"0.625rem",lineHeight:"1rem",marginInline:"0.25rem 0.25rem",paddingInline:"0.25rem 0.25rem",fontWeight:700,borderRadius:"4px",color:"#fff",textAlign:"center",whiteSpace:"nowrap",variants:{variant:{defaulted:{backgroundColor:"#df164c"},retired:{backgroundColor:"#df164c"},walkover:{backgroundColor:"black"},double_walkover:{backgroundColor:"black"}}}});function i2({matchUpStatus:t}){const e=t==null?void 0:t.toLowerCase(),n=["WALKOVER","DOUBLE_WALKOVER"].includes(t)?"WO":(t==null?void 0:t.slice(0,3))||"",r=document.createElement("div");r.className=s2({variant:e});const s=document.createElement("abbr");return s.setAttribute("title",t),s.style.textDecoration="none",s.style.borderBottom="none",s.innerHTML=n,r.appendChild(s),r}const o2=zt({marginInlineEnd:".5rem",backgroundColor:"pink",marginInlineStart:2,height:40,width:40});function c2({teamLogo:t}){console.log({teamLogo:t});const e=document.createElement("div");return e.className=o2(),e}const a2=zt({flexDirection:"column",position:"relative",display:"flex"}),u2=zt({alignItems:"stretch",display:"flex"}),l2=zt({marginInlineEnd:".25rem",color:"green"});function d2({dim:t="20px"}={}){const e=l2();return`
26
+ `}function Gw({tournamentParticipants:t=[],possiblyDisablingAction:e,activeDrawPositions:n,positionAssignments:r,returnParticipants:s,appliedPolicies:i,drawDefinition:o,drawPosition:c,validActions:a,structureId:u,structure:l,drawId:f,event:p}){var A,C,v,P;if(n.includes(c))return{};const h=(A=a.find(U=>U.type===pc))==null?void 0:A.availableParticipantIds,d=(C=i==null?void 0:i[vs])==null?void 0:C.otherFlightEntries,m=(v=i==null?void 0:i[vs])==null?void 0:v.restrictQualifyingAlternates,g=(o.entries??[]).filter(({entryStage:U})=>!m||(l.stage===Pt?U===Pt:U!==Pt)).sort((U,O)=>(U.entryPosition??1/0)-(O.entryPosition??1/0)).map(({participantId:U})=>U).filter(Boolean),{allPositionedParticipantIds:I}=rS({drawDefinition:o}),S=r.map(U=>U.participantId).filter(Boolean),T=g.filter(U=>l.stage&&[Pt,It,Ie].includes(l.stage)?!(I!=null&&I.includes(U)):!S.includes(U)),y=((p==null?void 0:p.entries)??[]).filter(U=>U.entryStatus===dr&&rE({restrictQualifyingAlternates:m,structure:l,entry:U})&&(l.stage&&[Pt,It,Ie].includes(l.stage)?!(I!=null&&I.includes(U.participantId)):!S.includes(U.participantId))).sort((U,O)=>(U.entryPosition??1/0)-(O.entryPosition??1/0)).map(U=>U.participantId);let b=Vt(T.concat(y));if(d){const U=p?be({event:p}).flightProfile:void 0,O=(P=U==null?void 0:U.flights)==null?void 0:P.filter(D=>D.drawId!==f).map(D=>D.drawEntries.filter(M=>M.participantId&&![ti,Or,po].includes(M.entryStatus)&&!g.includes(M.participantId)).map(({participantId:M})=>M)).flat().filter(Boolean);O!=null&&O.length&&b.push(...O)}h!=null&&h.length&&(b=b.filter(U=>!h.includes(U)));const N=s?t==null?void 0:t.filter(U=>b.includes(U.participantId)):void 0;return N==null||N.forEach(U=>{const O=(o.entries??[]).find(D=>D.participantId===U.participantId);U.entryPosition=O==null?void 0:O.entryPosition}),N==null||N.sort((U,O)=>(U.entryPosition||1/0)-(O.entryPosition||1/0)),b.length?{validAlternatesAction:bt({payload:{drawId:f,structureId:u,drawPosition:c},willDisableLinks:e,method:tO,availableAlternatesParticipantIds:b,type:iT,availableAlternates:N})}:{}}function rE({restrictQualifyingAlternates:t,structure:e,entry:n}){const{stage:r}=e;if(!n.entryStage||n.entryStage===r||r===Pt&&!t||n.entryStage===It&&r===Re)return!0}const iu={[Jn]:{policyName:"matchUpActionsDefault",enabledStructures:[{stages:[],stageSequences:[],enabledActions:[],disabledActions:[]}],participants:{enforceGender:!0},processCodes:{substitution:["RANKING.IGNORE","RATING.IGNORE"]}}},id="positionAction",Ih="matchUpAction";function sE({actionType:t=id,appliedPolicies:e,drawDefinition:n,structure:r}){var p;const s=t===id&&vs||t===Ih&&Jn,i=t===id&&lT||t===Ih&&iu,o=s&&((e==null?void 0:e[s])||(i==null?void 0:i[s])),c=(p=n.links)==null?void 0:p.filter(h=>{var d;return((d=h==null?void 0:h.target)==null?void 0:d.structureId)===(r==null?void 0:r.structureId)}),a=(c==null?void 0:c.map(({target:h})=>h.feedProfile))??[],{enabledStructures:u,disabledStructures:l}=o||{},f=l==null?void 0:l.find(h=>{const{stages:d,stageSequences:m,structureTypes:g,feedProfiles:I}=h;return(!(I!=null&&I.length)||Array.isArray(I)&&I.some(S=>a.includes(S)))&&(!(d!=null&&d.length)||Array.isArray(d)&&(d==null?void 0:d.includes(r==null?void 0:r.stage)))&&(!(g!=null&&g.length)||Array.isArray(g)&&(g==null?void 0:g.includes(r==null?void 0:r.structureType)))&&(!(m!=null&&m.length)||Array.isArray(m)&&m.includes(r==null?void 0:r.stageSequence))});return{enabledStructures:u,actionsDisabled:f,actionsPolicy:o}}function iE({activePositionOverrides:t,activeDrawPositions:e,action:n}){return n&&t.includes(n)?!0:!e.length}function oE({enabledStructures:t,drawDefinition:e,structure:n}){var u;if(t===!1)return{};if(!(t!=null&&t.length))return{policyActions:{enabledActions:[],disabledActions:[]}};const{stage:r,stageSequence:s,structureType:i}=n||{},o=(u=e.links)==null?void 0:u.filter(l=>{var f;return((f=l==null?void 0:l.target)==null?void 0:f.structureId)===(n==null?void 0:n.structureId)}),c=(o==null?void 0:o.map(({target:l})=>l.feedProfile))||[];return{policyActions:t.find(l=>{const{stages:f,stageSequences:p,structureTypes:h,feedProfiles:d}=l||{},m=!(f!=null&&f.length)||Array.isArray(f)&&f.includes(r),g=!(p!=null&&p.length)||Array.isArray(p)&&p.includes(s),I=!(h!=null&&h.length)||Array.isArray(h)&&h.includes(i),S=!(d!=null&&d.length)||Array.isArray(d)&&d.some(T=>c.includes(T));return g&&I&&S&&l&&m})}}function Pn({action:t,policyActions:e}){var s;const n=!(e!=null&&e.enabledActions)||((s=e==null?void 0:e.disabledActions)==null?void 0:s.length)&&e.disabledActions.includes(t);return n?!1:((e==null?void 0:e.enabledActions.length)===0||(e==null?void 0:e.enabledActions.includes(t)))&&!n}const Ww="replaceTieMatchUpParticipantId",Hw="assignTieMatchUpParticipantId",cE="removeTieMatchUpParticipantId",aE="assignMatchUpSideParticipant",qw="removeMatchUpSideParticipant",Yw="substituteParticipant",uE="REMOVE_SUBSTITUTION",zw="REPLACE_PARTICIPANT",lE="REMOVE_PARTICIPANT",dE="setMatchUpStatus",fE="SUBSTITUTION",Kw="SCHEDULE",pE="REFEREE",Jw="STATUS",hE="START",Qw="SCORE",mE="END";function Sh({restrictAdHocRoundParticipants:t=!0,policyDefinitions:e,tournamentParticipants:n=[],inContextDrawMatchUps:r,tournamentRecord:s,drawDefinition:i,participantId:o,matchUpsMap:c,sideNumber:a,matchUpId:u,event:l}){var Y,z,J,Q,X,Z,nt,rt,K,it,st,dt,mt,Mt,Nt,St,ct,Et,gt,Ft,yt,wt,Xt,$t;if(!i)return{error:lt};if(!u)return{error:$e};if(a&&![1,2].includes(a))return G({result:{error:tt},context:{sideNumber:a}});const f=(Y=e==null?void 0:e[vs])==null?void 0:Y.otherFlightEntries,{drawId:p}=i,{matchUp:h,structure:d}=ie({drawDefinition:i,matchUpId:u,event:l});if(!h)return{error:Ye};const m=ge({tournamentRecord:s,drawDefinition:i,structure:d,event:l}).appliedPolicies??{};Object.assign(m,e??{});const g=Qr({drawDefinition:i,structure:d}),I=(m==null?void 0:m[Jn])??iu[Jn],{enabledStructures:S}=sE({actionType:Ih,appliedPolicies:m,drawDefinition:i,structure:d}),{policyActions:T}=oE({enabledStructures:S,drawDefinition:i,structure:d});c=c??ln({drawDefinition:i}),r||({matchUps:r}=xe({tournamentParticipants:n,inContext:!0,drawDefinition:i,matchUpsMap:c,event:l}));const E=r==null?void 0:r.find(At=>At.matchUpId===u),y=a&&((z=E==null?void 0:E.sides)==null?void 0:z.find(At=>At.sideNumber===a)),b=((J=E==null?void 0:E.sides)==null?void 0:J.map(At=>{var Dt;return At.participantId||((Dt=At.participant)==null?void 0:Dt.participantid)}).filter(Boolean))??[],{assignedPositions:N,allPositionsAssigned:A}=ke({structure:d}),{structureId:C}=d??{},v=[];if(!C)return{validActions:v};if(g){const At=((d==null?void 0:d.matchUps)??[]).filter(({roundNumber:ut})=>ut===h.roundNumber),Dt=((Q=i==null?void 0:i.entries)==null?void 0:Q.filter(({entryStatus:ut})=>ut&&ho.includes(ut)).map(fe))??[],at=At.map(ut=>(ut.sides??[]).flatMap(fe)).flat().filter(Boolean),ot=Dt.filter(ut=>!b.includes(ut)&&(!t||!at.includes(ut))),Lt=n==null?void 0:n.filter(ut=>ot==null?void 0:ot.includes(ut.participantId)).map(ut=>pt(ut,void 0,!0));Lt==null||Lt.forEach(ut=>{const Rt=(i.entries??[]).find(ne=>ne.participantId===ut.participantId);ut.entryPosition=Rt==null?void 0:Rt.entryPosition}),ot.length&&v.push({payload:{drawId:p,matchUpId:u,structureId:C,sideNumber:a},method:aE,type:pc,availableParticipantIds:ot,participantsAvailable:Lt});const ft=(l==null?void 0:l.entries)??[],Ct=Zw({eventEntries:ft,structure:d});let Ut=Vt(Dt.concat(Ct));if(f){const ut=l?be({event:l}):void 0,Rt=(X=ut==null?void 0:ut.flights)==null?void 0:X.filter(ne=>ne.drawId!==p).flatMap(ne=>ne.drawEntries.filter(Ae=>Ae.participantId&&![ti,Or,po].includes(Ae.entryStatus)).map(({participantId:Ae})=>Ae)).filter(Boolean);Rt!=null&&Rt.length&&Ut.push(...Rt)}Ut=Ut.filter(ut=>!b.includes(ut)&&!ot.includes(ut)&&(!t||!at.includes(ut)));const Kt=n==null?void 0:n.filter(ut=>Ut.includes(ut.participantId)).map(ut=>pt(ut,void 0,!0));if(Kt.forEach(ut=>{const Rt=(i.entries??[]).find(ne=>ne.participantId===ut.participantId);ut.entryPosition=Rt==null?void 0:Rt.entryPosition}),Kt.sort((ut,Rt)=>(ut.entryPosition||1/0)-(Rt.entryPosition||1/0)),Ut.length&&v.push({payload:{drawId:p,matchUpId:u,structureId:C,sideNumber:a},availableParticipantIds:Ut,participantsAvailable:Kt,method:aE,type:dr}),!Be(h)&&a){const ut=(Z=h.sides)==null?void 0:Z.find(Rt=>Rt.sideNumber===a);ut!=null&&ut.participantId&&v.push({payload:{drawId:p,matchUpId:u,structureId:C,sideNumber:a},method:qw,type:lE})}}const P=ki({drawDefinition:i,structure:d}),U=N==null?void 0:N.filter(At=>At.participantId).map(At=>At.drawPosition),O=N==null?void 0:N.filter(At=>At.bye).map(At=>At.drawPosition),D=h.collectionId,M=h.matchUpStatus===re||!D&&((nt=h.drawPositions)==null?void 0:nt.reduce((At,Dt)=>(O==null?void 0:O.includes(Dt))||At,!1));if(M)return{validActions:v,isByeMatchUp:M};Pn({policyActions:T,action:pE})&&v.push({type:pE,payload:{matchUpId:u}});const w=!Ra({matchUpStatus:h.matchUpStatus}),k=(rt=m==null?void 0:m.scoring)==null?void 0:rt.structures,_=(d==null?void 0:d.stage)&&(k==null?void 0:k.stage)&&(k==null?void 0:k.stage[d.stage]),F=(d==null?void 0:d.stageSequence)&&(_==null?void 0:_.stageSequence)&&_.stageSequence[d.stageSequence],W=!(((K=m==null?void 0:m.scoring)==null?void 0:K.requireAllPositionsAssigned)||(_==null?void 0:_.requireAllPositionsAssigned)||(F==null?void 0:F.requireAllPositionsAssigned))||A,j=h.sides&&h.sides.filter(At=>At==null?void 0:At.participantId).length===2,H=h.matchUpStatus&&[Fe,en].includes(h.matchUpStatus),B=gn({inContextDrawMatchUps:r,drawDefinition:i,matchUpId:u}),R=_i({inContextDrawMatchUps:r,drawDefinition:i,targetData:B}),q=(((it=E==null?void 0:E.drawPositions)==null?void 0:it.length)===2&&E.drawPositions.every(At=>U==null?void 0:U.includes(At))&&((st=E==null?void 0:E.sides)==null?void 0:st.length)===2&&E.sides.every(({participantId:At})=>At)||j)&&!(H&&R),V={method:rT,type:mc,payload:{drawId:p,matchUpId:u,penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0}};if(w&&v.push({payload:{drawId:p,matchUpId:u,schedule:{}},method:dE,type:Kw}),Pn({policyActions:T,action:mc})&&(y!=null&&y.participant||!a&&(b!=null&&b.length))&&v.push(V),w&&q&&v.push({type:Jw}),W&&q){const{matchUpId:At,matchUpFormat:Dt}=h,at={drawId:p,matchUpId:At,matchUpFormat:Dt,outcome:{scoreStringSide1:void 0,scoreStringSide2:void 0,sets:[]},winningSide:void 0};v.push({info:"set outcome and winningSide",method:dE,type:Qw,payload:at}),Pn({policyActions:T,action:hE})&&v.push({type:hE}),Pn({policyActions:T,action:mE})&&v.push({type:mE})}if(D&&E){const At=(dt=E.sides)==null?void 0:dt.find(ue=>ue.participant),Dt=E.gender===hs&&E.sideNumber&&((mt=E.sides)==null?void 0:mt.filter(ue=>ue.particiapntId).length)===1&&((Nt=(Mt=At==null?void 0:At.participant)==null?void 0:Mt.person)==null?void 0:Nt.sex),at=E.matchUpType,ot=(St=I==null?void 0:I.participants)!=null&&St.enforceGender?E.gender:void 0,Lt=(ct=E.sides)==null?void 0:ct.flatMap(ue=>{var he;return((he=ue.participant)==null?void 0:he.individualParticipants)||ue.participant}).filter(Boolean),ft=Lt==null?void 0:Lt.map(fe),Ct=(Et=E.sides)==null?void 0:Et.filter(ue=>!a||ue.sideNumber===a).flatMap(ue=>{var he;return((he=ue.participant)==null?void 0:he.individualParticipants)||ue.participant}).filter(Boolean),Ut=Ct==null?void 0:Ct.map(fe),Kt=r==null?void 0:r.find(ue=>ue.matchUpId===E.matchUpTieId),ut=(gt=Kt==null?void 0:Kt.sides)==null?void 0:gt.map(ue=>ue.participant.individualParticipants.filter(({participantId:he,person:$i})=>!(Ut!=null&&Ut.includes(he))&&(!ot||ot===Io||$i.sex===ot||ot===hs&&Dt&&$i.sex!==Dt))),Rt=a?ut==null?void 0:ut[a-1]:ut==null?void 0:ut.map((ue,he)=>({participants:ue,sideNumber:he+1})),ne=a?(Ft=ut==null?void 0:ut[a-1])==null?void 0:Ft.map(fe):ut==null?void 0:ut.map((ue,he)=>({participants:ue==null?void 0:ue.map(fe),sideNumber:he+1})),Ae=a&&(at===gi&&!(Ut!=null&&Ut.length)||at===Tr&&((Ut==null?void 0:Ut.length)??0)<2)||!a&&(at===gi&&((Ut==null?void 0:Ut.length)??0)<2||at===Tr&&((Ut==null?void 0:Ut.length)??0)<4),Ee=ne==null?void 0:ne.filter(ue=>!(ft!=null&&ft.includes(ue))),Un=Rt==null?void 0:Rt.filter(({participantId:ue})=>Ee.includes(ue));if(Ae&&(Ee!=null&&Ee.length)&&v.push({availableParticipantIds:Ee,method:Hw,availableParticipants:Un,type:pc,payload:{participantId:void 0,tieMatchUpId:u,drawId:p}}),Ut!=null&&Ut.length&&(!Be(h)||(yt=y==null?void 0:y.substitutions)!=null&&yt.length)&&v.push({method:cE,type:lE,existingParticipantIds:Ut,payload:{participantId:void 0,tieMatchUpId:u,drawId:p}}),Un!=null&&Un.length&&(!a&&(Ut!=null&&Ut.length)||a&&(y!=null&&y.participant))&&v.push({availableParticipantIds:Ee,method:Ww,availableParticipants:Un,type:zw,existingParticipantIds:Ut,payload:{existingParticipantId:void 0,participantId:void 0,tieMatchUpId:u,drawId:p}}),Pn({policyActions:T,action:uE})&&((wt=y==null?void 0:y.substitutions)!=null&&wt.length)){const ue=((Xt=y.participant)==null?void 0:Xt.participantType)===xt&&[y.participantId]||(($t=y.participant)==null?void 0:$t.participantType)===_t&&y.participant.individualParticipantIds||[],he=y.substitutions.map($i=>$i.participantId).filter($i=>ue.includes($i));(!o||he.includes(o))&&v.push({method:cE,type:uE,substitutedParticipantIds:he,payload:{participantId:void 0,tieMatchUpId:u,drawId:p}})}const Xe=e==null?void 0:e[Jn],Lr=Xe==null?void 0:Xe.substituteWithoutScore,jn=Xe==null?void 0:Xe.substituteAfterCompleted;if(Pn({policyActions:T,action:fE})&&b.length===2&&(!a&&(Ut!=null&&Ut.length)||a&&(y!=null&&y.participant))&&(Lr||Be(h))&&(jn||h.matchUpStatus&&!We.includes(h.matchUpStatus))&&(Ct!=null&&Ct.length)&&Rt.length){const ue=Ct.map(fe);v.push({info:"list of team players available for substitution",method:Yw,availableParticipantIds:ne,existingParticipantIds:ue,availableParticipants:Rt,existingParticipants:Ct,type:fE,payload:{substituteParticipantId:void 0,existingParticipantId:void 0,sideNumber:a,matchUpId:u,drawId:p}})}}return{structureIsComplete:P,validActions:v,isDoubleExit:H}}function Zw({eventEntries:t,structure:e}){const n=s=>s.entryStatus===dr&&rE({structure:e,entry:s}),r=(s,i)=>(s.entryPosition||1/0)-(i.entryPosition||1/0);return t.filter(n).sort(r).map(fe)}function gE({policyDefinitions:t,tournamentRecord:e,drawDefinition:n,participantId:r,sideNumber:s,matchUpId:i,drawId:o,event:c}){if(!e)return{error:et};o||(o=(He({tournamentRecord:e}).matchUps||[]).reduce((p,h)=>h.matchUpId===i?h.drawId:p,void 0),n=(e.events||[]).map(p=>p.drawDefinitions||[]).flat().reduce((p,h)=>h.drawId===o?h:p,void 0));const{policyDefinitions:a}=Zi({policyTypes:[vs],tournamentRecord:e,drawDefinition:n,event:c});return t=t||a,n?Sh({tournamentParticipants:e.participants,policyDefinitions:t,drawDefinition:n,participantId:r,sideNumber:s,matchUpId:i,event:c}):{error:rr}}function Xw(t){const{tournamentRecords:e,participantId:n,tournamentId:r,sideNumber:s,matchUpId:i,eventId:o,drawId:c}=t??{};if(typeof e!="object"||typeof r!="string"||typeof i!="string"||typeof c!="string")return{error:tt};const a=e[r];if(!a)return{error:et};const u=Je({tournamentRecord:a,eventId:o,drawId:c});return u.error?u:gE({drawDefinition:u.drawDefinition,tournamentRecord:a,participantId:n,sideNumber:s,matchUpId:i,drawId:c})}function tk({ignoreDisabled:t=!0,tournamentRecords:e,venueIds:n=[],dates:r=[]}){var f,p;if(!Array.isArray(r))return{error:tt,dates:r};if(!Array.isArray(n))return{error:tt,venueIds:n};if(!r.every(Yn))return{error:bn};const i=Co({tournamentRecords:e,ignoreDisabled:t,dates:r});if(i.error)return i;const o=(f=i==null?void 0:i.venues)==null?void 0:f.filter(({venueId:h})=>!(n!=null&&n.length)||n.includes(h)),c=(p=i.courts)==null?void 0:p.reduce((h,d)=>{var m;return(m=d.dateAvailability)==null||m.forEach(g=>{const I=g.date;h.includes(I)||h.push(I)}),h},[]).filter(h=>!r.length||r.includes(h)),a={venueIds:o==null?void 0:o.map(({venueId:h})=>h)},{matchUps:u}=ks({afterRecoveryTimes:!0,tournamentRecords:e,matchUpFilters:a});return{venuesReport:o==null?void 0:o.map(h=>ek(c,h,u))}}function ek(t,e,n){const{venueId:r,courts:s,venueName:i}=e,o={};return t.forEach(c=>{let a=0,u=0,l=0;for(const h of s){const d=h.dateAvailability.find(I=>I.date===c),m=d&&Tc({courtDate:d}),g=m==null?void 0:m.reduce((I,S)=>{const{startTime:T,endTime:E}=S,y=jt(E)-jt(T);return I+y},0);g&&(l+=1),a+=g}const f=n.filter(({schedule:h})=>h.venueId===r&&as(c,h.scheduledDate));f.forEach(({schedule:h})=>{const d=de(h.scheduledTime),m=An(d,h.averageMinutes),g=jt(m)-jt(d);u+=g});const p=a?(u/a*100).toFixed(2):"100";o[c]={scheduledMatchUpsCount:f.length,availableCourts:l,availableMinutes:a,scheduledMinutes:u,percentUtilization:p}}),{venueId:r,venueName:i,venueReport:o}}function nk({tournamentRecords:t}){const e=Object.keys(t);return{...$,tournamentIds:e}}const rk={getParticipantScaleItem:Vw,getCompetitionDateRange:Ly,getTournamentIds:nk,competitionScheduleMatchUps:nh,getSchedulingProfileIssues:jw,allCompetitionMatchUps:ks,competitionMatchUps:Ip,matchUpActions:Xw,getCompetitionVenues:Ap,getVenuesAndCourts:Co,getVenuesReport:tk,credits:sd};function IE({tournamentRecord:t,courtIds:e,dates:n}){if(!t)return{error:et};if(!Array.isArray(e))return{info:sn("courtIds"),error:Tt};const r=Array.isArray(n)&&n.length?{dates:n}:!0,s=i=>ae({creationTime:!1,element:i,extension:{value:r,name:Er}});for(const i of t.venues||[])for(const o of i.courts||[])if(e!=null&&e.includes(o.courtId)){const c=s(o);if(c.error)return c}return{...$}}function sk({tournamentRecords:t,courtIds:e,dates:n}){if(!t)return{error:Gt};if(!Array.isArray(e))return{error:Tt,info:sn("courtIds")};for(const r of Object.values(t))IE({tournamentRecord:r,courtIds:e,dates:n});return{...$}}function SE({tournamentRecord:t,venueIds:e}){if(!t)return{error:et};if(!Array.isArray(e))return{error:Tt,info:sn("venueIds")};for(const n of t.venues||[])if(e!=null&&e.includes(n.venueId)){const r=ae({creationTime:!1,element:n,extension:{name:Er,value:!0}});if(r.error)return r}return{...$}}function ik({tournamentRecords:t,venueIds:e}){if(!t)return{error:Gt};if(!Array.isArray(e))return{error:Tt,info:sn("venueIds")};for(const n of Object.values(t))SE({tournamentRecord:n,venueIds:e});return{...$}}function TE({tournamentRecord:t,courtIds:e,enableAll:n,dates:r}){if(!t)return{error:et};if(!Array.isArray(e)&&!n)return{error:Tt,info:sn("courtIds")};for(const s of t.venues||[])for(const i of s.courts||[])if(n||e!=null&&e.includes(i.courtId))if(Array.isArray(r)){const{extension:o}=xn({element:i,name:Er});if(o){const c=o.value;Array.isArray(c.dates)&&(c.dates=c.dates.filter(a=>!r.includes(a))),ae({creationTime:!1,element:i,extension:{name:Er,value:c}})}}else Ar({element:i,name:Er});return{...$}}function ok({tournamentRecords:t,enableAll:e,courtIds:n,dates:r}){if(!t)return{error:Gt};if(!e&&!Array.isArray(n))return{error:Tt,info:sn("courtIds")};for(const s of Object.values(t))TE({tournamentRecord:s,courtIds:n,enableAll:e,dates:r});return{...$}}function yE({tournamentRecord:t,venueIds:e,enableAll:n}){if(!t)return{error:et};if(!Array.isArray(e)&&!n)return{error:Tt,info:sn("venueIds")};for(const r of t.venues||[])(n||e!=null&&e.includes(r.venueId))&&Ar({element:r,name:Er});return{...$}}function ck({tournamentRecords:t,venueIds:e,enableAll:n}){if(!t)return{error:Gt};if(!n&&!Array.isArray(e))return{error:Tt,info:sn("venueIds")};for(const r of Object.values(t))yE({tournamentRecord:r,venueIds:e,enableAll:n});return{...$}}function EE({tournamentRecord:t,drawDefinition:e,matchUpId:n,drawId:r}){const s="removeCourtAssignment";if(!n)return{error:$e};if(!e&&!r)return{error:Hn};let i;if(!e){if(!t)return{error:et};({drawDefinition:e}=Je({tournamentRecord:t,drawId:r}))}if(e)({matchUp:i}=ie({drawDefinition:e,matchUpId:n}));else{if(!t)return{error:et};const o=He({tournamentRecord:t,inContext:!1}).matchUps||[];({matchUp:i}=cI({matchUps:o,matchUpId:n}))}return i?(i.timeItems&&i.timeItems.find(c=>[oo,Qs].includes(c.itemType))&&(i.timeItems=i.timeItems.filter(({itemType:c})=>![oo,Qs].includes(c)),qt({tournamentId:t==null?void 0:t.tournamentId,context:s,drawDefinition:e,matchUp:i})),{...$}):{error:Ye}}function Th({matchUpsCount:t=0}){const n=`Schedule would be deleted from ${t} ${t===1?"matchUp":"matchUps"}; use { force: true }`;return{error:Rv,info:n}}function yh({tournamentRecord:t,venueId:e,force:n}){if(!t)return{error:et};if(typeof e!="string")return{error:Vs};const s=He({tournamentRecord:t,contextFilters:{venueIds:[e]}}).matchUps||[];if(!s.length||n)for(const o of s){const c=EE({matchUpId:o.matchUpId,drawId:o.drawId,tournamentRecord:t});if(c.error)return c}else return Th({matchUpsCount:s.length});let i;return t.venues=(t.venues||[]).filter(o=>(o==null?void 0:o.venueId)!==e?!0:(i=!0,!1)),i?(Ht({payload:{venueId:e,tournamentId:t.tournamentId},topic:AI,key:e}),{...$}):{error:di}}function ak({tournamentRecord:t,venueIds:e,force:n}){if(!t)return{error:et};if(!Array.isArray(e))return{error:tt};for(const r of t.venues||[]){const{venueId:s}=r;if(e.includes(s)){const{venueId:i}=r,o=yh({tournamentRecord:t,venueId:i,force:n});if(o.error)return o}}return{...$}}function uk({tournamentRecords:t,venueId:e,force:n}){if(!t)return{error:Gt};if(typeof e!="string")return{error:Vs};let r;for(const s of Object.values(t)){const i=yh({tournamentRecord:s,venueId:e,force:n});if(i.error&&i.error!==di)return i;i.success&&(r=!0)}return By({tournamentRecords:t}),r?$:{error:di}}function lk({tournamentRecord:t,schedulingProfile:e}){return t?Array.isArray(e)?cd({tournamentRecord:t,schedulingProfile:e}):{error:tt}:{error:et}}function dk({tournamentRecord:t,schedulingProfile:e}){return Ti({tournamentRecord:t,extension:{name:qs,value:e}})}function od({tournamentRecord:t}){var s;if(!t)return{error:et};const e=t.tournamentId,{extension:n}=Bn({name:qs,tournamentRecord:t});let r=(n==null?void 0:n.value)||[];if(r.length){const i=(s=t.venues)==null?void 0:s.map(({venueId:p,courts:h})=>(h==null?void 0:h.length)&&p),o=_l({tournamentRecords:{[e]:t}}),{eventIds:c,drawIds:a}=o,{updatedSchedulingProfile:u,modifications:l,issues:f}=ed({schedulingProfile:r,venueIds:i,eventIds:c,drawIds:a});if(l){r=u;const p=dk({tournamentRecord:t,schedulingProfile:r});return p.error?p:{schedulingProfile:r,modifications:l,issues:f}}}return{schedulingProfile:r,modifications:0}}function cd({requireCourts:t=!0,tournamentRecord:e,schedulingProfile:n}){if(!n){const{modifications:a,issues:u}=od({tournamentRecord:e});return{success:!a,modifications:a,issues:u}}const{venueIds:r,eventIds:s,drawIds:i}=Fy({tournamentRecord:e,requireCourts:t}),{modifications:o,issues:c}=ed({schedulingProfile:n,venueIds:r,eventIds:s,drawIds:i});return{success:!o,modifications:o,issues:c}}function Eh(t){if(!(t!=null&&t.tournamentRecord)&&!Array.isArray(t==null?void 0:t.venueMatchUps))return{error:et};if(!(t!=null&&t.courtId))return{error:Ho};const{scheduleVisibilityFilters:e,tournamentRecord:n,matchUpFilters:r,venueMatchUps:s,courtId:i}=t,{schedulingProfile:o}=od({tournamentRecord:n});if(Array.isArray(s))return{matchUps:u({matchUps:s,courtId:i})};const{matchUps:c}=He({scheduleVisibilityFilters:e,tournamentRecord:n,matchUpFilters:r});return{matchUps:u({matchUps:c,courtId:i})};function u({matchUps:l,courtId:f}){const p=l.filter(h=>{var m,g,I;const d=(g=(m=h.schedule)==null?void 0:m.allocatedCourts)==null?void 0:g.map(({courtId:S})=>S);return((I=h.schedule)==null?void 0:I.courtId)===f||(d==null?void 0:d.includes(f))});return nd({matchUps:p,schedulingProfile:o})}}function fk({scheduleVisibilityFilters:t,tournamentRecord:e,matchUpFilters:n,venueId:r}){if(!e)return{error:et};if(!r)return{error:Vs};const{schedulingProfile:s}=od({tournamentRecord:e}),{matchUps:i}=He({scheduleVisibilityFilters:t,tournamentRecord:e,matchUpFilters:n});return{matchUps:c({matchUps:i,venueId:r})};function c({matchUps:a,venueId:u}){const l=a.filter(f=>{var h,d,m;const p=(d=(h=f.schedule)==null?void 0:h.allocatedCourts)==null?void 0:d.map(({venueId:g})=>g);return((m=f.schedule)==null?void 0:m.venueId)===u||(p==null?void 0:p.includes(u))});return nd({matchUps:l,schedulingProfile:s})}}function bE({tournamentRecord:t,drawDefinition:e,disableNotice:n,courtId:r,force:s}){const i=io({tournamentRecord:t,courtId:r});if(i.error)return i;const o=i.venue,{matchUps:c}=Eh({tournamentRecord:t,courtId:r});if(!(c!=null&&c.length)||s){for(const a of c||[]){const u=EE({matchUpId:a.matchUpId,drawId:a.drawId,tournamentRecord:t,drawDefinition:e});if(u.error)return u}o&&(o.courts=(o.courts||[]).filter(a=>a.courtId!==r),n||Ht({topic:so,payload:{venue:o,tournamentId:t.tournamentId},key:o.venueId}))}else return Th({matchUpsCount:c.length});return{...$}}function pk({tournamentRecords:t,courtId:e,force:n}){if(!t)return{error:Gt};if(typeof e!="string")return{error:Ho};let r,s;for(const i of Object.values(t)){if(s=bE({tournamentRecord:i,courtId:e,force:n}),s.error&&s.error!==Kd)return s;s.success&&(r=!0)}return r?{...$}:s}function ad(t){return parseInt(t)}function NE({startTime:t="",endTime:e=""}={}){if(!t||!e||!pi.test(t)||!pi.test(e))return!1;const[n,r]=t.split(":").map(ad),[s,i]=e.split(":").map(ad);return s<n?!1:!(n===s&&i<r)}function hk(t,e){const[n,r]=t.startTime.split(":").map(ad),[s,i]=e.startTime.split(":").map(ad);return n<s?-1:n>s?1:r<i?-1:r>i?1:0}function AE({dateAvailability:t}){if(!t)return{error:nv};if(!Array.isArray(t))return{error:Hd};const e="Dates must be formated => YYYY-MM-DD",n="Times must be 24 hour => 00:00";for(const r of t){if(typeof r!="object")return{error:Hd};const{date:s,startTime:i,endTime:o,bookings:c=[]}=r;if(!i||!o)return{error:Hd};if(s&&!Vr.test(s))return{error:bn,dateAvailability:{date:s},info:e};if(!pi.test(i))return{error:sr,dateAvailability:{startTime:i},info:n};if(!pi.test(o))return{error:sr,dateAvailability:{endTime:o},info:n};if(i===o)return{error:sr,dateAvailability:{startTime:i,endTime:o},info:"startTime and endTime are equivalent"};if(!NE({startTime:i,endTime:o}))return{error:sr,dateAvailability:{startTime:i,endTime:o},info:"endTime must be after startTime"};if(c){if(!Array.isArray(c))return{error:Wd};for(const a of c){if(typeof a!="object")return{error:Wd};const{startTime:u,endTime:l}=a;if(!pi.test(u))return{error:sr,booking:{startTime:u},info:n};if(!pi.test(l))return{error:sr,booking:{endTime:l},info:n};if(u===l)return{error:sr,dateAvailability:{startTime:u,endTime:l},info:"startTime and endTime are equivalent"};if(!NE({startTime:u,endTime:l}))return{error:sr,dateAvailability:{startTime:u,endTime:l},info:"endTime must be after startTime"}}}}return{valid:!0}}function vE({tournamentRecord:t,dateAvailability:e,disableNotice:n,venueMatchUps:r,courtId:s,force:i}){if(!t)return{error:et};if(!s)return{error:Ho};const o=AE({dateAvailability:e});if(o.error)return o;const{updatedDateAvailability:c,totalMergeCount:a}=mk(e);e=c;const u=io({tournamentRecord:t,courtId:s});if(u.error)return u;const{court:l,venue:f}=u,{matchUps:p}=Eh({tournamentRecord:t,venueMatchUps:r,courtId:s});return p!=null&&p.length&&console.log("scheduled court matchUps",p.length),l&&(l.dateAvailability=e,!n&&f&&Ht({payload:{venue:f,tournamentId:t.tournamentId},topic:so,key:f.venueId})),{...$,totalMergeCount:a}}function mk(t){let e=0;const n=t.reduce((s,i)=>{const{date:o,startTime:c,endTime:a,bookings:u}=i;return s[o]||(s[o]=[]),s[o].push({startTime:c,endTime:a,bookings:u}),s},{}),r=[];return Object.keys(n).forEach(s=>{n[s].sort(hk);const{mergedAvailability:i,mergeCount:o}=gk(n[s]);r.push(...i.map(c=>({date:s,...c}))),e+=o}),{updatedDateAvailability:r,totalMergeCount:e}}function gk(t){let e,n,r,s=t.length,i=0;const o=[];for(;t.length&&s;){const a=t.shift(),{startTime:u,endTime:l,bookings:f}=a;if(s-=1,!e)e=u,r=f,n=l;else if(ea(Pe(n),Pe(u),!1)>0){const h={startTime:e,endTime:n};r!=null&&r.length&&(h.bookings=r),o.push(h),e=u,r=f,n=l}else f&&(r?r.push(f):r=f),n=l,i+=1}const c={startTime:e,endTime:n};return r!=null&&r.length&&(c.bookings=r),o.push(c),{mergedAvailability:o,mergeCount:i}}const CE=()=>({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});function bh({tournamentRecord:t,disableNotice:e,venueMatchUps:n,modifications:r,courtId:s,force:i}){if(!t)return{error:et};if(!s)return{error:Ho};if(!r||typeof r!="object")return{error:Ir};const o=io({tournamentRecord:t,courtId:s});if(o.error)return o;const{venue:c,court:a}=o,u=Object.keys(CE()).filter(h=>h!=="courtId");if(!Object.keys(r).filter(h=>u.includes(h)).length)return{error:Qd};const f=u.filter(h=>!["dateAvailability"].includes(h)),p=Object.keys(r).filter(h=>f.includes(h));if(a&&p.forEach(h=>Object.assign(a,{[h]:r[h]})),r.dateAvailability){const h=vE({dateAvailability:r.dateAvailability,tournamentRecord:t,venueMatchUps:n,disableNotice:e,courtId:s,force:i});if(h.error)return h}return e||Ht({payload:{venue:c,tournamentId:t.tournamentId},topic:so,key:c==null?void 0:c.venueId}),{...$,court:pt(a)}}function Ik({tournamentRecords:t,disableNotice:e,modifications:n,courtId:r,force:s}){if(!t)return{error:Gt};if(!r)return{error:Tt,info:"missing courtId"};let i,o;for(const c of Object.values(t)){const a=bh({tournamentRecord:c,disableNotice:e,modifications:n,courtId:r,force:s});a!=null&&a.error&&(o=a),i=!0}return i?{...$}:o}const Sk=()=>({venueId:void 0,venueName:"",venueAbbreviation:"",onlineResources:[],venueType:void 0,addresses:[],contacts:[],courts:[],roles:[]});function Nh({tournamentRecord:t,disableNotice:e,venueId:n,courtId:r,court:s}){const{venue:i}=Js({tournamentRecord:t,venueId:n});if(!i)return{error:di};i.courts||(i.courts=[]);const o={...CE(),venueId:n,courtId:r};if(o.courtId||(o.courtId=Yt()),i.courts.some(a=>a.courtId===o.courtId))return{error:Ev};{const a=((s==null?void 0:s.dateAvailability)||[]).map(f=>{var p;return{...f,date:Bt(f.date),startTime:de(f.startTime),endTime:de(f.endTime),bookings:(p=f.bookings)==null?void 0:p.map(({startTime:h,endTime:d,bookingType:m})=>({startTime:de(h),endTime:de(d),bookingType:m}))}}),u=Object.keys(o);for(const f of u)if(s!=null&&s[f])if(f==="dateAvailability"){const p=AE({dateAvailability:a});if(!p.valid&&p.error)return p;o.dateAvailability=a}else o[f]=s[f];const l=o;return i.courts.push(l),e||Ht({payload:{venue:i,tournamentId:t.tournamentId},topic:so,key:i.venueId}),{...$,court:pt(o),venueId:n}}}function Ah({courtNameRoot:t="Court",dateAvailability:e=[],venueAbbreviationRoot:n,tournamentRecord:r,courtNames:s=[],courtTimings:i,courtsCount:o,startTime:c,courtIds:a,endTime:u,idPrefix:l,venueId:f,dates:p}){if(!f)return{error:Vs};const h=Js({tournamentRecord:r,venueId:f});if(h.error)return h;const{venue:d}=h;if(!Me(o)||!s)return{error:yv};o=o??s.length;const I=ht(0,o).map(S=>{const T=i==null?void 0:i[S],E=T?p.map(y=>({date:Sr(y),startTime:c,endTime:u,...T})):e;return T&&c&&u&&E.push({startTime:c,endTime:u}),{courtName:s[S]||n&&(d==null?void 0:d.venueAbbreviation)&&`${d==null?void 0:d.venueAbbreviation} ${S+1}`||`${t} ${S+1}`,dateAvailability:E}}).map((S,T)=>{const E=(a==null?void 0:a.pop())||l&&`${l}-${T+1}`;return Nh({disableNotice:!0,tournamentRecord:r,courtId:E,venueId:f,court:S})}).map(S=>S.court).filter(Boolean);return I.length!==o?{error:"Not all courts could be generated",result:h}:(d&&Ht({payload:{venue:d,tournamentId:r.tournamentId},topic:so,key:d.venueId}),{...$,courts:pt(I)})}function PE({tournamentRecord:t,modifications:e,venueId:n,force:r}){var d,m,g,I;if(!t)return{error:et};if(!e||typeof e!="object")return{error:Ir};if(!n)return{error:Vs};const{matchUps:s}=fk({tournamentRecord:t,venueId:n}),i=Js({tournamentRecord:t,venueId:n});if(i.error)return i;const o=i.venue,c=Object.keys(Sk()).filter(S=>S!=="venueId");if(!Object.keys(e).filter(S=>c.includes(S)).length)return{error:Qd};const u=c.filter(S=>!["courts","onlineResources"].includes(S)),l=Object.keys(e).filter(S=>u.includes(S));o&&l.forEach(S=>Object.assign(o,{[S]:e[S]}));const f=((d=o==null?void 0:o.courts)==null?void 0:d.map(S=>S.courtId))??[],p=((m=e.courts)==null?void 0:m.map(S=>S.courtId))||[],h=f.filter(S=>!p.includes(S));if(h.length){const S=(g=o==null?void 0:o.courts)==null?void 0:g.filter(E=>h.includes(E.courtId)),T=S==null?void 0:S.map(E=>{var b;return((b=Eh({courtId:E.courtId,tournamentRecord:t,venueMatchUps:s}).matchUps)==null?void 0:b.length)??0}).reduce((E,y)=>E+y);if(o&&(!T||r))o.courts=(I=o.courts)==null?void 0:I.filter(E=>p.includes(E.courtId));else return Th({matchUpsCount:T})}if(e.courts)for(const S of e.courts){const{courtId:T}=S||{};let E=bh({modifications:S,disableNotice:!0,tournamentRecord:t,venueMatchUps:s,courtId:T,force:r});if(E.error===Kd&&(E=Nh({disableNotice:!0,tournamentRecord:t,venueId:n,court:S})),E.error)return E}return cd({tournamentRecord:t}),o&&Ht({payload:{venue:o,tournamentId:t.tournamentId},topic:so,key:o==null?void 0:o.venueId}),{...$,venue:pt(o)}}function Tk({tournamentRecords:t,modifications:e,venueId:n,force:r}){if(!t)return{error:Gt};if(typeof n!="string")return{error:Vs};let s,i;for(const o of Object.values(t)){const c=PE({tournamentRecord:o,modifications:e,venueId:n,force:r});if(c.success&&(i=!0),c.error&&(s=c.error),c.error&&c.error!==di)return c}return By({tournamentRecords:t}),i?{...$}:{error:s}}function yk(t){const{tournamentRecords:e,venueId:n}=t;if(typeof n!="string"||!n)return{error:Vs};let r;for(const s of Object.values(e)){const{venue:i}=Js({tournamentRecord:s,venueId:n});if(i){const o=Ah({...t,tournamentRecord:s});if(o.error)return o;r=!0}}return r?$:{error:di}}function Ek({tournamentRecords:t,disableNotice:e,venue:n,context:r}){if(typeof n!="object")return{error:tt};n.venueId||(n.venueId=Yt());let s;for(const i of Object.values(t)){const o=ma({disableNotice:!0,tournamentRecord:i,context:r,venue:n});if(o!=null&&o.error)return o;s=o.venue}return e||Ht({topic:bI,payload:{venue:n}}),bt({...$,venue:s})}const bk={disableCourts:sk,disableVenues:ik,enableCourts:ok,enableVenues:ck,deleteCourt:pk,deleteVenue:uk,modifyCourt:Ik,modifyVenue:Tk,addCourts:yk,addVenue:Ek};function Nk({convertExtensions:t,removeExtensions:e}){const n=Ou();return{tournamentId:os(),tournamentRecords:pt(n,t,!1,e)}}function Ak(){var r;const t=Ou(),{extension:e}=zu({name:Ki,tournamentRecords:t}),n=((r=e==null?void 0:e.value)==null?void 0:r.tournamentIds)||[];return Object.keys(t).forEach(s=>{n.includes(s)||delete t[s]}),Qc(t)}function vk(t,e=!0){return typeof t!="object"||Array.isArray(t)?{error:Ir}:t!=null&&t.tournamentId?Dg(e?pt(t):t):{error:tt}}function vh(t,e=!0){if(typeof t!="object")return{error:Ir};if(Array.isArray(t)){if(!(t.filter(r=>r==null?void 0:r.tournamentId).length===t.length))return{error:Wm};t=Object.assign({},...t.map(r=>({[r.tournamentId]:r})))}else if(t!=null&&t.tournamentId)t={[t.tournamentId]:t};else if(!Object.keys(t).every(r=>t[r].tournamentId===r))return{error:Wm};return Qc(e?pt(t):t)}(function(){const t={getState:o=>Nk({convertExtensions:o==null?void 0:o.convertExtensions,removeExtensions:o==null?void 0:o.removeExtensions}),version:()=>Es(),reset:()=>(Qc({}),e())};return s([qD,$w,rk,KD,Rw,bk]),t.devContext=o=>(zo(o),e()),t.getDevContext=o=>ze(o),t.setState=(o,c,a)=>{Hi(c,a);const u=vh(o,c);return e(u)},t.setTournamentRecord=(o,c,a)=>{Hi(c,a);const u=vk(o,c);return e(u)},t.removeTournamentRecord=o=>{const c=Xd(o);return e(c)},t.removeUnlinkedTournamentRecords=()=>{const o=Ak();return e(o)},t.executionQueue=(o,c)=>i(o,c),t;function e(o){return o!=null&&o.error?(t.error=o.error,t.success=!1):(t.error=void 0,t.success=!0),t}function n(o,c,a,u){var g,I;delete t.success,delete t.error;const l=Date.now(),f=c({tournamentRecords:o,...a}),p=Date.now()-l,h=ze(),d={method:u},m=typeof h.result=="object"&&h.result.error;return![void 0,!1].includes(h.perf)&&(isNaN(h.perf)||p>h.perf)&&(d.elapsed=p),(m||h.params&&!Array.isArray(h.params)||Array.isArray(h.params)&&((g=h.params)!=null&&g.includes(u)))&&(d.params=a),(m||!m&&h.result&&!Array.isArray(h.result)||Array.isArray(h.result)&&((I=h.result)!=null&&I.includes(u)))&&(d.result=f),Object.keys(d).length>1&&console.log("ce:",d),f}function r(o,c,a){const u=Ou(),l=os(),f=(c==null?void 0:c.rollbackOnError)&&pt(u,!1,!0),p=n(u,o,{activeTournamentId:l,...c},a);p!=null&&p.error&&f&&vh(f);const h=(p==null?void 0:p.success)&&(c==null?void 0:c.delayNotify)!==!0&&(c==null?void 0:c.doNotNotify)!==!0,d=Kc(),m=Date.now();return d&&(Object.values(u).forEach(g=>{Dl({tournamentRecord:g,value:{version:Es(),timeStamp:m}})}),p.modificationsApplied=!0),h&&Di({directives:[{method:o,params:c}],mutationStatus:d,timeStamp:m}),(h||!(p!=null&&p.success)||c!=null&&c.doNotNotify)&&fi(),p}function s(o){o.forEach(c=>{Object.keys(c).forEach(a=>{t[a]=u=>{if(ze())return r(c[a],u,a);try{return r(c[a],u,a)}catch(l){Xc({engineName:"competitionEngine",methodName:a,params:u,err:l})}}})})}function i(o,c){var m;if(!Array.isArray(o))return{error:tt};const a=Ou(),u=os(),l=c&&pt(a,!1,!0);let f;const p=[];for(const g of o){if(typeof g!="object")return{error:tt};const{method:I,params:S}=g;if(!t[I]){const E={error:vg,methodName:I},y=ze();return(y.result&&!Array.isArray(y.result)||Array.isArray(y.result)&&((m=y.result)!=null&&m.includes(I)))&&console.log("ce:",E),E}const T=n(a,t[I],{activeTournamentId:u,...S},I);if(T!=null&&T.error)return l&&vh(l),{...T,rolledBack:!!l};p.push({...T,methodName:I}),f=Date.now()}const h=Kc();return h&&Object.values(a).forEach(g=>{Dl({tournamentRecord:g,value:{version:Es(),timeStamp:f}})}),Di({directives:o,mutationStatus:h,timeStamp:f}),fi(),{success:p.every(g=>g.success),results:p}}})();function Ch({structureName:t=je,structureAbbreviation:e,drawDefinition:n,matchUpType:r,structureId:s}){if(!n)return{error:lt};const i=Ze({stage:je,structureAbbreviation:e,structureName:t,matchUps:[],structureId:s,matchUpType:r});return n.structures.push(i),Zt({drawDefinition:n,structureIds:[s]}),{...$}}function kc({targetEntryRound:t=1,finishingPositions:e,sourceRoundNumber:n,sourceStructureId:r,targetStructureId:s,linkType:i=js.Winner}){return!r||!s?{error:En}:{link:bt({linkType:i,source:{roundNumber:n,structureId:r,finishingPositions:e},target:{feedProfile:Cr,roundNumber:t,structureId:s}})}}function Ph({idPrefix:t,roundNumber:e,roundPosition:n,uuids:r}){return t?`${t}-${e}-${n}`:(r==null?void 0:r.pop())||Yt()}function ud({includeMatchUpType:t,matchUpType:e,roundNumber:n,matchUps:r,idPrefix:s,isMock:i,uuids:o,nodes:c}){let a=0;const u=[];let l=1;const f=n-1,p=c==null?void 0:c.length;for(;a<(p||0);){const h=c==null?void 0:c[a],d=c==null?void 0:c[a+1];f&&(h.roundNumber=f),d&&f&&(d.roundNumber=f);const m=Ph({roundPosition:l,roundNumber:n,idPrefix:s,uuids:o}),g={roundPosition:l,children:[h,d],matchUpId:m};u.push(g);const I={drawPositions:g.children.map(S=>S==null?void 0:S.drawPosition).filter(Boolean),matchUpStatus:Le,matchUpId:g.matchUpId,roundPosition:l,roundNumber:n};t&&e&&(I.matchUpType=e),i&&(I.isMock=!0),r.push(I),l++,a+=2}return{roundNodes:u,matchUps:r}}function rs({finishingPositionOffset:t,finishingPositionLimit:e,qualifyingRoundNumber:n,qualifyingPositions:r,matchUpType:s,roundLimit:i,idPrefix:o,drawSize:c,isMock:a,uuids:u}){if(isNaN(c)||c<2||r&&c<=r)return{matchUps:[],roundsCount:0};if(r&&(!mr(c)||c%r)){let g=r;for(;g<c;)g=2*g;c=g}const l=r&&!(c%2)&&(!isNaN(r)||n&&!isNaN(n))&&(c/r===Math.round(c/r)||n&&c/n===Math.round(c/n));if(!mr(c)&&!l)return{matchUps:[],roundsCount:0};const f=ht(1,c+1).map(g=>({drawPosition:g}));let p,h=[],d=1;for({roundNodes:p,matchUps:h}=ud({matchUpType:s,roundNumber:d,idPrefix:o,matchUps:h,isMock:a,nodes:f,uuids:u}),d++,i=i||n;p.length>1;)r&&p.length===r&&(i=d-1),{roundNodes:p,matchUps:h}=ud({nodes:p,matchUpType:s,roundNumber:d,idPrefix:o,matchUps:h,isMock:a,uuids:u}),d++;const m=d-1;return h=ja({finishingPositionOffset:t,finishingPositionLimit:e,roundsCount:m,roundLimit:i,matchUps:h}),i?h=h.filter(g=>i&&(g.roundNumber||0)<=i):i=d-1,{drawSize:c,matchUps:h,roundsCount:m,roundLimit:i}}function UE({qualifyingProfiles:t,appliedPolicies:e,idPrefix:n,isMock:r,uuids:s}){var m;const i="generateQualifyingSTructures",o=[],c=[],a=[],u=(g,I)=>g.stageSequence-I.stageSequence,l=(g,I)=>g.roundTarget-I.roundTarget;let f=0,p=0,h,d=1;for(const g of t.sort(l)){const I=g.structureProfiles||[];d=g.roundTarget||d;let S=1,T=0,E,y,b;for(const N of(I||[]).sort(u)){let A=N.drawSize||_d(N.participantsCount);const{qualifyingRoundNumber:C,qualifyingPositions:v,structureOptions:P,matchUpFormat:U,structureName:O,structureId:D,drawType:M}=N,w=N.matchUpType;let k,_,F;if(!oe(A))return G({result:{error:Eu},stack:i});const L=t.length>1?`${d}-`:"",W=I.length>1||L?S:"",j=O||(L||W?`${Pt} ${L}${W}`:Pt);if(M===Pr){const{structures:H,groupCount:B,maxRoundNumber:R}=za({structureName:N.structureName||j,structureId:D||(s==null?void 0:s.pop()),stage:Pt,structureOptions:P,appliedPolicies:e,stageSequence:S,matchUpType:w,roundTarget:d,drawSize:A,idPrefix:n,isMock:r,uuids:s});T=B,k=R,_=H[0],h=[1]}else({drawSize:A,matchUps:F,roundLimit:k}=rs({qualifyingRoundNumber:C,qualifyingPositions:v,matchUpType:w,drawSize:A,idPrefix:n,isMock:r,uuids:s})),_=Ze({structureName:N.structureName||j,structureId:D||(s==null?void 0:s.pop()),qualifyingRoundNumber:k,stage:Pt,matchUpFormat:U,stageSequence:S,matchUpType:w,roundLimit:k,matchUps:F}),d&&ae({element:_,extension:{name:Hr,value:d}}),T=((m=F==null?void 0:F.filter(H=>H.roundNumber===k))==null?void 0:m.length)||0;if(S>1){const{link:H}=kc({sourceStructureId:y,sourceRoundNumber:E,targetStructureId:_.structureId,finishingPositions:b===Ai?[1]:void 0,linkType:b});a.push(H),f+=(A||0)-T}else f+=A||0;b=M===Pr?Ai:vi,y=_.structureId,E=k,c.push(_),S+=1}p+=T,o.push({qualifiersCount:T,finalQualifyingRoundNumber:E,finalQualifyingStructureId:y,finishingPositions:h,roundTarget:d,linkType:b}),T=0,d+=1}return{qualifiersCount:p,qualifyingDrawPositionsCount:f,qualifyingDetails:o,structures:c,...$,links:a}}function Uh({drawDefinition:t,structureId:e}){const n=Ot({drawDefinition:t,structureId:e});if(n.error)return n;const{matchUps:r}=Qt({structure:n.structure});return Cn({matchUps:r})}function OE({finishingPositions:t,drawDefinition:e,structureId:n}){const{roundProfile:r}=Uh({drawDefinition:e,structureId:n}),s=r&&Object.keys(r);return s==null?void 0:s.reduce((i,o)=>(ME(r==null?void 0:r[o]).forEach(a=>{t.forEach(u=>{Ck({position:u,rangeDefinition:a})&&(i[u]={roundNumber:o})})}),i),{})}function Ck({position:t,rangeDefinition:e}){if(!Array.isArray(e)||e.reduce((i,o)=>i||isNaN(o),!1))return!1;const[n,r]=e;return ht(n,(r||n)+1).includes(t)}function ME(t){var e,n;return[Vt(((e=t==null?void 0:t.finishingPositionRange)==null?void 0:e.loser)||[]),Vt(((n=t==null?void 0:t.finishingPositionRange)==null?void 0:n.winner)||[])]}function Pk(t){return ME(t).map(e=>ht(e[0],e[1]&&e[1]+1||e[0]+1))}function ld({drawDefinition:t,structureIds:e}){if(e&&!Array.isArray(e))return{error:tt,context:{structureIds:e}};if(!t)return{error:lt};e=e||(t.structures||[]).filter(o=>o.stage!==Pt).map(({structureId:o})=>o);const n=e.map(o=>{const{roundProfile:c}=Uh({drawDefinition:t,structureId:o}),a=c&&Object.values(c);return a==null?void 0:a.map(Pk).flat()}).flat(),r=n.filter(o=>(o==null?void 0:o.length)===1).sort(Ve).flat();return{positionsNotPlayedOff:Vt(n.flat()).filter(o=>!r.includes(o)),positionsPlayedOff:r}}function Oh({excludeRoundNumbers:t=[],playoffPositions:e=[],drawDefinition:n,structureId:r}){if(!n)return{error:lt};if(!r)return{error:En};if(!e)return{error:Tt,info:"missing playoffPositions"};const s=ld({drawDefinition:n});if(s.error)return s;const i=s.positionsPlayedOff,o=e.filter(g=>!i.includes(g)),c=OE({finishingPositions:o,drawDefinition:n,structureId:r}),a=Object.values(c).reduce((g,I)=>g.includes(I.roundNumber)?g:g.concat(I.roundNumber),[]).map(g=>vt(g)).filter(g=>!t.includes(g)),u=OE({finishingPositions:i,drawDefinition:n,structureId:r}),l=u?Object.values(u).reduce((g,I)=>g.includes(I.roundNumber)?g:g.concat(I.roundNumber),[]).map(g=>vt(g)):[],f=a.filter(g=>!l.includes(g)).sort(Ve),{roundProfile:p}=Uh({drawDefinition:n,structureId:r}),h=f.map(g=>{const I=p==null?void 0:p[g].finishingPositionRange.loser,[S,T]=I??[0,0];return ht(S,(T||S)+1)}).flat().sort(Ve),{playoffRoundsRanges:d}=Uk({playoffSourceRounds:f,roundProfile:p}),m=[...f,...l];return{playoffPositionsReturned:h,playedOffSourceRounds:l,playoffRoundsRanges:d,playoffSourceRounds:f,sourceRounds:m,roundProfile:p}}function Uk({playoffSourceRounds:t,roundProfile:e}){return{playoffRoundsRanges:t.map(r=>{const s=e[r].finishingPositionRange.loser,[i,o]=s,c=ht(i,(o||i)+1);return{finishingPositionRange:s.join("-"),finishingPositions:c,roundNumber:r}})}}function ou({drawDefinition:t,structureId:e}){if(!t)return{error:lt};const{positionsNotPlayedOff:n,positionsPlayedOff:r}=ld({drawDefinition:t}),{structures:s}=lr({drawDefinition:t}),i=s.filter(a=>!e&&a.stage!==je||a.structureId===e),o={},c=tr({inContext:!0,drawDefinition:t}).matchUps;for(const a of i){const u=a==null?void 0:a.structureId,l=Ok({playoffPositions:n,drawDefinition:t,structure:a,matchUps:c}),{error:f,...p}=l;if(f)return l;o[u]={structureId:u,...p}}return e?{positionsPlayedOff:r,...o[e]}:{availablePlayoffProfiles:Object.values(o),availablePlayoffRounds:Object.values(o),positionsPlayedOff:r}}function Ok({playoffPositions:t,drawDefinition:e,structure:n,matchUps:r}){var p,h,d,m,g,I,S,T;const s=n==null?void 0:n.structureId,{links:i}=$a({drawDefinition:e,structureId:s});if(n.structureType===mn||n.structures){const E=(h=(p=ee({structure:n}))==null?void 0:p.positionAssignments)==null?void 0:h.length,y=n.structures.length,b=(E??0)/y,N=((d=i.source)==null?void 0:d.flatMap(({source:k})=>(k==null?void 0:k.finishingPositions)||[]))||[],A=ht(1,b+1).filter(k=>!N.includes(k)),C=((g=(m=r.find(k=>k.containerStructureId===s&&k.finishingPositionRange))==null?void 0:m.finishingPositionRange)==null?void 0:g.winner)||[0,1],v=i==null?void 0:i.source.map(({target:k})=>k.structureId),{positionsPlayedOff:P,positionsNotPlayedOff:U}=ld({structureIds:v,drawDefinition:e}),O=[...P??[],...U],D=ht(C[0],C[1]+1).filter(k=>!O.includes(k)),M=Ge(D,D.length/A.length),w=A.map((k,_)=>{const F=M[_],L=[Math.min(...F||[]),Math.max(...F||[])].join("-");return{finishingPosition:k,finishingPositions:F,finishingPositionRange:L}});return{positionsNotPlayedOff:D,playoffFinishingPositionRanges:w,finishingPositionsAvailable:A,finishingPositionsPlayedOff:N,positionsPlayedOff:P,groupCount:y,groupSize:b}}const o=((I=i==null?void 0:i.source)==null?void 0:I.filter(E=>E.linkCondition!==fs).map(E=>{var y;return(y=E.source)==null?void 0:y.roundNumber}))||[],c=((S=i==null?void 0:i.source)==null?void 0:S.filter(E=>E.linkCondition===fs).map(E=>{var y;return(y=E.source)==null?void 0:y.roundNumber}))||[],{playoffSourceRounds:a,playoffRoundsRanges:u,roundProfile:l,error:f}=Oh({excludeRoundNumbers:o,playoffPositions:t,drawDefinition:e,structureId:s});for(const E of c){const y=i==null?void 0:i.source.find(v=>v.source.roundNumber===E),b=y==null?void 0:y.target.roundNumber,N=y==null?void 0:y.target.structureId,A=r.filter(({roundNumber:v,structureId:P})=>P===N&&v===b),C=A.filter(({sides:v})=>v.find(P=>P.participantFed&&!P.participantId)).length;if(a&&C===A.length){a.push(E);const v=(T=l==null?void 0:l[E].finishingPositionRange)==null?void 0:T.loser;if(v){const P=Math.min(...v),U=P+C,O=ht(P,U),D={finishingPositionRange:[P,U-1].join("-"),finishingPositions:O,roundNumber:E};u.push(D)}}}return a&&a.sort(Ve),u.sort((E,y)=>E.roundNumber-y.roundNumber),{playoffRounds:a,playoffRoundsRanges:u,error:f}}function Mk({playoffGroups:t,drawDefinition:e,structureId:n}){var c;if(!e)return{error:lt};if(typeof n!="string"||!Array.isArray(t))return{error:tt};const r=t.map(({finishingPositions:a})=>a).flat(),i=(c=ou({drawDefinition:e,structureId:n}).playoffFinishingPositionRanges)==null?void 0:c.filter(a=>r.includes(a.finishingPosition));return{positionRangeMap:i==null?void 0:i.reduce((a,u)=>(a[u.finishingPosition]=u,a),{})}}function Dk({includeMatchUpType:t,drawPosition:e,roundNumber:n,matchUpType:r,idPrefix:s,matchUps:i,isMock:o,uuids:c,nodes:a,fed:u}){const l=a.length,f=e?e-l:void 0,p=ht(0,l).map(m=>f?f+m:void 0),h=[];for(let m=0;m<l;m++){const g=p.shift(),I={drawPosition:g,fed:u+1,feed:!0},S=a[m];S.roundNumber=n-1;const T=Ph({roundPosition:S.roundPosition,roundNumber:n,idPrefix:s,uuids:c}),E={roundPosition:S.roundPosition,drawPositions:[g],matchUpStatus:Le,roundNumber:n,matchUpId:T};t&&(E.matchUpType=r),o&&(E.isMock=!0),i.push(E);const y={children:[S,I]};h.push(y)}const d=e?e-l:void 0;return{roundNodes:h,matchUps:i,drawPosition:d}}function ci(t){let{feedRoundsProfile:e,feedRounds:n=0,skipRounds:r=0,baseDrawSize:s,drawSize:i}=t;const{linkFedFinishingRoundNumbers:o,finishingPositionOffset:c,linkFedRoundNumbers:a,feedsFromFinal:u,isConsolation:l,matchUpType:f,idPrefix:p,isMock:h,uuids:d,fmlc:m}=t;s=s||k(i);const g=wk({drawSize:s}),I=g.length;let S=0;if(e!=null&&e.length)S=e.reduce((_,F)=>_+F,0);else if(i){let _=i-s;e=g.filter(F=>F<=_?(_-=F,!0):!1),S=e.reduce((F,L)=>F+L,0),n=e.length}else r>=I?n=0:u&&(n=I-u,r=0),e=g.filter((_,F)=>u&&!n||n&&F>=r+n||F<r?0:_),S=e.reduce((_,F)=>_+F,0),i=s+S,n=e.length;const T=[...g,...e].sort((_,F)=>F-_),E=T.length,b=[...(a??[]).map(_=>_-1),...(o??[]).map(_=>E-_)].map(_=>T[_]).reduce((_,F)=>_+F,0);S=S-b;let N=0,A=[],C,v=1,U=ht(0,s).map((_,F)=>({drawPosition:F+1+S})),O=S+1;for(const _ of g){if({roundNodes:C,matchUps:A}=ud({matchUpType:f,roundNumber:v,idPrefix:p,matchUps:A,isMock:h,nodes:U,uuids:d}),v++,e.includes(_)){const F=Mn(e)[_],L=ht(0,F),W=E+1-v,j=(o==null?void 0:o.includes(W))||(a==null?void 0:a.includes(v));L.forEach(()=>{({roundNodes:C,matchUps:A,drawPosition:O}=Dk({drawPosition:!j&&O||void 0,nodes:C,matchUpType:f,roundNumber:v,idPrefix:p,matchUps:A,isMock:h,uuids:d,fed:N})),v++,N+=1})}U=C}E!==v-1&&console.log("ERROR");const D=s-S;A=ja({finishingPositionOffset:l?D:c,positionsFed:S,roundsCount:E,matchUps:A,fmlc:m});const w=C!=null&&C.length?C[0]:C;return w&&(w.roundNumber=v-1,w.matchUps=A),{draw:w,matchUps:A,roundsCount:E};function k(_){const F=Fd(_);return F>_?F/2:F}}function wk({drawSize:t}){const e=Math.ceil(Math.log(t)/Math.log(2));return ht(0,e).reverse().map(r=>Math.pow(2,r))}function DE(t){const{finishingPositionOffset:e=0,stageSequence:n=1,staggeredEntry:r,structureName:s,stage:i=It,matchUpType:o,structureId:c,idPrefix:a,drawSize:u,isMock:l,uuids:f}=t,p={finishingPositionOffset:e,matchUpType:o,drawSize:u,idPrefix:a,isMock:l,uuids:f},{matchUps:h}=r?ci(p):rs(p),d=Ze({structureId:c||(f==null?void 0:f.pop()),structureName:s||It,stageSequence:n,matchUpType:o,matchUps:h,stage:i}),m=[d],g=[];if(u>2){const I=u/2,{matchUps:S}=rs({finishingPositionOffset:e+I,idPrefix:a&&`${a}-c`,drawSize:I,matchUpType:o,isMock:l}),T=t.consolationStructureName||(s?`${s} ${Re}`:Re),E=Ze({structureName:T,matchUps:S,structureId:f==null?void 0:f.pop(),stage:Re,stageSequence:1,matchUpType:o});m.push(E);const y={linkType:js.Loser,source:{roundNumber:1,structureId:d.structureId},target:{roundNumber:1,feedProfile:ra.TopDown,structureId:E.structureId}};g.push(y)}return{...$,structures:m,links:g}}function wE({consolationStructure:t,roundOffset:e=0,mainStructure:n,roundsCount:r,feedPolicy:s,fmlc:i}){const c=t.matchUps.reduce((l,f)=>(f.drawPositions||[]).filter(Boolean).length&&!l.includes(f.roundNumber)?l.concat(f.roundNumber):l,[]),a=(s==null?void 0:s.roundGroupedOrder)||[],u=s==null?void 0:s.roundFeedProfiles;return ht(1+e,r+1+e).map(l=>{const f=u&&u[l-1]?u[l-1]:l%2?Ni:uo,p=l-e<=2?l-e:(l-e-2)*2+2,h={linkType:lo,source:{roundNumber:l,structureId:n.structureId},target:{feedProfile:f,roundNumber:p,structureId:t.structureId}},d=a[l-1];return d&&(h.target.groupedOrder=d),ze()&&(h.source.structureName=n.structureName,h.target.structureName=t.structureName),l===2&&i&&(h.linkCondition=fs,h.target.feedProfile=Ni),c.includes(p)?h:void 0}).filter(Boolean)}function kE(t){const{finishingPositionOffset:e,structureName:n=It,stageSequence:r=1,structureNameMap:s,staggeredEntry:i,stage:o=It,matchUpType:c,structureId:a,drawSize:u,idPrefix:l,isMock:f,uuids:p}=t,h={finishingPositionOffset:e,matchUpType:c,drawSize:u,idPrefix:l,isMock:f,uuids:p},{matchUps:d,roundsCount:m}=i?ci(h):rs(h),g=Ze({structureId:a||(p==null?void 0:p.pop()),structureName:n,stageSequence:r,matchUpType:c,matchUps:d,stage:o}),I=[g],S=[];if(u>2){const y=[0,2].slice(0,u/16).map((b,N)=>{const A=N+1,{consolationStructure:C}=kk({idPrefix:l&&`${l}-c${N}`,structureId:p==null?void 0:p.pop(),structureNameMap:s,stageSequence:A,roundOffset:b,matchUpType:c,drawSize:u,isMock:f,index:N,uuids:p});I.push(C);const v=wE({consolationStructure:C,roundsCount:2,mainStructure:g,roundOffset:b});return{consolationStructure:C,links:v}}).map(b=>b.links).flat();if(S.push(...y),u>=4&&u<=16||u>32){const{matchUps:b}=rs({idPrefix:l&&`${l}-p3t4`,finishingPositionOffset:2,drawSize:2,matchUpType:c,isMock:f}),N=Ze({structureName:(s==null?void 0:s[Ie])||Ie,structureId:p==null?void 0:p.pop(),matchUps:b,stageSequence:2,stage:Ie,matchUpType:c}),A={linkType:js.Loser,source:{roundNumber:m-1,structureId:g.structureId},target:{structureId:N.structureId,feedProfile:ra.TopDown,roundNumber:1}};I.push(N),S.push(A)}}return{structures:I,links:S,...$}}function kk({stageSequence:t=1,structureNameMap:e,roundOffset:n=0,matchUpType:r,structureId:s,idPrefix:i,drawSize:o,isMock:c,index:a,uuids:u}){const l=o/(2*Math.pow(2,n)),{matchUps:f,roundsCount:p}=ci({finishingPositionOffset:l,baseDrawSize:l,isConsolation:!0,feedRounds:1,matchUpType:r,idPrefix:i,isMock:c,uuids:u}),h=`${Re} ${a+1}`,d=(e==null?void 0:e[h])||h;return{consolationStructure:Ze({matchUps:f,stage:Re,structureName:d,stageSequence:t,matchUpType:r,structureId:s}),consolationRoundsCount:p}}function _c(t){let{matchUpType:e}=t;const{finishingPositionOffset:n=0,addNameBaseToAttributeName:r,playoffStructureNameBase:s,finishingPositionNaming:i,finishingPositionLimit:o,playoffAttributes:c,stageSequence:a=1,exitProfile:u="0",exitProfileLimit:l,roundOffsetLimit:f,roundOffset:p=0,drawDefinition:h,staggeredEntry:d,sequenceLimit:m,stage:g=It,structureId:I,drawSize:S,idPrefix:T,isMock:E,uuids:y}=t;if(!(!c||!l||(c==null?void 0:c[u]))||S<2||m&&a>m)return{};const N=[],A=[],C=[];e=e||(h==null?void 0:h.matchUpType);const v=n+1,P=n+S,U=`${v}-${P}`,O=c==null?void 0:c[u],D=s&&`${s} `||"",M=i==null?void 0:i[U],w=(M==null?void 0:M.name)||(O==null?void 0:O.name)&&(r?`${D}${O==null?void 0:O.name}`:O.name)||`${D}${U}`,k=(M==null?void 0:M.abbreviation)||(O==null?void 0:O.abbreviation),_={idPrefix:T&&`${T}-${w}-RP`,finishingPositionOffset:n,matchUpType:e,drawSize:S,isMock:E,uuids:y},{matchUps:F}=d?ci(_):rs(_),L=Ze({structureId:I||(y==null?void 0:y.pop()),structureAbbreviation:k,stageSequence:a,structureName:w,matchUpType:e,roundOffset:p,matchUps:F,stage:g});N.push(...F),A.push(L);const W=Math.ceil(Math.log(S)/Math.log(2)),j=f?Math.min(f-p,W):!o||v<o?W:0;return S>2&&ht(1,j+1).forEach(B=>H(B)),{structureId:L.structureId,matchUps:N,structureName:w,structures:A,links:C,...$};function H(B){const R=S/Math.pow(2,B);if(R<2)return;const x=S/Math.pow(2,B)+n;if(x+1>o)return;const{structures:q,structureId:V,matchUps:Y,links:z}=_c({finishingPositionOffset:x,exitProfile:`${u}-${B}`,roundOffset:p+B,stageSequence:a+1,drawSize:R,addNameBaseToAttributeName:r,playoffStructureNameBase:s,finishingPositionNaming:i,finishingPositionLimit:o,playoffAttributes:c,exitProfileLimit:l,roundOffsetLimit:f,drawDefinition:h,sequenceLimit:m,matchUpType:e,idPrefix:T,uuids:y,stage:g});if(L.structureId&&V){const J={linkType:js.Loser,source:{roundNumber:B,structureId:L.structureId},target:{roundNumber:1,feedProfile:ra.TopDown,structureId:V}};z&&L&&z.push(J),z!=null&&z.length&&C.push(...z)}return q!=null&&q.length&&A.push(...q),Y!=null&&Y.length&&N.push(...Y),{structureId:V,childLinks:z,structures:A}}}function ko(t){const{finishingPositionOffset:e,stageSequence:n=1,policyDefinitions:r,feedsFromFinal:s,staggeredEntry:i,structureName:o,stage:c=It,structureId:a,matchUpType:u,skipRounds:l,feedRounds:f,idPrefix:p,drawSize:h,isMock:d,uuids:m,fmlc:g}=t,I=t.feedPolicy||(r==null?void 0:r[Bu]),S={finishingPositionOffset:e,matchUpType:u,skipRounds:l,drawSize:h,idPrefix:p,isMock:d,uuids:m},{matchUps:T}=i?ci(S):rs(S),E=Ze({structureId:a||(m==null?void 0:m.pop()),structureName:o||It,stageSequence:n,matchUpType:u,matchUps:T,stage:c}),y=[E],b=[],N=h/2,{matchUps:A,roundsCount:C}=ci({finishingPositionOffset:N,idPrefix:p&&`${p}-c`,isConsolation:!0,feedsFromFinal:s,baseDrawSize:N,matchUpType:u,feedRounds:f,skipRounds:l,isMock:d,uuids:m,fmlc:g});if(h>2){const v=Ze({matchUps:A,structureId:m==null?void 0:m.pop(),structureName:Re,stage:Re,stageSequence:1,matchUpType:u});y.push(v);const P=wE({consolationStructure:v,mainStructure:E,roundsCount:C,feedPolicy:I,fmlc:g});b.push(...P)}return{...$,structures:y,links:b}}function _E({compassAttributes:t=Vf,olympicAttributes:e=jf,requireSequential:n=!0,playoffMatchUpFormat:r,sourceStructureId:s,policyDefinitions:i,stageSequence:o,drawDefinition:c,playoffGroups:a,matchUpType:u,feedPolicy:l,groupCount:f,idPrefix:p,isMock:h,uuids:d}){var N,A;l=l||(i==null?void 0:i[Bu]);const m="processPlayoffGroups";let g=0;const I=[],S=[],T=[],{error:E,positionRangeMap:y}=Mk({structureId:s,drawDefinition:c,playoffGroups:a});if(E)return G({result:{error:E},stack:m});if(!(!y||(a==null?void 0:a.every(C=>{const{finishingPositions:v=[]}=C;if(!v.length)return!1;const P=v.sort(Ve).map((U,O)=>(v[O+1]||U)-U).every(U=>U<2);return(!n||P)&&v.every(U=>y[U])}))))return G({context:{validFinishingPositions:Object.values(y)},result:{error:tt},stack:m});for(const C of a){const v=C.finishingPositions,P=y&&v.map(k=>{var _;return(_=y[k])==null?void 0:_.finishingPositions}).flat(),U=f*v.length,O=Vo(U),D=O===2&&Ms||C.drawType||Ms;P&&(g=Math.min(...P)-1);const M={structureId:C.structureId??(d==null?void 0:d.pop()),structureNameMap:C.structureNameMap,structureName:C.structureName,idPrefix:p&&`${p}-po`,appliedPolicies:i,finishingPositionOffset:g,stage:Ie,stageSequence:o,matchUpType:u,drawSize:O,isMock:h,uuids:d},w=({playoffStructures:k,playoffLinks:_})=>{const[F]=k,L=dd({playoffStructureId:F.structureId,finishingPositions:v,sourceStructureId:s});T.push(L),T.push(..._),S.push(...k),I.push({structureId:F.structureId,finishingPositions:v}),g+=U};if(D===Ms){const{matchUps:k}=rs({finishingPositionLimit:g+U,idPrefix:p&&`${p}-po`,finishingPositionOffset:g,matchUpType:u,drawSize:O,isMock:h,uuids:d}),_=Ze({structureId:C.structureId??(d==null?void 0:d.pop()),structureName:C.structureName,matchUpFormat:r,stage:Ie,stageSequence:o,matchUps:k});S.push(_);const F=dd({playoffStructureId:_.structureId,finishingPositions:v,sourceStructureId:s});T.push(F),g+=U,I.push({structureId:_.structureId,finishingPositions:v})}else if([oc,cc,Ie].includes(D)){const{structureName:k}=C,_={structureId:C.structureId??(d==null?void 0:d.pop()),playoffStructureNameBase:k,idPrefix:p&&`${p}-po`,addNameBaseToAttributeName:!0,finishingPositionOffset:g,stage:Ie,roundOffset:0,stageSequence:o,drawSize:O,isMock:h,uuids:d};D===oc?Object.assign(_,{playoffAttributes:t,roundOffsetLimit:3}):D===cc&&Object.assign(_,{playoffAttributes:e,roundOffsetLimit:2});const F=_c(_);if(F.error)return F;if((N=F.links)!=null&&N.length&&T.push(...F.links),(A=F.structures)!=null&&A.length&&S.push(...F.structures),S.sort(Pi),F.structureId){const L=dd({playoffStructureId:F.structureId,finishingPositions:v,sourceStructureId:s});T.push(L),I.push({structureId:F.structureId,finishingPositions:v})}g+=U}else if([ac,Da,Oa,Ua,Pa,Ma].includes(D)){const k=[d==null?void 0:d.pop(),d==null?void 0:d.pop()],_={structureId:C.structureId??(d==null?void 0:d.pop()),structureName:C.structureName,idPrefix:p&&`${p}-po`,finishingPositionOffset:g,uuids:k,stage:Ie,matchUpType:u,feedPolicy:l,drawSize:O,isMock:h},F={[ac]:{fmlc:!0,feedRounds:1},[Ma]:{feedRounds:1},[Oa]:{feedsFromFinal:3},[Ua]:{feedsFromFinal:2},[Pa]:{feedsFromFinal:1}};Object.assign(_,F[D]||{});const{structures:L,links:W}=ko(_),[j]=L,H=dd({playoffStructureId:j.structureId,finishingPositions:v,sourceStructureId:s});T.push(H),T.push(...W),S.push(...L),I.push({structureId:j.structureId,finishingPositions:v}),g+=U}else if([Pr].includes(D)){const{structures:k,links:_}=za({...M,structureOptions:C.structureOptions||{groupSize:4}});w({playoffStructures:k,playoffLinks:_})}else if([Ca].includes(D)){const{structures:k,links:_}=DE(M);w({playoffStructures:k,playoffLinks:_})}else if([xP].includes(D)){const{structures:k,links:_}=kE(M);w({playoffStructures:k,playoffLinks:_})}else if([Xn].includes(D)){const k=Ze({structureId:C.structureId??(d==null?void 0:d.pop()),structureName:C.structureName,finishingPosition:ua,stage:Ie,stageSequence:o,matchUps:[]});w({playoffStructures:[k],playoffLinks:[]})}}return{finishingPositionTargets:I,positionRangeMap:y,structures:S,links:T}}function dd({playoffStructureId:t,finishingPositions:e,sourceStructureId:n}){return{linkType:Ai,source:{structureId:n,finishingPositions:e},target:{structureId:t,feedProfile:Cr,roundNumber:1}}}function _k(t){const{drawDefinition:e,structureOptions:n,requireSequential:r}=t,s={structureName:It,...t,stage:It},{structures:i,groupCount:o,groupSize:c}=za(s);o<1&&console.log(Mv);const a=(n==null?void 0:n.playoffGroups)||[{finishingPositions:[1],structureName:Ie}],[u]=i,{structures:l,links:f}=_E({sourceStructureId:u.structureId,requireSequential:r,drawDefinition:e,playoffGroups:a,groupCount:o,groupSize:c,...t});return l&&i.push(...l),{...$,structures:i,links:f}}function Fk({mainStructure:t,consolationStructure:e,deciderStructure:n}){const s=e.matchUps.reduce((l,f)=>(f.drawPositions||[]).filter(Boolean).length&&!l.includes(f.roundNumber)?l.concat(f.roundNumber):l,[]),i=t.matchUps.reduce((l,f)=>!l||f.roundNumber>l?f.roundNumber:l,void 0),o=e.matchUps.reduce((l,f)=>!l||f.roundNumber>l?f.roundNumber:l,void 0),c=s.map((l,f)=>{const h=s.indexOf(l)%2?Ni:uo,d=1+f;return{linkType:lo,source:{roundNumber:d,structureId:t.structureId},target:{feedProfile:h,roundNumber:l,structureId:e.structureId}}}),a={linkType:vi,source:{roundNumber:o,structureId:e.structureId},target:{feedProfile:Ni,roundNumber:i,structureId:t.structureId}},u=[{linkType:vi,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:Ni,roundNumber:1,structureId:n.structureId}},{linkType:lo,source:{roundNumber:i,structureId:t.structureId},target:{feedProfile:Ni,roundNumber:1,structureId:n.structureId}}];return[...c,a,...u]}function Lk({structureName:t,matchUpType:e,idPrefix:n,drawSize:r,isMock:s,uuids:i}){const o=[],{matchUps:c}=ci({linkFedFinishingRoundNumbers:[1],drawSize:r+1,matchUpType:e,idPrefix:n,isMock:s}),a=Ze({structureName:t||It,structureId:i==null?void 0:i.pop(),stageSequence:1,stage:It,matchUpType:e,matchUps:c});o.push(a);const u=r/2,{matchUps:l}=ci({finishingPositionOffset:u,idPrefix:n&&`${n}-c`,drawSize:r-1,isConsolation:!0,matchUpType:e,isMock:s,uuids:i}),f=Ze({matchUps:l,structureId:i==null?void 0:i.pop(),structureName:ZI,stage:Re,stageSequence:2,matchUpType:e});o.push(f);const{matchUps:p}=rs({idPrefix:n&&`${n}-p1t2`,drawSize:2,matchUpType:e,isMock:s}),h=Ze({matchUps:p,structureId:i==null?void 0:i.pop(),structureName:QI,stageSequence:3,stage:Ie,matchUpType:e});o.push(h);const d=Fk({mainStructure:a,consolationStructure:f,deciderStructure:h});return{structures:o,links:d,...$}}function Rk(t){const{qualifyingRoundNumber:e,finishingPositionOffset:n,qualifyingPositions:r,matchUpType:s,idPrefix:i,drawSize:o,isMock:c,uuids:a}=t;if(!oe(o)||o<2)return{matchUps:[],roundsCount:0};if(mr(o))return rs(t);const u=Bk(o),l=u.shift(),f=ht(1,((l==null?void 0:l.participantsCount)||0)+1).map(g=>({drawPosition:g}));let p=[],h=1;({matchUps:p}=ud({roundNumber:h,matchUpType:s,idPrefix:i,matchUps:p,isMock:c,nodes:f,uuids:a})),h++;let d=t.roundLimit||e;for(const g of u){const I=g.participantsCount/2,S=ht(1,I+1);r&&I===r&&(d=h-1);const T=S.map(E=>{const y=Ph({roundPosition:E,roundNumber:h,idPrefix:i,uuids:a});return{roundPosition:E,roundNumber:h,matchUpId:y}});p.push(...T),h++}const m=h-1;return p=ja({finishingPositionOffset:n,lucky:!0,roundsCount:m,roundLimit:d,matchUps:p}),d&&(p=p.filter(g=>g.roundNumber<=d)),{matchUps:p,roundsCount:m,roundLimit:d}}function Bk(t){const e=vt(t);let n=e%2?e+1:e;const r=!!(Math.ceil(n/2)%2),s=[{participantsCount:n,preFeedRound:r}];for(;n>2;){const i=Math.ceil(n/2),o=i===1,c=!!(!o&&i%2);n=!o&&c?i+1:i;const a=!!(n!==2&&Math.ceil(n/2)%2);s.push({participantsCount:n,preFeedRound:a,feedRound:c})}return s}function FE(t){var d;const{compassAttributes:e=Vf,olympicAttributes:n=jf,stageSequence:r=1,structureName:s,structureId:i,stage:o=It,matchUpType:c,drawSize:a,uuids:u}=t,{appliedPolicies:l}=ge(t),f=((d=t.policyDefinitions)==null?void 0:d[Bu])||(l==null?void 0:l[Bu]);t.skipRounds=t.skipRounds||a<=4&&(f!=null&&f.feedMainFinal?0:1)||0;const p=()=>{const{matchUps:m}=rs(t);return{structures:[Ze({structureName:s||It,structureId:i||(u==null?void 0:u.pop()),stageSequence:r,matchUpType:c,matchUps:m,stage:o})],links:[],...$}};return{generators:{[Xn]:()=>({structures:[Ze({structureName:s||It,structureId:i||(u==null?void 0:u.pop()),finishingPosition:uc,stageSequence:r,matchUps:[],matchUpType:c,stage:o})],links:[],...$}),[Ci]:()=>{const{matchUps:m}=Rk(t);return{structures:[Ze({structureName:s||It,structureId:i||(u==null?void 0:u.pop()),stageSequence:r,matchUpType:c,matchUps:m,stage:o})],links:[],...$}},[Ms]:()=>p(),[va]:()=>Lk(t),[oc]:()=>_c({...t,roundOffsetLimit:3,playoffAttributes:e}),[cc]:()=>_c({...t,roundOffsetLimit:2,playoffAttributes:n}),[Ie]:()=>_c(t),[ic]:()=>{const{matchUps:m}=ci({drawSize:a,uuids:u,matchUpType:c});return{structures:[Ze({structureName:s||It,structureId:i||(u==null?void 0:u.pop()),stageSequence:r,matchUpType:c,stage:It,matchUps:m})],links:[],...$}},[Ca]:()=>DE(t),[ac]:()=>ko({...t,feedRounds:1,fmlc:!0}),[JI]:()=>ko({...t,feedRounds:1}),[Bf]:()=>ko({...t,feedsFromFinal:1}),[xf]:()=>ko({...t,feedsFromFinal:2}),[$f]:()=>ko({...t,feedsFromFinal:3}),[Da]:()=>ko(t),[el]:()=>kE(t),[Pr]:()=>za(t),[Ds]:()=>_k(t)}}}function Mh(t){var j,H,B,R,x,q;const{enforceMinimumDrawSize:e=!0,overwriteExisting:n,appliedPolicies:r,staggeredEntry:s,drawDefinition:i,tieFormat:o,drawSize:c,isMock:a,uuids:u}=t||{},l=t.drawTypeCoercion??((j=r==null?void 0:r[pf])==null?void 0:j.drawTypeCoercion)??!0,f="generateDrawStructuresAndLinks";let p=l&&t.drawSize===2&&na.SingleElimination||t.drawType||na.SingleElimination;const h=[],d=[],m=(t==null?void 0:t.matchUpType)??Oe,g=(H=i==null?void 0:i.structures)==null?void 0:H.filter(({stage:V})=>V===Pt);g&&h.push(...g);const I=g==null?void 0:g.map(({structureId:V})=>V),S=(B=i==null?void 0:i.structures)==null?void 0:B.find(({stage:V,stageSequence:Y})=>V===It&&Y===1),T=(R=i==null?void 0:i.links)==null?void 0:R.filter(V=>V.target.structureId===(S==null?void 0:S.structureId)&&(I==null?void 0:I.includes(V.source.structureId))),E=(V,Y)=>{var z;if(V.linkType===Ai&&(Y!=null&&Y.structures)){const J=V.source.finishingPositions||[];return Y.structures.length*J.length}else if(V.linkType===vi&&((z=Y==null?void 0:Y.matchUps)!=null&&z.length)){const J=V.source.roundNumber;return Y.matchUps.filter(({roundNumber:X})=>X===J).length}},y=g==null?void 0:g.map(V=>{var Z,nt,rt;const Y=T==null?void 0:T.find(K=>K.target.structureId===V.structureId),z=((nt=(Z=ee({structure:V}))==null?void 0:Z.positionAssignments)==null?void 0:nt.length)??0;if(!Y)return z;const J=Y==null?void 0:Y.source.structureId,Q=(rt=i.structures)==null?void 0:rt.find(K=>K.structureId===J),X=E(Y,Q)||0;return z-X}).filter(Boolean).reduce((V,Y)=>V+Y,0),b=T==null?void 0:T.map(V=>{const Y=V.source.structureId,z=g==null?void 0:g.find(J=>J.structureId===Y);return E(V,z)}).filter(Boolean).reduce((V,Y)=>V+Y,0),N=!!(S&&!((x=S==null?void 0:S.matchUps)!=null&&x.length));if(g!=null&&g.length&&!N)return{error:Ag};const A=!(g!=null&&g.length)&&t.qualifyingProfiles,C=(A==null?void 0:A.length)&&UE({idPrefix:t.idPrefix,qualifyingProfiles:A,appliedPolicies:r,isMock:a,uuids:u});if(C!=null&&C.error)return C;const{qualifyingDrawPositionsCount:v,qualifyingDetails:P,qualifiersCount:U}=C||{qualifyingDrawPositionsCount:y,qualifiersCount:b};v&&(C!=null&&C.structures&&h.push(...C.structures),C!=null&&C.links&&d.push(...C.links)),Object.assign(t,bt({drawSize:c,matchUpType:m,tieFormat:o}));const O=p!==Xn&&(isNaN(c)||c<2||!s&&![ic,Ci].includes(p)&&([Ds,Pr].includes(p)&&c<3||![Pr,Ds].includes(p)&&!mr(c)));if(O&&!v)return G({context:{drawSize:c,invalidDrawSize:O},result:{error:xd},stack:f});const D=XI.includes(p);if(vt(c)<4&&D){if(l)p=Ms;else if(e)return G({context:{enforceMinimumDrawSize:e,invalidDrawSize:O,drawSize:c,drawType:p},result:{error:xd},stack:f})}const{generators:M,error:w}=FE(t);if(w)return{error:w};const k=M[p];if(!k)return{error:Ym};const _=k==null?void 0:k();if(_.error)return _;const{structures:F,links:L}=_;if(F!=null&&F.length){const V=F.find(({stage:Y,stageSequence:z})=>Y===It&&z===1);if(S&&V){if(N){const Y=V.structureId;if(V.structureId=S.structureId,L!=null&&L.length)for(const z of L)z.source.structureId===Y&&(z.source.structureId=S.structureId),z.target.structureId===Y&&(z.target.structureId=S.structureId)}else if(!n)return{error:Ag}}h.push(...F)}h.sort(Pi),L!=null&&L.length&&d.push(...L);const W=_.structures.find(({stage:V,stageSequence:Y})=>V===It&&Y===1);for(const V of P||[]){const{finalQualifyingRoundNumber:Y,finalQualifyingStructureId:z,roundTarget:J,finishingPositions:Q,linkType:X}=V,Z=W&&((q=kc({targetStructureId:W.structureId,sourceStructureId:z,sourceRoundNumber:Y,finishingPositions:Q,targetEntryRound:J,linkType:X}))==null?void 0:q.link);if(Z!=null&&Z.error)return Z;Z&&d.push(Z)}return T&&d.push(...T),{...$,qualifyingResult:{qualifyingDrawPositionsCount:v,qualifiersCount:U},structures:h,links:d}}function Li(t){var h,d,m,g,I,S,T,E;const{provisionalPositioning:e,drawDefinition:n,stageSequence:r,structureId:s,stage:i}=t;if(!n)return{error:lt};const{entryProfile:o}=Aa({drawDefinition:n}),c=i&&r&&((m=(d=(h=o==null?void 0:o[i])==null?void 0:h.stageSequence)==null?void 0:d[r])==null?void 0:m.qualifiersCount)||i&&((g=o==null?void 0:o[i])==null?void 0:g.qualifiersCount)||0,a={};if(!s)return{qualifiersCount:c,roundQualifiersCounts:a};const{structure:u}=Ot({drawDefinition:n,structureId:s}),l=(I=n.links)==null?void 0:I.filter(y=>{var b;return((b=y==null?void 0:y.target)==null?void 0:b.structureId)===(u==null?void 0:u.structureId)});let f=0;if(l!=null&&l.length)for(const y of l){const b=(S=Ot({structureId:y.source.structureId,drawDefinition:n}))==null?void 0:S.structure;if((b==null?void 0:b.stage)===Pt){const N=y.source.roundNumber,A=y.target.roundNumber;let C=0;if(b.structureType===mn){const v=((T=b.structures)==null?void 0:T.length)||0,P=((E=y.source.finishingPositions)==null?void 0:E.length)||0;C=v*P}else{const v=Qt({matchUpFilters:{roundNumbers:[N]},structure:b,afterRecoveryTimes:!1,provisionalPositioning:e,inContext:!1}).matchUps;C=(v==null?void 0:v.length)||0}a[A]||(a[A]=0),a[A]+=C,f+=C}}const p=Object.keys(a);if(p.length<=1){const y=p[0]||1;a[y]=Math.max(a[y]||0,c)}return f=Math.max(f,c),{qualifiersCount:f,roundQualifiersCounts:a}}function cu({stage:t,drawDefinition:e}){var r;const{entryProfile:n}=Aa({drawDefinition:e});return((r=n==null?void 0:n[t])==null?void 0:r.drawSize)||0}function xk(t){const{provisionalPositioning:e,drawDefinition:n,stageSequence:r,stage:s}=t,i=cu({stage:s,drawDefinition:n}),{qualifiersCount:o}=Li({provisionalPositioning:e,drawDefinition:n,stageSequence:r,stage:s});return i&&i-o}function au({stageSequence:t=1,drawDefinition:e,drawSize:n,stage:r}){if(!e)return{error:lt};if(!_a({drawDefinition:e,stage:r}))return{error:xs};const s=eS({drawDefinition:e,stage:r}),{qualifiersCount:i}=Li({drawDefinition:e,stageSequence:t,stage:r}),o=s+i;if(n<o)return{error:yu};const{entryProfile:c}=Na({attributes:[{[r]:{drawSize:n}}],drawDefinition:e});return Zt({drawDefinition:e}),{...$,entryProfile:c}}function $k({alternatesCount:t,drawDefinition:e,stage:n}){var r;return e?_a({drawDefinition:e,stage:n})?(Na({attributes:[{[n]:{alternates:t}}],drawDefinition:e}),t||(e.entries=((r=e.entries)==null?void 0:r.filter(s=>s.entryStatus!==dr))||[]),Zt({drawDefinition:e}),{...$}):{error:xs}:{error:lt}}function Vk({wildcardsCount:t=0,drawDefinition:e,stageSequence:n,stage:r}){if(!e)return{error:lt};if(!_a({drawDefinition:e,stage:r}))return{error:xs};const s=cu({drawDefinition:e,stage:r}),{qualifiersCount:i}=Li({drawDefinition:e,stageSequence:n,stage:r}),o=YP({drawDefinition:e,stage:r}),c=eS({drawDefinition:e,stage:r});return t<o?{error:Object.assign(yu,{message:"Number of Wildcards cannot be less than number of Wildcards already entered"})}:c+t+i>s?{error:yu,info:"Total stage Entries cannot be greater than drawPositions"}:(Na({attributes:[{[r]:{wildcardsCount:t}}],drawDefinition:e}),Zt({drawDefinition:e}),{...$})}function Dh({qualifiersCount:t=0,drawDefinition:e,stage:n}){return e?_a({drawDefinition:e,stage:n})?n!==It?{error:yu,info:"qualifiersCount can only be set for main stage"}:(Na({attributes:[{[n]:{qualifiersCount:t}}],drawDefinition:e}),Zt({drawDefinition:e}),{...$}):{error:xs}:{error:lt}}function wh(t){var T;const{modifyOriginal:e=!0,stageSequence:n=1,isMock:r}=t||{},s="generateDrawTypeAndModifyDrawDefinition";if(!t.drawDefinition)return G({result:{error:lt},stack:s});const i=e?t.drawDefinition:pt(t.drawDefinition,!1,!0);let{tieFormat:o,matchUpType:c}=t;if(o){const E=vn({tieFormat:o});if(E.error)return E}o=Dr(o||((T=hn({drawDefinition:i}))==null?void 0:T.tieFormat)),c=c||i.matchUpType||Oe,t.tieFormat=o,t.matchUpType=c;const a=cu({drawDefinition:i,stage:It});t.drawSize=t.drawSize||a,!a&&t.drawSize&&au({drawSize:t.drawSize,drawDefinition:i,stageSequence:n,stage:It});const u=ln({drawDefinition:i}).drawMatchUps.map(Qe),l=Mh(t);if(l.error)return G({result:l,stack:s});const{structures:f,links:p,qualifyingResult:h}=l;i.structures=f,i.links=p;const d=Math.max(t.qualifiersCount||0,(h==null?void 0:h.qualifiersCount)||0);if(h!=null&&h.qualifyingDrawPositionsCount&&!cu({stage:Pt,drawDefinition:i})){const y=au({drawSize:h.qualifyingDrawPositionsCount,stage:Pt,drawDefinition:i});if(y.error)return y}if(d){const E=Dh({qualifiersCount:d,drawDefinition:i,stage:It});if(E.error)return E}const m=t.drawSize||a;Object.assign(t,bt({drawSize:m,matchUpType:c,tieFormat:o}));const{matchUps:g,matchUpsMap:I}=xe({drawDefinition:i});o&&(g==null||g.forEach(E=>{if(!u.includes(E.matchUpId)){const{tieMatchUps:y}=Jl({tieFormat:o,isMock:r});Object.assign(E,{tieMatchUps:y,matchUpType:c})}}));const{inContextDrawMatchUps:S}=Ic({drawDefinition:i,matchUpsMap:I});return Zt({drawDefinition:i}),{inContextDrawMatchUps:S,drawDefinition:i,matchUpsMap:I,...$,structures:f,matchUps:g,links:p}}function jk({targetParticipantIds:t,policyAttributes:e,idCollections:n,participants:r}){if(!Array.isArray(e))return{error:eg};if(!Array.isArray(r))return{error:Yc};const s={};return t.forEach(i=>{const o=r.find(a=>a.participantId===i),{values:c}=LE({policyAttributes:e,idCollections:n,participants:r,participant:o});c&&c.forEach(a=>{s[a]||(s[a]=[]),s[a].includes(i)||s[a].push(i)})}),s}function LE({policyAttributes:t,idCollections:e,participants:n,participant:r}){if(!Array.isArray(t))return{error:eg};if(!r)return{error:qo};const s=[];return t.forEach(c=>{const{directive:a,groupings:u,key:l,significantCharacters:f}=c||{};if(l){const p=l.split(".");o({value:r,keys:p,significantCharacters:f})}else if(a){const p=c==null?void 0:c.includeIds,h=((e==null?void 0:e[a])||[]).filter(d=>!p||p.includes(d));h!=null&&h.length&&(n!=null&&n.length)&&h.forEach(d=>{var g;const m=n.find(I=>I.participantId===d);if((g=m==null?void 0:m.individualParticipantIds)!=null&&g.includes(r.participantId)){const I=m==null?void 0:m.participantId;s.push(I)}})}else u&&Object.keys(u).forEach(p=>{u[p].includes(r.participantId)&&s.push(p)})}),{values:Vt(s)};function o({value:c,keys:a=[],significantCharacters:u}){for(const[f,p]of a.entries())if(c!=null&&c[p])if(Array.isArray(c[p])){const h=c[p],d=a.slice(f);h.forEach(m=>o({value:m,keys:d,significantCharacters:u}))}else c=c[p],l({value:c,index:f});function l({value:f,index:p}){if(f&&p===a.length-1&&["string","number"].includes(typeof f)){const h=u?f.slice(0,u):f;s.push(h)}}}}function RE({candidatePositionAssignments:t,participantsWithGroupings:e,policyAttributes:n,idCollections:r}){const s=Object.assign({},...e.map(i=>({[i.participantId]:i})));return t.map(i=>{const o=s[i.participantId],{values:c}=LE({participants:e,policyAttributes:n,idCollections:r,participant:o});return{...i,values:c}})}function BE({participantIdGroups:t,positionAssignments:e,groupsToAvoid:n}){return Object.assign({},...e.filter(r=>r==null?void 0:r.participantId).map(r=>{const{drawPosition:s,participantId:i}=r,o=t?t[i]||[]:[],c=!!n.some(a=>o.includes(a));return{[s]:{participantGroups:o,includesGroupsToAvoid:c}}}))}function Gk(t){const{unfilledPositions:e,chunkedDrawPositions:n}=t,r=BE(t);return n.map(o=>{const c=e.filter(f=>o.includes(f)),a=i(c),l=c.filter(f=>!a.includes(f)).filter(f=>{var h;const p=xE(f);return!((h=r[p])!=null&&h.includesGroupsToAvoid)});return{unassigned:c,unpaired:a,pairedNoConflict:l}});function i(o){return o.filter(a=>!c(a));function c(a){const u=xE(a);return!o.includes(u)}}}function Wk(t){const{unfilledPositions:e,chunkedDrawPositions:n}=t,r=BE(t);return n.map(s=>{const i=e.filter(u=>s.includes(u)),o=i.length===s.length?i:[],c=s.filter(u=>{var l;return(l=r[u])==null?void 0:l.includesGroupsToAvoid}).length;return{unassigned:i,unpaired:o,pairedNoConflict:c?[]:i,conflictsCount:c}})}function xE(t){return Number(t%2?t+1:t-1)}function Hk({allGroups:t,participantId:e}){return Object.keys(t).filter(n=>t[n].includes(e))}function qk({selectedParticipantGroups:t,participantIdGroups:e,positionAssignments:n,drawPositionChunks:r,unfilledPositions:s,isRoundRobin:i}){const o=r.map(c=>i?Wk({groupsToAvoid:t,chunkedDrawPositions:c,participantIdGroups:e,positionAssignments:n,unfilledPositions:s}):Gk({groupsToAvoid:t,chunkedDrawPositions:c,participantIdGroups:e,positionAssignments:n,unfilledPositions:s}));if(i){const c=o.map(l=>l.map(f=>f.unassigned).filter(f=>f==null?void 0:f.length)).filter(l=>l==null?void 0:l.length).sort((l,f)=>(f.length||0)-(l.length||0)),a=o.map(l=>l.map(f=>f.unpaired).filter(f=>f==null?void 0:f.length)).filter(l=>l==null?void 0:l.length),u=o.map(l=>l.map(f=>f.pairedNoConflict).filter(f=>f==null?void 0:f.length)).filter(l=>l==null?void 0:l.length).sort((l,f)=>(f.length||0)-(l.length||0));return{unassigned:c,unpaired:a,pairedNoConflict:u}}else{const c=o.map(l=>l.map(f=>f.unassigned).filter(f=>f==null?void 0:f.length)).filter(l=>l==null?void 0:l.length),a=o.map(l=>l.map(f=>f.unpaired).filter(f=>f==null?void 0:f.length)).filter(l=>l==null?void 0:l.length),u=o.map(l=>l.map(f=>f.pairedNoConflict).filter(f=>f==null?void 0:f.length)).filter(l=>l==null?void 0:l.length);return{unassigned:c,unpaired:a,pairedNoConflict:u}}}function $E({participantIds:t,positionAssignments:e}){const n=e.map(r=>r.participantId);return t.filter(r=>!n.includes(r))}function Yk({useSpecifiedGroupKey:t=!1,targetParticipantIds:e,largestFirst:n=!0,allGroups:r,groupKey:s}){var l;const i=Object.assign({},...Object.keys(r).map(f=>[f,r[f].filter(p=>e.includes(p))]).filter(f=>f[1].length).map(([f,p])=>({[f]:p}))),o=Object.keys(i).reduce((f,p)=>i[p].length>f?i[p].length:f,0),c=Object.keys(i).filter(f=>i[f].length===o),a=Dn(n?c:Object.keys(i));return s=t&&((l=i[s])!=null&&l.length)?s:a,{participantId:s&&i[s]?Dn(i[s]):Dn(e),groupKey:s}}function zk({drawPositionGroups:t,positionAssignments:e}){const n=Object.assign({},...e.map(r=>({[r.drawPosition]:r})));return t.map(r=>r.filter(Boolean).map(s=>n[s]).filter(Boolean).filter(s=>!s.participantId&&!s.bye).map(s=>s.drawPosition)).flat().filter(Boolean)}function Kk({candidatePositionAssignments:t,unseededParticipantIds:e,participantIdGroups:n,drawPositionChunks:r,drawPositionGroups:s,pairedPriority:i,allGroups:o,groupKey:c}){const u=s.reduce((C,v)=>v.length>C?v.length:C,0)<=2,l=$E({positionAssignments:t,participantIds:e}),f=zk({positionAssignments:t,drawPositionGroups:s}),{participantId:p,groupKey:h}=Yk({targetParticipantIds:l,useSpecifiedGroupKey:u,allGroups:o,groupKey:c}),d=Hk({participantId:p,allGroups:o}),m=qk({positionAssignments:t,isRoundRobin:u,selectedParticipantGroups:d,participantIdGroups:n,drawPositionChunks:r,unfilledPositions:f}),{unassigned:g,unpaired:I,pairedNoConflict:S}=m,T=(S==null?void 0:S.length)&&S[0],E=(I==null?void 0:I.length)&&I[0],y=i&&T?T:E,b=i?E:T,N=(y==null?void 0:y.length)&&y||(b==null?void 0:b.length)&&b;let A;if(N!=null&&N.length){const C=cn(N);A=cn(C)}else{const C=cn(g[0]);A=cn(C)}return{newGroupKey:h,selectedParticipantId:p,targetDrawPosition:A}}function fd({isRoundRobin:t,groupedParticipants:e}){const n=[];return t?e.forEach(r=>{const s=r.map(c=>c.drawPosition),{uniqueMatchUpGroupings:i}=yp({drawPositions:s}),o=Object.assign({},...r.map(c=>({[c.drawPosition]:c})));i.forEach(c=>{tn(o[c[0]].values||[],o[c[1]].values||[])&&(n.push(c),r.conflict=!0)})}):e.forEach(r=>{var i,o;tn(((i=r[0])==null?void 0:i.values)||[],((o=r[1])==null?void 0:o.values)||[])&&(n.push(r),r.conflict=!0)}),n}function Jk({positionedParticipants:t,potentialDrawPositions:e,avoidanceConflicts:n,drawPositionGroups:r,isRoundRobin:s}){return n.map(i=>{const o=i.map(a=>a.drawPosition);return i.filter(a=>e.includes(a.drawPosition)).map(a=>{const l=e.filter(f=>!(o!=null&&o.includes(f))).filter(f=>{const p=r.find(T=>T.includes(f)).find(T=>T!==f),h=t.find(T=>T.drawPosition===p),m=fd({isRoundRobin:s,groupedParticipants:[[a,h]]}),I=[t.find(T=>T.drawPosition===f),h],S=fd({isRoundRobin:s,groupedParticipants:[I]});return!m.length&&!S.length});if(l.length)return{drawPosition:a.drawPosition,possibleDrawPositions:l}}).filter(Boolean)}).flat(1)}function VE(t){const{initialPositionAssignments:e,participantsWithGroupings:n,opponentsToPlaceCount:r,unseededByePositions:s,drawPositionGroups:i,policyAttributes:o,idCollections:c,allGroups:a}=t,u=[];let l;const f=Math.min(...(i||[]).map(T=>T==null?void 0:T.length).filter(Boolean)),p=f>2,h=pt(e,!1,!0).filter(T=>!T.qualifier),d=e.filter(T=>!T.participantId&&(!T.bye||(s==null?void 0:s.includes(T.drawPosition)))).map(T=>T.drawPosition);ht(0,r).forEach(()=>{const{newGroupKey:T,selectedParticipantId:E,targetDrawPosition:y}=Kk({...t,candidatePositionAssignments:h,allGroups:a,groupKey:l});l=T,h.forEach(b=>{b.drawPosition===y&&(b.participantId=E)})});let m=RE({candidatePositionAssignments:h,participantsWithGroupings:n,policyAttributes:o,idCollections:c}),g=Ge(m,f),I=fd({groupedParticipants:g,isRoundRobin:p}),S=0;for(;S<20&&I.length;){const T=Jk({positionedParticipants:m,potentialDrawPositions:d,avoidanceConflicts:I,drawPositionGroups:i,isRoundRobin:p});if(T.length){const E=Qk({candidatePositionAssignments:h,swapOptions:T});E.error&&console.log({result:E}),m=RE({candidatePositionAssignments:h,participantsWithGroupings:n,policyAttributes:o,idCollections:c}),g=Ge(m,f),I=fd({groupedParticipants:g,isRoundRobin:p}),S++}else S=20}return h.forEach(T=>{if(T.bye&&T.participantId){const E=zm;u.push(E)}if(T.qualifier&&T.participantId){const E=zm;u.push(E)}}),{positionAssignments:h,conflicts:I.length,groupedParticipants:g,errors:u}}function Qk({candidatePositionAssignments:t,swapOptions:e}){const n=cn(e);if(!n)return{error:{message:"No swap options"}};const r=n.drawPosition,s=cn(n.possibleDrawPositions),i=t.find(u=>u.drawPosition===r),o=t.find(u=>u.drawPosition===s),c={participantId:o.participantId,qualifier:o.qualifier,bye:o.bye},a={participantId:i.participantId,qualifier:i.qualifier,bye:i.bye};return Object.assign(i,c),Object.assign(o,a),{...$}}function Zk({provisionalPositioning:t,unseededParticipantIds:e,inContextDrawMatchUps:n,unseededByePositions:r,tournamentRecord:s,drawDefinition:i,seedBlockInfo:o,participants:c,matchUpsMap:a,structureId:u,avoidance:l,drawSize:f,entries:p,event:h}){var j;if(!l)return{error:Q1};const{candidatesCount:d=1,policyAttributes:m,targetDivisions:g}=l;let{roundsToSeparate:I}=l;const S="randomUnseededSeparation",{structure:T}=Ot({drawDefinition:i,structureId:u}),{matchUps:E}=Qt({provisionalPositioning:t,matchUpsMap:a,structure:T,event:h});if(g&&mr(g)&&!I){const H=I1(g)||0,B=E.reduce((R,x)=>x.roundNumber>R?x.roundNumber:R,0);I=B<H?1:B-H+1}const{positionAssignments:y}=ke({structure:T}),b=Qf({participantsProfile:{convertExtensions:!0},participants:c}),N=y==null?void 0:y.filter(H=>!H.participantId),A=y==null?void 0:y.map(H=>H.drawPosition),C=(T==null?void 0:T.structureType)===mn,v=C?{structure:T,matchUps:E,allDrawPositions:A,roundsToSeparate:I}:{matchUps:E,allDrawPositions:A,roundsToSeparate:I},{drawPositionGroups:P,drawPositionChunks:U}=C?Xk(v):t_(v),O={};O.groupParticipants=c.filter(H=>H.participantType===Fn).map(H=>H.participantId),O.teamParticipants=c.filter(H=>H.participantType===se).map(H=>H.participantId),O.pairParticipants=c.filter(H=>H.participantType===_t).map(H=>H.participantId);const D=jk({targetParticipantIds:e,policyAttributes:m,idCollections:O,participants:c}),M=Object.assign({},...e.map(H=>{const B=Object.keys(D).filter(R=>D[R].includes(H));return{[H]:B}})),w=$E({participantIds:e,positionAssignments:y});if(w.length>((N==null?void 0:N.length)||0))return{error:pg};let k;const _=w.length,F=ht(0,d).map(()=>VE({initialPositionAssignments:y,participantsWithGroupings:b,unseededParticipantIds:e,opponentsToPlaceCount:_,pairedPriority:!1,unseededByePositions:r,participantIdGroups:M,drawPositionChunks:U,drawPositionGroups:P,policyAttributes:m,idCollections:O,allGroups:D,drawSize:f}));if(k=F.reduce((H,B)=>!H||(B.conflicts||0)<(H.conflicts||0)?B:H,void 0),!k||k.conflicts){const H=ht(0,d).map(()=>VE({initialPositionAssignments:y,participantsWithGroupings:b,unseededParticipantIds:e,opponentsToPlaceCount:_,pairedPriority:!0,unseededByePositions:r,participantIdGroups:M,drawPositionChunks:U,drawPositionGroups:P,policyAttributes:m,idCollections:O,allGroups:D,drawSize:f,entries:p}));k=F.concat(...H).filter(R=>{var x;return!((x=R.errors)!=null&&x.length)}).reduce((R,x)=>!R||(x.conflicts||0)<(R.conflicts||0)?x:R,void 0)}if(!k)return{error:Jd};const L=(((j=ee({structure:T}))==null?void 0:j.positionAssignments)??[]).filter(H=>H.participantId).map(H=>H.participantId),W=k.positionAssignments.filter(H=>!L.includes(H.participantId));for(const H of W)if(H.bye){const B=Vn({tournamentRecord:s,drawDefinition:i,seedBlockInfo:o,structureId:u,matchUpsMap:a,event:h,...H});if(B.error)return G({result:B,stack:S})}else{const B=_r({automaticPlacement:!0,inContextDrawMatchUps:n,tournamentRecord:s,drawDefinition:i,seedBlockInfo:o,structureId:u,matchUpsMap:a,event:h,...H});if(B.error)return G({result:B,stack:S,context:{assignment:H}})}return{...$}}function Xk(t){const{structure:{structures:e}}=t,n=e.map(r=>r.positionAssignments.map(s=>s.drawPosition));return{drawPositionGroups:n,drawPositionChunks:[n]}}function t_({allDrawPositions:t,roundsToSeparate:e,matchUps:n}){const r=n.filter(p=>p.roundNumber===1).map(p=>p.drawPositions),s=r.flat().sort(Ve),i=Math.max(...s),o=t.filter(p=>p>i),c=s.length,u=ht(c===2?1:2,c).filter(p=>p===Fd(p)),f=u.slice(0,e||u.length).reverse().map(p=>Ge(s,p));return o.length&&console.log({fedDrawPositions:o}),{drawPositionGroups:r,drawPositionChunks:f}}function e_({provisionalPositioning:t,inContextDrawMatchUps:e,unseededByePositions:n,multipleStructures:r,tournamentRecord:s,drawDefinition:i,seedBlockInfo:o,participants:c,matchUpsMap:a,structureId:u,structure:l,drawSize:f,event:p}){var P,U;const h="positionUnseededParticipants";l||({structure:l}=Ot({drawDefinition:i,structureId:u})),u||({structureId:u}=l);const{positionAssignments:d}=ke({structure:l}),{seedAssignments:m}=Mr({provisionalPositioning:t,drawDefinition:i,structure:l}),g=m==null?void 0:m.map(O=>O.participantId).filter(Boolean),{stage:I,stageSequence:S}=l,T=I===Pt?(U=(P=Ke({element:l,name:Hr}))==null?void 0:P.extension)==null?void 0:U.value:void 0,y=mo({provisionalPositioning:t,drawDefinition:i,stageSequence:S,entryStatuses:ho,structureId:u,roundTarget:T,stage:I}),N=y.filter(O=>!(g!=null&&g.includes(O.participantId))).map(O=>O.participantId),A=d==null?void 0:d.filter(O=>!O.participantId&&!O.bye&&!O.qualifier).map(O=>O.drawPosition);if(!r&&N.length>((A==null?void 0:A.length)||0))return G({result:{error:pg},context:{unseededParticipantsCount:N.length,unfilledDrawPositionsCount:A==null?void 0:A.length},stack:h});const{appliedPolicies:C}=ge({tournamentRecord:s,drawDefinition:i,event:p});let{avoidance:v}=C??{};if(l.stage===Ie){const O=y.reduce((D,M)=>(D[M.groupingValue]||(D[M.groupingValue]=[]),D[M.groupingValue].push(M.participantId),D),{});Object.keys(O).length&&(v||(v={policyName:"Playoff Avoidance"}),v.policyAttributes||(v.policyAttributes=[]),v.policyAttributes.push({groupings:O}))}return v&&c?Zk({provisionalPositioning:t,unseededParticipantIds:N,inContextDrawMatchUps:e,unseededByePositions:n,tournamentRecord:s,drawDefinition:i,seedBlockInfo:o,participants:c,matchUpsMap:a,structureId:u,avoidance:v,drawSize:f,entries:y}):n_({provisionalPositioning:t,unseededParticipantIds:N,inContextDrawMatchUps:e,unfilledDrawPositions:A,multipleStructures:r,tournamentRecord:s,drawDefinition:i,seedBlockInfo:o,structureId:u,matchUpsMap:a,drawSize:f,event:p})}function n_({provisionalPositioning:t,unseededParticipantIds:e,inContextDrawMatchUps:n,unfilledDrawPositions:r,multipleStructures:s,tournamentRecord:i,drawDefinition:o,seedBlockInfo:c,matchUpsMap:a,structureId:u,drawSize:l,event:f}){const p=l>2?on(r):r.reverse();for(const h of e){const d=p.pop();if(!s||d){const m=_r({provisionalPositioning:t,inContextDrawMatchUps:n,tournamentRecord:i,drawDefinition:o,seedBlockInfo:c,participantId:h,drawPosition:d,matchUpsMap:a,structureId:u,event:f});if(m!=null&&m.error&&console.log("!!!!!",{result:m}),m!=null&&m.error)return G({result:m,stack:"randomUnseededDistribution"})}}return{...$}}function r_({provisionalPositioning:t,drawDefinition:e,structure:n}){const{positionAssignments:r}=ke({structure:n}),{seedAssignments:s}=Mr({provisionalPositioning:t,drawDefinition:e,structure:n}),i=Object.assign({},...(s||[]).filter(o=>o.participantId).map(o=>({[o.participantId]:o})));return r==null?void 0:r.map(o=>i[o.participantId]?{...o,seedNumber:i[o.participantId].seedNumber,seedValue:i[o.participantId].seedValue}:"").filter(Boolean)}function s_({orderedSortedFirstRoundSeededDrawPositions:t,validSeedBlocks:e,byesToPlace:n}){const r=[];e.forEach(i=>{if(n-r.length>i.drawPositions.length)r.push(...i.drawPositions);else{const c=kh(Ge(i.drawPositions,2));let a,u=t[r.length];for(;a=uu(c,u);)r.push(a),u=t[r.length]}});const s=r.map(i=>Array.isArray(i)?on(i):i).flat(1/0);return S1(n)&&e.map(o=>o.seedNumbers[0]).includes(n)?t:s}function uu(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();const n=t[0].flat(1/0).length,r=t[1].flat(1/0).length;if(n===r){const s=t[0].flat(1/0).includes(e)?t[0]:t[1];return uu(e?s:t[Math.round(Math.random())],e)}return n<r?uu(t[1],e):uu(t[0],e)}function kh(t){const e=Math.floor(t.length/2);return t.length>2?[kh(t.slice(0,e)),kh(t.slice(e))]:t}function i_({provisionalPositioning:t,relevantMatchUps:e,appliedPolicies:n,drawDefinition:r,seedBlockInfo:s,byesToPlace:i,structure:o}){var E;s||(s=Oo({provisionalPositioning:t,appliedPolicies:n,drawDefinition:r,structure:o}));const{isFeedIn:c,isLuckyStructure:a,isContainer:u}=s;let{validSeedBlocks:l}=s;(E=n==null?void 0:n.seeding)!=null&&E.containerByesIgnoreSeeding&&(l=[]);const f=r_({provisionalPositioning:t,drawDefinition:r,structure:o})??[],p=Vt([].concat(...e.map(y=>y.drawPositions))),h=f.filter(y=>p.includes(y.drawPosition)),d=(y,b)=>Pc(y.seedValue)-Pc(b.seedValue),g=l.reduce((y,b)=>{const N=h.filter(A=>{var C;return(C=b.drawPositions)==null?void 0:C.includes(A.drawPosition)}).sort(d);return y.concat(...N)},[]).map(y=>y.drawPosition),I=s_({orderedSortedFirstRoundSeededDrawPositions:g,validSeedBlocks:l,byesToPlace:i}),S=jE({orderedSeedDrawPositions:g,relevantMatchUps:e}).slice(0,f.length),T=jE({orderedSeedDrawPositions:I,relevantMatchUps:e}).slice(0,f.length);return{strictSeedOrderByePositions:S,blockSeedOrderByePositions:T,isLuckyStructure:a,positionedSeeds:f,isContainer:u,isFeedIn:c}}function jE({orderedSeedDrawPositions:t,relevantMatchUps:e}){const r=e.map(i=>i.drawPositions).map(i=>i==null?void 0:i.sort((o,c)=>o-c)).filter(i=>(i==null?void 0:i[0])+1===(i==null?void 0:i[1]));return t.map(i=>r.find(o=>o==null?void 0:o.includes(i))).filter(Boolean).map(i=>i==null?void 0:i.reduce((o,c)=>t.includes(c)?o:c,void 0)).filter(Boolean)}function o_({provisionalPositioning:t,seedOrderByePositions:e,isLuckyStructure:n,appliedPolicies:r,drawDefinition:s,seedLimit:i,structure:o,isFeedIn:c}){var M,w;const a=(M=r==null?void 0:r.seeding)==null?void 0:M.seedingProfile,u=o.stage===Pt,{positionAssignments:l}=ke({structure:o}),f=l==null?void 0:l.filter(k=>k.participantId).map(k=>k.drawPosition),p={isCollectionMatchUp:!1},{matchUps:h,roundMatchUps:d}=Qt({provisionalPositioning:t,matchUpFilters:p,structure:o}),m=(d==null?void 0:d[1])||[],g=o.structureType===mn?h:m,I=Vt([].concat(...g.map(k=>k.drawPositions))),S=Math.min(...I)-1,T=f==null?void 0:f.filter(k=>I.includes(k)),E=k=>{const _=Math.ceil(k.length/2),F=[k.slice(0,_),k.slice(_)],L=F.map(V=>[].concat(...V.flat(1/0)).length),W=Math.min(...L.flat(1/0)),j=Math.max(...L.flat(1/0)),H=L.indexOf(j),B=W!==j,R=on(F),[x,q]=!W||B?[F[H],F[1-H]]:[R[0],R[1]];return{greaterHalf:x,lesserHalf:q}},y=k=>{const{greaterHalf:_,lesserHalf:F}=E(k),{greaterHalf:L,lesserHalf:W}=E(_),H=on(L.flat(1/0)).pop(),B=L.flat().filter(x=>x!==H);return{newlyFilteredChunks:[...F,...W,B],drawPosition:H}},b=k=>!e.includes(k),N=k=>!(T!=null&&T.includes(k)),A=k=>{let F=Ge(k.sort(Ve),Math.ceil(k.length/4)).map(j=>j.filter(N));const L=[].concat(...F.flat(1/0)).length,W=[];for(let j=0;j<L;j++){const{newlyFilteredChunks:H,drawPosition:B}=y(F);W.push(B),F=H}return W},{validSeedBlocks:C}=Oo({provisionalPositioning:t,allPositions:!0,appliedPolicies:r,drawDefinition:s,structure:o}),v=C==null?void 0:C.map(k=>{var _;return(_=k.drawPositions)==null?void 0:_.map(F=>F+S)});let P;if(c){const k=I.length,{seedBlocks:_}=xl({cluster:Ka(a)===Lf,participantsCount:k});P=_.map(L=>L.map(W=>W+S)).map(A).filter(L=>L.length)}else u?P=v==null?void 0:v.map(k=>k.filter(N)):P=v==null?void 0:v.map(A).filter(k=>k.length);const U=g.map(k=>k.drawPositions).map(k=>k==null?void 0:k.sort((_,F)=>_-F)).filter(k=>(k==null?void 0:k[0])+1===(k==null?void 0:k[1])),O=k=>U.reduce((_,F)=>F.includes(k)?F.reduce((L,W)=>W!==k?W:L,void 0):_,void 0);let D=P.map(k=>k.map(O)).flat(1/0).filter(N).filter(b).filter(Boolean);if(u&&!o.structures){const k=i%4,_=D.slice(0,k),F=(w=d[o.roundLimit])==null?void 0:w.length,L=Ge(D.slice(k),F).map(on).flat();D=_.concat(L)}return{unseededByePositions:D}}function c_({provisionalPositioning:t,drawDefinition:e,matchUpsMap:n,structure:r,event:s}){var v;const i={isCollectionMatchUp:!1},{matchUps:o,roundMatchUps:c}=Qt({afterRecoveryTimes:!1,provisionalPositioning:t,drawDefinition:e,matchUpFilters:i,matchUpsMap:n,structure:r,event:s}),a=(c==null?void 0:c[1])||[],u=(r==null?void 0:r.structureType)===mn,l=u?o:a,f=u?((v=r==null?void 0:r.structures)==null?void 0:v.length)||0:o.length,{structureId:p,stage:h,stageSequence:d}=r,m=mo({entryStatuses:ps,provisionalPositioning:t,drawDefinition:e,stageSequence:d,structureId:p,stage:h}),{qualifiersCount:g}=Li({provisionalPositioning:t,drawDefinition:e,stageSequence:d,structureId:p,stage:h}),I=m.length+g,{positionAssignments:S,unassignedPositions:T}=ke({structure:r}),E=T==null?void 0:T.map(P=>P.drawPosition),y=S==null?void 0:S.filter(P=>P.bye).length,b=S==null?void 0:S.filter(P=>P.bye).map(P=>P.drawPosition),N=l.map(P=>P.drawPositions).filter(P=>P==null?void 0:P.reduce((U,O)=>!(b!=null&&b.includes(O))&&U,!0)).flat(1/0).filter(P=>E==null?void 0:E.includes(P)),A=S==null?void 0:S.length;let C=A?A-I:0;return C>f&&r.stageSequence===1&&r.stage!==Re&&(C=f),{placedByes:y,byesCount:C,relevantMatchUps:l,placedByePositions:b,roundMatchUps:c,positionsToAvoidDoubleBye:N}}function GE({provisionalPositioning:t,tournamentRecord:e,appliedPolicies:n,drawDefinition:r,seedBlockInfo:s,matchUpsMap:i,structureId:o,structure:c,seedLimit:a,seedsOnly:u,event:l}){var P;c||({structure:c}=Ot({drawDefinition:r,structureId:o})),o||(o=c==null?void 0:c.structureId);const f=!((c==null?void 0:c.structures)??(c==null?void 0:c.stage)===Pt),{byesCount:p,placedByes:h,relevantMatchUps:d}=c_({provisionalPositioning:t,drawDefinition:r,matchUpsMap:i,structure:c,event:l}),m=p-(h||0);if(m<=0)return{...$};const{strictSeedOrderByePositions:g,blockSeedOrderByePositions:I,isLuckyStructure:S,isFeedIn:T}=i_({provisionalPositioning:t,relevantMatchUps:d,appliedPolicies:n,drawDefinition:r,seedBlockInfo:s,byesToPlace:m,structure:c}),E=(c==null?void 0:c.structureType)&&[mn,tl].includes(c.structureType)&&((P=n==null?void 0:n.seeding)==null?void 0:P.containerByesIgnoreSeeding),y=f&&(I!=null&&I.length)?I:g;let{unseededByePositions:b}=o_({provisionalPositioning:t,seedOrderByePositions:y,isLuckyStructure:S,appliedPolicies:n,drawDefinition:r,seedLimit:a,structure:c,isFeedIn:T});const N=U=>U%2,A=(U,O)=>(U||[]).every(D=>N(D)?O!==D+1:O!==D-1);let C=[].concat(...y);if(!u)for(;b.length;){const U=b.find(O=>A(C,O));U?(C.push(U),b=b.filter(O=>O!==U)):(C.push(...b),b=[])}E&&(C=on(C),ze({ignoreSeededByes:E})&&console.log({byePositions:C}));const v=C.slice(0,m);for(const U of v){const O=Vn({provisionalPositioning:t,tournamentRecord:e,drawDefinition:r,drawPosition:U,matchUpsMap:i,structureId:o,structure:c,event:l});if(O!=null&&O.error)return O}return{...$,unseededByePositions:b,byeDrawPositions:v}}function a_(t){let{structure:e,structureId:n}=t;e||({structure:e}=Ot(t)),n||({structureId:n}=e);const r="positionQualifiers",s=[];if(e.stage===Re)return G({result:{error:xs},stack:r});const{unplacedRoundQualifierCounts:i,positionAssignments:o,roundDrawPositions:c}=u_(t);for(const a of Object.keys(i)){const u=o==null?void 0:o.filter(l=>c[a].includes(l.drawPosition)&&!l.participantId&&!l.qualifier&&!l.bye).map(l=>l.drawPosition);if(i[a]>(u||0))return G({result:{error:Sv},context:{unfilledDrawPositions:u},stack:r});ht(0,i[a]).forEach(()=>{const l=cn(u);s.push(l),o==null||o.forEach(f=>{f.drawPosition===l&&(f.qualifier=!0,delete f.participantId,delete f.bye)})})}return{...$,qualifierDrawPositions:s}}function u_({drawDefinition:t,structure:e,structureId:n}){e||({structure:e}=Ot({drawDefinition:t,structureId:n})),n||({structureId:n}=e);const{positionAssignments:r}=ke({structure:e}),{stage:s,stageSequence:i}=e,{qualifiersCount:o,roundQualifiersCounts:c}=Li({drawDefinition:t,stageSequence:i,structureId:n,stage:s}),u=(c?Object.keys(c):[]).map(I=>vt(I)),{matchUps:l}=Qt({structure:e}),{roundProfile:f}=Cn({matchUps:l}),p=Object.assign({},...u.filter(I=>f==null?void 0:f[I]).map(I=>{var S,T;return{[I]:((T=(S=f==null?void 0:f[I])==null?void 0:S.drawPositions)==null?void 0:T.filter(Boolean))??[]}})),h=r==null?void 0:r.filter(I=>I.qualifier).map(I=>I.drawPosition),d=o-((h==null?void 0:h.length)??0),m=h==null?void 0:h.length;return{unplacedRoundQualifierCounts:Object.assign({},...u.map(I=>{const S=r==null?void 0:r.filter(T=>{var E,y;return T.qualifier&&((y=(E=p[I])==null?void 0:E.drawPositions)==null?void 0:y.includes(T.drawPosition))}).map(T=>T.drawPosition);return{[I]:((c==null?void 0:c[I])??0)-((S==null?void 0:S.length)??0)}})),unplacedQualifiersCount:d,placedQualifiersCount:m,roundQualifiersCounts:c,positionAssignments:r,roundDrawPositions:p,qualifiersCount:o}}function WE({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:n,appliedPolicies:r,validSeedBlocks:s,drawDefinition:i,seedingProfile:o,seedBlockInfo:c,participants:a,groupsCount:u,structureId:l,matchUpsMap:f,structure:p,event:h}){const d=[],m=[];let g=0;if(p||({structure:p}=Ot({drawDefinition:i,structureId:l})),l||(l=p==null?void 0:p.structureId),r||(r=ge({drawDefinition:i}).appliedPolicies),!s){const I=p&&Oo({provisionalPositioning:t,appliedPolicies:r,drawDefinition:i,structure:p});I!=null&&I.error&&m.push(I.error),s=I==null?void 0:I.validSeedBlocks}return u=u??(s==null?void 0:s.length)??0,ht(0,u).forEach(()=>{if(g<(u||0)){const I=l_({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:i,seedingProfile:o,seedBlockInfo:c,participants:a,structureId:l,matchUpsMap:f,event:h});I!=null&&I.success&&(g++,d.push(...I.seedPositions??[])),I.error&&m.push({seedPositionError:I.error})}}),m.length?{error:m}:{...$,seedPositions:d}}function l_({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:r,seedingProfile:s,seedBlockInfo:i,participants:o,structureId:c,matchUpsMap:a,event:u}){const{unplacedSeedParticipantIds:l,unfilledPositions:f}=jl({provisionalPositioning:t,randomize:!0,drawDefinition:r,seedBlockInfo:i,structureId:c,event:u}),{appliedPolicies:p}=ge({drawDefinition:r}),{avoidance:h}=p??{};h&&o&&(l==null?void 0:l.length)>2;const d=[];for(const m of l){const g=f.pop();if(!g)return{error:Wc};d.push(g);const I=_r({provisionalPositioning:t,inContextDrawMatchUps:e,tournamentRecord:n,drawDefinition:r,seedingProfile:s,participantId:m,seedBlockInfo:i,drawPosition:g,matchUpsMap:a,structureId:c,event:u});if(!I.success)return I}return{...$,seedPositions:d}}function lu({applyPositioning:t=!0,provisionalPositioning:e,inContextDrawMatchUps:n,multipleStructures:r,placeByes:s=!0,tournamentRecord:i,appliedPolicies:o,placementGroup:c,drawDefinition:a,seedingProfile:u,participants:l,structureId:f,matchUpsMap:p,seedLimit:h,seedsOnly:d,drawType:m,drawSize:g,event:I}){var M;const S=[];t||(rC(),a=pt(a,!1,!0));const T=w=>(t||Zd(),G({result:w,stack:"automatedPositioning"})),E=w=>(t||Zd(),w),y=Ot({drawDefinition:a,structureId:f});if(y.error)return T(y);const b=y.structure;if(!b)return{error:Te};o||(o=(M=ge({drawDefinition:a,structure:b,event:I}))==null?void 0:M.appliedPolicies);const{qualifiersCount:N}=Li({stageSequence:b.stageSequence,provisionalPositioning:e,stage:b.stage,drawDefinition:a,structureId:f}),A=ho,C=mo({stageSequence:b.stageSequence,provisionalPositioning:e,stage:b.stage,placementGroup:c,drawDefinition:a,entryStatuses:A,structureId:f});if(!(C!=null&&C.length)&&!N)return E({...$});p=p??ln({drawDefinition:a}),n||({matchUps:n}=xe({inContext:!0,drawDefinition:a,matchUpsMap:p}));let v=[];const P=Oo({provisionalPositioning:e,appliedPolicies:o,drawDefinition:a,structure:b});if(P.error)return P;const{validSeedBlocks:U}=P;if(S.push({validSeedBlocks:U}),Ka(b.seedingProfile||u)===Rf){let w=s?GE({provisionalPositioning:e,tournamentRecord:i,appliedPolicies:o,drawDefinition:a,seedBlockInfo:P,matchUpsMap:p,structure:b,seedLimit:h,seedsOnly:d,event:I}):void 0;if(w!=null&&w.error)return T(w);v=w.unseededByePositions,S.push({action:"positionByes",unseededByePositions:v});const k=b.seedingProfile?{positioning:b.seedingProfile}:u;if(w=WE({seedingProfile:k,provisionalPositioning:e,inContextDrawMatchUps:n,tournamentRecord:i,appliedPolicies:o,validSeedBlocks:U,drawDefinition:a,seedBlockInfo:P,participants:l,matchUpsMap:p,structure:b,event:I}),w.error)return T(w);S.push({seedPositions:w.seedPositions,action:"positionSeedBlocks"})}else{if(m!==Ci){const k=b.seedingProfile?{positioning:b.seedingProfile}:u,_=WE({seedingProfile:k,provisionalPositioning:e,inContextDrawMatchUps:n,tournamentRecord:i,appliedPolicies:o,validSeedBlocks:U,drawDefinition:a,seedBlockInfo:P,participants:l,matchUpsMap:p,structure:b,event:I});if(_.error)return T(_);S.push({action:"positionSeedBlocks",seedPositions:_.seedPositions})}const w=s?GE({provisionalPositioning:e,tournamentRecord:i,appliedPolicies:o,drawDefinition:a,seedBlockInfo:P,matchUpsMap:p,structure:b,seedLimit:h,seedsOnly:d,event:I}):void 0;if(w!=null&&w.error)return console.log("positionByes",{result:w}),T(w);v=w==null?void 0:w.unseededByePositions,S.push({action:"positionByes",byeDrawPositions:w==null?void 0:w.byeDrawPositions,unseededByePositions:v})}const O={};if(!d){let w=a_({inContextDrawMatchUps:n,tournamentRecord:i,appliedPolicies:o,validSeedBlocks:U,drawDefinition:a,seedBlockInfo:P,participants:l,matchUpsMap:p,structure:b});if(w.error||(w.conflicts&&(O.qualifierConflicts=w.conflicts),S.push({action:"positionQualifiers",qualifierDrawPositions:w.qualifierDrawPositions}),w=e_({provisionalPositioning:e,inContextDrawMatchUps:n,unseededByePositions:v,multipleStructures:r,tournamentRecord:i,drawDefinition:a,seedBlockInfo:P,participants:l,matchUpsMap:p,structureId:f,structure:b,drawSize:g,event:I}),w.error))return T(w);w.conflicts&&(O.unseededConflicts=w.conflicts),S.push({action:"positionUnseededParticipants"})}const{positionAssignments:D}=ee({drawDefinition:a,structure:b});return Zt({drawDefinition:a,structureIds:[f]}),t||Zd(),{positionAssignments:D,conflicts:O,...$,positioningReport:S}}function d_({applyPositioning:t=!0,tournamentRecord:e,drawDefinition:n,seedingProfile:r,structureId:s,placeByes:i,seedsOnly:o,drawSize:c,event:a}){if(!a)return{error:wn};if(!n)return{error:rr};const u=e==null?void 0:e.participants;return lu({tournamentRecord:e,applyPositioning:t,drawDefinition:n,seedingProfile:r,participants:u,structureId:s,placeByes:i,seedsOnly:o,drawSize:c})}function pd(t){var d;const{applyPositioning:e=!0,provisionalPositioning:n,tournamentRecord:r,drawDefinition:s,seedingProfile:i,structureId:o,placeByes:c,seedsOnly:a,event:u}=t;if(!u)return{error:wn};if(!s)return{error:rr};if(!ki({drawDefinition:s,structureId:o})&&!n)return{error:Hm};const f=(d=jT({drawDefinition:s,structureId:o}).playoffStructures)==null?void 0:d.sort((m,g)=>nl(m)-nl(g)),p=[],h=r==null?void 0:r.participants;if(f)for(const m of f){const{structureId:g}=m,I=lu({structureId:g,provisionalPositioning:n,applyPositioning:e,drawDefinition:s,seedingProfile:i,participants:h,placeByes:c,seedsOnly:a});if(I.error)return I;I.positionAssignments&&p.push({positionAssignments:I.positionAssignments,structureId:g})}return{...$,structurePositionAssignments:p}}function f_(t){var N,A,C;const e="generateAndPopulateRRplayoffStructures";if(!t.playoffGroups)return G({result:{error:Tt},info:"playoffGroups required",stack:e});const{sourceStructureId:n,requireSequential:r,drawDefinition:s,playoffGroups:i,groupCount:o,groupSize:c,event:a}=t,{structures:u=[],links:l=[],finishingPositionTargets:f,positionRangeMap:p,error:h}=_E({requireSequential:r,sourceStructureId:n,playoffGroups:i,groupCount:o,groupSize:c,...t});if(h)return{error:h};const d=f==null?void 0:f.map(({finishingPositions:v})=>v).flat().map(v=>p[v].finishingPositions).flat();s.structures.push(...u),s.links.push(...l);const{matchUps:m,matchUpsMap:g}=xe({inContext:!0,drawDefinition:s}),I=u.map(({structureId:v})=>v),S=m==null?void 0:m.filter(({structureId:v})=>I.includes(v)).map(Qe),T=(N=g==null?void 0:g.drawMatchUps)==null?void 0:N.filter(({matchUpId:v})=>S==null?void 0:S.includes(v));if(T!=null&&T.length){const v=(A=hn({drawDefinition:s,event:a}))==null?void 0:A.tieFormat;v&&T.forEach(P=>{const{tieMatchUps:U}=Jl({isMock:t.isMock,tieFormat:v});Object.assign(P,{tieMatchUps:U,matchUpType:yr})})}const{positionAssignments:E}=ee({structureId:n,drawDefinition:s}),y={};E==null||E.forEach(v=>{var D;const P=xn({element:v,name:Ys}),U=(D=P==null?void 0:P.extension)==null?void 0:D.value,O=U==null?void 0:U.groupOrder;O&&(y[O]||(y[O]=[]),y[O].push(v.participantId))});const b=pd({provisionalPositioning:t.provisionalPositioning,structureId:n,applyPositioning:!0,event:t.event,drawDefinition:s});return b.error&&((C=b.error)==null?void 0:C.code)!==Hm.code?G({result:b,stack:e}):{structures:u,links:l,positionsPlayedOff:d,drawDefinition:s,...$}}function _h(t){var x,q;const e="genPlayoffStructure";if(!t.drawDefinition)return G({result:{error:lt},stack:e});const n=ou(t);if(n.error)return G({result:n,stack:e});const{structureId:r,addNameBaseToAttributeName:s,playoffStructureNameBase:i,playoffAttributes:o,playoffPositions:c,tournamentRecord:a,exitProfileLimit:u,roundProfiles:l,roundNumbers:f,idPrefix:p,isMock:h,event:d,uuids:m}=t,g=pt(t.drawDefinition,!1,!0),{structure:I}=Ot({structureId:r,drawDefinition:g});if(!I)return G({result:{error:Te}});if(I.structureType===mn||I.structures)return f_({sourceStructureId:I.structureId,...t,...n,drawDefinition:g});const{playoffRoundsRanges:S,playoffRounds:T}=n,{playoffPositionsReturned:E,error:y,playoffSourceRounds:b,playoffRoundsRanges:N}=Oh(t);if(y)return G({result:{error:y},stack:e});const A=(l==null?void 0:l.length)&&Object.assign({},...l),C=f||typeof l=="object"&&l.map(V=>Object.keys(V)).flat(),v=Array.isArray(C)&&C.map(V=>!isNaN(V)&&vt(V)).filter(Boolean);if(v){if(!Array.isArray(v))return G({result:{error:tt},context:{validRoundNumbers:v},stack:e});v.forEach(V=>{if(!(T!=null&&T.includes(V)))return G({result:{error:tt},context:{roundNumber:V},stack:e})})}c&&c.forEach(V=>{if(!(E!=null&&E.includes(V)))return G({result:{error:tt},context:{playoffPosition:V},stack:e})});const P=v||b,U=v?S:N,O=[],D=[];for(const V of P??[]){const Y=U==null?void 0:U.find(K=>K.roundNumber===V);if(!Y)return G({result:{error:tt},context:{roundNumber:V},stack:e});const z=Y.finishingPositions.length,J=Math.min(...Y.finishingPositions)-1,Q=2,X=V&&(A==null?void 0:A[V])&&Q+A[V]-1,Z=_c({exitProfile:`0-${V}`,addNameBaseToAttributeName:s,playoffStructureNameBase:i,finishingPositionOffset:J,playoffAttributes:o,exitProfileLimit:u,stage:Ie,roundOffset:0,drawDefinition:g,sequenceLimit:X,stageSequence:Q,drawSize:z,idPrefix:p,isMock:h,uuids:m});if(Z.error)return G({result:Z,stack:e});const{structures:nt,links:rt}=Z;if(nt!=null&&nt.length&&O.push(...nt),rt!=null&&rt.length&&D.push(...rt),Z.structureId&&V){const K={linkType:js.Loser,source:{structureId:r,roundNumber:V},target:{structureId:Z.structureId,feedProfile:ra.TopDown,roundNumber:1}};D.push(K)}}if(!O.length)return G({result:{error:tt},info:"No structures generated",stack:e});g.structures.push(...O),g.links.push(...D);const{matchUps:M,matchUpsMap:w}=xe({inContext:!0,drawDefinition:g}),k=O.map(({structureId:V})=>V),_=M==null?void 0:M.filter(({structureId:V})=>k.includes(V)).map(Qe),F=(x=w==null?void 0:w.drawMatchUps)==null?void 0:x.filter(({matchUpId:V})=>_==null?void 0:_.includes(V));if(F!=null&&F.length){const V=(q=hn({drawDefinition:g,event:d}))==null?void 0:q.tieFormat;V&&F.forEach(Y=>{const{tieMatchUps:z}=Jl({tieFormat:V,isMock:h});Object.assign(Y,{tieMatchUps:z,matchUpType:Jt})})}const L=M==null?void 0:M.filter(V=>Qo({matchUp:V})&&V.structureId===r);L==null||L.forEach(V=>{const{matchUpId:Y,score:z,winningSide:J}=V,Q=gn({inContextDrawMatchUps:M,drawDefinition:g,matchUpId:Y}),X=KT({inContextDrawMatchUps:M,tournamentRecord:a,drawDefinition:g,matchUpsMap:w,winningSide:J,targetData:Q,matchUpId:Y,structure:I,matchUp:V,score:z,event:d});X.error&&console.log(X.error)});const W=M==null?void 0:M.filter(V=>V.matchUpStatus===re&&V.structureId===r);W==null||W.forEach(V=>{const{matchUpId:Y}=V,z=gn({inContextDrawMatchUps:M,drawDefinition:g,matchUpId:Y}),{targetLinks:{loserTargetLink:J},targetMatchUps:{loserMatchUpDrawPositionIndex:Q,loserMatchUp:X}}=z,Z=J.target.structureId,nt=X.drawPositions[Q],rt=Vn({drawPosition:nt,structureId:Z,tournamentRecord:a,drawDefinition:g,event:d});rt.error&&console.log(rt.error)});const j=[],H=Ic({inContextDrawMatchUps:M,drawDefinition:g,matchUpsMap:w}).goesToMap,{structure:B}=Ot({drawDefinition:t.drawDefinition,structureId:r}),{matchUps:R}=Qt({structure:B});return R.forEach(V=>{var J,Q;const Y=H==null?void 0:H.loserMatchUpIds[V.matchUpId];if(Y&&V.loserMatchUpId!==Y){V.loserMatchUpId=Y;const X={tournamentId:a==null?void 0:a.tournamentId,eventId:(J=t.event)==null?void 0:J.eventId,context:e,matchUp:V};j.push(X)}const z=H==null?void 0:H.winnerMatchUpIds[V.matchUpId];if(z&&V.winnerMatchUpId!==z){V.winnerMatchUpId=z;const X={tournamentId:a==null?void 0:a.tournamentId,eventId:(Q=t.event)==null?void 0:Q.eventId,context:e,matchUp:V};j.push(X)}}),{structures:O,matchUpModifications:j,links:D,drawDefinition:g,...$}}function HE({drawDefinition:t,drawSize:e}){if(!t)return{error:lt};const n=au({stage:je,stageSequence:1,drawDefinition:t,drawSize:e});return n.error?n:(Zt({drawDefinition:t}),{...$})}function qE(t){var O,D,M,w,k;const{drawType:e=Ms,attachConsolation:n=!0,applyPositioning:r=!0,tournamentRecord:s,staggeredEntry:i,automated:o,placeByes:c,isMock:a,event:u}=t;let l=t==null?void 0:t.drawDefinition;if(!l)return{error:lt};const f=(O=dn({tournamentRecord:s,inContext:!0}))==null?void 0:O.tournamentParticipants,p=je,h=mo({stageSequence:1,drawDefinition:l,stage:p}),d=[Pr,va,Ds].includes(e)?h.length:Vo(h.length);if(!i&&e===ic&&h.length<2||e===Pr&&h.length<3)return{error:xd};let{tieFormat:m,matchUpType:g}=t;if(m){const _=vn({tieFormat:m});if(_.error)return _}m=Dr(m||((D=hn({drawDefinition:l}))==null?void 0:D.tieFormat)),g=g||l.matchUpType||_n.Singles;const{structures:I}=lr({stageSequence:1,drawDefinition:l,stage:p});if(I.length>1)return{error:Go};if((w=(M=I==null?void 0:I[0])==null?void 0:M.matchUps)!=null&&w.length)return{error:Go};const T=(k=I==null?void 0:I[0])==null?void 0:k.structureId;Object.assign(t,bt({structureName:t.structureName||je,structureId:T,matchUpType:g,tieFormat:m,drawSize:d,stage:p}));const E=FE(t);if(E.error)return E;const y=E.generators[e];if(!y)return{error:Ym};const b=y==null?void 0:y();if(b.error)return b;const{structures:N,links:A}=b,C=N.map(_=>Qt({structure:_}).matchUps).flat();m&&C.forEach(_=>{const{tieMatchUps:F}=Jl({tieFormat:m,isMock:a});Object.assign(_,{tieMatchUps:F,matchUpType:g})}),(!r||!n)&&(l=pt(l,!1,!0)),l.links||(l.links=[]),A.length&&l.links.push(...A);const v=N.map(({structureId:_})=>_);l.structures||(l.structures=[]);const P=l.structures.map(({structureId:_})=>_);l.structures=l.structures.map(_=>v.includes(_.structureId)?N.find(({structureId:F})=>F===_.structureId):_);const U=N.filter(({structureId:_})=>!P.includes(_));return U.length&&l.structures.push(...U),o&&lu({seedingProfile:t.seedingProfile,participants:f,applyPositioning:r,tournamentRecord:s,drawDefinition:l,structureId:T,placeByes:c,drawSize:d,event:u}),n&&Zt({drawDefinition:l}),{links:A,structures:N,...$}}function Fh(t){var M,w,k;if(!t.drawDefinition)return{error:lt};const e="generateQualifyingStructure";let n=t.drawSize||_d(t.participantsCount);const{qualifyingRoundNumber:r,qualifyingPositions:s,targetStructureId:i,structureOptions:o,appliedPolicies:c,drawDefinition:a,structureName:u,structureId:l,roundTarget:f,drawType:p,idPrefix:h,isMock:d,uuids:m}=t;let g,I,S,T,E=0,y,b=1;if(!oe(n))return G({result:{error:Eu},stack:e});const N=Ot({structureId:i,drawDefinition:a});if(N.error)return G({context:{targetStructureId:i},result:N,stack:e});if(!N.structure)return{error:Te};const A=N.structure,C=A.matchUpType;if(A.stage===Pt)if(A.stageSequence&&A.stageSequence>1)b=A.stageSequence-1;else{let _=i,F=2,L;for(;!L&&_;){A.stageSequence=F;const W=(w=(M=a.links.find(j=>j.source.structureId===_))==null?void 0:M.target)==null?void 0:w.structureId;if(_=W,F+=1,!W)L=!0;else{const j=Ot({structureId:W,drawDefinition:a});if(!j.structure)return{error:Te};if(j.error)return G({context:{targetTargetStructureId:W},result:j,stack:e});j.structure.stage!==Pt&&(L=!0)}}}const v=f?`${f}-`:"",P=`${b}`,U=u||(v||P?`${Pt} ${v}${P}`:Pt);if(p===Pr){const{maxRoundNumber:_,structures:F,groupCount:L}=za({structureName:u||U,structureId:l||(m==null?void 0:m.pop()),stage:Pt,structureOptions:o,appliedPolicies:c,stageSequence:b,matchUpType:C,roundTarget:f,idPrefix:h,drawSize:n,isMock:d,uuids:m});E=L,g=_,S=F[0],y=[1]}else({drawSize:n,matchUps:T,roundLimit:g,roundsCount:I}=rs({qualifyingRoundNumber:r,qualifyingPositions:s,matchUpType:C,idPrefix:h,drawSize:n,isMock:d,uuids:m})),g||(g=I),S=Ze({structureName:u||U,structureId:l||(m==null?void 0:m.pop()),qualifyingRoundNumber:g,stage:Pt,stageSequence:b,matchUpType:C,roundLimit:g,matchUps:T}),f&&ae({element:S,extension:{name:Hr,value:f}}),E=(k=T==null?void 0:T.filter(_=>_.roundNumber===g))==null?void 0:k.length;const O=p===Pr?js.Position:js.Winner,{link:D}=kc({sourceStructureId:S.structureId,sourceRoundNumber:g,targetStructureId:i,finishingPositions:y,linkType:O});return{qualifyingDrawPositionsCount:n,qualifiersCount:E,...$,structure:S,link:D}}function Lh({drawDefinition:t,tournamentId:e,structure:n,eventId:r,link:s}){var a;if(!t)return{error:lt};if(!n)return{error:Wi};if(!s)return{error:Km};const i=s.target.structureId,o=Ot({drawDefinition:t,structureId:i});if(o.error)return G({stack:"attachQualifyingStructure",context:{targetStructureId:i},result:o});t.structures||(t.structures=[]),t.links||(t.links=[]),t.structures.push(n),t.links.push(s);const c=((a=Qt({structure:n}))==null?void 0:a.matchUps)||[];return Oi({drawDefinition:t,tournamentId:e,matchUps:c,eventId:r}),Zt({drawDefinition:t,structureIds:[n.structureId]}),{...$}}function p_({matchUps:t,matchUpType:e}){var D;if(!t)return{error:$s};let n=[],r=[],s=0;e&&(t=t.filter(M=>M.matchUpType===e));const i=Vt(t.map(({matchUpType:M})=>M));if(i.length>1)if(i.includes(Jt))t=t.filter(M=>M.matchUpType===Jt);else if(i.includes(Oe))t=t.filter(M=>M.matchUpType===Oe);else if(i.includes(me))t=t.filter(M=>M.matchUpType===me);else return{};if(!cr(t)||!t.length)return{};const o=(M,w)=>vt(M)-vt(w),c=Vt(t.map(M=>M.drawPositions).flat().filter(Boolean)).sort(o),u=ht(1,Math.max(...c)+1).filter(M=>!c.includes(M)).sort(o),{roundMatchUps:l}=Cn({matchUps:t}),f=l==null?void 0:l[1],p=(l==null?void 0:l[2])||[],h=(f==null?void 0:f[0])||{},d=h.drawId,m=h.structureId,g=l?Object.keys(l).map(M=>vt(M)):[],I=Math.max(...g),S=((D=l==null?void 0:l[I])==null?void 0:D.length)||0,T=Math.ceil(Math.log(S)/Math.log(2)),E=ht(1,T+1).map(M=>{const w=Math.pow(2,M-1),k=I+T-M+1;return ht(1,w+1).map(_=>({drawId:d,structureId:m,matchUpId:Yt(),drawPositions:[],sides:[],roundNumber:k,roundPosition:_,finishingRound:M}))});T&&(t=t.concat(...E.flat()));const b=(f==null?void 0:f.map(M=>M.drawPositions)).flat(1/0),A=p.map(M=>M.drawPositions).flat(1/0).filter(M=>!b.includes(M)).sort(o),C=p.filter(M=>{var w;return(w=M.drawPositions)==null?void 0:w.reduce((k,_)=>A.includes(_)||k,void 0)}).map(M=>{var F,L;const w=(F=M.drawPositions)==null?void 0:F.reduce((W,j)=>A.includes(j)?j:W,void 0),k=(L=M.drawPositions)==null?void 0:L.indexOf(w),_=M.sides[k];return{[w]:_}});if(u!=null&&u.length&&(A==null?void 0:A.length)===(u==null?void 0:u.length)){const M=A.map((F,L)=>[F,u[L]].sort(o)),w=Object.assign({},...C),k=pt(f==null?void 0:f[0].finishingRound,!1,!0),_=pt(f==null?void 0:f[0].finishingPositionRange,!1,!0);r=M.map((F,L)=>{const W=Math.max(...F||[])/2;return{sides:F==null?void 0:F.map(H=>w[H]||{bye:!0,drawPosition:H}),drawId:d,structureId:m,roundPosition:W,drawPositions:F,roundNumber:1,finishingRound:k,matchUpId:Yt(),matchUpStatus:"BYE",sideNumber:L+1,finishingPositionRange:_}}),t=t.concat(...r)}const v=I+T;return ht(1,v+1).forEach(M=>{const w=[],k=O({matchUps:t,roundNumber:M}),F=O({matchUps:t,roundNumber:M-1}).map(h_).filter(Boolean),L=(k==null?void 0:k.length)===(n==null?void 0:n.length),W=(k==null?void 0:k.length)===(n==null?void 0:n.length)/2;M===1&&k.forEach(j=>{const H=j.drawPositions||[],{matchUpId:B,structureId:R}=j,x=[{...j.sides[0],drawPosition:H[0],matchUpId:B,structureId:R},{...j.sides[1],drawPosition:H[1],matchUpId:B,structureId:R}],q={...j,children:x};w.push(q)}),L?(s++,k.forEach((j,H)=>{const B=j.drawPositions||[],{matchUpId:R,structureId:x}=j,q=B.filter(Boolean).reduce((J,Q)=>b.includes(Q)?J:Q,void 0),Y=[{...j.sides.filter(Boolean).reduce((J,Q)=>Q.participantId&&!F.includes(Q.participantId)?Q:J,void 0),drawPosition:q,feedRoundNumber:s,sides:j.sides,matchUpId:R,structureId:x},n[H]],z={...j,children:Y};w.push(z)})):W&&k.forEach((j,H)=>{const B=[n[H*2],n[H*2+1]],R={...j,children:B};w.push(R)}),n=w}),{hierarchy:n[0],missingMatchUps:r,maxRound:I,finalRound:v,matchUps:t};function O({matchUps:M,roundNumber:w}){return M.filter(k=>k.roundNumber===w).sort((k,_)=>k.roundPosition-_.roundPosition)}}function h_(t){if(t.matchUpStatus===re)return t.sides.reduce((e,n)=>n.participantId||e,void 0);if(t.winningSide)return t.sides.reduce((e,n)=>n.sideNumber===t.winningSide?n.participantId:e,void 0)}function YE(t){var s,i;const e=Fh(t);if(e.error)return e;const{structure:n,link:r}=e;return!n||!r?{error:tt}:Lh({tournamentId:(s=t.tournamentRecord)==null?void 0:s.tournamentId,eventId:((i=t.event)==null?void 0:i.eventId)||t.eventId,drawDefinition:t.drawDefinition,structure:n,link:r})}function zE(t){return KE(t)}function KE({matchUpModifications:t,tournamentRecord:e,drawDefinition:n,structures:r,links:s=[],event:i}){var g,I,S;if(!n)return{error:lt};if(!Array.isArray(r)||!Array.isArray(s))return G({result:{error:tt}});const o="attachStructures",c=T=>{var E;return[T.source.structureId,T.source.roundNumber||((E=T.source.finishingPositions)==null?void 0:E.join("|")),T.target.roundNumber].join("|")},a=(g=n.links)==null?void 0:g.map(c);if(s.some(T=>{const E=c(T);return a==null?void 0:a.includes(E)}))return G({result:{error:Lv},info:"playoff structure exists",stack:o});s.length&&((I=n.links)==null||I.push(...s));const l=r.map(({structureId:T})=>T),f=(S=n.structures)==null?void 0:S.map(({structureId:T})=>T);n.structures=(n.structures||[]).map(T=>l.includes(T.structureId)?r.find(({structureId:E})=>E===T.structureId):T);const p=r==null?void 0:r.filter(({structureId:T})=>!(f!=null&&f.includes(T)));p.length&&n.structures.push(...p),Ic({drawDefinition:n});const h=r.map(T=>{var E;return((E=Qt({structure:T}))==null?void 0:E.matchUps)||[]}).flat();Oi({tournamentId:e==null?void 0:e.tournamentId,eventId:i==null?void 0:i.eventId,drawDefinition:n,matchUps:h});const d=r.map(({structureId:T})=>T);if(Zt({drawDefinition:n,structureIds:d}),t!=null&&t.length){const T={};t.forEach(y=>{var N;const b=(N=y.matchUp)==null?void 0:N.matchUpId;b&&(T[b]=y)});const E=y=>{y.matchUps.forEach(b=>{if(T[b.matchUpId]){const{tieMatchUps:N,...A}=T[b.matchUpId].matchUp;if(Object.assign(b,A),N!=null&&N.length){const C={};N.forEach(v=>T[v.matchUpId]=v),b.tieMatchUps.forEach(v=>Object.assign(v,C[v.matchUpId]))}T[b.matchUpId].matchUp=b,qt(T[b.matchUpId])}})};n.structures.forEach(y=>{if(f!=null&&f.includes(y.structureId))if(y.structures)for(const b of y.structures)E(b);else E(y)})}const m=p.map(kn("structureId"));return{...$,addedStructureIds:m}}function hd(t){var o,c;const{structures:e,links:n,matchUpModifications:r,error:s}=_h(t);if(s)return{error:s};const i=t.drawDefinition;return zE({tournamentId:(o=t.tournamentRecord)==null?void 0:o.tournamentId,eventId:((c=t.event)==null?void 0:c.eventId)||t.eventId,matchUpModifications:r,drawDefinition:i,structures:e,links:n})}function JE({tournamentRecord:t,matchUpIds:e=[],drawDefinition:n,structureId:r,event:s}){var f;if(typeof n!="object")return{error:lt};if(typeof r!="string")return{error:En};if(!Array.isArray(e))return{error:tt};const i=(f=n.structures)==null?void 0:f.find(p=>p.structureId===r);if(!i)return{error:Te};const o=i==null?void 0:i.matchUps,c=o==null?void 0:o.find(p=>!!p.roundPosition);if(i.structures||c||i.finishingPosition===fo)return{error:Go};const a=[],l=((o==null?void 0:o.filter(({matchUpId:p,score:h})=>(Be({score:h})&&a.push(p),e.includes(p))))??[]).map(kn("matchUpId"));if(l.length){i.matchUps=(i.matchUps??[]).filter(({matchUpId:d})=>!l.includes(d)),ei({tournamentId:t==null?void 0:t.tournamentId,matchUpIds:l,action:"deleteAdHocMatchUps",eventId:s==null?void 0:s.eventId,drawDefinition:n});const p=Vt(i.matchUps.map(kn("roundNumber"))),h=O1(p);if(h.length){h.reverse();for(const d of h)i.matchUps.forEach(m=>{m.roundNumber&&m.roundNumber>d&&(m.roundNumber-=1,qt({tournamentId:t==null?void 0:t.tournamentId,context:["adHoc round deletion"],eventId:s==null?void 0:s.eventId,drawDefinition:n,matchUp:m}))})}if(a.length){i.positionAssignments=Vt(i.matchUps.flatMap(g=>(g.sides??[]).map(I=>I.participantId)).filter(Boolean)).map(g=>({participantId:g}));const d=(i==null?void 0:i.matchUpFormat)??(n==null?void 0:n.matchUpFormat)??(s==null?void 0:s.matchUpFormat),m=Jf({positionAssignments:i.positionAssignments,matchUps:i.matchUps,tournamentRecord:t,drawDefinition:n,matchUpFormat:d,event:s});m.error&&console.log(m)}Zt({structureIds:[r],eventId:s==null?void 0:s.eventId,drawDefinition:n})}return{...$}}function QE({drawDefinition:t,orderMap:e}){return t?((typeof e!="object"||!Object.values(e).every(n=>oe(n)))&&G({result:{error:tt},context:{orderMap:e}}),t.structures||(t.structures=[]),t.structures.forEach(n=>{const r=e[n.structureId];r&&(n.structureOrder=r)}),t.structures.sort((n,r)=>jo(n.structureOrder)-jo(r.structureOrder)),{...$}):{error:lt}}function ZE({drawDefinition:t,structureDetails:e}){if(!or(e))return{error:tt};if(!t)return{error:lt};const n=Object.assign({},...e.map(s=>{if(!or(s))return;const{structureId:i,structureName:o}=s||{};if(!(!i||!o))return{[i]:o}}).filter(Boolean));if(!Object.values(n).length)return{error:Tt};let r=0;for(const s of t.structures||[]){const i=n[s.structureId];i&&(s.structureName=i,r+=1)}return{...$,modificationsApplied:r}}function XE({tournamentRecord:t,drawDefinition:e,structureId:n,event:r}){var m;if(typeof n!="string")return{error:tt};if(!e)return{error:lt};if(!n)return{error:En};const s=e.structures||[],i=[],o=s.find(({stage:g,stageSequence:I})=>g===It&&I===1),c=n===o.structureId,a=s.find(({stage:g})=>g===Pt);if(c&&!a)return{error:M1};const u=[],l=[n],f=g=>{var I;return(I=e.links)==null?void 0:I.map(S=>S.source.structureId===g&&S.target.structureId!==o.structureId&&S.target.structureId).filter(Boolean)},p=s.map(({structureId:g})=>g),h=Object.assign({},...p.map(g=>({[g]:f(g)})));for(;l.length;){const g=l.pop(),{structure:I}=Ot({structureId:g,drawDefinition:e}),{matchUps:S}=Qt({structure:I}),T=Xf(S);u.push(...T),e.links=((m=e.links)==null?void 0:m.filter(y=>y.source.structureId!==g&&y.target.structureId!==g))||[],(!c||g!==n)&&(e.structures=(e.structures??[]).filter(y=>(g&&g===y.structureId&&i.push(g),y.structureId!==g)));const E=g&&h[g].filter(y=>y!==o.structureId||n===o.structureId);E!=null&&E.length&&l.push(...E)}const{matchUps:d}=xe({drawDefinition:e});return d==null||d.forEach(g=>{g.winnerMatchUpId&&u.includes(g.winnerMatchUpId)&&delete g.winnerMatchUpId,g.loserMatchUpId&&u.includes(g.loserMatchUpId)&&delete g.loserMatchUpId}),c&&(o.positionAssignments=[],o.seedAssignments=[],o.matchUps=[],o.extensions&&(o.extensions=[])),ei({tournamentId:t==null?void 0:t.tournamentId,matchUpIds:u,action:"removeStructure",eventId:r==null?void 0:r.eventId,drawDefinition:e}),Zt({drawDefinition:e,eventId:r==null?void 0:r.eventId}),{...$,removedMatchUpIds:u,removedStructureIds:i}}function md({participantIdPairings:t,addToStructure:e=!0,tournamentRecord:n,matchUpIds:r=[],drawDefinition:s,matchUpsCount:i,roundNumber:o,structureId:c,newRound:a}){var m,g,I,S,T,E;if(typeof s!="object")return{error:lt};if(!c&&((m=s.structures)==null?void 0:m.length)===1&&(c=(I=(g=s.structures)==null?void 0:g[0])==null?void 0:I.structureId),typeof c!="string")return{error:En};const u=(S=s.structures)==null?void 0:S.find(y=>y.structureId===c);if(!u)return{error:Te};if(!i){const y=((T=s==null?void 0:s.entries)==null?void 0:T.filter(N=>{const A=N.entryStatus;return ps.includes(A)}))??[],b=Math.floor((y==null?void 0:y.length)/2)||1;if(a)i=b;else{const N=b-(((E=u.matchUps)==null?void 0:E.length)||0);N>0&&(i=N)}}if(t&&!Array.isArray(t)||i&&!oe(i)||r&&!Array.isArray(r)||!t&&!i)return{error:tt,info:"matchUpsCount or pairings error"};let l;const f=u.matchUps??[],p=f==null?void 0:f.reduce((y,b)=>(b.roundPosition&&(l=!0),((b==null?void 0:b.roundNumber)||0)>y?b.roundNumber:y),0);if(u.structures||l||u.finishingPosition===fo)return{error:Go};if(o&&o-1>(p||0))return{error:tt,info:"roundNumber error"};const h=o??(a&&(p??0)+1||p||1);t=t??ht(0,i).map(()=>({participantIds:[void 0,void 0]}));const d=t==null?void 0:t.map(y=>{const b=(y==null?void 0:y.participantIds)??[void 0,void 0];b.push(void 0,void 0);const A=b.slice(0,2).map((C,v)=>bt({sideNumber:v+1,participantId:C}));return{matchUpStatus:pe.ToBePlayed,matchUpId:r.pop()??Yt(),roundNumber:h,sides:A}});if(e){const y=Rh({tournamentRecord:n,drawDefinition:s,structureId:c,matchUps:d});if(y.error)return y}return{matchUpsCount:d.length,matchUps:d,...$}}function Rh({tournamentRecord:t,drawDefinition:e,structureId:n,matchUps:r}){var u,l,f,p,h,d;if(typeof e!="object")return{error:lt};if(!n&&((u=e.structures)==null?void 0:u.length)===1&&(n=(f=(l=e.structures)==null?void 0:l[0])==null?void 0:f.structureId),typeof n!="string")return{error:En};if(!cr(r))return{error:tt,info:sn("matchUps")};const s=(p=e.structures)==null?void 0:p.find(m=>m.structureId===n);if(!s)return{error:Te};const o=(s==null?void 0:s.matchUps).find(m=>!!m.roundPosition);if(s.structures||o||s.finishingPosition===fo)return{error:Go};const c=((d=(h=He({tournamentRecord:t,inContext:!1}))==null?void 0:h.matchUps)==null?void 0:d.map(Qe))??[],a=r.map(Qe);return tn(c,a)?{error:Fv,info:"One or more matchUpIds already present in tournamentRecord"}:(s.matchUps.push(...r),Oi({tournamentId:t==null?void 0:t.tournamentId,drawDefinition:e,matchUps:r}),Zt({drawDefinition:e,structureIds:[n]}),{...$})}const m_={generateAndPopulatePlayoffStructures:_h,attachPlayoffStructures:zE,addPlayoffStructures:hd,setStructureOrder:QE,renameStructures:ZE,generateQualifyingStructure:Fh,attachQualifyingStructure:Lh,addQualifyingStructure:YE,getAvailablePlayoffRounds:ou,getAvailablePlayoffProfiles:ou,getSourceRounds:Oh,getDrawStructures:lr,getPositionsPlayedOff:ld,getQualifiersCount:Li,removeStructure:XE,generateAdHocMatchUps:md,deleteAdHocMatchUps:JE,addAdHocMatchUps:Rh,addVoluntaryConsolationStage:HE,addVoluntaryConsolationStructure:Ch,generateVoluntaryConsolation:qE,buildDrawHierarchy:p_,generateDrawTypeAndModifyDrawDefinition:wh,generateDrawStructuresAndLinks:Mh};function Bh({participantsCount:t,participantCount:e}){if(t=t||e,!t)return{error:tt};const n=Vo(t);return n?{drawSize:n}:G({result:{error:tt},stack:"getEliminationDrawSize",context:{participantsCount:t}})}function xh(t){let{drawSizeProgression:e=!1,policyDefinitions:n,drawSize:r}=t||{};const{requireParticipantCount:s=!0,tournamentRecord:i,drawDefinition:o,event:c}=t||{},a="getSeedsCount",u=(t==null?void 0:t.participantsCount)||(t==null?void 0:t.participantCount);if(!n){const g=Zi({tournamentRecord:i,drawDefinition:o,event:c});if(g.error)return G({result:g,stack:a});n=g.policyDefinitions}const l=oe(u);if(u&&!l)return G({result:{error:tt},context:{participantsCount:u},stack:a});if(s&&!l)return G({result:{error:dv},stack:a});if(isNaN(r))if(u)({drawSize:r}=Bh({participantsCount:u}));else return G({result:{error:Eu},stack:a});if((s&&u||r)>r)return{error:lg};const p=n[tc];if(!p)return{error:Z1};const h=p.seedsCountThresholds;return h?(p.drawSizeProgression!==void 0&&(e=p.drawSizeProgression),{seedsCount:h.filter(g=>e?g.drawSize<=r:r===g.drawSize).reduce((g,I)=>u>=I.minimumParticipantCount?I.seedsCount:g,0)}):{error:R1}}function tb({requireParticipantCount:t=!0,enforcePolicyLimits:e=!0,drawSizeProgression:n,participantsCount:r,participantCount:s,appliedPolicies:i,drawDefinition:o,seedingProfile:c,structureId:a,seedsCount:u}){var S,T;r=r??s;const l=Ot({drawDefinition:o,structureId:a});if(l.error)return l;const f=l.structure;if(!f)return{error:Te};const{positionAssignments:p}=ke({structure:f}),h=(p==null?void 0:p.length)||0;if(u>h)return{error:L1};const d=(S=f.structures)==null?void 0:S.length,m=oe(c==null?void 0:c.groupSeedingThreshold)&&c.groupSeedingThreshold,g=(T=$l({roundRobinGroupsCount:d,drawSize:h}))==null?void 0:T.seedGroups,{seedsCount:I}=xh({policyDefinitions:i,requireParticipantCount:t,drawSizeProgression:n,participantsCount:r,drawSize:h});return I&&(i!=null&&i[tc])&&u>I&&e&&(u=I),f.seedLimit=u,f.seedAssignments=ht(1,u+1).map(E=>{const y=g==null?void 0:g.find(A=>A.includes(E)),b=y&&Math.min(...y),N=m&&E>=m?b:E;return{participantId:void 0,seedNumber:E,seedValue:N}}),Zt({drawDefinition:o,structureIds:[a]}),{...$,seedLimit:u}}function g_({positionAssignments:t,participantFactors:e}){if(!e||!t)return{error:Tt};let n=pt(e,!1,!0);const r=t.map(({drawPosition:d})=>d),s=t.filter(d=>!d.participantId&&!d.bye&&!d.qualifier).map(cU);let i,o=!0;for(;o;)({drawPositionResolutions:i,remainingPreferences:o,participantPreferences:n}=I_({participantPreferences:n,drawPositionResolutions:i}));const c=Object.keys(i).map(d=>vt(d));let a=s.filter(d=>!c.includes(d)),u=Object.keys(n);const f=ht(1,((d,m)=>Math.log(m)/Math.log(d))(2,(r==null?void 0:r.length)||0)+1).map(d=>Math.pow(2,d)),p={};for(const d of f){const m=Ge(r,d).filter(S=>tn(S,a)),g={};if(u.forEach(S=>{m.forEach(T=>{const E=T.join("|");tn(T,e[S].preferences)&&(g[E]||(g[E]=[]),g[E].push(S))})}),on(Object.keys(g)).forEach(S=>{const T=g[S].filter(E=>u.includes(E));for(;T.length;){const E=cn(T),y=S.split("|").map(b=>vt(b)).filter(b=>a.includes(vt(b)));if(y.length){const b=cn(y);a=a.filter(A=>A!==b),u=u.filter(A=>A!==E),i[b]=E;const N=S.split("|").length;p[N]||(p[N]=0),p[N]+=1}}}),!a.length)break}const h={chunkResolution:p};return u.length&&(u.forEach(d=>{const m=cn(a);m&&(i[m]=d)}),h.randomAssignment=u.length),{drawPositionResolutions:i,report:h}}function I_({participantPreferences:t,drawPositionResolutions:e={}}){const n=Object.keys(t).reduce((o,c)=>{const u=t[c].preferences[0];return u&&(o[u]||(o[u]=[]),o[u].push(c)),o},{}),r=Math.min(...Object.values(n).filter(o=>o.length).map(o=>o.length)),s=Object.keys(n).filter(o=>n[o].length&&r&&n[o].length===r);s.forEach(o=>{const c=n[o],a=cn(c);e[o]=a,delete t[a]});let i;return Object.values(t).forEach(o=>{o.preferences=o.preferences.filter(c=>{const a=!s.includes(c.toString());return a&&(i=!0),a})}),{drawPositionResolutions:e,remainingPreferences:i,participantPreferences:t}}function $h({drawPositions:t,structure:e}){if([Pt,It].includes(e.stage)&&e.stageSequence===1)return;const{positionAssignments:n}=ee({structure:e}),r=n==null?void 0:n.filter(({drawPosition:s})=>t==null?void 0:t.includes(s));r==null||r.forEach(s=>{ae({element:s,extension:{name:Vu,value:!0}})})}function Vh(t){const{participantIdAttributeName:e="participantId",isQualifierPosition:n,positionActionName:r,tournamentRecord:s,drawDefinition:i,participantId:o,drawPosition:c,structureId:a,event:u}=t,l="positionParticipantAction";if(!i)return{error:lt};let{inContextDrawMatchUps:f,matchUpsMap:p}=t;p||(p=ln({drawDefinition:i}),Object.assign(t,{matchUpsMap:p})),f||({matchUps:f}=xe({inContext:!0,drawDefinition:i,matchUpsMap:p}),Object.assign(t,{inContextDrawMatchUps:f}));const{positionAssignments:h}=ee({drawDefinition:i,structureId:a}),d=h==null?void 0:h.find(T=>T.drawPosition===c);if(d!=null&&d.participantId){const T=d.participantId,E=_r({inContextDrawMatchUps:f,tournamentRecord:s,drawDefinition:i,participantId:o,drawPosition:c,structureId:a,matchUpsMap:p,event:u});return E.success?S({removedParticipantId:T}):G({result:E,stack:l})}const m=Ac({inContextDrawMatchUps:f,tournamentRecord:s,drawDefinition:i,drawPosition:c,structureId:a,matchUpsMap:p,event:u});if(m.error)return G({result:m,stack:l});const g=m.participantId,I=_r({inContextDrawMatchUps:f,isQualifierPosition:n,tournamentRecord:s,drawDefinition:i,participantId:o,drawPosition:c,structureId:a,matchUpsMap:p,event:u});if(!I.success)return G({result:I,stack:l});return S({removedParticipantId:g});function S({removedParticipantId:T}){const{structure:E}=Ot({drawDefinition:i,structureId:a});$h({drawPositions:[c],structure:E});const y={[e]:o,name:r,drawPosition:c,structureId:a};return Ll({drawDefinition:i,positionAction:y}),G({result:{...$,context:{removedParticipantId:T},stack:l}})}}function eb({alternateParticipantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:s}){return Vh({positionActionName:"alternateDrawPositionAssignment",participantIdAttributeName:"alternateParticipantid",participantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:s})}function nb({structurePositionAssignments:t,provisionalPositioning:e,tournamentRecord:n,drawDefinition:r,event:s}){var c;if(!r)return{error:lt};if(!Array.isArray(t))return{error:tt};const i="setPositionAssignments";for(const a of t){const{structureId:u,positionAssignments:l}=a;if(!l)continue;const f=Ot({drawDefinition:r,structureId:u});if(f.error)return f;const p=f.structure;if(!p)return{error:Te};const h=(c=ee({structure:p}).positionAssignments)==null?void 0:c.map(({drawPosition:I})=>I),d=l==null?void 0:l.map(({drawPosition:I})=>I);if(qe(h,d).length!==(h==null?void 0:h.length))return G({result:{error:tt},info:"drawPositions do not match",stack:i});const m=ln({drawDefinition:r}),{matchUps:g}=xe({inContext:!0,drawDefinition:r,matchUpsMap:m});for(const I of l||[]){const{drawPosition:S,participantId:T,bye:E,qualifier:y}=I;if(E){const b=Vn({tournamentRecord:n,drawDefinition:r,drawPosition:S,matchUpsMap:m,structureId:u,structure:p,event:s});if(b!=null&&b.error)return b}else if(y)l.forEach(b=>{b.drawPosition===S&&(b.qualifier=!0,delete b.participantId,delete b.bye)});else if(T){const b=_r({provisionalPositioning:e,inContextDrawMatchUps:g,tournamentRecord:n,drawDefinition:r,participantId:T,drawPosition:S,matchUpsMap:m,structureId:u,event:s});if(b!=null&&b.error)return b}}ni({tournamentId:n==null?void 0:n.tournamentId,drawDefinition:r,structure:p,event:s})}const o=t.map(({structureId:a})=>a);return Zt({tournamentId:n==null?void 0:n.tournamentId,eventId:s==null?void 0:s.eventId,drawDefinition:r,structureIds:o}),{...$}}function gd({drawDefinition:t,stages:e}){return((t==null?void 0:t.structures)||[]).filter(r=>!(e!=null&&e.length)||e.includes(r.stage)).map(r=>{const{positionAssignments:s}=ee({structure:r});return s?s.map(kn("participantId")):[]}).flat()}function pr(t){const e=((t==null?void 0:t.entries)??[]).filter(Boolean).reduce((r,s)=>{const{entryStage:i,entryStatus:o}=s,c=`_${i||It}${o||""}`;return r[c]||(r[c]=[]),r[c].push(s),r},{}),n=r=>isNaN(r)?1/0:r;return Object.keys(e).map(r=>e[r].sort((s,i)=>n(s.entryPosition)-n(i.entryPosition)).map((s,i)=>{const o=i+1;return{...s,entryPosition:o}})).flat()}function Ri(t){return[po,Or].includes(t)}function jh({autoEntryPositions:t=!0,ignoreAssignment:e,tournamentRecord:n,drawDefinition:r,participantIds:s,entryStatus:i,entryStage:o,extension:c,eventSync:a,drawId:u,stage:l,event:f}){var v,P,U,O,D,M,w,k,_,F,L,W;if(!s||!Array.isArray(s))return{error:bs,method:"modifyEntriesStatus",participantIds:s};if(!r&&!f)return{error:Wt};if(i&&!GP.includes(i))return{error:zd};if(o&&!Ff.includes(o))return{error:xs};const p="modifyEntriesStatus",h=[];if(!i&&!c)return G({result:{error:Tt},info:"Missing entryStatus",stack:p});if(c&&!ur({extension:c,requiredAttributes:["name"]}))return G({result:{error:tt},info:"Invalid extension",context:{extension:c},stack:p});const d=[];(v=f==null?void 0:f.drawDefinitions)==null||v.forEach(j=>{const H=gd({stages:l&&[l],drawDefinition:j});d.push(...H)});const m=(n==null?void 0:n.participants)||[];if(!s.every(j=>{var B;const H=(B=Ps({tournamentParticipants:m,participantId:j}))==null?void 0:B.participantType;return!(H&&[jr.Pair,jr.Team].includes(H)&&Ri(i))&&!(i&&(f!=null&&f.eventType)&&H===xt&&[$n,ds].includes(f.eventType)&&[dr,...Gf].includes(i))}))return{error:zd};const I=f&&be({event:f}).flightProfile,S=(P=I==null?void 0:I.flights)==null?void 0:P.find(j=>j.drawId===u),T=j=>{const H=(j||[]).filter(x=>!l||!x.entryStage||l===x.entryStage).filter(({participantId:x})=>s.includes(x)),B=x=>i&&d.includes(x.participantId)&&!(Gf.includes(x.entryStatus)&&Gf.includes(i));return H.every(x=>B(x)&&!e?!1:(i&&(x.entryStatus=i,delete x.entryPosition),o&&(x.entryStage=o,delete x.entryPosition),c&&(c.value?ae({element:x,extension:c}):Ar({element:x,name:c.name})),!0))?{...$}:{error:Yo}},E=({flight:j,drawDefinition:H})=>{f&&(f.entries=pr({entries:f.entries||[]})),j&&(j.drawEntries=pr({entries:j.drawEntries})),H&&(H.entries=pr({entries:H.entries}))},y=j=>{const{flight:H,drawDefinition:B}=j,R="updateDrawEntries";if(H){const x=T(H.drawEntries);if(x.error)return G({result:x,stack:R})}if(B){const x=T(B.entries);if(x.error)return G({result:x,stack:R});h.includes(B.drawId)||h.push(B.drawId)}return{...$}},b=((U=f==null?void 0:f.entries)==null?void 0:U.find(({entryPosition:j})=>j))||((O=S==null?void 0:S.drawEntries)==null?void 0:O.find(({entryPosition:j})=>j))||((D=r==null?void 0:r.entries)==null?void 0:D.find(({entryPosition:j})=>j));if(t&&!b&&E({flight:S,drawDefinition:r}),S||r){const j=y({flight:S,drawDefinition:r});if(j.error)return G({result:j,stack:p})}const N=((M=f==null?void 0:f.drawDefinitions)==null?void 0:M.map(({drawId:j})=>j))||[],A=((w=I==null?void 0:I.flights)==null?void 0:w.filter(j=>!N.includes(j.drawId)))||[];for(const j of A){const H=j&&y({flight:j});if(H!=null&&H.error)return G({result:H,stack:p})}const C=((k=I==null?void 0:I.flights)==null?void 0:k.length)===1&&(((_=f==null?void 0:f.drawDefinitions)==null?void 0:_.length)||0)<=((F=I==null?void 0:I.flights)==null?void 0:F.length);if(!S&&!r&&i&&jP.includes(i))return{error:Iv};if(!S&&!r||i===ti||a&&C){const j=T(f==null?void 0:f.entries);if(j!=null&&j.error)return G({result:j,stack:p});let H;if(i===ti&&((L=I==null?void 0:I.flights)==null||L.every(B=>{const R=T(B.drawEntries);return R.error?(H=R.error,!1):(B.drawEntries=B.drawEntries.filter(({participantId:x})=>!s.includes(x)),!0)}),(W=f==null?void 0:f.drawDefinitions)==null||W.every(B=>{var x;const R=T(B.entries);return R.error?(H=R.error,!1):(B.entries=(x=B.entries)==null?void 0:x.filter(({participantId:q})=>!s.includes(q)),!0)})),H)return G({result:{error:H},stack:p})}t&&E({flight:S,drawDefinition:r});for(const j of(f==null?void 0:f.drawDefinitions)||[])h.length&&!h.includes(j.drawId)||Zt({tournamentId:n.tournamentId,eventId:f==null?void 0:f.eventId,drawDefinition:j});return{...$}}function rb({stage:t,drawDefinition:e}){return!!(t===je||_a({stage:t,drawDefinition:e})&&cu({stage:t,drawDefinition:e}))}function sb({entryStatus:t=Ur,drawDefinition:e,stageSequence:n,stage:r}){if(t===dr)return WP({stage:r,drawDefinition:e})?{positionsAvailable:1/0,...$}:{error:gv};const s=xk({drawDefinition:e,stageSequence:n,stage:r}),i=HP({drawDefinition:e,stage:r}),o=al({entryStatus:lc,drawDefinition:e,stage:r}),c=al({entryStatus:Ur,drawDefinition:e,stage:r}),a=o+c,u=a>=s,l=s-a;return r!==je&&u?{error:fg}:t===lc?o<i?{...$}:{error:fg}:{positionsAvailable:l,...$}}function Gh(t){const{entryStatus:e=un.DirectAcceptance,entryStageSequence:n,entryStage:r=It,ignoreStageSpace:s,drawDefinition:i,entryPosition:o,participant:c,roundTarget:a,extensions:u,extension:l,drawType:f}=t,p="addDrawEntry";if(!i)return{error:lt};if(!r)return{error:Qm};if(f!==Xn&&!rb({stage:r,drawDefinition:i}))return G({result:{error:xs},stack:p});const h=sb({stageSequence:n,stage:r,drawDefinition:i,entryStatus:e});if(!s&&!h.success)return{error:h.error};if(l&&!ur({extension:l}))return G({result:{error:tt},info:"Invalid extension",context:{extension:l},stack:p});const d=t.participantId||(c==null?void 0:c.participantId);if(!d)return G({result:{error:Ce},stack:p});const m=e===un.LuckyLoser&&Mo({participantId:d,drawDefinition:i,entryStatus:e}),g=r===je&&Mo({participantId:d,drawDefinition:i,entryStage:r}),I=e!==un.LuckyLoser&&r!==je&&Mo({drawDefinition:i,participantId:d});if(I||m||g)return G({context:{invalidEntry:I,invalidLuckyLoser:m,invalidVoluntaryConsolation:g},result:{error:Yd},stack:p});const S=bt({entryStageSequence:n,participantId:d,entryPosition:o,entryStatus:e,entryStage:r,extensions:u});return l&&ae({element:S,extension:l}),a&&ae({extension:{name:"roundEntry",value:a},element:S}),i.entries||(i.entries=[]),i.entries.push(S),Zt({drawDefinition:i}),{...$}}function ib(t){const e="addDrawEntries",{entryStatus:n=un.DirectAcceptance,stage:r=As.Main,autoEntryPositions:s=!0,ignoreStageSpace:i,drawDefinition:o,participantIds:c,stageSequence:a,roundTarget:u,extension:l}=t;if(!r)return{error:Qm};if(!o)return{error:lt};if(!Array.isArray(c))return{error:gr};if(!rb({stage:r,drawDefinition:o}))return{error:xs};if(l&&!ur({extension:l}))return G({result:{error:tt},info:"Invalid extension",context:{extension:l},stack:e});const f=sb({drawDefinition:o,stageSequence:a,entryStatus:n,stage:r});if(!i&&!f.success)return{error:f.error};const p=f.positionsAvailable??0;if(!i&&r!==je&&p<c.length)return{error:lg};const h=c.reduce((d,m)=>{const g=n===un.LuckyLoser&&Mo({participantId:m,drawDefinition:o,entryStatus:n}),I=r===je&&Mo({entryStage:r,drawDefinition:o,participantId:m});return n!==un.LuckyLoser&&r!==je&&Mo({drawDefinition:o,participantId:m})||g||I?d.concat(m):d},[]);return c.filter(d=>d&&!h.includes(d)).forEach(d=>{const m={entryStageSequence:a,entryStage:r,participantId:d,entryStatus:n};l&&ae({element:m,extension:l}),u&&ae({extension:{name:Hr,value:u},element:m}),o.entries||(o.entries=[]),o.entries.push(m)}),s&&(o.entries=pr({entries:o.entries})),Zt({drawDefinition:o}),h!=null&&h.length?{info:"some participantIds could not be added",participantIdsNotAdded:h,...$}:{...$}}function ob({autoEntryPositions:t=!0,entryStageSequence:e,ignoreStageSpace:n,drawDefinition:r,participantIds:s,entryStatus:i,roundTarget:o,entryStage:c,extension:a,drawId:u,event:l}){if(!(s!=null&&s.length))return{error:Ns};if(!l)return{error:wn};if(!u)return{error:Hn};const f=(l.entries||[]).map(fe);if(s.filter(m=>!f.includes(m)).length)return{error:q1};if(r){const m=ib({stageSequence:e,autoEntryPositions:t,stage:c,ignoreStageSpace:n,drawDefinition:r,participantIds:s,entryStatus:i,roundTarget:o,extension:a});if(m.error)return m}const{flightProfile:h}=be({event:l}),d=h==null?void 0:h.flights.find(m=>m.drawId===u);return d!=null&&d.drawEntries&&(s.forEach(m=>{const g=i===ka&&Wh({participantId:m,entryStatus:i,flight:d}),I=c===je&&Wh({participantId:m,entryStage:c,flight:d});!(i!==ka&&c!==je&&Wh({flight:d,participantId:m}))&&!g&&!I&&d.drawEntries.push({participantId:m,entryStatus:i,entryStage:c})}),t&&(d.drawEntries=pr({entries:d.drawEntries}))),{...$}}function Wh({participantId:t,entryStatus:e,entryStage:n,flight:r}){var i;const s=(i=r.drawEntries)==null?void 0:i.find(o=>o.participantId===t&&(!e||e===o.entryStatus)&&(!n||n===o.entryStage));return t&&s}function Id({autoEntryPositions:t=!0,tournamentParticipants:e,tournamentRecord:n,participantIds:r,event:s}){var l,f;const i="removeEventEntries";if(!(s!=null&&s.eventId))return{error:Wt};if(!Array.isArray(r))return G({result:{error:Ns},stack:i});if(r=r==null?void 0:r.filter(Boolean),!(r!=null&&r.length))return G({result:{error:Ns},stack:i});const{eventId:o}=s;if(e||(e=dn({participantFilters:{participantIds:r},tournamentRecord:n,withEvents:!0,withDraws:!0}).tournamentParticipants),e==null?void 0:e.every(p=>{const h=p.events.find(m=>m.eventId===o),d=(h==null?void 0:h.drawIds)||[];return p.draws.filter(m=>d.includes(m.drawId)&&m.positionAssignments).length}))return G({result:{error:Yo},stack:i});const a=[];s.entries=(s.entries||[]).filter(p=>{const h=!r.includes(p==null?void 0:p.participantId);return h||a.push(p.participantId),h}),t&&(s.entries=pr({entries:s.entries}));const{flightProfile:u}=be({event:s});return(l=u==null?void 0:u.flights)==null||l.forEach(p=>{p.drawEntries=(p.drawEntries||[]).filter(h=>!r.includes(h.participantId))}),(f=s.drawDefinitions)==null||f.forEach(p=>{p.entries=(p.entries||[]).filter(h=>!r.includes(h.participantId))}),{...$,participantIdsRemoved:a}}function Fs(t){var v;const{entryStatus:e=Ur,autoEntryPositions:n=!0,participantIds:r=[],entryStageSequence:s,ignoreEventGender:i,entryStage:o=It,tournamentRecord:c,ignoreStageSpace:a,drawDefinition:u,roundTarget:l,extensions:f,extension:p,drawId:h,event:d}=t,m="addEventEntries";if(!d)return{error:Wt};if(!(r!=null&&r.length))return G({result:{error:Ns},stack:m});if(!(d!=null&&d.eventId))return{error:wn};const g=[],I=[];if(f&&(!Array.isArray(f)||!f.every(ur))||p&&!ur({extension:p}))return G({result:{error:tt},context:bt({extension:p,extensions:f}),info:"Invalid extension(s)",stack:m});const S=!!c,T=[];let E;const y=((v=c==null?void 0:c.participants)==null?void 0:v.filter(P=>{var D,M,w;if(!r.includes(P.participantId))return!1;const U=d.eventType===Oe&&P.participantType===xt&&!Ri(e),O=d.eventType===me&&P.participantType===_t;return U&&(!d.gender||i||[hs,Io].includes(d.gender)||d.gender===((D=P.person)==null?void 0:D.sex))||O&&!Ri(e)||d.eventType===me&&P.participantType===xt&&Ri(e)?!0:U&&d.gender&&!i&&![hs,Io].includes(d.gender)&&d.gender!==((M=P.person)==null?void 0:M.sex)?(T.push({participantId:P.participantId,sex:(w=P.person)==null?void 0:w.sex}),!1):d.eventType===se&&(P.participantType===se||Ri(e)&&P.participantType===xt)}).map(P=>P.participantId))||[],b=r.filter(P=>!S||y.includes(P));d.entries||(d.entries=[]);const N=d.entries.map(P=>{var U;return P.participantId||((U=P.participant)==null?void 0:U.participantId)});if(b.forEach(P=>{if(!N.includes(P)){const U=bt({participantId:P,entryStatus:e,entryStage:o,extensions:f});p&&ae({element:U,extension:p}),l&&ae({extension:{name:Hr,value:l},element:U}),s&&(U.entryStageSequence=s),g.push(U.participantId),d.entries.push(U)}}),h&&!Ri(o)){const P=ob({participantIds:b,autoEntryPositions:n,entryStageSequence:s,ignoreStageSpace:a,drawDefinition:u,entryStatus:e,roundTarget:l,entryStage:o,extension:p,drawId:h,event:d});P.error&&(E=P.error)}if([me,se].includes(d.eventType)){const P=(d.entries||[]).map(w=>w.participantId),U=(d.entries||[]).filter(w=>Ri(w.entryStatus)).map(w=>w.participantId),D=((c==null?void 0:c.participants)||[]).filter(w=>P.includes(w.participantId)&&[_t,se].includes(w.participantType)).map(w=>w.individualParticipantIds).flat(1/0),M=U.filter(w=>D.includes(w));M.length&&(I.push(...M),Id({participantIds:M,autoEntryPositions:!1,tournamentRecord:c,event:d}))}if(b.length!==r.length)return G({result:{error:gr},context:{misMatchedGender:T,gender:d.gender},stack:m});n&&(d.entries=pr({entries:d.entries||[]}));const C=g.length-I.length;return G({result:{...$,addedEntriesCount:C},stack:m,info:E})}function cb({addIndividualParticipantsToEvents:t,individualParticipantIds:e,groupingParticipantId:n,tournamentRecord:r,suppressErrors:s}){const i="removeIndividualParticipantIds";if(!r)return G({result:{error:et},stack:i});if(!n||!e)return G({result:{error:Tt},stack:i});const c=(r.participants||[]).find(f=>f.participantId===n);if(!c)return G({result:{error:_e},stack:i});if(![se,Fn].includes(c.participantType))return G({result:{participantType:c.participantType,error:xr},stack:i});const a=ab({individualParticipantIds:e,groupingParticipant:c,tournamentRecord:r,suppressErrors:s}),{removed:u,error:l}=a;if(l)return G({result:a,stack:i});if(t)for(const f of r.events||[]){const p=(f.entries||[]).map(({participantId:h})=>h).filter(Boolean);if(p.includes(n)){const h=u==null?void 0:u.filter(d=>!p.includes(d));Fs({participantIds:h,entryStatus:Or,tournamentRecord:r,event:f})}}return u&&Ht({topic:nn,payload:{tournamentId:r.tournamentId,participants:[c]}}),{...$,...a}}function ab({individualParticipantIds:t=[],groupingParticipant:e,tournamentRecord:n,suppressErrors:r,mappedMatchUps:s,participants:i}){var h;const o=[];if(!e)return{removed:o};const c=[],a=[];i||({participants:i,mappedMatchUps:s}=Fi({withMatchUps:!0,tournamentRecord:n,withEvents:!0}));const u=i==null?void 0:i.find(({participantId:d})=>d===e.participantId),l=(h=u==null?void 0:u.events)==null?void 0:h.map(({eventId:d})=>d),f=(e.individualParticipantIds||[]).filter(d=>{var S;const m=t==null?void 0:t.includes(d),g=m&&((S=i==null?void 0:i.find(T=>T.participantId===d))==null?void 0:S.matchUps.filter(({eventId:T})=>l.includes(T)).map(({matchUpId:T})=>s==null?void 0:s[T]).filter(({winningSide:T,score:E})=>T||Be({score:E}))),I=m&&!(g!=null&&g.length);if(m&&!I&&a.push(d),I){o.push(d);for(const T of n.events||[])for(const E of T.drawDefinitions||[]){const{extension:y}=Ke({element:E,name:Wr});let b=y==null?void 0:y.value[e.participantId];y&&b&&(b=b.filter(A=>A.participantId!==d),ae({element:E,extension:y}),Ba({drawDefinition:E}));const N=tr({drawDefinition:E,inContext:!1}).matchUps||[];for(const A of N){const C=A.sides||[];for(const v of C){const P=v.lineUp||[];P.find(O=>O.participantId===d)&&(v.lineUp=P.filter(O=>O.participantId!==d),qt({tournamentId:n==null?void 0:n.tournamentId,drawDefinition:E,matchUp:A}))}}}}else c.push(d);return!I});e.individualParticipantIds=f;const p={groupingParticipantId:e.participantId,cannotRemove:a,notRemoved:c,removed:o};return a.length&&!r&&{...p,cannotRemove:a,error:qd}||p}function Hh({participantRole:t=Rg.Competitor,individualParticipantIds:e=[],groupingTypes:n=[jr.Team,jr.Group],tournamentRecord:r}){if(!r)return{error:et};const s=r.participants||[],{participants:i,mappedMatchUps:o}=Fi({withMatchUps:!0,tournamentRecord:r,withEvents:!0});let c=0;return s.filter(a=>(a.participantRole===t||!a.participantRole)&&a.participantType&&n.includes(a.participantType)).forEach(a=>{const{removed:u}=ab({groupingParticipant:a,individualParticipantIds:e,tournamentRecord:r,mappedMatchUps:o,participants:i});u&&c++}),c?$:{error:lv}}function Fc(t){var h,d,m;if(!(t!=null&&t.tournamentRecord))return{error:et};if(!((h=t==null?void 0:t.participantIds)!=null&&h.length))return{error:Ns};const{addIndividualParticipantsToEvents:e,tournamentRecord:n,participantIds:r}=t,s=((d=n.participants)==null?void 0:d.length)||0;if(!s)return{...$};const i=(m=n.events||[])==null?void 0:m.filter(({eventType:g})=>g===we).map(g=>{var I;return(I=g==null?void 0:g.drawDefinitions)==null?void 0:I.map(({drawId:S})=>S)}).flat(1/0),{tournamentParticipants:o}=dn({participantFilters:{participantIds:r},tournamentRecord:n,withDraws:!0}),c=()=>{const I=(He({matchUpFilters:{drawIds:i,matchUpTypes:[me]},tournamentRecord:n}).matchUps||[]).map(({sides:S})=>S==null?void 0:S.map(({participantId:T})=>T)).flat().filter(Boolean);return qe(I,r)},a=(i==null?void 0:i.length)&&c(),u=o.filter(g=>{var I;return(I=g.draws)==null?void 0:I.filter(S=>(!(i!=null&&i.length)||!(i!=null&&i.includes(S.drawId)))&&S.positionAssignments).length});if(a!=null&&a.length||u.length)return{error:Yo};const l={},f={};for(const g of n.events||[]){const I=Id({tournamentParticipants:o,tournamentRecord:n,participantIds:r,event:g});if(I.error)return I;l[g.eventId]=I.participantIdsRemoved}n.participants=n.participants.filter(g=>{const I=r.includes(g.participantId)||g.participantType===_t&&g.individualParticipantIds.some(S=>r.includes(S));if(!I&&g.participantType===we&&g.individualParticipantIds.some(S=>r.includes(S))&&(g.individualParticipantIds=g.individualParticipantIds.filter(S=>!r.includes(S))),I&&e&&[_t,se].includes(g.participantType))for(const S of g.individualParticipantIds||[])r.includes(S)||(f[g.participantId]||(f[g.participantId]=[]),f[g.participantId].push(S));return!I});const p=s-n.participants.length;if(Hh({individualParticipantIds:r,tournamentRecord:n}),e)for(const g of n.events||[]){const S=l[g.eventId].map(T=>f[T]||[]).flat();Fs({participantIds:S,entryStatus:Or,tournamentRecord:n,event:g})}return p&&Ht({payload:{participantIds:r,tournamentId:n.tournamentId},topic:NI}),p?{...$,participantsRemovedCount:p}:{error:qd}}function ub({selected:t=!0,drawDefinition:e,entryStatuses:n,drawId:r,event:s,stage:i}){var a;let o=s.entries??[];if(r){const{flightProfile:u}=be({event:s}),l=(a=u==null?void 0:u.flights)==null?void 0:a.find(f=>f.drawId===r);l?o=l.drawEntries:e.entries&&(o=e==null?void 0:e.entries)}const c=o.filter(u=>(!(n!=null&&n.length)||!u.entryStatus||n.includes(u.entryStatus))&&(!i||!u.entryStage||u.entryStage===i)&&(!t||u.entryStatus&&ps.includes(u.entryStatus)));return{entries:o,stageEntries:c}}function lb({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:n,participantId:r,drawId:s,stage:i,event:o}){var S;const c="destroyGroupEntry";if(!e)return{error:et};if(!r)return G({result:{error:Ce},stack:c});if(!o)return{error:Wt};if(!o.eventType||![_n.Doubles,_n.Team].includes(o.eventType))return G({result:{error:ui},stack:c});const a=e.participants||[],u=a.find(T=>T.participantId===r);if(!u)return G({result:{error:_e},stack:c});if(!u.participantType||![jr.Pair,jr.Team].includes(u.participantType)||u.participantType===we&&o.eventType!==we||u.participantType===_t&&o.eventType!==$n)return{error:xr};const f=(o.entries||[]).find(T=>T.participantId===r);if(!f)return{error:dg};const{stageEntries:p}=ub({selected:!1,drawDefinition:n,drawId:s,event:o,stage:i}),h=p.map(fe),d=a.filter(({participantId:T})=>h.includes(T)).map(({individualParticipantIds:T})=>T).flat().filter(Boolean),m=(S=u.individualParticipantIds)==null?void 0:S.filter(T=>Br(T,d).length===1);let g=Id({participantIds:[r],tournamentRecord:e,event:o});if(g.error||m!=null&&m.length&&(g=Fs({participantIds:m,entryStatus:Or,entryStage:f.entryStage,tournamentRecord:e,drawDefinition:n,drawId:s,event:o}),g.error))return g;let I;return t&&Fc({participantIds:[r],tournamentRecord:e}).success&&(I=!0),{...$,participantRemoved:I}}function db({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:n,participantId:r,drawId:s,event:i}){return lb({removeGroupParticipant:t,tournamentRecord:e,drawDefinition:n,participantId:r,drawId:s,event:i})}function S_(t){if(!t.tournamentRecord)return{error:et};const{participantIds:e,...n}=t;let r=0;const s=[];for(const i of e){const o=lb({participantId:i,...n});o.success&&(r+=1),o.error&&s.push(o.error)}return r?{destroyedCount:r,...$}:{error:s}}function Sd(t){const{tournamentRecord:e,replaceWithBye:n,drawDefinition:r,destroyPair:s,entryStatus:i,matchUpsMap:o,drawId:c}=t,a="removeDrawPositionAssignment",u=Ac(t);if(u.error)return G({result:u,stack:a});const{participantId:l}=u,{drawPosition:f,event:p,structureId:h}=t;if([dr,ti].includes(i)&&l){const{tournamentRecord:g}=t,{participant:I}=zs({tournamentRecord:g,participantId:l}),{participantType:S,individualParticipantIds:T}=I||{};if(s&&S===_t){const E=db({tournamentRecord:g,drawDefinition:r,participantId:l,event:p});if(E.error)return G({result:E,stack:a});T&&jh({participantIds:T,tournamentRecord:g,drawDefinition:r,entryStatus:i,drawId:c,event:p})}else jh({participantIds:[l],tournamentRecord:g,drawDefinition:r,entryStatus:i,drawId:c,event:p})}if(n){const g=Vn({tournamentRecord:e,drawDefinition:r,drawPosition:f,structureId:h,matchUpsMap:o,event:p});if(g.error)return G({result:g,stack:a})}const{structure:d}=Ot({drawDefinition:r,structureId:h});return $h({structure:d,drawPositions:[f]}),Ll({drawDefinition:r,positionAction:{name:"removeDrawPositionAssignment",replaceWithBye:n,drawPosition:f,entryStatus:i,structureId:h}}),u}function fb({tournamentRecord:t,drawDefinition:e,drawPositions:n,structureId:r,event:s}){if(!e)return{error:lt};if(!r)return{error:En};if((n==null?void 0:n.length)!==2)return{error:tt,drawPositions:n};const i=ln({drawDefinition:e}),{matchUps:o}=xe({inContext:!0,drawDefinition:e,matchUpsMap:i}),{structure:c}=Ot({drawDefinition:e,structureId:r});if(!c)return{error:Te};let a;if(c.structureType===mn?a=E_({inContextDrawMatchUps:o,tournamentRecord:t,drawDefinition:e,drawPositions:n,matchUpsMap:i,structure:c,event:s}):a=T_({inContextDrawMatchUps:o,tournamentRecord:t,drawDefinition:e,drawPositions:n,matchUpsMap:i,structure:c,event:s}),a.error)return a;if($h({structure:c,drawPositions:n}),Ll({drawDefinition:e,positionAction:{name:"swapDrawPositionAssignments",drawPositions:n,structureId:r}}),ni({tournamentId:t==null?void 0:t.tournamentId,drawDefinition:e,structure:c,event:s}),s.eventType===ds){const l=Qt({matchUpFilters:{matchUpTypes:[yr]},inContext:!0,structure:c}).matchUps.filter(p=>{var h;return(h=p.drawPositions)==null?void 0:h.some(d=>n.includes(d))}),f=Qt({structure:c,matchUpFilters:{matchUpTypes:[yr]}}).matchUps;l.forEach(p=>{(p.sides||[]).forEach(h=>{var m;const d=h==null?void 0:h.drawPosition;if(n.includes(d)){const g=h.participantId,I=f.find(({matchUpId:T})=>T===p.matchUpId),S=(m=p==null?void 0:p.sides)==null?void 0:m.reduce((T,E,y)=>E.drawPosition===d?y:T,void 0);Fp({inContextTargetMatchUp:p,drawPositionSideIndex:S,teamParticipantId:g,tournamentRecord:t,drawDefinition:e,matchUp:I,event:s})}})})}return Zt({drawDefinition:e,structureIds:[r]}),{...$}}function T_({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,drawPositions:r,matchUpsMap:s,structure:i,event:o}){const c=i==null?void 0:i.positionAssignments.filter(l=>r==null?void 0:r.includes(l.drawPosition));if(!c)return{error:tt,structure:i,info:"Missing positionAssignments"};if(c.filter(({bye:l})=>l).length===2)return{...$};if(c.filter(({qualifier:l})=>l).length===2)return{...$};const a=c.some(({qualifier:l})=>l);return c.some(({bye:l})=>l)&&!a?pb({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,assignments:c,matchUpsMap:s,structure:i,event:o}):y_({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,assignments:c,matchUpsMap:s,structure:i,event:o})}function pb({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,assignments:r,matchUpsMap:s,structure:i,event:o}){const c=r.find(({bye:d})=>d),a=r.find(({participantId:d})=>d),u=c.drawPosition,{participantId:l,drawPosition:f}=a,{structureId:p}=i;let h=Sd({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,structureId:p,matchUpsMap:s});return h.error||(h=Sd({drawPosition:f,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,structureId:p,matchUpsMap:s}),h.error)||(Vn({drawPosition:f,tournamentRecord:e,drawDefinition:n,structureId:p,matchUpsMap:s,event:o}),h=_r({drawPosition:u,inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,structureId:p,participantId:l,matchUpsMap:s,event:o}),h.error)?h:{...$}}function y_({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,assignments:r,matchUpsMap:s,structure:i,event:o}){const c=Object.assign({},...r.map((a,u)=>{const{drawPosition:l}=a,f={...r[1-u],drawPosition:l};return{[l]:f}}));return i.positionAssignments=i.positionAssignments.map(a=>c[a.drawPosition]||a),$p({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,matchUpsMap:s,assignments:r,structure:i,event:o}),{...$}}function E_({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,drawPositions:r,matchUpsMap:s,structure:i,event:o}){var l;const c=(l=i.structures)==null?void 0:l.reduce((f,p)=>{const h=p==null?void 0:p.positionAssignments.filter(d=>r==null?void 0:r.includes(d.drawPosition));return h&&f.push(...h),f},[]);if(c.filter(({bye:f})=>f).length===2)return{...$};if(c.filter(({qualifier:f})=>f).length===2)return{...$};$p({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,matchUpsMap:s,assignments:c,structure:i,event:o});const a=c.some(({qualifier:f})=>f);if(c.some(({bye:f})=>f)&&!a)pb({inContextDrawMatchUps:t,tournamentRecord:e,drawDefinition:n,assignments:c,matchUpsMap:s,structure:i,event:o});else{const f=pt(c,!1,!0);c.forEach((p,h)=>{const d=f[1-h].participantId;p.qualifier=f[1-h].qualifier,p.participantId=d})}return{...$}}function hb({inheritance:t=!0,tournamentRecord:e,drawDefinition:n,matchUpId:r,event:s}){var a,u;if(!n)return{error:lt};const i=(a=ie({drawDefinition:n,matchUpId:r}))==null?void 0:a.matchUp;if(!(i!=null&&i.tieMatchUps))return{error:qn};const o=(u=ie({inContext:!0,drawDefinition:n,matchUpId:r,event:s}))==null?void 0:u.matchUp;let c=0;return((i==null?void 0:i.sides)||[]).forEach(l=>{l.lineUp&&delete l.lineUp}),((o==null?void 0:o.sides)||[]).forEach(l=>{if(c+=1,t===!1){const f=o==null?void 0:o.tieFormat,p=l.participantId;f&&p&&Uc({drawDefinition:n,participantId:p,lineUp:[],tieFormat:f})}qt({tournamentId:e==null?void 0:e.tournamentId,context:"resetMatchUpLineUps",eventId:s==null?void 0:s.eventId,drawDefinition:n,matchUp:i})}),{...$,modificationsCount:c}}function mb({tournamentRecord:t,drawDefinition:e,drawPosition:n,structureId:r,subOrder:s,event:i}){var m;if(!e)return{error:lt};if(!r)return{error:En};if(!n)return{error:Wc};const{structure:o}=Ot({drawDefinition:e,structureId:r});if(!o)return{error:Te};let c=o;o.structures&&o.structureType===mn&&(c=(m=o.structures)==null?void 0:m.find(g=>{var I;return(I=g.positionAssignments)==null?void 0:I.find(S=>S.drawPosition===n)}));const a=c==null?void 0:c.positionAssignments,u=a==null?void 0:a.find(g=>g.drawPosition===n);u&&ae({element:u,extension:{name:rc,value:s}});const p=((i==null?void 0:i.eventType)===Jt||e.matchUpType===Jt||(i==null?void 0:i.tieFormat)||(e==null?void 0:e.tieFormat)||(o==null?void 0:o.tieFormat))&&{matchUpTypes:[Jt]},{matchUps:h}=Qt({structure:c,afterRecoveryTimes:!1,inContext:!0,matchUpFilters:p,event:i}),d=(o==null?void 0:o.matchUpFormat)||e.matchUpFormat;return Jf({positionAssignments:a,tournamentRecord:t,drawDefinition:e,matchUpFormat:d,matchUps:h,event:i}),Zt({drawDefinition:e,structureIds:[r]}),{...$}}const b_={setSubOrder:mb,clearDrawPosition:Ac,assignDrawPosition:_r,setPositionAssignments:nb,automatedPositioning:lu,assignDrawPositionBye:Vn,swapDrawPositionAssignments:fb,alternateDrawPositionAssignment:eb,resolveDrawPositions:g_,resetMatchUpLineUps:hb,initializeStructureSeedAssignments:tb,getNextSeedBlock:jl};function gb({drawDefinition:t,event:e,matchUpId:n}){if(!t)return{error:lt};if(!n)return{error:$e};const{matchUp:r}=ie({drawDefinition:t,event:e,matchUpId:n});return r?Ar({element:r,name:$u}):{error:Ye}}function N_(t,e){return(t||"").localeCompare(e||"")}function A_({maxIterations:t=4e3,valueSortedPairings:e,pairingValues:n,valueObjects:r,deltaObjects:s}){const i=Object.assign({},...e.map(S=>({[S.pairing]:S.value}))),o=Object.keys(n);let c=[];const a=Ib({actorsCount:o.length,valueSortedPairings:e,pairingValueMap:i,deltaObjects:s,valueObjects:r}),u=[qh(a)];c.push(a);let l=a.value,f=a,p=0,h=0,d=o.length,m;do d-=1,m=o.length*n[o[0]].length;while(m>t&&d>5);const g=[];o.forEach(S=>{n[S].slice(0,d).forEach(E=>{h+=1;const y=_o(S,E.opponent);if(!g.includes(y)){const b=Ib({stipulated:[[S,E.opponent]],actorsCount:o.length,valueSortedPairings:e,pairingValueMap:i,deltaObjects:s,valueObjects:r});if(!u.includes(qh(b))){u.push(qh(b)),c.push(b);const{maxDelta:N,value:A}=b;N<f.maxDelta&&(f=b),(A<l||A===l&&Math.round(Math.random()))&&(l=A),g.push(y),p+=1}}}),c=c.filter(E=>Math.abs(E.value-l)<5)}),c.sort((S,T)=>S.maxDiff-T.maxDiff);const I=cn(c);return{candidatesCount:p,deltaCandidate:f,maxIterations:t,iterations:h,candidate:I}}function qh(t){return t.participantIdPairings.map(({participantIds:e})=>e.sort().join("|")).sort().join("/")}function Ib({valueSortedPairings:t,stipulated:e=[],pairingValueMap:n,deltaObjects:r,valueObjects:s,actorsCount:i}){const o=[].concat(...e),c=[];let a=0;e.filter(Boolean).forEach(p=>{const[h,d]=p,m=_o(h,d),g=n[m];c.push({participantIds:p,value:g}),a+=n[m]}),Ge(t,i).map(p=>on(p).map(h=>({...h,value:h.value+Math.random()*Math.round(Math.random())}))).flat().forEach(p=>{const h=p.pairing.split("|");if(!h.reduce((m,g)=>o.includes(g)||m,!1)){o.push(...h);const m=p.value;a+=m,c.push({participantIds:h,value:m})}}),c.sort((p,h)=>p.value-h.value);const l=c.reduce((p,h)=>{const[d,m]=h.participantIds,g=_o(d,m),I=r[g];return I>p?I:p},0),f=c.reduce((p,h)=>{const[d,m]=h.participantIds,g=_o(d,m),I=s[g];return I>p?I:p},0);return{value:a,participantIdPairings:c,maxDelta:l,maxDiff:f}}function _o(t,e){return[t,e].sort(N_).join("|")}function Sb({participantIds:t}){const e={},n=[];t.forEach(s=>{e[s]=t.filter(i=>i!==s),e[s].forEach(i=>{const o=_o(i,s);n.includes(o)||n.push(o)})});const r=Object.assign({},...n.map(s=>({[s]:0})));return{uniquePairings:n,possiblePairings:e,deltaObjects:r}}function v_({matchUps:t}){const e=[];for(const n of t){const r=n.sides.map(kn("participantId"));if(r.length===2){const[s,i]=r,o=_o(s,i);e.includes(o)||e.push(o)}}return{encounters:e}}function C_({possiblePairings:t,valueObjects:e}){const n={};for(const s of Object.keys(t)){const i=t[s].map(o=>r(s,o));n[s]=i.sort((o,c)=>o.value-c.value)}function r(s,i){const o=_o(s,i);return{opponent:i,value:e[o]}}return{pairingValues:n}}const P_=0;function U_({tournamentParticipants:t,adHocRatings:e,eventType:n,scaleName:r,pairing:s}){var o;const i=((o=wr[r])==null?void 0:o.defaultInitialization)??P_;return s.split("|").map(c=>{var a;if(n===$n){const u=(a=t==null?void 0:t.find(l=>l.participantId===c))==null?void 0:a.individualParticipantIds;return u?u==null?void 0:u.map(l=>e[l]||i):i*2}else return e[c]||i})}function O_({tournamentParticipants:t,adHocRatings:e={},possiblePairings:n,uniquePairings:r,maxIterations:s,deltaObjects:i,valueObjects:o,eventType:c,scaleName:a,salted:u}){r.forEach(I=>{const S=U_({tournamentParticipants:t,adHocRatings:e,scaleName:a,eventType:c,pairing:I}),T=typeof u=="number"&&u||.5,E=u&&(Math.round(Math.random())?T:T*-1)||0,y=Math.abs(S[0]-S[1])+E,b=Math.abs(S[0]-S[1]);i[I]=b,o[I]||(o[I]=0),o[I]+=y?Math.pow(y,2):0});const l=r.map(I=>({pairing:I,value:o[I]})).sort((I,S)=>I.value-S.value),{pairingValues:f}=C_({possiblePairings:n,valueObjects:o}),{candidate:p,candidatesCount:h,deltaCandidate:d,iterations:m}=A_({valueSortedPairings:l,maxIterations:s,pairingValues:f,deltaObjects:i,valueObjects:o}),{participantIdPairings:g}=p;return{participantIdPairings:g,candidatesCount:h,deltaCandidate:d,iterations:m,candidate:p}}const M_=100,D_=100,w_=4e3;function Tb({encounterValue:t=M_,sameTeamValue:e=D_,maxIterations:n=w_,generateMatchUps:r=!0,tournamentParticipants:s,tournamentRecord:i,participantIds:o,addToStructure:c,drawDefinition:a,adHocRatings:u,structureId:l,salted:f=.5,matchUpIds:p,eventType:h,structure:d,scaleName:m}){if(!a)return{error:lt};if(!d&&!l)return{error:Te};if(d||(d=Ot({drawDefinition:a,structureId:l}).structure),!or(d))return{error:Wi};if(!(o!=null&&o.length))return{error:Ns};const{encounters:g}=v_({matchUps:(d==null?void 0:d.matchUps)??[]}),I={};for(const D of g)I[D]||(I[D]=0),I[D]+=t;const S=s==null?void 0:s.filter(({participantType:D})=>D===se);if(S)for(const D of S){const M=D.individualParticipantIds??[],{uniquePairings:w}=Sb({participantIds:M});for(const k of w)I[k]||(I[k]=0),I[k]+=e}const{uniquePairings:T,possiblePairings:E,deltaObjects:y}=Sb({participantIds:o}),b={tournamentParticipants:s,possiblePairings:E,drawDefinition:a,participantIds:o,uniquePairings:T,maxIterations:n,adHocRatings:u,deltaObjects:y,valueObjects:I,eventType:h,scaleName:m,structure:d,salted:f},{candidatesCount:N,participantIdPairings:A,iterations:C,candidate:v}=O_(b);if(!N)return{error:Jd};let P;if(r){const D=md({structureId:d==null?void 0:d.structureId,participantIdPairings:A,tournamentRecord:i,addToStructure:c,newRound:!0,drawDefinition:a,matchUpIds:p});if(D.error)return D;P=D.matchUps}const{maxDelta:U,maxDiff:O}=v;return{...$,participantIdPairings:A,candidatesCount:N,iterations:C,matchUps:P,maxDelta:U,maxDiff:O}}function Yh({tournamentParticipants:t,restrictEntryStatus:e,adHocRatings:n={},generateMatchUps:r,tournamentRecord:s,addToStructure:i,participantIds:o,encounterValue:c,sameTeamValue:a,drawDefinition:u,scaleAccessor:l,maxIterations:f,structureId:p,matchUpIds:h,scaleName:d,eventType:m,salted:g,event:I}){var y,b,N,A;if(typeof u!="object"||u.drawType&&u.drawType!==Xn)return{error:Gi};if(!Array.isArray(u==null?void 0:u.entries)&&o&&!Array.isArray(o))return{error:tt,info:"Missing Entries"};m=m??(I==null?void 0:I.eventType);const S=(y=u==null?void 0:u.entries)==null?void 0:y.filter(C=>{const v=C.entryStatus;return!e||ps.includes(v)}).map(fe);if(o){const C=o.filter(v=>!(S!=null&&S.includes(v)));if(C!=null&&C.length)return{error:bs,invalidParticipantIds:C}}else o=S;if(!p){const C=(N=(b=u==null?void 0:u.structures)==null?void 0:b.filter(v=>v.stageSequence===1))==null?void 0:N.reduce((v,P)=>{const U=P.stage&&ao[P.stage];return Qr({drawDefinition:u,structure:P})&&U>(ao[v==null?void 0:v.stage]||1)?P:v},void 0);p=C==null?void 0:C.structureId}const T=(A=u==null?void 0:u.structures)==null?void 0:A.find(C=>C.structureId===p);if(!T)return{error:Te};if(!Qr({drawDefinition:u,structure:T}))return{error:Gi};t=t??s.participants??[];for(const C of o??[]){const v=t==null?void 0:t.find(U=>U.participantId===C);let P=yb({scaleName:`${d}.${pI}`,scaleAccessor:l,participant:v,eventType:m});!P&&d&&(P=yb({scaleAccessor:l,participant:v,scaleName:d,eventType:m})),P&&!n[C]&&(n[C]=P)}return Tb({tournamentParticipants:t,generateMatchUps:r,tournamentRecord:s,addToStructure:i,participantIds:o,encounterValue:c,sameTeamValue:a,drawDefinition:u,maxIterations:f,adHocRatings:n,matchUpIds:h,structure:T,eventType:m,salted:g})}function yb({scaleType:t=to,scaleAccessor:e,participant:n,scaleName:r,eventType:s}){var a;const i={eventType:s||_n.Singles,scaleType:t,scaleName:r},o=n&&Ts({scaleAttributes:i,participant:n}),c=(a=o==null?void 0:o.scaleItem)==null?void 0:a.scaleValue;return e&&or(c)?c[e]:c}function Eb({drawDefinition:t,matchUpId:e,outcome:n,matchUp:r}){var i,o;if(!r&&!t)return{error:lt};if(!n)return{error:Tt,info:"missing outcome"};if(!r&&!e)return{error:Rn};if(!r){const c=ie({drawDefinition:t,matchUpId:e});if(c.error)return c;r=c.matchUp}return typeof n!="object"||!((i=n.score)!=null&&i.scoreStringSide1)||!((o=n.score)!=null&&o.scoreStringSide2)?{error:tt}:ae({element:r,extension:{name:$u,value:n}})}function k_({matchUps:t}){if(!t)return{error:$s};const e=t.map(s=>s.drawPositions).flat();ze()&&t.forEach(s=>{var i;if(!Array.isArray(s.drawPositions)){console.log("drawPositions not an array",s);return}(i=s.drawPositions)==null||i.forEach(o=>{bb(o)||console.log("invalid drawPosition",s)})});const n=e==null?void 0:e.every(bb),r=t.find(s=>!Array.isArray(s.drawPositions));return n&&!r}function bb(t){return t!==null&&(t===void 0||!isNaN(t))}function Nb({drawDefinition:t,matchUpId:e,event:n}){if(!t)return{error:lt};const{matchUp:r}=ie({drawDefinition:t,matchUpId:e,event:n});return ae({extension:{name:ec,value:!0},element:r})}function Ab({tournamentRecord:t,drawDefinition:e,matchUpId:n,event:r}){if(!e)return{error:lt};const{matchUp:s}=ie({drawDefinition:e,matchUpId:n,event:r});return(s==null?void 0:s.matchUpType)!==yr?{error:qn}:Ja({enableAutoCalc:!0,tournamentRecord:t,drawDefinition:e,matchUpId:n,event:r})}function vb({drawDefinition:t,finishingOrder:e}){var S;if(!t)return{error:lt};const n="setOrderOfFinish";if(!Array.isArray(e))return G({result:{error:tt},info:sn("finishingOrder"),stack:n});const{completedMatchUps:r,matchUpsMap:s}=To({inContext:!0,drawDefinition:t}),i=(r==null?void 0:r.map(Qe))||[],o=e.map(Qe),{matchUpTypes:c,roundNumbers:a,structureIds:u,matchUpTieIds:l}=(r||[]).filter(({matchUpId:T})=>o.includes(T)).reduce((T,E)=>{const{matchUpTieId:y,matchUpType:b,roundNumber:N,structureId:A}=E;return T.matchUpTypes.includes(b)||T.matchUpTypes.push(b),T.roundNumbers.includes(N)||T.roundNumbers.push(N),T.structureIds.includes(A)||T.structureIds.push(A),T.matchUpTieIds.includes(y)||T.matchUpTieIds.push(y),T},{matchUpTypes:[],roundNumbers:[],structureIds:[],matchUpTieIds:[]});if(c.length>1||l.length>1||a.length>1||u.length>1)return G({result:{error:tt},info:"matchUpType, structureId and roundNumber must be equivalent",stack:n});let f,p;const h={},d=[],m=[];if(!e.every(({orderOfFinish:T,matchUpId:E})=>(d.push(E),T&&m.push(T),h[E]=T,f=i.includes(E),p=T===void 0||oe(T)&&Math.floor(T)>0,f&&p)))return G({result:{error:f?tt:Hc},info:!f&&"matchUps must be completed"||!p&&"orderOfFinish must be integer > 0 or undefined"||void 0,stack:n});const I=r==null?void 0:r.filter(T=>T.structureId===u[0]&&T.roundNumber===a[0]&&T.matchUpType===c[0]&&T.matchUpTieId===l[0]&&!d.includes(T.matchUpId));for(const T of I||[]){const{orderOfFinish:E}=T||{};if(E){if(!oe(E))return G({context:{orderOfFinish:E,matchUp:T},result:{error:tt},stack:n});m.push(E)}}if($m(m).length!==m.length||Math.max(...m)>m.length)return G({result:{error:tt},info:"Values not unique or greater than expected number of values",stack:n});if(u.length){const T=Va({matchUpFilters:{matchUpIds:o},structureId:u[0],drawDefinition:t,matchUpsMap:s});if(T.error)return G({result:T,stack:n});(S=T.completedMatchUps)==null||S.forEach(E=>E.orderOfFinish=h[E.matchUpId])}return{...$}}const __={resetScorecard:Xp,setMatchUpStatus:Ja,setMatchUpFormat:Gl,updateTieMatchUpScore:ms,isValidMatchUpFormat:nr,disableTieAutoCalc:Nb,enableTieAutoCalc:Ab,addFinishingRounds:ja,addMatchUpTimeItem:Ln,resetMatchUpTimeItems:IM,checkInParticipant:fh,checkOutParticipant:ph,getCheckedInParticipantIds:Fa,addMatchUpScheduleItems:kl,addMatchUpScheduledDate:Cp,addMatchUpScheduledTime:wi,addMatchUpStartTime:Up,addMatchUpEndTime:Op,addMatchUpStopTime:Mp,addMatchUpResumeTime:Dp,addMatchUpTimeModifiers:vp,addGoesTo:Ic,setOrderOfFinish:vb,setDelegatedOutcome:Eb,removeDelegatedOutcome:gb,drawMatic:Yh,addMatchUpOfficial:UT,findMatchUp:eU,getRoundMatchUps:Cn,validDrawPositions:k_,validateScore:rp};function Td({drawDefinition:t,policyDefinitions:e}){var i;if(!t)return{error:lt};if(!e||typeof e!="object")return{error:Au};t.extensions||(t.extensions=[]);const n=((i=ge({drawDefinition:t}))==null?void 0:i.appliedPolicies)??{},r=[Lu,HC],s=Object.keys(e).every(o=>!n[o]||r.includes(o)?(n[o]=e[o],!0):!1);if(s){const c=ae({element:t,extension:{name:zi,value:n}});if(c.error)return c}return Zt({drawDefinition:t}),s?{...$}:{error:ng}}const F_={attachPolicies:Td};function Cb({excludedMatchUpStatuses:t=[],includeEventParticipants:e,includeQualifyingStage:n,finishingRoundLimit:r,policyDefinitions:s,roundNumberLimit:i,tournamentRecord:o,drawDefinition:c,matchUpsLimit:a,requirePlay:u,requireLoss:l,allEntries:f,winsLimit:p,event:h}){var F,L,W,j,H;if(!c)return{error:lt};const d=[As.Main,As.PlayOff];n&&d.push(As.Qualifying);const m=h!=null&&h.eventType?{matchUpTypes:[h.eventType]}:void 0,g=c!=null&&c.matchUpType?{matchUpTypes:[c.matchUpType]}:void 0,I=e&&h?((F=si({contextFilters:{stages:d},matchUpFilters:m,tournamentRecord:o,inContext:!0,event:h}))==null?void 0:F.matchUps)||[]:((L=tr({contextFilters:{stages:d},matchUpFilters:g,tournamentRecord:o,inContext:!0,drawDefinition:c}))==null?void 0:L.matchUps)||[],T=mo({stage:je,drawDefinition:c}).map(({participantId:B})=>B),E={},y={},b={},N={};s||(s=Zi({policyTypes:[Xg],tournamentRecord:o,drawDefinition:c,event:h}).policyDefinitions);const A=s==null?void 0:s[Xg];t=t.length&&t||(A==null?void 0:A.excludedMatchUpStatuses)||[],e=e!==void 0?e:A==null?void 0:A.includeEventParticipants,f=f!==void 0?f:A==null?void 0:A.allEntries,r=r||(A==null?void 0:A.finishingRoundLimit),i=i||(A==null?void 0:A.roundNumberLimit),a=a||(A==null?void 0:A.matchUpsLimit),u===void 0&&(u=(A==null?void 0:A.requirePlay)!==void 0?A.requirePlay:!0),l===void 0&&(l=(A==null?void 0:A.requireLoss)!==void 0?A.requireLoss:!0),p=p||(A==null?void 0:A.winsLimit);for(const B of I){if(u&&B.winningSide&&![1,2].includes(B.winningSide)&&B.matchUpStatus!==Fe||B.finishingRound&&r&&B.finishingRound>=r||B.finishingRound&&i&&B.finishingRound<=i)continue;const R=(W=B.sides)==null?void 0:W.find(({sideNumber:q})=>B.winningSide&&q===3-B.winningSide),x=(j=B.sides)==null?void 0:j.find(({sideNumber:q})=>B.winningSide&&q===B.winningSide);if((H=B.sides)==null||H.forEach(q=>{var Y;const V=(Y=q==null?void 0:q.participant)==null?void 0:Y.participantId;V&&(b[V]=q.participant,B.matchUpStatus===Fe&&!u&&(y[V]=q.participant,E[V]||(E[V]=0),t.includes(B.matchUpStatus)||(E[V]+=1)))}),R!=null&&R.participant){const q=R.participant.participantId;y[q]=R.participant,E[q]||(E[q]=0),B.matchUpStatus&&!t.includes(B.matchUpStatus)&&(E[q]+=1)}if(x!=null&&x.participant){const q=x.participant.participantId;N[q]||(N[q]=0),N[q]+=1,E[q]||(E[q]=0),B.matchUpStatus&&!t.includes(B.matchUpStatus)&&(E[q]+=1)}}const C=(o==null?void 0:o.participants)&&!u&&!l&&f,v=C?((e&&h?h.entries:c.entries)||[]).filter(B=>![ti,Or].includes(B.entryStatus)).map(({participantId:B})=>B):[],P=Object.keys(y),U=C?((o==null?void 0:o.participants)||[]).filter(({participantId:B})=>v.includes(B)):l&&Object.values(y)||Object.values(b),O=B=>!l||P.includes(B),D=B=>!u||(E[B]||0)>=0,M=B=>!p||(N[B]||0)<=p,w=B=>!a||E[B]<=a,k=B=>!T.includes(B);return{eligibleParticipants:U.filter(B=>O(B.participantId)&&D(B.participantId)&&M(B.participantId)&&w(B.participantId)&&k(B.participantId)).map(B=>{var R;return{...B,individualParticipants:(R=B.individualParticipantIds)==null?void 0:R.map(x=>{var q;return(q=o==null?void 0:o.participants)==null?void 0:q.find(V=>V.participantId===x)})}}),losingParticipantIds:P,...$}}function L_({provisionalPositioning:t,drawDefinition:e,seedBlockInfo:n,structureId:r,event:s}){if(!e)return{error:lt,nextUnfilledDrawPositions:[]};if(!r)return{error:En,nextUnfilledDrawPositions:[]};const i=Ot({drawDefinition:e,structureId:r});if(i.error)return i;const{positionAssignments:o=[]}=ke({structure:i.structure}),{unfilledPositions:c}=jl({provisionalPositioning:t,randomize:!0,drawDefinition:e,seedBlockInfo:n,structureId:r,event:s}),a=o.filter(u=>!u.participantId&&!u.bye&&!u.qualifier).map(u=>u.drawPosition);return c!=null&&c.length?{nextUnfilledDrawPositions:c}:{nextUnfilledDrawPositions:a}}function Pb({tournamentParticipants:t,drawDefinition:e,event:n}){if(!e)return{error:lt};const r=xe({tournamentParticipants:t,inContext:!0,drawDefinition:e,event:n}),s=pt(r.matchUps,!1,!0),i=Vt(s.reduce((c,a)=>c.concat(...a.sides.map(u=>u.participantId).filter(Boolean)),[])),o=Object.assign({},...i.map(c=>{const a=s.filter(u=>u.sides.map(f=>f.participantId).filter(Boolean).includes(c));return{[c]:a}}));return{participantIds:i,participantIdMatchUps:o}}function Ub({byeAdvancements:t=!1,tournamentParticipants:e,drawDefinition:n}){if(!n)return{error:lt};const{participantIds:r,participantIdMatchUps:s}=Pb({tournamentParticipants:e,drawDefinition:n}),i=r.map(o=>{const a=s[o].filter(p=>[De,re].includes(p.matchUpStatus)||p.winningSide),u=a.map(p=>{const h=p.sides.find(g=>g.bye),d=p.sides.find(g=>g.participantId===o).sideNumber;return(p.winningSide||t&&h&&d)===d?p.finishingPositionRange.winner:p.finishingPositionRange.loser}),l=p=>Math.abs(p[0]-p[1]),f=u.reduce((p,h)=>p&&l(p)<l(h)?p:h,void 0);return{[o]:{relevantMatchUps:a,finishingPositionRanges:u,finishingPositionRange:f}}});return Object.assign({},...i)}function zh({targetRoundNumber:t,finishingPosition:e,drawDefinition:n,structureId:r,linkType:s}){const{links:i}=$a({drawDefinition:n,structureId:r})||{},c=((i==null?void 0:i.target)||[]).filter(({linkType:u})=>u===s).filter(({target:u})=>!t||t===u.roundNumber).map(u=>{const l=u.source.structureId,{structure:f}=Ot({structureId:l,drawDefinition:n});if(!(e&&(f==null?void 0:f.finishingPosition)!==e))return u}).filter(Boolean);return{sourceStructureIds:c.map(({source:u})=>u.structureId),relevantLinks:c}}function R_({tournamentParticipants:t,returnParticipants:e,drawPosition:n,participant:r,drawId:s,event:i}){var c;const o=((c=i==null?void 0:i.entries)==null?void 0:c.filter(({entryStatus:a})=>[Or,po].includes(a)).map(({participantId:a})=>a))||[];if(o.length){const a=r.individualParticipantIds,u=e?t.filter(({participantId:p})=>o.includes(p)):void 0,l=e?t.filter(({participantId:p})=>a.includes(p)):void 0;return{validModifyAssignedPairAction:bt({payload:{participantId:r.participantId,replacementIndividualParticipantId:void 0,existingIndividualParticipantId:void 0,drawPosition:n,drawId:s},method:rO,availableIndividualParticipantIds:o,availableIndividualParticipants:u,existingIndividualParticipantIds:a,existingIndividualParticipants:l,type:sT},!1,!1,!0)}}return{}}function B_({tournamentParticipants:t=[],sourceStructuresComplete:e,possiblyDisablingAction:n,isWinRatioFedStructure:r,activeDrawPositions:s,positionAssignments:i,drawDefinition:o,drawPosition:c,structureId:a,structure:u,drawId:l,event:f}){var I,S,T,E,y;if(s.includes(c)||r&&!e)return{};const{sourceStructureIds:p,targetStructureIds:h}=((I=o.links)==null?void 0:I.reduce((b,N)=>{var v,P;const A=(v=N.source)==null?void 0:v.structureId,C=(P=N.target)==null?void 0:P.structureId;return b.sourceStructureIds.includes(A)||b.sourceStructureIds.push(A),b.targetStructureIds.includes(C)||b.targetStructureIds.push(C),b},{sourceStructureIds:[],targetStructureIds:[]}))||{},d=[],m=((S=o.links)==null?void 0:S.filter(b=>{var N;return((N=b.target)==null?void 0:N.structureId)===u.structureId}))||[];for(const b of m){const N=(T=b==null?void 0:b.source)==null?void 0:T.structureId,{structure:A}=Ot({structureId:N,drawDefinition:o}),C=(A==null?void 0:A.finishingPosition)===fo&&((p==null?void 0:p.length)!==1||(h==null?void 0:h.length)!==1),v={};if(C){const{matchUps:D}=Qt({drawDefinition:o,structure:u,event:f}),{initialRoundNumber:M}=Uo({drawPosition:c,matchUps:D}),w=(E=o.links)==null?void 0:E.find(_=>{var F;return((F=_.target)==null?void 0:F.structureId)===(u==null?void 0:u.structureId)&&_.target.roundNumber===M}),k=(y=w==null?void 0:w.source)==null?void 0:y.roundNumber;v.roundNumbers=[k]}const{completedMatchUps:P}=Va({structureId:N,inContext:!0,matchUpFilters:v,drawDefinition:o}),U=i.map(D=>D.participantId).filter(Boolean),O=P==null?void 0:P.filter(({matchUpType:D,winningSide:M})=>M&&((f==null?void 0:f.eventType)!==we||D===we)).map(({winningSide:D,sides:M})=>D&&(M==null?void 0:M[1-(D-1)])).map(kn("participantId")).filter(D=>D&&!U.includes(D));O==null||O.forEach(D=>{d.includes(D)||d.push(D)})}const g=t==null?void 0:t.filter(b=>d==null?void 0:d.includes(b.participantId));return g==null||g.forEach(b=>{const N=(o.entries||[]).find(A=>A.participantId===b.participantId);b.entryPosition=N==null?void 0:N.entryPosition}),d!=null&&d.length?{validLuckyLosersAction:{type:aT,method:eO,availableLuckyLosers:g,availableLuckyLoserParticipantIds:d,willDisableLinks:n,payload:{drawId:l,structureId:a,drawPosition:c}}}:{}}function x_({positionSourceStructureIds:t,unassignedParticipantIds:e,possiblyDisablingAction:n,provisionalPositioning:r,tournamentParticipants:s,isWinRatioFedStructure:i,positionAssignments:o,returnParticipants:c,appliedPolicies:a,drawDefinition:u,isByePosition:l,drawPosition:f,structureId:p,event:h}){var E,y,b;const{drawId:d}=u,m=[];let g,I,S=[];const T=(y=(E=a==null?void 0:a[tc])==null?void 0:E.validSeedPositions)==null?void 0:y.ignore;if(T||({unplacedSeedParticipantIds:g,unplacedSeedAssignments:I,unfilledPositions:S}=jl({provisionalPositioning:r,randomize:!0,drawDefinition:u,structureId:p,event:h})),S!=null&&S.length||(S=o.filter(N=>!N.participantId&&!N.bye&&!N.qualifier).map(N=>N.drawPosition)),l||m.push({payload:{drawId:d,structureId:p,drawPosition:f,isPositionAction:!0},willDisableLinks:n,method:oO,type:pp}),i&&T){const N=o.map(U=>U.participantId).filter(Boolean),A={structureIds:t},{completedMatchUps:C}=To({inContext:!0,matchUpFilters:A,drawDefinition:u}),v=Vt((b=(C??[]).filter(({matchUpType:U})=>(h==null?void 0:h.eventType)!==we||U===we))==null?void 0:b.map(({sides:U})=>U==null?void 0:U.map(kn("participantId"))).flat().filter(U=>U&&!N.includes(U))),P=c?s==null?void 0:s.filter(U=>v==null?void 0:v.includes(U.participantId)).map(U=>pt(U,void 0,!0)):void 0;return P==null||P.forEach(U=>{const O=(u.entries??[]).find(D=>D.participantId===U.participantId);U.entryPosition=O==null?void 0:O.entryPosition}),P!=null&&P.length&&m.push(bt({payload:{drawId:d,structureId:p,drawPosition:f},willDisableLinks:n,method:nT,type:pc,availableParticipantIds:v,participantsAvailable:P})),{validAssignmentActions:m}}if(S.includes(f)||l){let N;if(I!=null&&I.length){const C=I.filter(v=>g==null?void 0:g.includes(v.participantId));C.sort($_),N=C.map(v=>v.participantId)}else N=e;const A=c?s==null?void 0:s.filter(C=>N.includes(C.participantId)).map(C=>pt(C,void 0,!0)):void 0;A!=null&&A.length&&m.push(bt({payload:{drawId:d,structureId:p,drawPosition:f},willDisableLinks:n,method:nT,type:pc,availableParticipantIds:N,participantsAvailable:A}))}return{validAssignmentActions:m}}function $_(t,e){return t.bye||Pc(t.seedValue)<Pc(e.seedValue)||t.seedValue&&!e.seedValue?-1:(t.seedNumber||0)-(e.seedNumber||0)}function V_({drawPositionInitialRounds:t,tournamentParticipants:e,positionAssignments:n,returnParticipants:r,appliedPolicies:s,drawDefinition:i,drawPosition:o,structureId:c,drawId:a}){var y,b,N;const u=[],l=[],f=[],p=[],h=n.map(A=>A.participantId).filter(Boolean),d=s==null?void 0:s[vs],m=!(d!=null&&d.disableRoundRestrictions)&&t[o],g=d==null?void 0:d.requireCompletedStructures,{sourceStructureIds:I,relevantLinks:S}=zh({targetRoundNumber:m,linkType:vi,drawDefinition:i,structureId:c})||{};I!=null&&I.length&&p.push(...I);const{sourceStructureIds:T,relevantLinks:E}=zh({targetRoundNumber:m,linkType:Ai,drawDefinition:i,structureId:c})||{};T!=null&&T.length&&p.push(...T);for(const A of S){const C=(y=i.structures)==null?void 0:y.find(P=>P.structureId===A.source.structureId);if((C==null?void 0:C.stage)!==Pt)continue;const v=ki({structureId:A.source.structureId,drawDefinition:i});if(!g||v){const P=C.qualifyingRoundNumber,{matchUps:U}=Qt({matchUpFilters:{roundNumbers:[P],hasWinningSide:!0},afterRecoveryTimes:!1,tournamentParticipants:e,inContext:!0,structure:C});for(const O of U){const D=O.sides.find(w=>(w==null?void 0:w.sideNumber)===O.winningSide),M=O.matchUpStatus===re&&((b=O.sides)==null?void 0:b.find(({participantId:w})=>w));if(D||M){const{participantId:w,participant:k}=D||M||{};w&&!h.includes(w)&&(k&&r&&u.push(k),l.push(w))}}}}for(const A of E){const C=(N=i.structures)==null?void 0:N.find(P=>P.structureId===A.source.structureId);if((C==null?void 0:C.stage)!==Pt)continue;const v=ki({structureId:A.source.structureId,drawDefinition:i});if(!g||v){const{positionAssignments:P}=ee({structure:C}),U=(P==null?void 0:P.map(O=>{var w;const D=O.participantId,M=(w=Ke({element:O,name:Ys}).extension)==null?void 0:w.value;return M?{participantId:D,groupOrder:M==null?void 0:M.groupOrder}:{}}).filter(({groupOrder:O,participantId:D})=>O===1&&!h.includes(D)).map(({participantId:O})=>O))??[];if(U&&l.push(...U),r){const O=e.filter(({participantId:D})=>U.includes(D));u.push(...O)}}}return l.length&&f.push(bt({payload:{qualifyingParticipantId:void 0,drawPosition:o,structureId:c,drawId:a},method:Z0,type:fp,qualifyingParticipantIds:l,qualifyingParticipants:r?u:void 0})),{validAssignmentActions:f,sourceStructureIds:p}}function j_({onlyAssignedPositions:t=!0,possiblyDisablingAction:e,tournamentParticipants:n,inactiveDrawPositions:r,activeDrawPositions:s,positionAssignments:i,returnParticipants:o,byeDrawPositions:c,drawDefinition:a,isByePosition:u,drawPosition:l,structureId:f,structure:p,drawId:h,event:d}){if(s.includes(l))return{};const m=v=>!t||v.participantId||v.qualifier||v.bye,g=r==null?void 0:r.filter(v=>v!==l&&!(u&&c.includes(v))),I=(i==null?void 0:i.filter(v=>m(v)&&(g==null?void 0:g.includes(v.drawPosition))))||[],S=I.map(({drawPosition:v})=>v),{matchUps:T}=Qt({afterRecoveryTimes:!1,inContext:!0,drawDefinition:a,structure:p,event:d}),E=T.filter(({drawPositions:v})=>tn(v,S)),y=Object.assign({},...E.map(v=>{var P;return(P=v.sides)==null?void 0:P.filter(({sourceDrawPositionRange:U})=>U).map(({drawPosition:U,sourceDrawPositionRange:O})=>({[U]:O}))}).flat()),b=I.map(v=>v.participantId).filter(Boolean),N=(n||[]).filter(v=>b.includes(v.participantId)),A=Object.assign({},...N.map(v=>({[v.participantId]:v}))),C=I.map(v=>{const P=A==null?void 0:A[v.participantId],U=y[v.drawPosition];return bt({...v,participant:o?pt(P,!1,!0):void 0,sourceDrawPositionRange:U})});return C.length?{validSwapAction:{payload:{drawId:h,structureId:f,drawPositions:[l]},willDisableLinks:e,method:nO,type:uT,availableAssignments:C}}:{}}function Ob(t){const{policyDefinitions:e,tournamentParticipants:n=[],returnParticipants:r=!0,provisionalPositioning:s,tournamentRecord:i,drawDefinition:o,drawPosition:c,event:a}=t;if(!a)return{error:Wt};if(!o)return{error:lt};if(!t.structureId)return{error:En};let u=Ot({structureId:t.structureId,drawDefinition:o});if(u.error)return u;const l=u.containingStructure||u.structure;if(!l)return{error:Te};const f=l.structureId;if(u=qa({drawDefinition:o,structureId:f}),c===void 0&&!u.isAdHoc)return{error:Wc};if(u.isAdHoc)return Sh(t);if(u.error)return u;const{drawPositionInitialRounds:p,inactiveDrawPositions:h,activeDrawPositions:d,byeDrawPositions:m}=u,g=ge({tournamentRecord:i,drawDefinition:o,structure:l,event:a}).appliedPolicies??{};Object.assign(g,e||{});const{actionsPolicy:I,enabledStructures:S,actionsDisabled:T}=sE({actionType:id,appliedPolicies:g,drawDefinition:o,structure:l}),E=(I==null?void 0:I.activePositionOverrides)||[],{sourceStructureIds:y}=zh({finishingPosition:uc,targetRoundNumber:1,linkType:Ai,drawDefinition:o,structureId:f})||{};let b;y!=null&&y.length&&(b=y.reduce((q,V)=>ki({structureId:V,drawDefinition:o})&&q,!0));const N=y.length,A=y.length&&!b,{policyActions:C}=oE({enabledStructures:S,drawDefinition:o,structure:l}),v=![Pt,It].includes(l.stage)||l.stageSequence!==1,{drawId:P}=o,U=[],{assignedPositions:O,positionAssignments:D}=ke({structure:l}),M=O==null?void 0:O.find(q=>q.drawPosition===c),w=D==null?void 0:D.map(q=>q.drawPosition);if(!(w!=null&&w.includes(c)))return{error:Wo};const{stage:k,stageSequence:_}=l,F=[k];k===Re&&F.push(It),k===It&&F.push(Re);const L=mo({entryStatuses:ho,provisionalPositioning:s,drawDefinition:o,stageSequence:_,structureId:f,stages:F}),W=gd({drawDefinition:o,stages:F}),j=L.filter(q=>!W.includes(q.participantId)).map(q=>q.participantId),H=m.includes(c),B=d.includes(c);if(T)return{info:"Actions Disabled for structure",isByePosition:H,isActiveDrawPosition:B,isDrawPosition:!0,hasPositionAssigned:!!M,validActions:[]};if(Pn({policyActions:C,action:pc})&&!B&&D&&!A&&(!M||H)){const{validAssignmentActions:q}=x_({positionSourceStructureIds:y,unassignedParticipantIds:j,possiblyDisablingAction:v,isWinRatioFedStructure:N,tournamentParticipants:n,positionAssignments:D,returnParticipants:r,appliedPolicies:g,drawDefinition:o,isByePosition:H,drawPosition:c,structureId:f,event:a});q==null||q.forEach(V=>U.push(V))}if(Pn({policyActions:C,action:fp})){const{validAssignmentActions:q}=V_({drawPositionInitialRounds:p,tournamentParticipants:n,positionAssignments:D,returnParticipants:r,appliedPolicies:g,drawDefinition:o,drawPosition:c,structureId:f,drawId:P});q==null||q.forEach(V=>U.push(V))}const{participantId:R}=M||{},x=R&&n.find(q=>q.participantId===R);if(M){Pn({policyActions:C,action:cT})&&!B&&(U.push({type:cT,method:eT,payload:{drawId:P,structureId:f,drawPosition:c},willDisableLinks:v}),H||U.push({type:oT,method:X0,payload:{drawId:P,structureId:f,drawPosition:c},willDisableLinks:v}),Pn({policyActions:C,action:pp})&&!H&&U.push({type:pp,method:eT,payload:{drawId:P,structureId:f,drawPosition:c,replaceWithBye:!0},willDisableLinks:v}));const q=l.stage===Pt||l.stage===It&&l.stageSequence===1;if(!H&&iE({activePositionOverrides:E,activeDrawPositions:d,action:hc})&&Pn({policyActions:C,action:hc})&&Vl({drawDefinition:o,structureId:f,drawPosition:c})&&q){const{seedAssignments:V}=Mr({drawDefinition:o,structure:l}),{seedNumber:Y,seedValue:z}=(V==null?void 0:V.find(J=>J.participantId===R))||{};U.push({type:hc,method:cO,participant:x,seedNumber:Y,payload:{drawId:P,structureId:f,participantId:R,seedValue:z}})}if(!H&&iE({activePositionOverrides:E,activeDrawPositions:d,action:Il})&&Pn({policyActions:C,action:Il})&&Vl({drawDefinition:o,structureId:f,drawPosition:c})&&q){const{seedAssignments:V}=Mr({drawDefinition:o,structure:l}),{seedNumber:Y}=(V==null?void 0:V.find(z=>z.participantId===R))||{};U.push({type:Il,method:iO,participant:x,seedNumber:Y,payload:{drawId:P,structureId:f,participantId:R}})}if(!H&&R){if(Pn({policyActions:C,action:mc})){const V={type:mc,method:rT,participant:x,payload:{drawId:P,penaltyCode:void 0,penaltyType:void 0,participantIds:[],notes:void 0}};U.push(V)}if(Pn({policyActions:C,action:Sl})){const V={type:Sl,method:sO,participant:x,payload:{participantId:R,otherName:void 0}};U.push(V)}}if(Pn({policyActions:C,action:uT})){const{validSwapAction:V}=j_({possiblyDisablingAction:v,tournamentParticipants:n,inactiveDrawPositions:h,activeDrawPositions:d,positionAssignments:D,returnParticipants:r,byeDrawPositions:m,drawDefinition:o,isByePosition:H,drawPosition:c,structureId:f,structure:l,drawId:P});V&&U.push(V)}}if(Pn({policyActions:C,action:iT})&&!A){const{validAlternatesAction:q}=Gw({possiblyDisablingAction:v,tournamentParticipants:n,positionAssignments:D,activeDrawPositions:d,returnParticipants:r,appliedPolicies:g,drawDefinition:o,drawPosition:c,validActions:U,structureId:f,structure:l,drawId:P,event:a});q&&U.push(q)}if(Pn({policyActions:C,action:aT})&&!A&&D){const{validLuckyLosersAction:q}=B_({sourceStructuresComplete:b,possiblyDisablingAction:v,isWinRatioFedStructure:N,tournamentParticipants:n,activeDrawPositions:d,positionAssignments:D,drawDefinition:o,drawPosition:c,structureId:f,structure:l,drawId:P});q&&U.push(q)}if((x==null?void 0:x.participantType)===_t&&Pn({policyActions:C,action:sT})){const{validModifyAssignedPairAction:q}=R_({tournamentParticipants:n,returnParticipants:r,drawPosition:c,participant:x,drawId:P,event:a});q&&U.push(q)}return{hasPositionAssigned:!!M,isActiveDrawPosition:B,isDrawPosition:!0,isByePosition:H,validActions:U}}function G_(t){return Object.assign(t,{inContext:!0}),To(t)}function W_(t){const{structure:e}=Ot(t);return Object.assign(t,{structure:e,inContext:!0}),Qt(t)}function H_(t){return Object.assign(t,{inContext:!0}),xe(t)}const q_={allPlayoffPositionsFilled:WT,isCompletedStructure:ki,getAllStructureMatchUps:Qt,getStructureMatchUps:Va,allStructureMatchUps:W_,allDrawMatchUps:H_,drawMatchUps:G_,getEliminationDrawSize:Bh,getParticipantIdMatchUps:Pb,getParticipantIdFinishingPositions:Ub,getEligibleVoluntaryConsolationParticipants:Cb,structureActions:RM,matchUpActions:Sh,positionActions:Ob,getStructureSeedAssignments:Mr,getNextUnfilledDrawPositions:L_,getExitProfiles:Wf,getValidGroupSizes:xp,getSeedingThresholds:jM,getSeedBlocks:xl,getSeedGroups:$l,getMatchUpContextIds:SM,getMatchUpParticipantIds:Hf,getMatchUpScheduleDetails:_f,generateTieMatchUpScore:La,matchUpDuration:GI,credits:sd};function Mb({validation:t=!0,tournamentRecord:e,drawDefinition:n,participantId:r,structureId:s,seedValue:i,event:o}){if(!n)return{error:lt};if(!s)return{error:En};const{structure:c}=Ot({drawDefinition:n,structureId:s});if(!c)return{error:Te};if(!(!t||Me(i)||i===void 0||i===""||typeof i=="string"&&i.split("-").every(p=>Me(p)&&vt(p)>0)))return{error:tt};const{seedAssignments:u}=Mr({drawDefinition:n,structure:c}),l=u==null?void 0:u.map(p=>p.seedNumber),f=u==null?void 0:u.find(p=>p.participantId===r);if(f){const p=typeof i=="string"?i.includes("-")&&i.split("-").map(h=>parseInt(h)).join("-")||parseInt(i)>0&&parseInt(i)||"":i&&i>0&&i||"";f.seedValue=p}else{const h={seedNumber:Math.max(0,...l||[])+1,participantId:r};i&&(h.seedValue=i),c.seedAssignments||(c.seedAssignments=[]),c.seedAssignments.push(h)}return cS({tournamentId:e==null?void 0:e.tournamentId,eventId:o==null?void 0:o.eventId,drawDefinition:n,structure:c}),{...$}}function Y_({autoEntryPositions:t=!0,drawDefinition:e,participantId:n,stages:r}){return e?n?gd({drawDefinition:e,stages:r}).includes(n)?{error:Yo}:(e!=null&&e.entries&&(e.entries=e.entries.filter(o=>o.participantId!==n)),t&&(e.entries=pr({entries:e.entries})),Zt({drawDefinition:e}),{...$}):{error:Ce}:{error:lt}}const z_={setStageAlternatesCount:$k,setStageWildcardsCount:Vk,setStageQualifiersCount:Dh,modifySeedAssignment:Mb,setStageDrawSize:au,addDrawEntries:ib,addDrawEntry:Gh,removeEntry:Y_,assignSeed:Do},K_={generateQualifyingLink:kc},J_=()=>({matchUpType:void 0,drawName:void 0,drawId:void 0,structures:[],entries:[],links:[]}),Q_=["drawId","structures"];function Db(t,e=!0){return t?typeof t!="object"?{error:Ir}:t.drawId?Z_(t)?e?pt(t):t:{error:Gi}:{error:Hn,method:"setState"}:{error:lt}}function Z_(t){const e=Object.keys(t);return Q_.reduce((n,r)=>e.includes(r)?n:!1,!0)}function wb({drawId:t=Yt(),matchUpType:e,drawType:n}){const r=J_();return Object.assign(r,{drawId:t,drawType:n,matchUpType:e})}let ss,kb=[];const X_=function(){const t={getState:s=>({drawDefinition:pt(ss,s==null?void 0:s.convertExtensions,!1,s==null?void 0:s.removeExtensions)}),version:()=>Es(),reset:()=>(ss=void 0,{...$}),newDrawDefinition:s=>(ss=wb({drawId:s==null?void 0:s.drawId,drawType:s==null?void 0:s.drawType}),{drawDefinition:pt(ss),drawId:ss.drawId,...$}),setDrawDescription:s=>ss?(ss.description=s==null?void 0:s.description,Zt({drawDefinition:ss}),{drawId:ss.drawId,...$}):{error:lt}};function e(s){return s!=null&&s.error?(t.error=s.error,t.success=!1):(t.error=void 0,t.success=!0,ss=s,t.drawId=s.drawId),t}return n([K_,q_,LS,z_,F_,__,b_,m_]),t.devContext=s=>(zo(s),t),t.setParticipants=(s=[])=>(kb=s,t),t.setState=(s,i,o)=>{Hi(i,o);const c=Db(s);return e(c)},t;function n(s){s.forEach(i=>{Object.keys(i).forEach(o=>{t[o]=c=>{if(ze())return r({params:c,governor:i,methodName:o});try{return r({params:c,governor:i,methodName:o})}catch(a){Xc({engineName:"drawEngine",methodName:o,params:c,err:a})}}})})}function r({params:s,governor:i,methodName:o}){delete t.success,delete t.error;const c=(s==null?void 0:s.rollbackOnError)&&pt(ss,!1,!0);s={...s,...{},tournamentParticipants:kb,drawDefinition:ss};const u=i[o](s);if(u!=null&&u.error)return c&&Db(c),{...u,rolledBack:!!c};const l=(u==null?void 0:u.success)&&(s==null?void 0:s.delayNotify)!==!0&&(s==null?void 0:s.doNotNotify)!==!0;return l&&Di(),(l||!(u!=null&&u.success)||s!=null&&s.doNotNotify)&&fi(),u}}(),tF={modifyCollectionDefinition:zl,orderCollectionDefinitions:qp,removeCollectionDefinition:Kl,addCollectionDefinition:Zl,removeCollectionGroup:Kp,calculateWinCriteria:gc,addCollectionGroup:Jp,modifyTieFormat:Qp};function Bi({matchUp:t}){const{extension:e}=xn({name:Wu,element:t});if(!e)return{error:an};const{history:n=[],undoHistory:r=[]}=e.value;return{history:n,undoHistory:r,...$}}function eF({matchUp:t,updateScore:e}){var C;const n=((C=Bi({matchUp:t}))==null?void 0:C.history)||[];if(!Array.isArray(n))return{error:tt,info:"history is not an array"};const{matchUpFormat:r}=t;if(!r)return{error:Vd};if(!nr(r))return{error:Xm};const s=yn(r),{bestOf:i,finalSetFormat:o,setFormat:c}=s,a=["0","15","30","40","A","G"],u={sets:[]};let l=[],f,p=[0,0],h=1,d=0,m,g=0;const I=v=>[1,2].includes(v),S=()=>(d+=1,{winningSide:void 0,side1Score:0,side2Score:0,setNumber:d,games:[]}),T=()=>({winningSide:void 0,points:[]}),E=()=>({winningSide:void 0,side1Score:"",side2Score:"",shots:[]});let y=E(),b=T(),N=S(),A=0;for(const v of n){A+=1,m=u.sets.length+1===i;const P=m&&o?o:c,{tiebreakAt:U,setTo:O,NoAD:D,tiebbreakFormat:M}=P,w=N.side1Score===U&&N.side1Score===N.side2Score,k=!!P.tiebreakSet,_=k?P.tiebreakSet:M,{tiebreakTo:F,NoAD:L}=_||{},W=()=>{f=void 0,p=[0,0],h=3-h,N.side1TiebreakScore=0,N.side2TiebreakScore=0,N.side1PointScore="",N.side2PointScore="",g=0},j=R=>{N.winningSide=R;const{s:x,...q}=N;u.sets.push(q),y=E(),b=T(),N=S(),W()},H=R=>{b.winningSide=R;const{g:x,...q}=b;N.games.push(q),y=E(),b=T(),W();const V=`side${R}Score`;N[V]+=1},B=R=>{y.winningSide=R;const{p:x,...q}=y;b.points.push(q),y=E(),g=0;const V=()=>p.reduce((Q,X)=>Q+X)%4/4>.5?h:3-h,Y=R-1;if(w||k){p[Y]+=1,f=V(),N[`side${R}TiebreakScore`]=p[Y],N[`side${3-R}TiebreakScore`]=p[1-Y];const z=L?1:2;if(p[Y]>=F&&p[Y]>=p[1-Y]+z)return H(R),{gameCompleted:!0}}else if(p[1-Y]===4&&p[Y]===3?p[1-Y]-=1:p[Y]+=1,N.side1PointScore=a[p[0]],N.side2PointScore=a[p[1]],p[Y]===5||p[Y]===4&&p[1-Y]<3||D&&p[Y]===4)return H(R),{gameCompleted:!0}};if(I(v.srv)&&(h=v.srv),["p","s","g","o"].includes(v.u)&&l.push(v.u),v.shotOutcome&&(y.shots.push(v),v.shotType==="SERVE"&&["OUT","NET"].includes(v.shotOutcome)&&(g+=1),g===2)){const x=3-h;B(x)}if(I(v.p)||oe(v.pointNumber)){const R=v.winningSide||v.p,x=B(R);if(x!=null&&x.gameCompleted)continue}if(I(v.g)||oe(v.gameNumber)){const R=v.winningSide||v.g;b.winningSide=R;const x=`side${R}Score`,q=`side${3-R}Score`;if(l.length&&(l.includes("p"),l=[]),H(R),N[x]===O&&N[x]-N[q]>=(D?1:2)&&(j(R),m))break}if(I(v.s)||oe(v.setNumber)){const R=v.winningSide||v.s;if(j(R),l.length&&(l.includes("p"),l.includes("g"),l=[]),m)break}}return A!==n.length&&console.log({error:"Match completed with excess history"}),(N.side1Score||N.side2Score||N.games.length||N.side1TiebreakScore||N.side2TiebreakScore)&&u.sets.push(N),u.scoreStringSide1=gs({...u,matchUpFormat:r}),u.scoreStringSide2=gs({...u,matchUpFormat:r,reversed:!0}),h=f||h,e&&(t.score=u),{...$,servingSide:h,score:u}}function xi({undoHistory:t,history:e,matchUp:n}){return ae({element:n,extension:{value:{history:e,undoHistory:t},name:Wu}})}function nF({matchUp:t,sideNumber:e}){if(![1,2].includes(e))return{error:rg};const{history:n=[]}=Bi({matchUp:t});return n.push({srv:e}),xi({matchUp:t,history:n})}function rF({matchUp:t}){return xi({matchUp:t})}function sF({matchUp:t,point:e}){if(!e)return{error:Tt};if(typeof e!="object")return{error:tt,context:{point:e}};const{history:n=[]}=Bi({matchUp:t});return n.push(e),xi({matchUp:t,history:n})}function iF({matchUp:t,game:e}){if(typeof e!="object")return{error:tt,context:{game:e}};const{history:n=[]}=Bi({matchUp:t});return n.push(e),xi({matchUp:t,history:n})}function oF({matchUp:t,shot:e}){if(typeof e!="object")return{error:Tt};const{history:n=[]}=Bi({matchUp:t});return n.push(e),xi({matchUp:t,history:n})}function cF({matchUp:t,set:e}){if(typeof e!="object")return{error:Tt};const{history:n=[]}=Bi({matchUp:t});return n.push(e),xi({matchUp:t,history:n})}function aF({matchUp:t}){const{history:e=[],undoHistory:n=[]}=Bi({matchUp:t});return n.length&&e.push(n.pop()),xi({matchUp:t,history:e,undoHistory:n})}function uF({matchUp:t}){const{history:e=[],undoHistory:n=[]}=Bi({matchUp:t});return n.push(e.pop()),xi({matchUp:t,history:e,undoHistory:n})}const lF={calculateHistoryScore:eF,setServingSide:nF,clearHistory:rF,addPoint:sF,addGame:iF,addShot:oF,addSet:cF,redo:aF,undo:uF,umo:{scoreboard:()=>{},addPoints:()=>{},addPoint:()=>{}}};function Kh(t){var R;const{matchUp:e,sideNumber:n,setNumber:r,isTiebreakValue:s,isPointValue:i}=t||{};let{matchUpFormat:o}=t||{};if(!e)return{error:Rn};o=o||(e==null?void 0:e.matchUpFormat);const c=yn(o),a=!!(e!=null&&e.winningSide),u=(R=e.score)==null?void 0:R.sets,l=u==null?void 0:u.length,f=r&&r-1,p=!!(u!=null&&u.find((x,q)=>x.setNumber===r&&q===f)),h=(u==null?void 0:u.filter(x=>x==null?void 0:x.winningSide))||[],d=(h==null?void 0:h.length)||0,m=r&&(u==null?void 0:u.slice(r))||[],g=!!(l&&r&&(m!=null&&m.reduce((x,q)=>(!q||!q.side1Score&&!q.side2Score&&!q.side1TiebreakScore&&!q.side2TiebreakScore&&!q.side1PointScore&&!q.side2PointScore)&&x,!0))),I=r<=l&&u.find(x=>x.setNumber===r),S=I&&gl({setObject:I,matchUpScoringFormat:c}),{isCompletedSet:T,sideGameScores:E,sideTiebreakScores:y}=S||{},b=!!(I&&!T&&g||r&&r===l+1&&!a),N=[1,2].includes(n),A=N?n-1:0,C=I&&N&&(!s&&!i&&E[A]!==void 0&&E[A]||s&&y[A]!==void 0&&y[A]),v=!!C,P=h==null?void 0:h.map(x=>gl({setObject:x,matchUpScoringFormat:c}).isValidSetOutcome).reduce((x,q)=>x&&q,!0),U=h.reduce((x,q)=>{const{winningSide:V}=q,Y=V-1;return x[Y]++,x},[0,0]),O=e==null?void 0:e.winningSide,D=O&&O-1,M=1-D,w=U[D],k=U[M],_=Math.max(...U),F=Mn(U)[_],{bestOf:L}=c||{},W=L&&Math.ceil(L/2)||1,j=_===W&&F===1&&U.indexOf(_)+1||void 0,H=w>k&&O===j;return{completedSetsHaveValidOutcomes:P,validMatchUpWinningSide:H,calculatedWinningSide:j,matchUpScoringFormat:c,validMatchUpOutcome:j&&P&&H,isLastSetWithValues:g,completedSetsCount:d,isCompletedMatchUp:a,isValidSideNumber:N,hasExistingValue:v,existingValue:C,isExistingSet:p,isActiveSet:b,...S}}const dF={tallyParticipantResults:hf,matchUpIsComplete:Qo,analyzeMatchUp:Kh,getMatchUpType:HI,scoreHasValue:Be,validMatchUps:cr,validMatchUp:$g};let Fo={},ai;function _b(t,e=!0){if(!t)return{error:Tt};if(typeof t!="object")return{error:Ir};if(t.matchUpId)ai=t.matchUpId,Fo[ai]=e?pt(t):t;else if(Array.isArray(t))for(const n of t.reverse())n.matchUpId&&(Fo[n.matchUpId]=e?pt(n):n,ai||(ai=n.matchUpId));else for(const n of Object.values(t))n.matchUpId&&(Fo[n.matchUpId]=e?pt(n):n,ai||(ai=n.matchUpId));return e?pt(t):t}function fF(){return Fo[ai]}function pF(){return Object.values(Fo)}function hF(){ai=void 0,Fo={}}function mF(t){return pt(Fo[ai],t==null?void 0:t.convertExtensions,!1,t==null?void 0:t.removeExtensions)}(()=>{const t={getState:s=>mF(s),version:()=>Es(),reset:()=>(hF(),{...$}),drawId:void 0,error:void 0,success:!1,devContext:s=>(zo(s),t),setState:(s,i,o)=>{Hi(i,o);const c=_b(s);return e(c)}};function e(s){return s!=null&&s.error?(t.error=s.error,t.success=!1):(t.error=void 0,t.success=!0,t.drawId=s.drawId),t}return n([tF,lF,dF,LS]),t;function n(s){s.forEach(i=>{Object.keys(i).forEach(o=>{t[o]=c=>{if(ze())return r({params:c,governor:i,methodName:o});try{return r({params:c,governor:i,methodName:o})}catch(a){Xc({engineName:"matchUpEngine",methodName:o,params:c,err:a})}}})})}function r({params:s,governor:i,methodName:o}){t.error=void 0,t.success=!1;const c=(s==null?void 0:s.matchUp)||fF(),a=(s==null?void 0:s.matchUps)||pF(),u=(s==null?void 0:s.rollbackOnError)&&pt(c,!1,!0);s={...s,matchUpId:c==null?void 0:c.matchUpId,matchUps:a,matchUp:c};const l=i[o](s);if(l!=null&&l.error)return u&&_b(u),{...l,rolledBack:!!u};const f=(l==null?void 0:l.success)&&(s==null?void 0:s.delayNotify)!==!0&&(s==null?void 0:s.doNotNotify)!==!0;return f&&Di(),(f||!(l!=null&&l.success)||s!=null&&s.doNotNotify)&&fi(),l}})();function Jh(t){const e=t||{};return e.tournamentId||(e.tournamentId=Yt()),e.startDate&&!hi(e.startDate)&&!Mu.test(e.startDate)?{error:bn}:e.endDate&&!hi(e.endDate)&&!Mu.test(e.endDate)?{error:bn}:(e.extensions&&(e.extensions=e.extensions.filter(ur)),{...e})}function Qh(t,e){var s;if(typeof t!="object")return{error:Ir};const n=((s=t.unifiedTournamentId)==null?void 0:s.tournamentId)||t.tournamentId;if(!n)return{error:is};const r=e!==!1?pt(t):t;return Qc({[n]:r}),Zc(n),r}function gF({convertExtensions:t=!1,removeExtensions:e=!1,tournamentId:n}){if(typeof n!="string")return{};const r=Jc(n);return{tournamentRecord:pt(r,t,!1,e)}}function IF(t,e,n){var r;if(e){const s=e.drawId||((r=e.matchUp)==null?void 0:r.drawId);if(s){const{event:i,drawDefinition:o}=Je({tournamentRecord:t,drawId:s});if(e={...e,event:i,drawDefinition:o},n){const c=ln({drawDefinition:o}),{matchUps:a}=xe({inContext:!0,drawDefinition:o,matchUpsMap:c});e.matchUpsMap=c,e.inContextDrawMatchUps=a}}if(e.eventId&&!e.event){const{event:i}=Je({eventId:e.eventId,tournamentRecord:t});i&&(e={...e,event:i})}}return e}function SF(t){return t.tournamentRecord?Cb(t):{error:et}}function TF({tournamentRecord:t,participantId:e}){if(!t)return{error:et};if(!e)return{error:Ce};const n=[e].concat((t.participants||[]).filter(s=>{var i;return(s==null?void 0:s.participantType)&&[se,_t].includes(s.participantType)&&((i=s.individualParticipantIds)==null?void 0:i.includes(e))}).map(s=>s.participantId));return{eventDetails:(t.events||[]).filter(s=>{const i=((s==null?void 0:s.entries)||[]).map(o=>o.participantId);return tn(i,n)}).map(s=>({eventName:s.eventName,eventId:s.eventId}))}}function yF({tournamentRecord:t,participantId:e}){if(!t)return{error:et};if(!e)return{error:Ce};const{tournamentParticipants:n}=dn({participantFilters:{participantTypes:[se,_t,Fn]},tournamentRecord:t});return(n||[]).filter(s=>{var i;return(i=s.individualParticipantIds)==null?void 0:i.includes(e)}).reduce((s,i)=>{const{participantType:o}=i;return s[o]||(s[o]=[]),s[o].push(i),s},{})}function EF({participantFilters:t={},tournamentRecord:e}){if(!e)return{error:et};if(typeof t!="object")return{error:Ir,context:{participantFilters:t}};const n={eventIds:t.eventIds},r=He({tournamentRecord:e,contextFilters:n}).matchUps||[],s=Object.assign({},...r.map(l=>({[l.matchUpId]:l}))),i=r.filter(({schedule:l})=>l&&Object.keys(l).length),o=fr({tournamentRecord:e,matchUps:r}).sourceMatchUpIds||[],c={};for(const l of i){const{sides:f}=l;let p;const h=(f==null?void 0:f.map(m=>{if(m.participant)return[m.participant].concat(...m.participant.individualParticipants||[]);o[l.matchUpId]&&!p&&(p=(o[l.matchUpId]||[]).map(g=>s[g]).filter(({winningSide:g,bye:I})=>!g&&!I))}).filter(Boolean).flat())||[];for(const m of h){const{participantId:g}=m;c[g]||(c[g]={potentialMatchUps:[],participant:m,matchUps:[]}),c[g].matchUps.push(l)}const d=(p==null?void 0:p.map(({sides:m})=>m).flat().map(({participant:m})=>m&&[m].concat(...m.individualParticipants||[])).filter(Boolean).flat())||[];for(const m of d){const{participantId:g}=m;c[g]||(c[g]={potentialMatchUps:[],participant:m,matchUps:[]}),c[g].potentialMatchUps.push(l)}}return{participantSchedules:Object.values(c).filter(({participant:l})=>!(t.participantIds&&!t.participantIds.includes(l.participantId)||t.participantTypes&&!t.participantTypes.includes(l.participantType))),...$}}function bF({tournamentRecord:t,drawDefinition:e,byeAdvancements:n=!1}){if(!t)return{error:et};const r=t.participants;return Ub({tournamentParticipants:r,byeAdvancements:n,drawDefinition:e})}function NF({participantRole:t=fn,tournamentRecord:e,persons:n}){var d;if(!e)return{error:et};if(!Array.isArray(n))return{error:tt};if(!Object.keys(ly).includes(t))return{error:cv};const r=(e.participants||[]).map(({person:m})=>m==null?void 0:m.personId).filter(Boolean),s=[],i=n.filter(m=>m&&(!m.personId||!r.includes(m.personId))).map(m=>(m.personId||(m.personId=Yt()),s.push(m.personId),m)),o=(m,g)=>Object.assign({},...Object.keys(m).filter(I=>!g.includes(I)).map(I=>({[I]:m[I]}))),c=i.map(m=>bt({extensions:m.participantExtensions,timeItems:m.participantTimeItems,participantType:xt,participantRole:t,person:o(m,["participantExtensions","participantTimeItems","pairedPersons"])}));let a=0,u=0,l=Ss({participants:c,tournamentRecord:e});if(l.error)return l;u=l.addedCount||0;const f=[],p=((d=dn({participantFilters:{participantTypes:[xt]},tournamentRecord:e}))==null?void 0:d.tournamentParticipants)||[];if(t===fn&&n.filter(({pairedPersons:m})=>m).forEach(({personId:m,pairedPersons:g})=>{Array.isArray(g)&&g.forEach(I=>{const S=[m,I.personId].map(T=>Ps({tournamentParticipants:p,personId:T})).filter(Boolean);if(S.length===2){const T=S.map(fe);f.push(bt({extensions:I.participantExtensions,timeItems:I.timeItems,participantRole:fn,individualParticipantIds:T,participantType:_t}))}})}),f.length){if(l=Ss({participants:f,tournamentRecord:e}),l.error)return l;a=l.addedCount||0}const h=u+a;return{...$,addedCount:h,newPersonIds:s}}function AF({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:n}){var i,o;const r=(n.events||[]).filter(c=>{var a;return(c==null?void 0:c.eventType)===we&&((a=c==null?void 0:c.entries)==null?void 0:a.some(u=>u.participantId===e))}),s=c=>!t.includes(c.participantId);for(const c of r){c.entries=(c.entries||[]).filter(s);const{flightProfile:a}=be({event:c});(i=a==null?void 0:a.flights)==null||i.forEach(u=>{u.drawEntries=(u.drawEntries||[]).filter(s)}),(o=c==null?void 0:c.drawDefinitions)==null||o.forEach(u=>{u.entries=(u.entries||[]).filter(s)})}return{...$}}function Zh({individualParticipantIds:t,groupingParticipantId:e,removeFromOtherTeams:n,tournamentRecord:r}){const s="addIndividualParticipantIds";if(!r)return G({result:{error:et},stack:s});if(!e||!t)return G({result:{error:Tt},stack:s});const i=r.participants||[],o=i.find(f=>f.participantId===e);if(!o)return G({result:{error:_e},stack:s});if(o!=null&&o.participantType&&![se,Fn].includes(o.participantType))return G({result:{error:xr},context:{participantType:o.participantType},stack:s});const c=t.filter(f=>{const p=i.find(h=>h.participantId===f);return(p==null?void 0:p.participantType)!==xt});if(c.length)return G({result:{error:gr,invalidParticipantIds:c},stack:s});o.individualParticipantIds||(o.individualParticipantIds=[]);const a=o.individualParticipantIds,u=t.filter(f=>!a.includes(f));u.length&&(n&&Hh({individualParticipantIds:u,tournamentRecord:r}),o.individualParticipantIds=o.individualParticipantIds.concat(...u));const{topics:l}=$r();if(l.includes(nn)){const f=i.find(({participantId:p})=>p===e);Ht({topic:nn,payload:{participants:[f]}})}return AF({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:r}),{groupingParticipant:pt(o,!1,!0),added:u.length,...$}}function vF({individualParticipantIds:t,groupingParticipantId:e,tournamentRecord:n}){const r="modifyIndividualParticipantIds";if(!n)return G({result:{error:et},stack:r});if(!e||!t)return G({result:{error:Tt},stack:r});const s=n.participants||[],i=s.find(h=>h.participantId===e);if(!i)return G({result:{error:_e},stack:r});if(![se,Fn].includes(i.participantType))return G({result:{error:xr},context:{participantType:i.participantType},stack:r});const o=t.filter(h=>{const d=s.find(m=>m.participantId===h);return(d==null?void 0:d.participantType)!==xt});if(o.length)return G({result:{error:gr,invalidParticipantIds:o},stack:r});const c=i.individualParticipantIds||[],a=t.filter(h=>!c.includes(h)),u=c.filter(h=>!t.includes(h)),l=Zh({individualParticipantIds:a,groupingParticipantId:e,tournamentRecord:n});if(l.error)return G({result:l,stack:r});const f=cb({individualParticipantIds:u,groupingParticipantId:e,tournamentRecord:n});if(f.error)return G({result:f,stack:r});const{topics:p}=$r();if(p.includes(nn)){const h=s.find(({participantId:d})=>d===e);Ht({topic:nn,payload:{tournamentId:n.tournamentId,participants:[h]}})}return{...l,...f}}function Fb({addParticipants:t=!0,participantAttribute:e,tournamentRecord:n,personAttribute:r,teamNames:s,accessor:i,uuids:o}){var d,m;if(!n)return{error:et};const c={},a=(n.participants||[]).filter(({participantType:g,participantRole:I})=>g===xt&&I===fn);let u=0;for(const g of a){const S=i&&((d=Yi({element:g,accessor:i}))==null?void 0:d.value)||r&&((m=g.person)==null?void 0:m[r])||e&&g[e];if(S){if(!Object.keys(c).includes(S)){c[S]={participantName:(s==null?void 0:s[u])||S,participantId:(o==null?void 0:o.pop())||Yt(),individualParticipantIds:[],participantRole:fn,participantType:se};const T={name:mf,value:r||e};ae({element:c[S],extension:T}),u+=1}c[S].individualParticipantIds.push(g.participantId)}}const l=Object.keys(c),f=(n.participants||[]).map(g=>{if(g.participantType!==se||g.participantRole!==fn)return;const{extension:I}=xn({name:mf,element:g}),S=I==null?void 0:I.value;if(l.includes(S))return g.participantId}).filter(Boolean);let p=0;const h=[];return Object.keys(c).forEach(g=>{const I=c[g],{participantId:S}=I;f.includes(S)||(n.participants||(n.participants=[]),t&&n.participants.push(I),h.push(I),p++)}),t&&p?(Ht({payload:{tournamentId:n.tournamentId,participants:h},topic:yi}),{...$,participantsAdded:p}):h.length?{...$,newParticipants:h}:{error:iv}}function CF({tournamentRecord:t,participantIds:e,signInState:n}){if(!t)return{error:et};if(!Array.isArray(e))return{error:Tt};if(![ya,_P].includes(n))return{error:tt,signInState:n};const s=t.participants||[];if(!s.length)return{error:Yc};const i=s.map(fe),o=e.filter(l=>!i.includes(l));if(o.length)return{error:tt,context:{invalidParticipantIds:o}};const c=[],a=new Date().toISOString();for(const l of s){const{participantId:f}=l;if(e.includes(f)){const h=PT({duplicateValues:!1,tournamentRecord:t,participantId:f,timeItem:{itemType:Ta,itemValue:n,createdAt:a}});if(h.error)return h;c.push(l)}}const{topics:u}=$r();return c.length&&u.includes(nn)&&Ht({topic:nn,payload:{tournamentId:t.tournamentId,participants:c}}),{...$}}function PF({clearExistingAssignments:t=!0,individualParticipantIds:e,reverseAssignmentOrder:n,initialTeamIndex:r=0,scaledParticipants:s=[],teamParticipantIds:i,tournamentRecord:o,scaleAttributes:c,teamNameBase:a,teamsCount:u,eventId:l,event:f}){var I,S,T,E;if(!o)return{error:et};if(!Array.isArray(i)&&!oe(u)&&!l||!oe(r)||s&&!Array.isArray(s)||c&&(typeof c!="object"||!Object.keys(c).length))return{error:tt};if(!c&&!s.length||!s&&!(e&&c))return{error:Tt,info:"Missing scaling details"};if(l&&!i){if((f==null?void 0:f.eventType)!==ds)return{error:ui};i=(I=f==null?void 0:f.entries)==null?void 0:I.filter(({entryStatus:y})=>y===Ur).map(fe)}if(!(i!=null&&i.length)&&!u)return{info:"Missing teamParticipantIds or teamsCount",error:Tt};let p=e||s.map(({participantId:y})=>y);n&&(i==null||i.reverse(),r+=1),r>((i==null?void 0:i.length)||0)-1&&(r=0);const h=(i==null?void 0:i.slice(r).concat(...i.slice(0,r)))||[],d=[];for(const y of o.participants||[]){const{participantId:b,participantType:N}=y;if(h.includes(b)){if(N!==vr)return{error:xr,participant:y};d.push(y)}}if(u&&d.length<u){const y=u-((d==null?void 0:d.length)||0),b=a||"Team",N=ht(0,y).map(P=>({participantName:`${b} ${P+1}`,participantType:vr,participantRole:fn})),{participants:A=[]}=Ss({participants:N,returnParticipants:!0,tournamentRecord:o}),C=A.map(fe),v=((S=o.participants)==null?void 0:S.filter(({participantId:P})=>C.includes(P)))??[];d.push(...v)}if(!d.length)return{error:yg};if(t)for(const y of d)y.individualParticipantIds=[];else{const y=d.map(b=>b).flat();e!=null&&e.length?p=p.filter(b=>!y.includes(b)):s=s==null?void 0:s.filter(({participantId:b})=>!y.includes(b))}if(!(e!=null&&e.length)&&!(s!=null&&s.length))return{error:Jd,info:"Nothing to be done"};if(!s.length){for(const y of o.participants||[]){const{participantId:b,participantType:N}=y;if(!p.includes(b))continue;if(N!==xt)return{error:xr,participant:y};const A=(T=Ts({scaleAttributes:c,participant:y}))==null?void 0:T.scaleItem,C=c!=null&&c.accessor?(E=A==null?void 0:A.scaleValue)==null?void 0:E[c==null?void 0:c.accessor]:A==null?void 0:A.scaleValue,v={participantId:b,scaleValue:C};s.push(v)}if(!s.length)return{error:_e}}s.sort((y,b)=>c!=null&&c.sortOrder?((b==null?void 0:b.scaleValue)||0)-((y==null?void 0:y.scaleValue)||0):((y==null?void 0:y.scaleValue)||1/0)-((b==null?void 0:b.scaleValue)||1/0));for(const y of s)if(!y.participantId)return{error:tt,scaledParticipant:y};let m=0;for(;m<s.length;){for(const y of d){if(m+1>s.length)break;const b=s[m];y.individualParticipantIds.push(b.participantId),m++}d.reverse()}const g=d.map(fe);for(const y of o.events||[]){if(y.eventType!==ds)continue;const b=(y.entries||[]).filter(N=>g.includes(N.participantId));for(const N of b){const A=N.participantId,C=d.find(U=>U.participantId===A),v=C==null?void 0:C.individualParticipantIds;y.entries=(y.entries||[]).filter(U=>!v.includes(U.participantId)),(y.drawDefinitions||[]).forEach(U=>{U.entries=(U.entries||[]).filter(O=>!v.includes(O.participantId))});const{flightProfile:P}=be({event:y});((P==null?void 0:P.flights)||[]).forEach(U=>{U.drawEntries=(U.drawEntries||[]).filter(O=>!v.includes(O.participantId))})}}return{...$,scaledParticipants:s}}function UF({individualParticipantIds:t=[],participantRoleResponsibilities:e,participantRole:n=uy,tournamentRecord:r,participantId:s,groupName:i}){if(!r)return{error:et};if(!i)return{error:Tt,info:"Missing groupName"};if(!Array.isArray(t))return{info:"Invalid individualParticipantIds",error:tt};const{tournamentParticipants:o}=dn({participantFilters:{participantTypes:[xt]},tournamentRecord:r}),c=o.map(f=>f.participantId);for(const f of t)if(!c.includes(f))return{error:xr,participantId:f};const a=bt({participantId:s||Yt(),participantRoleResponsibilities:e,participantName:i,individualParticipantIds:t,participantType:Fn,participantRole:n}),u=es({participant:a,tournamentRecord:r});if(u.error)return u;const{topics:l}=$r();return l.includes(yi)&&Ht({topic:yi,payload:{tournamentId:r.tournamentId,participants:[a]}}),{...$,participant:pt(a)}}function OF({tournamentRecord:t,participantId:e,participantOtherName:n}){if(!t)return{error:et};if(!e)return{error:Ce};const{participant:r}=zs({tournamentRecord:t,participantId:e});if(!r)return{error:_e};r.participantOtherName=n;const{topics:s}=$r();return s.includes(nn)&&Ht({topic:nn,payload:{tournamentId:t.tournamentId,participants:[r]}}),{...$}}function Lb({personFormat:t,person:e}){const n=g=>g.replace(/\W/g,""),r=g=>/^[a-z]*$/.test(n(g)),s=g=>/^[A-Z]*$/.test(n(g)),i=g=>/^[LAST]{4}/.test(n(g)),o=g=>g.toLowerCase().indexOf("l")<g.toLowerCase().indexOf("f"),c=g=>g.indexOf(",")>=0,a=g=>g.toLowerCase().indexOf("f.")>=0,u=g=>g.toLowerCase().indexOf("f")<0,l=g=>g.indexOf(" ")>0;if(!e)return;const f=l(t)?" ":"",p=g=>g.split(" ").map(I=>I.split("").map((S,T)=>T?S.toLowerCase():S.toUpperCase()).join("")).join(" ");let h=p((e==null?void 0:e.standardGivenName)??""),d=p((e==null?void 0:e.standardFamilyName)??"");if(!t)return`${h}${f}${d}`;a(t)&&!c(t)&&!o(t)&&(h=`${h[0]}.`),r(t)?(h=h.toLowerCase(),d=d.toLowerCase()):s(t)?(h=h.toUpperCase(),d=d.toUpperCase()):i(t)&&(d=d.toUpperCase());let m=`${h}${f}${d}`;return u(t)?m=d:o(t)&&(c(t)?m=`${d},${f}${h}`:m=`${d}${f}${h}`),m}function MF({participantMap:t,participant:e,formats:n}){const{participantType:r,individualParticipantIds:s,person:i}=e,o=r&&n[r];if(r!==vr&&o){const{personFormat:c,doublesJoiner:a}=o;r===xt&&(e.participantName=Lb({person:i,personFormat:c})),r===_t&&(e.participantName=s==null?void 0:s.map(u=>{var f;const l=(f=t[u])==null?void 0:f.person;return Lb({person:l,personFormat:c})}).filter(Boolean).join(a??"/"))}}function DF({tournamentRecord:t,formats:e}){if(!t)return{error:et};if(!or(e))return{error:Tt};const n=t.participants??[],r=yC(n,"participantId");for(const s of n)MF({participant:s,participantMap:r,formats:e});return{...$}}function wF({tournamentRecord:t,participantFilters:e}){if(!t)return{error:et};let n=t.participants||[];e&&(n=Hl({participants:n,participantFilters:e,tournamentRecord:t}));const r={},s=i=>{if(i.person){const{personId:o}=i.person;r[o]?r[o].participantIds.push(i.participantId):r[o]={...i.person,participantIds:[i.participantId]}}};return n.forEach(i=>{i.person&&s(i),i.individualParticipants&&i.individualParticipants.forEach(s)}),{tournamentPersons:Object.values(r)}}function kF({tournamentRecord:t,participantName:e,participantId:n}){if(!t)return{error:et};if(!n)return{error:Ce};if(!e)return{error:Tt,info:"Missing participantName"};const{participant:r}=zs({tournamentRecord:t,participantId:n});if(!r)return{error:_e};r.participantName=e;const{topics:s}=$r();return s.includes(nn)&&Ht({topic:nn,payload:{tournamentId:t.tournamentId,participants:[r]}}),{...$}}function _F({participants:t=[],tournamentRecord:e,arraysToMerge:n}){if(!e)return{error:et};e.participants||(e.participants=[]);const r=t.filter(dl).map(u=>({[u.participantId]:u})),s=Object.assign({},...r),i=[];e.participants=e.participants.map(u=>{if(s[u.participantId]){const l=Wp(u,s[u.participantId],n);return i.push(l),l}return u});const o=e.participants.map(fe),c=t.filter(({participantId:u})=>!o.includes(u)),{topics:a}=$r();return c.length&&(e.participants=e.participants.concat(...c),a.includes(yi)&&Ht({topic:yi,payload:{participants:c}})),i.length&&a.includes(nn)&&Ht({topic:nn,payload:{tournamentId:e.tournamentId,participants:i}}),{modifiedParticipantsCount:i.length,newParticipantsCount:c.length,...$}}function Xh(t){const{updateParticipantName:e=!0,groupingParticipantId:n,removeFromOtherTeams:r,tournamentRecord:s,pairOverride:i,participant:o}=t;if(!s)return{error:et};if(!o)return{error:qo};if(!o.participantId)return es({tournamentRecord:s,participant:o});const{participant:c}=zs({participantId:o.participantId,tournamentRecord:s});if(!c)return es({tournamentRecord:s,participant:o});const{participantRoleResponsibilties:a,individualParticipantIds:u,participantOtherName:l,participantName:f,participantRole:p,participantType:h,onlineResources:d,contacts:m,person:g}=o;if(h&&c.participantType!==h)return{error:ov};const I={};if(m&&(I.contacts=m),d&&(I.onlineResources=d),f&&typeof f=="string"&&(I.participantName=f),l&&typeof l=="string"&&(I.participantOtherName=l),Array.isArray(u)){const{tournamentParticipants:S}=dn({participantFilters:{participantTypes:[Ea.INDIVIDUAL]},tournamentRecord:s}),T=S==null?void 0:S.map(fe);if(T){const E=u.filter(y=>typeof y=="string"&&T.includes(y));([Fn,Jt].includes(h||c.participantType)||h===_t&&(E.length===2||i))&&(I.individualParticipantIds=E),c.participantType===Ea.PAIR&&e&&(I.participantName=FF({individualParticipants:S,newValues:I}))}}return Object.keys(ly).includes(p)&&(I.participantRole=p),Object.keys(Ea).includes(h)&&(I.participantType=h),Array.isArray(a)&&(I.participantRoleResponsibilties=a),c.participantType===Ea.INDIVIDUAL&&g&&LF({updateParticipantName:e,existingParticipant:c,newValues:I,person:g}),Object.assign(c,bt(I)),n&&Zh({individualParticipantIds:[c.participantId],groupingParticipantId:n,removeFromOtherTeams:r,tournamentRecord:s}),Ht({topic:nn,payload:{tournamentId:s.tournamentId,participants:[c]}}),{participant:pt(c),...$}}function FF({individualParticipants:t,newValues:e}){const n=e.individualParticipantIds;let r=t.filter(({participantId:s})=>n.includes(s)).map(({person:s})=>s==null?void 0:s.standardFamilyName).filter(Boolean).sort().join("/");return n.length===1&&(r+="/Unknown"),r}function LF({updateParticipantName:t,existingParticipant:e,newValues:n,person:r}){const s={},{standardFamilyName:i,standardGivenName:o,nationalityCode:c,personId:a,sex:u}=r;u&&Object.keys(iS).includes(u)&&(s.sex=u);let l;if(a&&typeof a=="string"&&(s.personId=a),c&&typeof c=="string"&&(RF(c)||c==="")&&(s.nationalityCode=c),i&&typeof i=="string"&&i.length>1&&(s.standardFamilyName=i,l=!0),o&&typeof o=="string"&&o.length>1&&(s.standardGivenName=o,l=!0),l&&t){const f=`${s.standardGivenName} ${s.standardFamilyName}`;n.participantName=f}Object.assign(e.person,s)}function RF(t){return ri.flatMap(({iso:e,ioc:n})=>[e,n]).filter(Boolean).includes(t)}function Rb({drawDefinition:t,timeItem:e}){if(!t)return{error:rr};if(!e)return{error:Sg};const n=e&&Object.keys(e),r=["itemType","itemValue"];if(!(r.filter(o=>n.includes(o)).length===r.length))return{error:Ig};t.timeItems||(t.timeItems=[]);const i=new Date().toISOString();return Object.assign(e,{createdAt:i}),t.timeItems.push(e),Ba({drawDefinition:t}),{...$}}function du(t){const{removePriorValues:e,tournamentRecord:n,participantId:r,scaleItem:s}=t;let i,o;if(!Bb({scaleItem:s}))return{error:Uu};if(r&&Array.isArray(n.participants)&&(o=n.participants.find(c=>c.participantId===r),o)){const c=xb({removePriorValues:e,participant:o,scaleItem:s});if(c.error)return c;i=!c.valueChanged;const{topics:a}=$r();a.includes(nn)&&Ht({topic:nn,payload:{tournamentId:n.tournamentId,participants:[o]}})}return i&&{...$,info:Eg,existingValue:s.scaleValue}||o&&{...$,newValue:s.scaleValue}||{error:_e}}function BF(t){var f;const{scaleItemsWithParticipantIds:e=[],removePriorValues:n,tournamentRecord:r,auditData:s,context:i}=t;if(!r)return{error:et};if(!r.participants)return{error:Yc};let o=0;const c={},a=[];for(const p of e){const h=p==null?void 0:p.participantId;if(Array.isArray(p==null?void 0:p.scaleItems))for(const d of p.scaleItems)if(Bb({scaleItem:d}))Array.isArray(c[h])||(c[h]=[]),c[h].push(d);else return{error:Uu}}r.participants.forEach(p=>{const{participantId:h}=p||{};Array.isArray(c[h])&&c[h].forEach(d=>{xb({participant:p,scaleItem:d,removePriorValues:n}),a.push(p),o++})});const u=o?void 0:zc,{topics:l}=$r();if(l.includes(nn)&&o&&Ht({topic:nn,payload:{tournamentId:r.tournamentId,participants:a}}),i){const{eventId:p,drawId:h,...d}=i,m=((f=d.scaleAttributes)==null?void 0:f.scaleType)&&[d.scaleAttributes.scaleType];if(Object.keys(d).length){const g={itemType:EI,itemValue:d};if(m&&(g.itemSubTypes=m),h||p){const{drawDefinition:I,event:S}=Je({tournamentRecord:r,eventId:p,drawId:h});h&&Rb({drawDefinition:I,timeItem:g}),p&&ii({event:S,timeItem:g})}else _s({tournamentRecord:r,timeItem:g})}}return s&&l.includes(ha)&&Ht({topic:ha,payload:s}),bt({...$,modificationsApplied:o,info:u})}function Bb({scaleItem:t}){const e=t&&Object.keys(t),n=["scaleType","eventType","scaleName"];return!!(n.filter(s=>e==null?void 0:e.includes(s)).length===n.length)}function xb({removePriorValues:t,participant:e,scaleItem:n}){if(!e)return{error:qo};const r=n&&Object.keys(n),s=["scaleType","eventType","scaleName"];if(!(s.filter(l=>r.includes(l)&&n[l]).length===s.length))return{error:Uu};const o=new Date().toISOString();e.timeItems||(e.timeItems=[]);const{scaleItem:c}=Ts({scaleAttributes:n,participant:e}),a=l=>[void 0,null,""].includes(l),u=!(a(c==null?void 0:c.scaleValue)&&a(n.scaleValue))&&JSON.stringify(c==null?void 0:c.scaleValue)!==JSON.stringify(n.scaleValue);if(u){const{scaleType:l,eventType:f,scaleName:p}=n,h=[eo,l,f,p].join("."),d=bt({itemValue:n.scaleValue,itemDate:n.scaleDate,createdAt:o,itemType:h});n.scaleId&&(d.itemSubTypes=[n.scaleId]),t&&(e.timeItems=e.timeItems.filter(m=>m.itemType!==h)),e.timeItems.push(d)}return{...$,valueChanged:u,newValue:n.scaleValue}}const xF={getTournamentPenalties:vy,modifyPenalty:Cy,removePenalty:Ay,addPenalty:Ny,createGroupParticipant:UF,scaledTeamAssignment:PF,deleteParticipants:Fc,addParticipants:Ss,addParticipant:es,addPersons:NF,addIndividualParticipantIds:Zh,removeIndividualParticipantIds:cb,modifyIndividualParticipantIds:vF,removeParticipantIdsFromAllTeams:Hh,getParticipantMembership:yF,generateTeamsFromParticipantAttribute:Fb,regenerateParticipantNames:DF,getParticipantIdFinishingPositions:bF,modifyParticipant:Xh,modifyParticipantName:kF,modifyParticipantOtherName:OF,mergeParticipants:_F,getPairedParticipant:Jr,filterParticipants:Hl,setParticipantScaleItem:du,setParticipantScaleItems:BF,modifyParticipantsSignInStatus:CF,getParticipantEventDetails:TF,getEligibleVoluntaryConsolationParticipants:SF,findParticipant:rP,getTournamentParticipants:dn,getParticipantSchedules:EF,getTournamentPersons:wF,getParticipants:Fi};function $F({removePriorValues:t=!0,stageSeedingScaleNames:e,seedingScaleNames:n,tournamentRecord:r,status:s=Kr,drawIds:i=[],event:o}){var h,d,m,g;if(!r)return{error:et};if(!o)return{error:Wt};const c=`${Qn}.${Zn}`,{timeItem:a}=ws({itemType:c,event:o}),u=(a==null?void 0:a.itemValue)||{[s]:{}},l=(((h=u[s].seeding)==null?void 0:h.seedingScaleNames)||n)&&{...(d=u[s].seeding)==null?void 0:d.seedingScaleNames,...n},f=(((m=u[s].seeding)==null?void 0:m.stageSeedingScaleNames)||e)&&{...(g=u[s].seeding)==null?void 0:g.stageSeedingScaleNames,...e};return u[s].seeding=bt({stageSeedingScaleNames:f,seedingScaleNames:l,published:!0,drawIds:i}),ii({event:o,timeItem:{itemValue:u,itemType:c},removePriorValues:t}),Ht({topic:EP,payload:{tournamentId:r.tournamentId,eventId:o.eventId,drawIds:i}}),{...$}}function VF({removePriorValues:t=!0,seedingScaleNames:e,tournamentRecord:n,status:r=Kr,stages:s,event:i}){var l,f;if(!n)return{error:et};if(!i)return{error:Wt};const o=`${Qn}.${Zn}`,{timeItem:c}=ws({itemType:o,event:i}),a=(c==null?void 0:c.itemValue)||{[r]:{}};if(a[r]){if(Array.isArray(s)&&((l=a[r].seeding)!=null&&l.stageSeedingScaleNames))for(const p of s)a[r].seeding.stageSeedingScaleNames[p]&&delete a[r].seeding.stageSeedingScaleNames[p];Array.isArray(e)&&((f=a[r].seeding)!=null&&f.seedingScaleNames)&&(a[r].seeding.seedingScaleNames=a[r].seeding.seedingScaleNames.filter(p=>!e.includes(p))),!s&&!e&&delete a[r].seeding}return ii({event:i,timeItem:{itemValue:a,itemType:o},removePriorValues:t}),Ht({topic:kI,payload:{tournamentId:n.tournamentId,eventId:i.eventId}}),{...$}}function jF({tournamentRecord:t,policyDefinitions:e}){if(!t)return{error:et};const n=t.events||[],r=(t==null?void 0:t.participants)||[],{tournamentInfo:s}=tu({tournamentRecord:t}),{venues:i}=Of({tournamentRecord:t}),o=n.map(a=>{const{eventId:u}=a,l=(({eventId:d,eventName:m,eventType:g,eventLevel:I,surfaceCategory:S,matchUpFormat:T,category:E,gender:y,startDate:b,endDate:N,ballType:A,discipline:C})=>({eventId:d,eventName:m,eventType:g,eventLevel:I,surfaceCategory:S,matchUpFormat:T,category:E,gender:y,startDate:b,endDate:N,ballType:A,discipline:C}))(a),f=pa({tournamentRecord:t,event:a}).scheduleTiming,p=(a.drawDefinitions||[]).map(d=>{const m=(({drawId:E,drawName:y,matchUpFormat:b,updatedAt:N})=>({matchUpFormat:b,updatedAt:N,drawName:y,drawId:E}))(d),{abandonedMatchUps:g,completedMatchUps:I,upcomingMatchUps:S,pendingMatchUps:T}=To({requireParticipants:!0,tournamentParticipants:r,context:{eventId:u},policyDefinitions:e,tournamentRecord:t,inContext:!0,scheduleTiming:f,drawDefinition:d,event:a});return{drawInfo:m,matchUps:{abandonedMatchUps:g,completedMatchUps:I,upcomingMatchUps:S,pendingMatchUps:T}}}),{timeItem:h}=ws({itemType:`${Qn}.${Zn}`,event:a});return Object.assign(l,{publish:h==null?void 0:h.itemValue,drawsData:p}),l});return{allEventData:{tournamentInfo:s,venuesData:i,eventsData:o}}}function GF({removePriorValues:t=!0,tournamentRecord:e,status:n=Kr,event:r}){if(!e)return{error:et};if(!r)return{error:Wt};const s=`${Qn}.${Zn}`,{timeItem:i}=ws({itemType:s,event:r}),o=(i==null?void 0:i.itemValue)||{[n]:{}};return delete o[n].structureIds,delete o[n].drawIds,ii({event:r,timeItem:{itemValue:o,itemType:s},removePriorValues:t}),Ht({topic:wI,payload:{tournamentId:e.tournamentId,eventId:r.eventId}}),{eventId:r.eventId,...$}}function $b({drawDefinition:t}){const e=t.links||[],n={},r={};let s=e.map(h=>{const d=h.source.structureId,m=h.target.structureId;return r[m]=r[m]||h.target.feedProfile===Cr,n[m]=Vt([...n[m]||[],d]).filter(Boolean),[h.source.structureId,h.target.structureId]});const i=s.length;ht(0,Math.ceil(i/2)).forEach(()=>{s=ht(0,i).map(h=>{const d=s[h],m=s.reduce((g,I)=>tn(d,I)?g.concat(...I):g,[])||[];return Vt(d.concat(...m))})});const o=s[0],c=(h,d)=>qe(h,d).length===h.length,a=s.slice(1).reduce((h,d)=>h&&c(d,o),!0),u=[o].filter(Boolean),l=[o].filter(Boolean);return(t.structures||[]).forEach(h=>{const{structureId:d,stage:m}=h;u.find(I=>I.includes(d))||(u.push([d]),m!==je&&l.push(d))}),{allStructuresLinked:a&&l.length===1,sourceStructureIds:n,hasDrawFeedProfile:r,structureGroups:u}}function Vb(t){const{tournamentParticipants:e=[],includePositionAssignments:n,policyDefinitions:r,tournamentRecord:s,inContext:i=!0,drawDefinition:o,noDeepCopy:c,sortConfig:a,context:u,event:l}=t;if(!o)return{error:lt};const f=(({matchUpFormat:b,updatedAt:N,drawType:A,drawName:C,drawId:v})=>({matchUpFormat:b,updatedAt:N,drawName:C,drawType:A,drawId:v}))(o);let p,h;const{allStructuresLinked:d,sourceStructureIds:m,hasDrawFeedProfile:g,structureGroups:I}=$b({drawDefinition:o});if(!d)return{error:W1};let S=!1,T=!1;const y=I.map(b=>{const N={},A=b.map(C=>{const{structure:v}=Ot({drawDefinition:o,structureId:C}),{seedAssignments:P}=Mr({drawDefinition:o,structure:v});return(v==null?void 0:v.stage)===It&&v.stageSequence===1&&(p=P),(v==null?void 0:v.stage)===Pt&&v.stageSequence===1&&(h=P),v}).sort((C,v)=>Pi(C,v,a)).map(C=>{var F;const{structureId:v}=C;let P=[];[It,Re,Ie].includes(C.stage)&&(P=p),C.stage===Pt&&(P=h);const{matchUps:U,roundMatchUps:O,roundProfile:D}=Qt({seedAssignments:(F=C==null?void 0:C.seedAssignments)!=null&&F.length?void 0:P,context:{drawId:f.drawId,...u},tournamentParticipants:e,policyDefinitions:r,tournamentRecord:s,drawDefinition:o,inContext:i,structure:C,event:l}),{positionAssignments:M}=ee({structure:C}),w=M==null?void 0:M.filter(dl).map(L=>{T=!0;const{drawPosition:W,participantId:j}=L,{extension:H}=Ke({element:L,name:Ys});return H&&{drawPosition:W,participantId:j,participantResult:H.value}}).filter(L=>L==null?void 0:L.participantResult),k=(({stageSequence:L,structureName:W,structureType:j,matchUpFormat:H,stage:B})=>({stageSequence:L,structureName:W,structureType:j,matchUpFormat:H,stage:B}))(C);k.sourceStructureIds=m[v],k.hasDrawFeedProfile=g[v],k.positionAssignments=M,k.structureActive=U.reduce((L,W)=>{var H;const j=[De,Gs,te,In,ce,Gr,en,Fe].includes(W.matchUpStatus);return L||j||!!W.winningSide||!!((H=W.score)!=null&&H.scoreStringSide1)},!1);const _=U.reduce((L,W)=>L&&[re,De,In,ce,te,zn].includes(W.matchUpStatus),!!U.length);return k.structureCompleted=_,N[v]=_,k.structureActive&&(S=!0),{...k,participantResults:w,seedAssignments:P,roundMatchUps:O,roundProfile:D,structureId:v}});return A.forEach(C=>{var v;n||delete C.positionAssignments,C.sourceStructuresComplete=(v=C.sourceStructureIds)==null?void 0:v.every(P=>N[P])}),A}).flat();return f.drawActive=S,f.participantPlacements=T,f.drawGenerated=y==null?void 0:y.reduce((b,N)=>b||!!(N!=null&&N.roundMatchUps),!1),f.drawCompleted=y==null?void 0:y.reduce((b,N)=>b&&N.structureCompleted,!0),{structures:c?y:pt(y,!1,!0),drawInfo:c?f:pt(f,!1,!0),...$}}function jb(t){var P;const{includePositionAssignments:e,tournamentRecord:n,participantsProfile:r,policyDefinitions:s,usePublishState:i,status:o=Kr,sortConfig:c,event:a}=t,u=pt(n,!1,!0),l=pt(a,!1,!0);if(!u)return{error:et};if(!l)return{error:Wt};const{eventId:f}=l,{tournamentId:p,endDate:h}=u,{timeItem:d}=ws({itemType:`${Qn}.${Zn}`,event:l}),m=(P=d==null?void 0:d.itemValue)==null?void 0:P[o],{tournamentParticipants:g}=dn({withGroupings:!0,withEvents:!1,withDraws:!1,...r,tournamentRecord:u}),I=({stage:U})=>{var O;return!i||!((O=m==null?void 0:m.stages)!=null&&O.length)||m.stages.includes(U)},S=({structureId:U})=>{var O;return!i||!((O=m==null?void 0:m.structureIds)!=null&&O.length)||m.structureIds.includes(U)},T=({drawId:U})=>{var O;return!i||!((O=m==null?void 0:m.drawIds)!=null&&O.length)||m.drawIds.includes(U)},y=(l.drawDefinitions||[]).filter(T).map(U=>(({drawInfo:O,structures:D})=>({...O,structures:D}))(Vb({context:{eventId:f,tournamentId:p,endDate:h},includePositionAssignments:e,tournamentParticipants:g,noDeepCopy:!0,policyDefinitions:s,tournamentRecord:u,drawDefinition:U,sortConfig:c,event:l}))).map(({structures:U,...O})=>{var D;return{...O,structures:(D=U==null?void 0:U.filter(S))==null?void 0:D.filter(I)}}).filter(U=>{var O;return(O=U.structures)==null?void 0:O.length}),{tournamentInfo:b}=tu({tournamentRecord:u}),A=(u.venues||[]).map(U=>(({venueData:O})=>({...O}))(Ju({tournamentRecord:u,venueId:U.venueId}))),C=(({eventId:U,eventName:O,eventType:D,eventLevel:M,surfaceCategory:w,matchUpFormat:k,category:_,gender:F,startDate:L,endDate:W,ballType:j,discipline:H})=>({eventId:U,eventName:O,eventType:D,eventLevel:M,surfaceCategory:w,matchUpFormat:k,category:_,gender:F,startDate:L,endDate:W,ballType:j,discipline:H}))(l),v={tournamentInfo:b,venuesData:A,eventInfo:C,drawsData:y};return v.eventInfo.publish={createdAt:d==null?void 0:d.createdAt,state:d==null?void 0:d.itemValue},{...$,eventData:v}}function fu(t){var N,A,C,v,P,U,O,D,M,w;let{policyDefinitions:e,drawIds:n,structureIds:r,stages:s}=t;const{includePositionAssignments:i,removePriorValues:o,tournamentRecord:c,status:a=Kr,event:u,drawIdsToRemove:l,drawIdsToAdd:f,stagesToRemove:p,stagesToAdd:h,structureIdsToRemove:d,structureIdsToAdd:m}=t;if(!c)return{error:et};if(!u)return{error:Wt};if(!e){const{appliedPolicies:k}=ge({tournamentRecord:c,event:u});e=k}const g=`${Qn}.${Zn}`,I=((N=u.drawDefinitions)==null?void 0:N.map(({drawId:k})=>k))||[],{timeItem:S}=ws({itemType:g,event:u});!n&&!f&&!l?n=I:!n&&(f!=null&&f.length||l!=null&&l.length)&&(n=((C=(A=S==null?void 0:S.itemValue)==null?void 0:A.PUBLIC)==null?void 0:C.drawIds)||[]),n=(n||[]).filter(k=>!(l!=null&&l.length)||!l.includes(k)),f!=null&&f.length&&(n=Vt(n.concat(...f.filter(k=>I.includes(k))))),!r&&(m!=null&&m.length||d!=null&&d.length)&&(r=((P=(v=S==null?void 0:S.itemValue)==null?void 0:v.PUBLIC)==null?void 0:P.structureIds)||[]),r=(r||[]).filter(k=>!(d!=null&&d.length)||!d.includes(k)),m!=null&&m.length&&(r=Vt(r.concat(...m))),!s&&(h!=null&&h.length||p!=null&&p.length)&&(s=((O=(U=S==null?void 0:S.itemValue)==null?void 0:U.PUBLIC)==null?void 0:O.stages)||[]),s=(s||[]).filter(k=>!(p!=null&&p.length)||!p.includes(k)),h!=null&&h.length&&(s=Vt(s.concat(...h)));const T=(D=S==null?void 0:S.itemValue)==null?void 0:D[a],E={itemValue:{[a]:{...T,drawIds:n,structureIds:r,stages:s}},itemType:g};ii({event:u,timeItem:E,removePriorValues:o});const{eventData:y}=jb({includePositionAssignments:i,usePublishState:!0,tournamentRecord:c,policyDefinitions:e,event:u}),b=(w=(M=y==null?void 0:y.eventInfo)==null?void 0:M.publish)==null?void 0:w.state;return y.drawsData=y.drawsData.filter(({drawId:k})=>{var _;return(_=b==null?void 0:b.PUBLIC)==null?void 0:_.drawIds.includes(k)}),Ht({payload:{eventData:y,tournamentId:c.tournamentId},topic:yP}),{...$,eventData:y}}const WF={getTournamentInfo:tu,getVenueData:Ju,getCourtInfo:FI,getAllEventData:jF,getEventData:jb,getDrawData:Vb,unPublishEventSeeding:VF,publishEventSeeding:$F,unPublishEvent:GF,publishEvent:fu,unPublishOrderOfPlay:Dy,publishOrderOfPlay:wy};function Gb({collectionPosition:t,teamParticipantId:e,dualMatchUpSide:n,drawDefinition:r,participantIds:s,collectionId:i}){var l;if(!i||!t||!Array.isArray(s))return{modifiedLineUp:(n==null?void 0:n.lineUp)||[],error:tt};const o=(n==null?void 0:n.lineUp)||((l=ba({participantId:e,drawDefinition:r}))==null?void 0:l.lineUp),c=[],a=[];return{modifiedLineUp:(o==null?void 0:o.map(f=>{var h;if(!s.includes(f.participantId))return f;const p=(h=f.collectionAssignments)==null?void 0:h.filter(d=>{const m=d.collectionId===i&&d.collectionPosition===t;return m&&(d.previousParticipantId&&c.push(d.previousParticipantId),a.push({participantId:f.participantId,...d})),!m});return{participantId:f.participantId,collectionAssignments:p}}).filter(Boolean))||[],assignmentsRemoved:a,previousParticipantIds:c}}function tm({tournamentRecord:t,drawDefinition:e,tieMatchUpId:n,event:r}){var E;if(!t)return{error:et};if(!e)return{error:Hn};if(!r)return{error:wn};const s=ln({drawDefinition:e}),{matchUp:i}=ie({matchUpId:n,drawDefinition:e,matchUpsMap:s});if(!i)return{error:Ye};const{matchUp:o,structure:c}=ie({tournamentParticipants:t.participants,matchUpId:n,inContext:!0,drawDefinition:e,matchUpsMap:s,event:r});if(!o)return{error:Ye};const{collectionPosition:a,drawPositions:u,collectionId:l,matchUpTieId:f,matchUpType:p}=o;if(p&&![Oe,me].includes(p))return{error:qn};const{positionAssignments:h}=ee({structure:c}),d=h==null?void 0:h.filter(y=>u==null?void 0:u.includes(y.drawPosition)),m=d==null?void 0:d.map(kn("participantId")),{tournamentParticipants:g}=dn({tournamentRecord:t,participantFilters:{participantTypes:[se],participantIds:m}}),{matchUp:I}=ie({matchUpId:f,drawDefinition:e,matchUpsMap:s}),{matchUp:S}=ie({matchUpId:f,inContext:!0,drawDefinition:e,matchUpsMap:s}),T=(E=hn({matchUp:I,drawDefinition:e,structure:c,event:r}))==null?void 0:E.tieFormat;return{inContextDualMatchUp:S,inContextTieMatchUp:o,relevantAssignments:d,collectionPosition:a,teamParticipants:g,collectionId:l,matchUpType:p,dualMatchUp:I,tieMatchUp:i,tieFormat:T,structure:c,...$}}function em(t){var B,R,x,q,V,Y,z,J,Q,X,Z,nt,rt;const e=tm(t);if(e.error)return e;const n="assignTieMatchUpParticipantId";let r=t.teamParticipantId;const{tournamentRecord:s,drawDefinition:i,participantId:o,event:c}=t;if(!o)return G({result:{error:Ce},stack:n});if(t.sideNumber&&![1,2].includes(t.sideNumber))return G({result:{error:rg},stack:n});const{inContextDualMatchUp:a,inContextTieMatchUp:u,relevantAssignments:l,collectionPosition:f,teamParticipants:p,collectionId:h,matchUpType:d,dualMatchUp:m,tieFormat:g}=e,I=(B=u==null?void 0:u.sides)==null?void 0:B.flatMap(K=>{var it,st;return((it=K.participant)==null?void 0:it.individualParticipantIds)||((st=K.participant)==null?void 0:st.participantId)||[]});if(I!=null&&I.includes(o))return G({result:{...$},stack:n});r=r||t.sideNumber&&((x=(R=a==null?void 0:a.sides)==null?void 0:R.find(K=>K.sideNumber===t.sideNumber))==null?void 0:x.participantId);const{tournamentParticipants:[S]}=dn({tournamentRecord:s,participantFilters:{participantIds:[o]}});if(!S)return G({result:{error:_e},stack:n});const{appliedPolicies:T}=ge({tournamentRecord:s,drawDefinition:i,event:c}),E=((q=t.policyDefinitions)==null?void 0:q[Jn])||(T==null?void 0:T[Jn])||iu[Jn];if((V=E==null?void 0:E.participants)!=null&&V.enforceGender&&[Se,Ne].includes(u==null?void 0:u.gender)&&(u==null?void 0:u.gender)!==((Y=S.person)==null?void 0:Y.sex))return{error:vu,info:"Gender mismatch"};const{individualParticipantIds:y,participantType:b}=S;if(d===Oe&&b!==xt)return{error:xr};const N=b===xt?[o]:y,A=r&&(p==null?void 0:p.find(({participantId:K})=>K===r))||(p==null?void 0:p.find(({individualParticipantIds:K})=>tn(N,K)));if(!A)return{error:yg};if(r||(r=A.participantId),!r)return{error:_e};const C=l==null?void 0:l.find(K=>K.participantId===(A==null?void 0:A.participantId)),v=C==null?void 0:C.drawPosition,P=(z=u==null?void 0:u.sides)==null?void 0:z.find(K=>K.drawPosition===v),U=t.sideNumber||(P==null?void 0:P.sideNumber);if(!g)return{error:Nu};if(!((J=g.collectionDefinitions)==null?void 0:J.find(K=>K.collectionId===h)))return{error:J1};if(!((Q=m==null?void 0:m.sides)!=null&&Q.length)){const{extension:K}=Ke({element:i,name:Wr}),it=pt((K==null?void 0:K.value)||{},!1,!0),st=({displaySideNumber:dt,drawPosition:mt,sideNumber:Mt})=>({drawPosition:mt,sideNumber:Mt,displaySideNumber:dt});m&&(m.sides=(X=a==null?void 0:a.sides)==null?void 0:X.map(dt=>{const mt=dt.participantId;return{...st(dt),lineUp:mt&&it[mt]||[]}}))}const D=(Z=m==null?void 0:m.sides)==null?void 0:Z.find(K=>K.sideNumber===U),M=(nt=u==null?void 0:u.sides)==null?void 0:nt.find(K=>K.sideNumber===U),w=(D==null?void 0:D.lineUp)||((rt=ba({participantId:r,drawDefinition:i}))==null?void 0:rt.lineUp),k=w==null?void 0:w.filter(K=>{var it;return(it=K.collectionAssignments)==null?void 0:it.find(st=>st.collectionPosition===f&&st.collectionId===h&&!st.previousParticipantId)}),_=k==null?void 0:k.map(K=>K==null?void 0:K.participantId),F=(_==null?void 0:_.length)>1&&_||(b===_t?S.individualParticipantIds:[o]),L=Gb({collectionPosition:f,teamParticipantId:r,dualMatchUpSide:D,drawDefinition:i,participantIds:F,collectionId:h});if(L.error)return G({result:L,stack:n});const{modifiedLineUp:W}=L;let j;if(d===me){if(b!==_t){let K=nm({collectionPosition:f,teamParticipantId:r,drawDefinition:i,modifiedLineUp:W,participantId:o,collectionId:h,tieFormat:g});if(K!=null&&K.error)return G({result:K,stack:n});if(K=H({side:M}),K.error)return K;j=K.deleteParticipantId,D&&(D.lineUp=W),m&&qt({tournamentId:s==null?void 0:s.tournamentId,matchUp:m,context:n,drawDefinition:i})}else if(b===_t)for(const K of F)nm({collectionPosition:f,teamParticipantId:r,drawDefinition:i,modifiedLineUp:W,participantId:K,collectionId:h,tieFormat:g})}else{const K=nm({collectionPosition:f,teamParticipantId:r,drawDefinition:i,modifiedLineUp:W,participantId:o,collectionId:h,tieFormat:g});if(K!=null&&K.error)return K}if(D&&(D.lineUp=W),m&&qt({tournamentId:s==null?void 0:s.tournamentId,matchUp:m,context:n,drawDefinition:i}),j){const{error:K}=Fc({participantIds:[j],tournamentRecord:s});K&&console.log("cleanup")}return{...$,modifiedLineUp:W};function H({side:K}){let it;if(K.participant){const st=K.participant.individualParticipantIds||[];if(st.filter(Boolean).length===1){const{participant:mt}=Jr({participantIds:st,tournamentRecord:s});st.push(o);const{participant:Mt}=Jr({participantIds:st,tournamentRecord:s});if(!Mt&&mt){mt.individualParticipantIds=st;const Nt=Xh({pairOverride:!0,tournamentRecord:s,participant:mt});if(Nt.error)return Nt}else it=mt==null?void 0:mt.participantId}}else{const dt=es({participant:{individualParticipantIds:[o],participantRole:fn,participantType:_t},pairOverride:!0,tournamentRecord:s});if(dt.error)return dt}return{...$,deleteParticipantId:it}}}function nm({collectionPosition:t,teamParticipantId:e,drawDefinition:n,modifiedLineUp:r,participantId:s,collectionId:i,tieFormat:o}){var l,f;const c=(l=ba({participantId:e,drawDefinition:n}))==null?void 0:l.lineUp,a=(f=r||c)==null?void 0:f.find(p=>(p==null?void 0:p.participantId)===s),u={collectionId:i,collectionPosition:t};if(a)a.collectionAssignments.push(u);else{const p={collectionAssignments:[u],participantId:s};r.push(p)}return Uc({participantId:e,lineUp:r,drawDefinition:n,tieFormat:o})}const HF="ASC",Wb="DESC";function Hb(t){var U,O,D;let{tieFormat:e}=t;const{useDefaultEventRanking:n,tournamentRecord:r,drawDefinition:s,scaleAccessor:i,singlesOnly:o,attach:c,event:a}=t;if((a==null?void 0:a.eventType)!==ds)return{error:ui};if(!r)return{error:et};if(!e&&!s)return{error:rr};if(e=e||((U=hn({drawDefinition:s,event:a}))==null?void 0:U.tieFormat),vn({tieFormat:e}).error)return{error:li};if(typeof i!="object"&&!n)return{error:tt,context:{scaleAccessor:i}};const u={},f=((s==null?void 0:s.entries)||a.entries).filter(M=>(M==null?void 0:M.entryStatus)===Ur).map(fe),{participants:p=[]}=Fi({withIndividualParticipants:!0,withScaleValues:!0,tournamentRecord:r}),h=p.filter(({participantId:M})=>f.includes(M)),d=M=>M===Ii?"rankings":"ratings",m=((O=a==null?void 0:a.category)==null?void 0:O.categoryName)||((D=a==null?void 0:a.category)==null?void 0:D.ageCategoryCode),{scaleName:g=m,scaleType:I=Ii,sortOrder:S,accessor:T}=i||{},E=d(I),y=(M,w)=>{var _,F,L;let k=(_=M[E])==null?void 0:_[w];if(!k&&n&&(k=(F=M[E])==null?void 0:F[gi]),Array.isArray(k)){const W=(L=k.find(j=>j.scaleName===g))==null?void 0:L.scaleValue;if(Me(W))return W;if(T&&typeof W=="object")return W[T]}return 0},b=(M,w,k)=>{const _=S===Wb?w:M,F=S===Wb?M:w;return y(_,k)-y(F,k)},N=(M,w)=>b(M,w,gi),A=(M,w)=>b(M,w,Tr),C=[],v=e.collectionDefinitions||[];for(const M of h){const w=M.individualParticipants.sort(N),k=o?w:M.individualParticipants.sort(A),_={};for(const L of v){const W=[],{collectionId:j,matchUpCount:H,matchUpType:B,gender:R}=L,x=B===gi;ht(0,H).forEach(q=>{const V=x?w:k,Y=q+1,z=[];ht(0,x?1:2).forEach(J=>{const Q=V.find(X=>{const Z=[Se,Ne].includes(R)&&R||R===hs&&[Se,Ne][J];return(!Z||Z===X.person.sex)&&!W.includes(X.participantId)}).participantId;Q&&(z.push(Q),W.push(Q),_[Q]||(_[Q]=[]),_[Q].push({collectionPosition:Y,collectionId:j}))}),x||C.push(z)})}const F=Object.keys(_).map(L=>({collectionAssignments:_[L],participantId:L}));u[M.participantId]=F}const P=[];for(const M of C){const{participant:w}=Jr({tournamentParticipants:p,participantIds:M});if(!w){const k={individualParticipantIds:M,participantRole:fn,participantType:_t};P.push(k)}}if(c){for(;P.length;)es({participant:P.pop(),tournamentRecord:r});ae({element:s,extension:{name:Wr,value:u}})}return{...$,lineUps:u,participantsToAdd:P}}function qb(t){const{matchUpFormat:e,matchUpStatus:n,winningSide:r,scoreString:s}=t;if(!s)return{outcome:{...fl,winningSide:r,matchUpStatus:n}};if(r&&![1,2,void 0].includes(r))return{error:tt,winningSide:r};const i=s&&vl({scoreString:s}),o={},c=gs({sets:i,matchUpFormat:e}),a=gs({sets:i,reversed:!0,matchUpFormat:e});return r===2?(o.scoreStringSide1=a,o.scoreStringSide2=c):(o.scoreStringSide1=c,o.scoreStringSide2=a),o.sets=vl({scoreString:o.scoreStringSide1}),bt({outcome:{matchUpStatus:n,winningSide:r,score:o}})}const qF={[ce]:2,[Fe]:1,[en]:1,[In]:1,[te]:4};function Yb(t){let{defaultWithScorePercent:e=2,winningSide:n}=t;const{matchUpStatusProfile:r=qF,matchUpFormat:s=Kn,pointsPerMinute:i=1,sideWeight:o=4}=t;if(!nr(s))return{error:Xm};if(typeof r!="object")return{error:tt};if(e>100&&(e=100),isNaN(e)||isNaN(i)||isNaN(o))return{error:tt};const c=Object.keys(r).filter(P=>Object.keys(DC).includes(P)&&P!==De);if(Object.keys(c).reduce((P,U)=>P+r[U],0)>100)return{error:tt,matchUpStatusProfile:r};const u=c.reduce((P,U)=>(P.pointer=P.pointer+r[U],P.valueMap.push([P.pointer,U]),P),{pointer:0,valueMap:[]}),l=Wn(1,100),f=(u.valueMap.find(P=>l<=P[0])||[100,De])[1],p={sets:[],scoreStringSide1:"",side2ScoreString:""};if([ce,te].includes(f)){n=n||Wn(1,2);const P={score:p,winningSide:n,matchUpStatus:f};if(!(f===te&&Wn(1,100)>100-e))return{outcome:P}}else if([Fe,en].includes(f))return{outcome:{score:p,matchUpStatus:f}};const h=yn(s),{bestOf:d,setFormat:m,finalSetFormat:g}=h||{},I=[],S=Wn(0,1),T=n?[n-1]:[...ht(0,o).map(()=>S),1-S],y=[In,te,us,mi].includes(f)&&(cn(ht(1,d))||1);let b;for(const P of ht(1,(d||0)+1)){const U=P===d,{set:O,incomplete:D,winningSideNumber:M}=YF({incomplete:y===P,matchUpStatus:f,pointsPerMinute:i,setFormat:U&&g||m,setNumber:P,weightedRange:T});if(I.push(O),D){b=M;break}if(Kh({matchUp:{score:{sets:I},matchUpFormat:s}}).calculatedWinningSide)break}const N=Kh({matchUp:{score:{sets:I},matchUpFormat:s}}),A=b?n||b:N.calculatedWinningSide,{score:C}=ty({score:{sets:I},winningSide:A,matchUpStatus:f});return{outcome:{score:C,winningSide:A,matchUpStatus:f}}}function YF({weightedRange:t=[0,1],pointsPerMinute:e,matchUpStatus:n,incomplete:r,setFormat:s,setNumber:i}){const o={setNumber:i},{setTo:c,tiebreakFormat:a,tiebreakAt:u,tiebreakSet:l,timed:f,minutes:p}=s,h=Wn(0,t.length-1),d=t[h];let m;if(f){const g=p*e,I=Math.round(g*.2),S=g+cn([1,-1])*I,T=T1(S,2),E=[T,S-T];d&&E.reverse(),m=t[h]+1;let y=E[0]>E[1]&&1||E[1]>E[0]&&2||0;if(r){const[A,C]=E;return Object.assign(o,{side1Score:A,side2Score:C}),We.includes(n)?{set:o,incomplete:r,winningSideNumber:m}:{set:o,incomplete:r}}y||(E[Wn(0,1)]+=1),y=E[0]>E[1]?1:2,y!==m&&E.reverse();const[b,N]=E;return Object.assign(o,{side1Score:b,side2Score:N,winningSide:m}),{set:o}}else{if(r)return o.side1Score=Wn(0,u),o.side2Score=Wn(0,u),We.includes(n)&&(m=t[h]+1),{set:o,incomplete:r,winningSideNumber:m};{const g=ht(1,c+1).map(N=>ht(0,c+2-N).map(()=>N)).flat(),I=g[Wn(0,g.length-1)],S=c&&FS({isSide1:!0,tiebreakAt:u,lowValue:I,setTo:c}),T=!S,E=t.length===1&&t[h]+1;if(!T){E?(S[0]>S[1]?1:2)!==E&&S.reverse():d&&S.reverse();const[N,A]=S;Object.assign(o,{side1Score:N,side2Score:A})}const y=gl({matchUpScoringFormat:{setFormat:s},setObject:o});let b;if(y.hasTiebreakCondition||T){const{NoAD:N,tiebreakTo:A}=a||l||{},C=ht(1,A+1).map(U=>ht(0,A+2-U).map(()=>U)).flat(),v=C[Wn(0,C.length-1)],P=dp({isSide1:!0,tiebreakNoAd:N,tiebreakTo:A,lowValue:v});if(P)if(T){const U=P[0]>P[1]?1:2;E?U!==E&&P.reverse():d&&P.reverse(),[o.side1TiebreakScore,o.side2TiebreakScore]=P,b=P[0]>P[1]&&1||P[1]>P[0]&&2||void 0}else y.leadingSide===2?[o.side1TiebreakScore,o.side2TiebreakScore]=P:[o.side2TiebreakScore,o.side1TiebreakScore]=P}o.winningSide=y.winningSide||y.leadingSide||E||b}}return{set:o}}function pu(t){var m,g,I;const{matchUpStatusProfile:e,completeAllMatchUps:n,randomWinningSide:r,tournamentRecord:s,completionGoal:i,drawDefinition:o,event:c}=t;if(!o)return{error:lt};const a=t.matchUpFormat||o.matchUpFormat||(c==null?void 0:c.matchUpFormat),u=o.structures.slice().sort(Pi);let l=0;const{matchUps:f,matchUpsMap:p}=xe({contextFilters:{stages:[It,Pt]},matchUpFilters:{matchUpTypes:[Jt],roundNumbers:[1]},inContext:!0,drawDefinition:o});if(f!=null&&f.length){const S=((m=c==null?void 0:c.category)==null?void 0:m.ageCategoryCode)||((g=c==null?void 0:c.category)==null?void 0:g.categoryName);if(S)Hb({singlesOnly:!0,tournamentRecord:s,drawDefinition:o,scaleAccessor:{scaleName:S,sortOrder:HF,scaleType:Ii},attach:!0,event:c});else{const T=(I=f[0])==null?void 0:I.structureId,{positionAssignments:E}=ee({drawDefinition:o,structureId:T});if(E!=null&&E.length){const{tournamentParticipants:y}=dn({participantFilters:{participantTypes:[Jt]},tournamentRecord:s}),b=N=>{const A=N.tieMatchUps.filter(({matchUpType:v})=>v===Oe),C=N.tieMatchUps.filter(({matchUpType:v})=>v===me);A.forEach((v,P)=>{const U=v.matchUpId;v.sides.forEach(O=>{const{drawPosition:D}=O,M=y==null?void 0:y.find(w=>{const{participantId:k}=w,_=E.find(F=>F.participantId===k);return(_==null?void 0:_.drawPosition)===D});if(M){const w=M.individualParticipantIds[P];em({teamParticipantId:M.participantId,participantId:w,tournamentRecord:s,drawDefinition:o,tieMatchUpId:U,event:c})}})}),C.forEach((v,P)=>{const U=v.matchUpId;v.sides.forEach(O=>{const{drawPosition:D}=O,M=y==null?void 0:y.find(w=>{const{participantId:k}=w,_=E.find(F=>F.participantId===k);return(_==null?void 0:_.drawPosition)===D});M&&M.individualParticipantIds.slice(P*2,P*2+2).forEach(k=>{em({teamParticipantId:M.participantId,participantId:k,tournamentRecord:s,drawDefinition:o,tieMatchUpId:U,event:c})})})})};f.forEach(b)}}}const h=typeof n=="string"&&n,d=h&&De;for(const S of u){if(l>=i)break;const{matchUps:T}=Qt({matchUpFilters:{matchUpTypes:[me,Oe]},afterRecoveryTimes:!1,tournamentRecord:s,inContext:!0,drawDefinition:o,matchUpsMap:p,structure:S,event:c}),E=T.filter(({winningSide:y})=>!y).sort(vo).map(Qe);for(const y of E){if(!isNaN(i)&&l>=i)break;const{matchUps:b}=Qt({matchUpFilters:{matchUpTypes:[me,Oe]},afterRecoveryTimes:!1,tournamentRecord:s,inContext:!0,drawDefinition:o,matchUpsMap:p,structure:S,event:c}),N=b.find(C=>C.matchUpId===y),A=[Fe,en].includes(N.matchUpStatus);if(N!=null&&N.readyToScore&&!A){const C=zF({winningSide:!r&&1,matchUpStatusProfile:e,tournamentRecord:s,drawDefinition:o,targetMatchUp:N,matchUpFormat:a,matchUpStatus:d,scoreString:h,event:c});if(C!=null&&C.error)return C;l+=1}}}return{...$,completedCount:l}}function zb(t){const{matchUpStatusCodes:e,policyDefinitions:n,tournamentRecord:r,drawDefinition:s,targetMatchUp:i,matchUpStatus:o,matchUpFormat:c,scoreString:a,winningSide:u,event:l}=t;if(!i||i.matchUpStatus===re)return;const{matchUpId:f}=i||{},{outcome:p}=qb({matchUpFormat:c,matchUpStatus:o,scoreString:a,winningSide:u});return e&&(p.matchUpStatusCodes=e),Qa({tournamentRecord:r,policyDefinitions:n,drawDefinition:s,matchUpFormat:c,matchUpId:f,outcome:p,event:l})}function zF(t){const{matchUpStatusProfile:e={},tournamentRecord:n,policyDefinitions:r,drawDefinition:s,matchUpStatus:i,matchUpFormat:o,targetMatchUp:c,scoreString:a,winningSide:u,event:l}=t;if(a||i)return zb(t);const{matchUpId:f}=c||{},{outcome:p}=Yb({matchUpStatusProfile:e,matchUpFormat:o,winningSide:u});return Qa({policyDefinitions:r,tournamentRecord:n,drawDefinition:s,matchUpFormat:o,matchUpId:f,outcome:p,event:l})}function KF({tournament:t}){if(!t)return{error:et};const{providerTournamentID:e,hostCountryCode:n,tournamentLevel:r,totalPrizeMoney:s,tournamentName:i,extensions:o,startDate:c,endDate:a}=t,u=Jh({hostCountryCode:n,tournamentLevel:r,totalPrizeMoney:s,tournamentName:i,tournamentId:e,extensions:o,startDate:c,endDate:a});u.events=[];for(const l of t.events||[]){const{extensions:f,ageCategory:p,discipline:h,eventType:d,eventId:m,gender:g,stages:I}=l,S={drawDefinitions:JF(I),category:{ageCategory:p},gender:["M",Se].includes(g)&&Se||["F",Ne].includes(g)&&Ne||void 0,eventType:["D",$n].includes(d)&&$n||["T",we].includes(d)?we:ls,extensions:f,discipline:h,eventId:m};u.events.push(S)}return{...$,tournamentRecord:u}}function JF(t){const e=[];for(const n of t||[]){const{stageType:r}=n,s=["M",It].includes(r)&&It||["Q",Pt].includes(r)&&Pt||["C",Re].includes(r)&&Re||["P",Ie].includes(r)&&Ie||void 0;for(const i of n.draws||[]){const{drawId:o,drawSize:c,matchUps:a}=i,u={stage:s,drawId:o,drawSize:c};e.push(u),console.log(a.map(({roundNumber:l,roundPosition:f})=>({roundNumber:l,roundPosition:f})),{draw:i,drawDefinition:u})}}return e}const QF={ABANDONED:"ABANDONED",ACTIVE:"ACTIVE",CANCELLED:"CANCELLED",COMPLETED:"COMPLETED",IN_PROGRESS:"IN_PROGRESS"};function ZF({tournamentRecord:t,status:e}){return t?e&&!Object.keys(QF).includes(e)?{error:tt,info:"Unknown status"}:(t.tournamentStatus=e,{...$}):{error:et}}function XF({tournamentRecord:t,onlineResource:e}){return t?e?(t.onlineResources||(t.onlineResources=[]),t.onlineResources.push(e),{...$}):{error:Tt}:{error:et}}function rm({tournamentRecord:t}){var s;if(!t)return{error:et};const e={positionsNoOutcomes:[],canBePruned:[],matchPlay:[],inactive:[],drawAnalysis:{}},n={};return((s=t.events)==null?void 0:s.map(i=>{const o=i.eventId;return n[o]=i,((i==null?void 0:i.drawDefinitions)||[]).map(c=>({drawDefinition:c,eventId:o}))}).flat().filter(Boolean)).forEach(({drawDefinition:i,eventId:o})=>{let c=0,a=0,u=0;const{allStructuresLinked:l}=$b({drawDefinition:i}),f=n[o],h=((i==null?void 0:i.structures)||[]).map(b=>{const{stage:N,stageSequence:A,structureId:C}=b,v=ao[N],{inContextStructureMatchUps:P}=qa({drawDefinition:i,structure:b,event:f}),U=P==null?void 0:P.filter(({winningSide:R})=>R),O=U.filter(Boolean).length||0;a+=O,u+=P.length-a;const D=Math.max(U.filter(({roundNumber:R})=>R===1).map(({roundPosition:R})=>R)),{positionAssignments:M}=ee({structure:b}),w=M==null?void 0:M.filter(({participantId:R})=>R);c+=(w==null?void 0:w.length)||0;const k=((M==null?void 0:M.length)||0)-((w==null?void 0:w.length)||0),{roundMatchUps:_,roundProfile:F,roundNumbers:L,maxMatchUpsCount:W}=Cn({matchUps:P}),j=F&&Object.keys(F).filter(R=>!F[R].inactiveRound).map(R=>parseInt(R)),H=F&&Object.keys(F).filter(R=>F[R].inactiveRound).map(R=>parseInt(R)),B=F&&Object.values(F).every(R=>R.inactiveRound);return{positionsAssignedCount:(w==null?void 0:w.length)||0,maxWinningSideFirstRoundPosition:D,unassignedPositionsCount:k,inactiveStructure:B,maxMatchUpsCount:W,inactiveRounds:H,roundMatchUps:_,activeRounds:j,roundNumbers:L,roundProfile:F,structureId:C,stageSequence:A,orderNumber:v,stage:N}}),d=h.find(b=>b.orderNumber===2&&b.stageSequence===1),m=h.filter(({inactiveStructure:b})=>!b).length,{links:g}=$a({drawDefinition:i,structureId:d.structureId}),I=vt(d.activeRounds[0])===1&&d.activeRounds.length===1&&m===1,S=h==null?void 0:h.every(({inactiveStructure:b})=>b),T=!g.length&&d.activeRounds.length&&(d.roundProfile[1].inactiveCount||d.inactiveRounds.length),E=i.drawId;c&&!a&&e.positionsNoOutcomes.push(E),S&&e.inactive.push(E),I&&e.matchPlay.push(E),T&&e.canBePruned.push(E);const y={matchUpsWithWinningSideCount:a,matchUpsNoOutcomeCount:u,positionsAssignedCount:c,allStructuresLinked:l,structuresData:h,inactiveDraw:S,isMatchPlay:I,drawId:E};e.drawAnalysis[E]=y}),{...$,drawsAnalysis:e}}function tL(t){var c,a,u,l,f;const e=(c=t.participants)==null?void 0:c.filter(({participantType:p})=>p===se),n=(e==null?void 0:e.length)===2,r=((a=t.events)==null?void 0:a.length)===1&&t.events[0],s=((u=r==null?void 0:r.drawDefinitions)==null?void 0:u.length)===1&&r.drawDefinitions[0],i=((l=s==null?void 0:s.structures)==null?void 0:l.length)===1&&s.structures[0],o=((f=i==null?void 0:i.positionAssignments)==null?void 0:f.length)===2;return!!(r.tieFormat&&n&&o)}function eL({tournamentRecord:t}){if(!t)return{error:et};const{drawsAnalysis:e}=rm({tournamentRecord:t}),n={isDual:tL(t),drawsAnalysis:e};return{...$,analysis:n}}function nL({tournamentRecord:t,promotionalName:e,tournamentName:n,formalName:r}){return t?(n&&(t.tournamentName=n),e&&(t.promotionalName=e),r&&(t.formalName=r),t.promotionalName===t.tournamentName&&delete t.promotionalName,t.formalName===t.tournamentName&&delete t.formalName,{...$}):{error:et}}function rL({tournamentRecord:t,notes:e}){return t?Kf({element:t,notes:e}):{error:et}}function sL({tournamentRecord:t,categories:e}){return t?(e=(e||[]).filter(n=>n.categoryName&&n.type),t.tournamentCategories=e,{...$}):{error:et}}function iL({tournamentRecord:t}){var i;if(!t)return{error:et};const{startDate:e,endDate:n}=t,r=ef(e,n),s=[];for(const o of t.venues||[])(i=o==null?void 0:o.courts)!=null&&i.length&&s.push(...o.courts);for(const o of s){const{startTime:c,endTime:a}=(o.dateAvailability||[]).reduce((l,f)=>{const p=jt(l.startTime),h=jt(l.endTime);return f.startTime&&jt(f.startTime)<p&&(l.startTime=f.startTime),f.endTime&&jt(f.endTime)>h&&(l.endTime=f.endTime),l},{startTime:"08:00",endTime:"18:00"}),u=r.map(l=>{var p;return((p=o.dateAvailability)==null?void 0:p.find(h=>h.date===l))||{date:l,startTime:c,endTime:a}});o.dateAvailability=u}return{...$}}function sm({tournamentRecord:t,startDate:e,endDate:n}){var i;if(!t)return{error:et};if(e&&!Vr.test(e)||n&&!Vr.test(n))return{error:bn};if(!e&&!n)return{error:sg};if(n&&e&&new Date(n)<new Date(e))return{error:tt};let r;(e&&t.startDate&&new Date(e)>new Date(t.startDate)||n&&t.endDate&&new Date(n)<new Date(t.endDate))&&(r=!0),e&&(t.startDate=e),n&&(t.endDate=n),e&&t.endDate&&new Date(e)>new Date(t.endDate)&&(t.endDate=e),n&&t.startDate&&new Date(n)<new Date(t.startDate)&&(t.startDate=n);const s=r&&((i=aL({tournamentRecord:t}))==null?void 0:i.unscheduledMatchUpIds);return iL({tournamentRecord:t}),Ht({topic:TP,payload:{startDate:e,endDate:n}}),{...$,unscheduledMatchUpIds:s}}function oL({tournamentRecord:t,startDate:e}){return sm({tournamentRecord:t,startDate:e})}function cL({tournamentRecord:t,endDate:e}){return sm({tournamentRecord:t,endDate:e})}function aL({tournamentRecord:t}){const e=He({tournamentRecord:t}).matchUps??[],n=t.startDate&&new Date(t.startDate),r=t.endDate&&new Date(t.endDate),s=[],i=[];for(const o of e){const{schedule:c,matchUpId:a}=o;if(c&&c.scheduledDate){const u=new Date(c.scheduledDate);(n&&u<n||r&&u>r)&&(i.push(a),s.includes(c.scheduledDate)||s.push(c.scheduledDate))}}return s.length&&!lh({scheduledDates:s,tournamentRecord:t}).clearedScheduleCount?{error:w1}:{unscheduledMatchUpIds:i}}const uL={analyzeTournament:eL,analyzeDraws:rm,addOnlineResource:XF,removeNotes:rU,addNotes:Kf,completeDrawMatchUps:pu,getRounds:tE,getProfileRounds:hh,setTournamentName:nL,setTournamentNotes:rL,setTournamentDates:sm,setTournamentEndDate:cL,setTournamentStartDate:oL,setTournamentCategories:sL,addTimeItem:Ha,addEventTimeItem:ii,addTournamentTimeItem:_s,addParticipantTimeItem:PT,addExtension:ae,addEventExtension:Yr,removeEventExtension:Yu,addTournamentExtension:Ti,removeTournamentExtension:Af,addParticipantExtension:lP,removeParticipantExtension:fP,addDrawDefinitionExtension:Nf,removeDrawDefinitionExtension:dP,setTournamentStatus:ZF,convertPointEight:KF};function lL({tournamentRecord:t}){if(!t)return{error:et};const e=[],{extension:n}=Bn({tournamentRecord:t,name:qr});n&&e.push({method:"addTournamentExtension",params:{extension:n}});const r=t.events||[];for(const s of r){const{eventId:i}=s,{extension:o}=Us({event:s,name:qr});o&&e.push({method:"addEventExtension",params:{eventId:i,extension:o}})}return{methods:e}}function dL({drawDefinition:t,courtDayDate:e,matchUpId:n}){return Qy({drawDefinition:t,courtDayDate:e,matchUpId:n})}function fL({tournamentRecord:t}){if(!t)return{error:et};const e=[],{extension:n}=Bn({name:Ji,tournamentRecord:t});n&&e.push({method:"addTournamentExtension",params:{extension:n}});const r=t.events||[];for(const s of r){const{eventId:i}=s,{extension:o}=Us({name:Ji,event:s});o&&e.push({params:{eventId:i,extension:o},method:"addEventExtension"})}return{methods:e}}function pL({scheduleAttributes:t=[Qs,oo,ga,Ia,Sa,zr,Xs,Os,Zs],tournamentRecord:e,drawDefinition:n,matchUpId:r}){var c,a;const s="clearMatchUpSchedule",i=n?(c=tr({matchUpFilters:{matchUpIds:[r]},inContext:!1,drawDefinition:n}).matchUps)==null?void 0:c[0]:(a=He({matchUpFilters:{matchUpIds:[r]},tournamentRecord:e,inContext:!1}).matchUps)==null?void 0:a[0];if(!i)return{error:Ye};const o=(i.timeItems||[]).filter(u=>(u==null?void 0:u.itemType)&&!t.includes(u==null?void 0:u.itemType));return i.timeItems=o,qt({tournamentId:e.tournamentId,context:s,drawDefinition:n,matchUp:i}),{...$}}const hL={allocateTeamMatchUpCourts:wl,addMatchUpCourtOrder:Pp,assignMatchUpCourt:Po,assignMatchUpVenue:bc,clearMatchUpSchedule:pL,addMatchUpScheduleItems:dy,addMatchUpScheduledDate:jp,addMatchUpScheduledTime:Gp,addMatchUpStartTime:fy,addMatchUpEndTime:py,addMatchUpStopTime:hy,addMatchUpResumeTime:my,addMatchUpOfficial:gy,getMatchUpFormatTiming:yf,modifyMatchUpFormatTiming:Vp,getModifiedMatchUpFormatTiming:ry,getEventMatchUpFormatTiming:_y,modifyEventMatchUpFormatTiming:iy,removeEventMatchUpFormatTiming:Ky,getMatchUpFormatTimingUpdate:lL,getMatchUpDependencies:fr,getMatchUpDailyLimits:Yy,setMatchUpDailyLimits:Sy,getMatchUpDailyLimitsUpdate:fL,validateSchedulingProfile:td,setSchedulingProfile:lk,getSchedulingProfile:od,removeMatchUpCourtAssignment:dL,clearScheduledMatchUps:lh,bulkScheduleMatchUps:OT,bulkRescheduleMatchUps:Iy};function mL({tournamentRecord:t,categoryName:e,categoryType:n}){if(!t)return{error:et};const{appliedPolicies:r}=ge({tournamentRecord:t}),s=r==null?void 0:r[Xo];return((s==null?void 0:s.matchUpFormats)||[]).filter(({categoryNames:o,categoryTypes:c})=>!e&&!c||e&&(o==null?void 0:o.includes(e))||n&&(c==null?void 0:c.includes(n)))}function Kb({tournamentRecord:t,categoryName:e,categoryType:n}){if(!t)return{error:et};const{appliedPolicies:r}=ge({tournamentRecord:t}),s=r==null?void 0:r[pf];return((s==null?void 0:s.allowedDrawTypes)||[]).filter(({categoryNames:o,categoryTypes:c})=>!e&&!c||e&&(o==null?void 0:o.includes(e))||n&&(c==null?void 0:c.includes(n)))}function Jb({policyDefinitions:t,drawDefinition:e,drawSize:n,drawId:r,event:s,stage:i}){if(!s)return{error:Wt};const{entries:o,stageEntries:c}=ub({drawDefinition:e,drawId:r,stage:i,event:s}),a=c.length,{drawSize:u}=Bh({participantsCount:a}),l=xh({drawSize:n??u,participantsCount:a,policyDefinitions:t});if(l.error)return G({result:l,stack:"getEntriesAndSeedsCount"});const{seedsCount:f}=l;return{entries:o,seedsCount:f,stageEntries:c}}const gL={attachPolicies:gh,attachEventPolicies:nE,removeEventPolicy:Bw,findPolicy:Xi,getSeedsCount:xh,getEntriesAndSeedsCount:Jb,getAllowedDrawTypes:Kb,getAllowedMatchUpFormats:mL,getAppliedPolicies:ge};function yd({participant:t,eventType:e}){var u,l,f,p,h,d;const n=(u=t==null?void 0:t.person)==null?void 0:u.personId,r=(f=(l=t==null?void 0:t.person)==null?void 0:l.personOtherIds)==null?void 0:f[0],s=(p=t==null?void 0:t.person)==null?void 0:p.tennisId,i=(d=(h=t==null?void 0:t.ratings)==null?void 0:h[e])==null?void 0:d.find(({scaleName:m})=>m===BS),o=i==null?void 0:i.scaleValue,{wtnRating:c,confidence:a}=o||{};return{timeStamp:i==null?void 0:i.scaleDate,personOtherId:r,confidence:a,wtnRating:c,personId:n,tennisId:s}}function IL({tournamentRecord:t}){if(!t)return{error:et};const e=t.tournamentId,{participantMap:n}=Fi({withScaleValues:!0,withEvents:!0,withSeeding:!0,tournamentRecord:t,withDraws:!0}),s=(He({matchUpFilters:{matchUpTypes:[gi,Tr]},tournamentRecord:t}).matchUps??[]).flatMap(({sides:d,matchUpType:m})=>d==null?void 0:d.flatMap(g=>{var I,S;return m===Tr?(I=g.participant)==null?void 0:I.individualParticipantIds:((S=g.participant)==null?void 0:S.participantId)||g.participantId}).filter(Boolean)).filter(Boolean),i=[],o={},c={},a={};let u=0;const l=({id:d,entry:m,eventId:g,eventType:I})=>{var P;const{qualifyingSeeding:S,mainSeeding:T,entryStatus:E,entryStage:y,drawId:b}=m;o[d]||(o[d]=[]);const{participant:N,events:A}=(n==null?void 0:n[d])??{},C=yd({participant:N,eventType:I}),v=(P=A==null?void 0:A[g])==null?void 0:P.ranking;E===oT&&i.push(d),o[d].push({participantType:N==null?void 0:N.participantType,participantId:d,tournamentId:e,eventType:I,eventId:g,drawId:b,entryStatus:E,entryStage:y,...C,ranking:v,mainSeeding:T,qualifyingSeeding:S})};for(const d of t.events??[]){const m={},g=C=>{m[C]||(m[C]={count:0}),m[C].count+=1},{drawDefinitions:I=[],eventType:S,eventId:T}=d,E=I.flatMap(C=>{const{drawId:v,entries:P}=C;u+=1;const U=({stage:k,stageSequence:_})=>k===It&&_===1||k===Pt,D=(C.structures??[]).filter(U).flatMap(({positionAssignments:k})=>k).map(({participantId:k})=>k).filter(Boolean),M=({participantId:k})=>D.includes(k),w=k=>{var H,B,R,x,q,V,Y,z;const{participantId:_,entryStatus:F,entryStage:L}=k;g(F);const W=(x=(R=(B=(H=n==null?void 0:n[_])==null?void 0:H.draws)==null?void 0:B[v])==null?void 0:R.seedAssignments)==null?void 0:x[It];return{qualifyingSeeding:(z=(Y=(V=(q=n==null?void 0:n[_])==null?void 0:q.draws)==null?void 0:V[v])==null?void 0:Y.seedAssignments)==null?void 0:z[Pt],participantId:_,mainSeeding:W,entryStatus:F,entryStage:L,drawId:v}};return P==null?void 0:P.filter(M).map(w)}),y=C=>{var U;const v=C.participantId,P=(U=n==null?void 0:n[v].participant.individualParticipantIds)==null?void 0:U.filter(O=>s.includes(O));return v&&{[v]:{individualParticipantIds:P}}};S===Zu?(()=>{const C=Object.assign({},...E.map(y).filter(Boolean)),v=P=>{C[P.participantId].individualParticipantIds.forEach(U=>{l({id:U,eventType:S,eventId:T,entry:P})})};E.forEach(v)})():E.forEach(C=>{l({id:C==null?void 0:C.participantId,eventType:S,eventId:T,entry:C})});const N=Object.values(m).reduce((C,v)=>C+v.count,0);Object.keys(m).forEach(C=>{m[C].pct=m[C].count/N*100}),a[T]={tournamentId:e,eventId:T,entries:E,entryStatuses:m};const A=Object.assign({},...ps.flatMap(C=>{var v,P;return[{[C+"_count"]:(v=m[C])==null?void 0:v.count},{[C+"_pct"]:(P=m[C])==null?void 0:P.pct}]}));c[T]={tournamentId:e,eventId:T,...A}}const f=Object.values(n??{}).filter(({participant:{participantType:d,participantRole:m}})=>d===xt&&m===fn),h={nonParticipatingEntriesCount:f.filter(({participant:d})=>!s.includes(d.participantId)).map(({participant:d})=>d.participantId).length,individualParticipantsCount:f.length,eventsCount:Object.values(a).length,drawDefinitionsCount:u,tournamentId:e};return{entryStatusReports:Object.values(c).flat(),participantEntryReports:Object.values(o).flat(),eventReports:Object.values(a).flat(),withDrawnParticipantIds:i,tournamentEntryReport:h}}function SL({eventType:t,matchUps:e,eventId:n,drawId:r}){const s={},i=m=>{const g=m==null?void 0:m.matchUpFormat;g&&(s[g]||(s[g]=0),s[g]+=1)},o=e.filter(m=>n?m.eventId===n:m.drawId===r).reduce((m,g)=>(i(g),(g.sides??[]).flatMap(I=>{var S;return(((S=I==null?void 0:I.participant)==null?void 0:S.individualParticipants)||[I==null?void 0:I.participant]).filter(Boolean)}).forEach(I=>m[I.participantId]=I),m),{}),c=Object.values(o),a=c.map(m=>yd({participant:m,eventType:t})).filter(({wtnRating:m})=>m),u=(c.length-a.length)/c.length*100,l=a.reduce((m,g)=>{const{wtnRating:I,confidence:S}=g;return m.totalWTN+=I,m.totalConfidence+=S,m},{totalWTN:0,totalConfidence:0}),f=a!=null&&a.length?l.totalWTN/a.length:0,p=a!=null&&a.length?l.totalConfidence/a.length:0,d=Object.values(s).reduce((m,g)=>m+(g||0),0);return{matchUpFormatCounts:s,matchUpsCount:d,avgConfidence:p,pctNoRating:u,avgWTN:f}}function TL({firstFlightOnly:t=!0,extensionProfiles:e,tournamentRecord:n}){var l;if(!n)return{error:is};const r={},s=Object.assign({},...(e??[]).map(({name:f,label:p,accessor:h})=>{var g,I,S;const d=(I=(g=Bn({tournamentRecord:n,name:f}))==null?void 0:g.extension)==null?void 0:I.value,m=h?(S=Yi({element:d,accessor:h}))==null?void 0:S.value:d;return{[p||f]:m}})),i=n==null?void 0:n.tournamentId,c=He({participantsProfile:{withScaleValues:!0},tournamentRecord:n}).matchUps??[],a=f=>{var h,d;const p=(h=kr({itemType:EI,itemSubTypes:[br],element:{timeItems:f}}))==null?void 0:h.timeItem;return(d=p==null?void 0:p.itemValue)==null?void 0:d.scaleBasis},u=(l=n==null?void 0:n.events)==null?void 0:l.flatMap(({timeItems:f,drawDefinitions:p=[],extensions:h,eventType:d,eventId:m,category:g})=>{var A,C,v,P;const I=h==null?void 0:h.find(U=>U.name===ar),S=(C=(A=I==null?void 0:I.value)==null?void 0:A.flights)==null?void 0:C.map(U=>({[U.drawId]:U.flightNumber})),T=S&&Object.assign({},...S),E=((P=(v=h==null?void 0:h.find(U=>U.name===ju))==null?void 0:v.value)==null?void 0:P.length)||0,y=Object.values(T),b=T&&Math.min(...y),N=a(f);return r[m]={totalPositionManipulations:0,maxPositionManipulations:0,generatedDrawsCount:0,drawDeletionsCount:E,seedingBasis:N?JSON.stringify(N):void 0,tournamentId:i,eventId:m},p.filter(U=>!t||!S||T[U.drawId]===b).flatMap(U=>{const{matchUpFormat:O,tieFormat:D,timeItems:M,extensions:w,structures:k,drawType:_,drawId:F}=U,{matchUpFormatCounts:L,matchUpsCount:W,avgConfidence:j,pctNoRating:H,avgWTN:B}=SL({eventType:d,matchUps:c,drawId:F}),R=a(M)||N,x=yL({extensions:w}),q=(x==null?void 0:x.length)||0;return r[m].totalPositionManipulations+=q,r[m].generatedDrawsCount+=1,q>r[m].maxPositionManipulations&&(r[m].maxPositionManipulations=q),k==null?void 0:k.filter(V=>V.stageSequence===1&&[Pt,It,Re,Ie].includes(V.stage)).map(V=>{var Ut,Kt;const Y=[It,Ie].includes(V.stage)?c.find(ut=>ut.structureId===V.structureId&&ut.finishingRound===1&&ut.winningSide):void 0,z=(Ut=Y==null?void 0:Y.sides)==null?void 0:Ut.find(ut=>ut.sideNumber===Y.winningSide),J=z==null?void 0:z.participant,Q=(J==null?void 0:J.participantType)===vr&&J.participantId,X=(J==null?void 0:J.participantType)===_t?J.individualParticipants:[],Z=yd({participant:(X==null?void 0:X[0])||J,eventType:d}),{personId:nt,personOtherId:rt,tennisId:K,confidence:it,wtnRating:st}=Z||{},dt=yd({participant:X==null?void 0:X[1],eventType:d}),{personId:mt,personOtherId:Mt,tennisId:Nt,confidence:St,wtnRating:ct}=dt||{},{ageCategoryCode:Et,categoryName:gt,subType:Ft}=g??{},yt=V.matchUpFormat||O,Xt=(L[yt]||0)/W*100,{tieFormatName:$t,tieFormatDesc:At}=Nl(D),{tieFormatName:Dt,tieFormatDesc:at}=Nl(V.tieFormat),ot=At===at,Lt=!ot&&Dt,ft=V.tieFormat&&!ot&&at,Ct=((Kt=x==null?void 0:x.filter(ut=>ut.structureId===V.structureId))==null?void 0:Kt.length)||0;return{...s,tournamentId:i,eventId:m,structureId:V.structureId,drawId:F,eventType:d,category:Ft,categoryName:gt,ageCategoryCode:Et,flightNumber:T[F],drawType:_,stage:V.stage,seedingBasis:R?JSON.stringify(R):void 0,winningPersonId:nt,winningPersonOtherId:rt,winningPersonTennisId:K,winningPersonWTNrating:st,winningPersonWTNconfidence:it,winningPerson2Id:mt,winningPerson2OtherId:Mt,winningPerson2TennisId:Nt,winningPerson2WTNrating:ct,winningPerson2WTNconfidence:St,winningTeamId:Q,positionManipulations:Ct,pctNoRating:H,matchUpFormat:yt,pctInitialMatchUpFormat:Xt,matchUpsCount:W,drawTieFormatName:$t,drawTieFormatDesc:At,tieFormatName:Lt,tieFormatDesc:ft,avgConfidence:j,avgWTN:B}})})});return{eventStructureReports:Object.values(r),structureReports:u}}function yL({extensions:t}){var e,n;return(n=(e=t==null?void 0:t.find(({name:r})=>r===xu))==null?void 0:e.value)==null?void 0:n.slice(1)}const EL={getStructureReports:TL,getEntryStatusReports:IL};function bL({representativeParticipantIds:t,drawDefinition:e}){if(!e)return{error:rr};if(!Array.isArray(t))return{error:tt};const n=xa((e==null?void 0:e.entries)||[]);return t.length&&qe(t,n).length<t.length?{error:tt}:Nf({drawDefinition:e,extension:{name:gf,value:t}})}function NL({drawDefinition:t}){var r;const e=Hu({name:"participantRepresentatives",drawDefinition:t});return e.error?e:{representativeParticipantIds:((r=e.extension)==null?void 0:r.value)||[]}}function AL({tournamentRecord:t,drawDefinition:e,participantId:n,sideNumber:r,matchUpId:s,event:i}){var l,f;if(n&&typeof n!="string")return{error:bs};if(!e)return{error:lt};if(!s)return{error:$e};const o=r===void 0;if(o&&(r=1),![1,2].includes(r))return{error:tt,sideNumber:r};const{matchUp:c,structure:a}=ie({drawDefinition:e,matchUpId:s,event:i});if(!c)return{error:Ye};if(!(!(a!=null&&a.structures)&&!(e.drawType&&e.drawType!==Xn)&&!((l=a==null?void 0:a.matchUps)!=null&&l.find(({roundPosition:p})=>!!p))))return{error:Bd};if(!n&&((f=c==null?void 0:c.score)!=null&&f.scoreStringSide1||We.includes(c==null?void 0:c.matchUpstatus)||c!=null&&c.matchUpStatus&&[Fe,en].includes(c.matchUpStatus)))return{error:qd,info:"matchUp has completed status or score"};if(c){if(c.sides=[1,2].map(p=>{var d;const h=((d=c.sides)==null?void 0:d.find(m=>m.sideNumber===p))||{sideNumber:p};return r===p?{...h,participantId:n}:h}),o)for(const p of c.sides)p.sideNumber&&(p.sideNumber=3-p.sideNumber);qt({tournamentId:t==null?void 0:t.tournamentId,context:"assignSideParticipant",drawDefinition:e,matchUp:c})}return{...$,sidesSwapped:o}}function vL({tournamentRecord:t,drawDefinition:e,sideNumber:n,matchUpId:r,event:s}){var a,u;if(!t)return{error:et};if(!e)return{error:lt};if(!r)return{error:$e};if(!n)return{error:Tt};if(![1,2].includes(n))return{error:tt,sideNumber:n};const{matchUp:i,structure:o}=ie({drawDefinition:e,matchUpId:r,event:s});return i?!(o!=null&&o.structures)&&!(e.drawType&&e.drawType!==Xn)&&!((a=o==null?void 0:o.matchUps)!=null&&a.find(({roundPosition:l})=>!!l))?((u=i.sides)==null||u.forEach(l=>{l.sideNumber===n&&delete l.participantId}),qt({tournamentId:t==null?void 0:t.tournamentId,context:"assignSideParticipant",drawDefinition:e,matchUp:i}),{...$}):{error:Bd}:{error:Ye}}function Qb(t){var W,j,H,B,R,x,q,V,Y,z,J,Q,X,Z,nt;const e=tm(t);if(e.error)return e;const n="replaceTieMatchUpParticipantid",{existingParticipantId:r,tournamentRecord:s,newParticipantId:i,drawDefinition:o,substitution:c,event:a}=t;if(!r||!i)return G({result:{error:Ce},stack:n});if(r===i)return{...$};const{inContextDualMatchUp:u,inContextTieMatchUp:l,collectionPosition:f,collectionId:p,dualMatchUp:h,tieMatchUp:d,tieFormat:m}=e,g=l==null?void 0:l.matchUpType,I=(W=l==null?void 0:l.sides)==null?void 0:W.find(rt=>{var K,it,st;return((K=rt.participant)==null?void 0:K.participantId)===r||((st=(it=rt.participant)==null?void 0:it.individualParticipantIds)==null?void 0:st.includes(r))});if(!I)return{error:_e};const{tournamentParticipants:S}=dn({tournamentRecord:s,participantFilters:{participantIds:[r,i]}});if(S.length!==2)return G({result:{error:Ce},stack:n});if(S[0].participantType!==S[1].participantType)return G({result:{error:xr},stack:n});const{appliedPolicies:T}=ge({tournamentRecord:s,drawDefinition:o,event:a}),E=(T==null?void 0:T[Jn])||iu[Jn],y=S.find(({participantId:rt})=>rt===i);if((j=E==null?void 0:E.participants)!=null&&j.enforceGender&&[Se,Ne].includes(l==null?void 0:l.gender)&&(l==null?void 0:l.gender)!==((H=y.person)==null?void 0:H.sex))return{error:vu,info:"Gender mismatch"};const b=(B=E==null?void 0:E.processCodes)==null?void 0:B.substitution,{extension:N}=Ke({element:o,name:Wr}),A=(N==null?void 0:N.value)||{};if(!((R=h==null?void 0:h.sides)!=null&&R.length)){const rt=({displaySideNumber:K,drawPosition:it,sideNumber:st})=>({drawPosition:it,sideNumber:st,displaySideNumber:K});h&&(h.sides=(x=u==null?void 0:u.sides)==null?void 0:x.map(K=>{const it=K.participantId;return{...rt(K),lineUp:it&&A[it]||[]}}))}const C=(q=h==null?void 0:h.sides)==null?void 0:q.find(({sideNumber:rt})=>rt===I.sideNumber);if(!C)return G({result:{sideNumber:I.sideNumber,existingParticipantId:r,error:an},stack:n});const v=(V=l==null?void 0:l.sides)==null?void 0:V.flatMap(rt=>{var K,it;return((K=rt.participant)==null?void 0:K.individualParticipantIds)||((it=rt.participant)==null?void 0:it.participantId)||[]});if(v!=null&&v.includes(i))return G({result:{error:Yd},stack:n});const P=(z=(Y=u==null?void 0:u.sides)==null?void 0:Y.find(({sideNumber:rt})=>rt===I.sideNumber))==null?void 0:z.participantId,U=C.lineUp,O=U==null?void 0:U.find(({participantId:rt})=>i===rt),D=U==null?void 0:U.reduce((rt,K)=>K.substitutionOrder>rt?K.substitutionOrder:rt,0),M=(U==null?void 0:U.map(rt=>{var it;const K=pt(rt,!1,!0);if(![r,i].includes(K.participantId))return K;if(!c&&[r,i].includes(K.participantId)&&(K.collectionAssignments=(it=K.collectionAssignments)==null?void 0:it.filter(st=>!(st.collectionPosition===f&&st.collectionId===p))),c&&r===K.participantId&&(K.collectionAssignments=K.collectionAssignments.map(st=>st.collectionPosition===f&&st.collectionId===p&&st.substitutionOrder===void 0?{...st,substitutionOrder:D}:st)),K.participantId===i){K.collectionAssignments||(K.collectionAssignments=[]);const st={collectionId:p,collectionPosition:f};c&&(st.previousParticipantId=r,st.substitutionOrder=(D||0)+1),K.collectionAssignments.push(st)}return K}))||[];if(!O){const rt={collectionId:p,collectionPosition:f};c&&(rt.substitutionOrder=(D||0)+1,rt.previousParticipantId=r);const K={collectionAssignments:[rt],participantId:i};M.push(K)}const w=g===me,{assignedParticipantIds:k}=Xu({lineUp:U,collectionPosition:f,collectionId:p}),{assignedParticipantIds:_}=Xu({lineUp:M,collectionPosition:f,collectionId:p});if(C.lineUp=M,P&&m){const rt=Uc({participantId:P,lineUp:M,drawDefinition:o,tieFormat:m});if(rt.error)return G({result:rt,stack:n})}else console.log("team participantId not found");let F,L;if(w){const{tournamentRecord:rt}=t;let K=Jr({participantIds:_,tournamentRecord:rt});if(!K.participant){const dt=es({returnParticipant:!0,pairOverride:!0,tournamentRecord:rt,participant:{participantRole:fn,individualParticipantIds:_,participantType:_t}});if(dt.error)return G({result:dt,stack:n});F=(J=dt.participant)==null?void 0:J.participantId}K=Jr({participantIds:k,tournamentRecord:rt});const it=(Q=K.participant)==null?void 0:Q.participantId;it&&Fc({participantIds:[it],tournamentRecord:rt}).success&&(L=it)}if(c||((X=I.substitutions)==null?void 0:X.length)===1){if(c){const rt=(d==null?void 0:d.processCodes)||[];b&&rt.push(...b),d&&(d.processCodes=rt)}else for(const rt of b||[]){const K=(Z=d==null?void 0:d.processCodes)==null?void 0:Z.lastIndexOf(rt);K!==void 0&&((nt=d==null?void 0:d.processCodes)==null||nt.splice(K,1))}d&&qt({tournamentId:s==null?void 0:s.tournamentId,matchUp:d,context:n,drawDefinition:o})}return h&&qt({tournamentId:s==null?void 0:s.tournamentId,matchUp:h,context:n,drawDefinition:o}),{...$,modifiedLineUp:M,participantRemoved:L,participantAdded:F}}function CL(t){var P,U,O,D,M,w,k,_,F,L,W,j,H,B,R;const{tournamentRecord:e,drawDefinition:n,participantId:r,event:s}=t,i="removeTieMatchUpParticiapantId";if(!r)return G({result:{error:Ce},stack:i});const o=tm(t);if(o.error)return o;const{appliedPolicies:c}=ge({tournamentRecord:e,drawDefinition:n,event:s}),a=(c==null?void 0:c[Jn])||iu[Jn],u=(P=a==null?void 0:a.processCodes)==null?void 0:P.substitution,{inContextDualMatchUp:l,inContextTieMatchUp:f,relevantAssignments:p,collectionPosition:h,teamParticipants:d,collectionId:m,matchUpType:g,dualMatchUp:I,tieMatchUp:S,tieFormat:T}=o;if(!I)return{error:Rn};const E=(U=f==null?void 0:f.sides)==null?void 0:U.find(x=>{var q,V,Y;return((q=x.participant)==null?void 0:q.participantId)===r||((Y=(V=x.participant)==null?void 0:V.individualParticipantIds)==null?void 0:Y.includes(r))});if(!E)return{error:_e};if(!((O=E.substitutions)!=null&&O.length)&&(Be({score:f==null?void 0:f.score})||f!=null&&f.winningSide))return{error:_v};const y=(M=(D=l==null?void 0:l.sides)==null?void 0:D.find(({sideNumber:x})=>x===E.sideNumber))==null?void 0:M.participantId;if(!y)return{error:_e};const{tournamentParticipants:[b]}=dn({tournamentRecord:e,participantFilters:{participantIds:[r]}});if(!b)return{error:_e};if(g===Oe&&b.participantType===_t)return{error:vu};const N=b.participantType===xt?[r]:b.individualParticipantIds;if(!((w=I==null?void 0:I.sides)!=null&&w.length)){const{extension:x}=Ke({element:n,name:Wr}),q=(x==null?void 0:x.value)||{},V=({displaySideNumber:Y,drawPosition:z,sideNumber:J})=>({drawPosition:z,sideNumber:J,displaySideNumber:Y});I.sides=(k=l==null?void 0:l.sides)==null?void 0:k.map(Y=>{const z=Y.participantId;return{...V(Y),lineUp:z&&q[z]||[]}})}let A=(_=I.sides)==null?void 0:_.find(({sideNumber:x})=>x===E.sideNumber);if(!A&&(((F=I.sides)==null?void 0:F.filter(({lineUp:x})=>!x).length)||0)<2){const x=d==null?void 0:d.map(({participantId:q})=>{var V;return{drawPosition:(V=p==null?void 0:p.find(Y=>Y.participantId===q))==null?void 0:V.drawPosition,teamParticipantId:q}});A=(L=I.sides)==null?void 0:L.find(q=>{var V;return((V=x==null?void 0:x.find(({drawPosition:Y})=>Y===q.drawPosition))==null?void 0:V.teamParticipantId)===y})}if(!A)return console.log({teamParticipantId:y,teamParticipants:d}),{error:_e,participantId:r};const{modifiedLineUp:C,previousParticipantIds:v}=Gb({collectionPosition:h,teamParticipantId:y,dualMatchUpSide:A,participantIds:N,drawDefinition:n,collectionId:m});if(A.lineUp=C,y&&T&&Uc({participantId:y,lineUp:C,drawDefinition:n,tieFormat:T}),g===me&&b.participantType===xt){const x=(W=f==null?void 0:f.sides)==null?void 0:W.find(Y=>Y.sideNumber===(A==null?void 0:A.sideNumber)),{participantId:q}=x||{},{tournamentParticipants:[V]}=dn({tournamentRecord:e,participantFilters:{participantIds:[q]},withEvents:!0});if(V){const Y=V==null?void 0:V.individualParticipantIds.filter(z=>z!==r);if(v&&Y.push(...v),Y.length>2)return{error:gr};if(V.draws.length){if(Y.length===1){const{participant:z}=Jr({participantIds:Y,tournamentRecord:e});if(!z){const Q=es({participant:{participantRole:fn,individualParticipantIds:Y,participantType:_t},pairOverride:!0,tournamentRecord:e});if(Q.error)return Q}}}else if(Y.length){V.individualParticipantIds=Y;const z=Xh({participant:V,pairOverride:!0,tournamentRecord:e});if(z.error)return z}else{const z=Fc({participantIds:[q],tournamentRecord:e});z.error&&console.log("cleanup",{result:z})}}else return{error:_e}}if(((j=E.substitutions)==null?void 0:j.length)===1){const x=(H=f==null?void 0:f.sides)==null?void 0:H.find(q=>q.sideNumber!==E.sideNumber);if(!((B=x==null?void 0:x.substitutions)!=null&&B.length)&&((R=S==null?void 0:S.processCodes)!=null&&R.length)){for(const q of u||[]){const V=S.processCodes.lastIndexOf(q);S.processCodes.splice(V,1)}qt({tournamentId:e==null?void 0:e.tournamentId,matchUp:S,context:i,drawDefinition:n})}}return qt({tournamentId:e==null?void 0:e.tournamentId,matchUp:I,context:i,drawDefinition:n}),{...$,modifiedLineUp:C}}function im({tournamentRecord:t,drawDefinition:e,stage:n=It,structureId:r,structure:s}){var c;if(!t)return{error:et};if(!s&&!e)return{error:lt};if(!s&&!r&&((c=e==null?void 0:e.structures)==null?void 0:c.filter(a=>a.stage===n).length)===1&&(s=e.structures.find(a=>a.stage===n)),!s&&!r)return{error:En};const{error:i,positionAssignments:o}=ee({drawDefinition:e,structureId:r,structure:s});return{error:i,positionAssignments:o||[],structureId:s==null?void 0:s.structureId}}function om({autoPublish:t=!0,policyDefinitions:e,tournamentRecord:n,drawIds:r=[],auditData:s,eventId:i,event:o}){var E,y,b;if(!n)return{error:et};const c="deleteDrawDefinitions";if(!e){const{appliedPolicies:N}=ge({tournamentRecord:n,event:o});e=N}const a=Array.isArray(r)?r[0]:void 0;if(!o){const N=Je({tournamentRecord:n,eventId:i,drawId:a});if(N.error)return N;o=N.event}const u=[],l=[],f=[];if(!(o!=null&&o.drawDefinitions))return G({result:{...$},info:"event has no drawDefinition",stack:c});const p=o.drawDefinitions.map(({drawId:N})=>N);if(r.length||(r=p),r=r.filter(N=>p.includes(N)),!r.length)return G({result:{...$},info:"nothing to do; no matching drawIds in event.",stack:c});const h=pt(be({event:o}).flightProfile,!1,!0),d=({participantId:N,drawPosition:A,qualifier:C,bye:v})=>({bye:v,qualifier:C,drawPosition:A,participantId:N}),m=o.drawDefinitions.filter(N=>{var A,C,v,P,U,O;if(r.includes(N.drawId)){const{drawId:D,drawType:M,drawName:w}=N,k=(A=h==null?void 0:h.flights)==null?void 0:A.find(R=>R.drawId===N.drawId);k&&(k.drawEntries=(C=k.drawEntries)==null?void 0:C.filter(R=>tS.includes(R.entryStatus)));const _=(P=(v=lr({stageSequence:1,drawDefinition:N,stage:It}))==null?void 0:v.structures)==null?void 0:P[0],F=_?im({structureId:_.structureId,tournamentRecord:n,drawDefinition:N}):void 0,L=(U=F==null?void 0:F.positionAssignments)==null?void 0:U.map(d),W=(O=lr({stage:Pt,drawDefinition:N}))==null?void 0:O.structures,j=W!=null&&W.length?W.map(R=>{const x=R.stageSequence,q=im({structureId:R.structureId,tournamentRecord:n,drawDefinition:N});return{positionAssignments:q==null?void 0:q.positionAssignments.map(d),stageSequence:x}}):void 0,H={action:aw,payload:{drawDefinitions:[N],eventId:i||(o==null?void 0:o.eventId),auditData:s}};f.push(H),u.push(bt({tournamentId:n.tournamentId,eventId:i||(o==null?void 0:o.eventId),qualifyingPositionAssignments:j,positionAssignments:L,auditData:s,drawType:M,drawName:w,drawId:D}));const{matchUps:B}=tr({event:o,drawDefinition:N});B==null||B.forEach(({matchUpId:R})=>l.push(R))}return!r.includes(N.drawId)});o.drawDefinitions=m,h&&Yr({event:o,extension:{name:ar,value:h}}),cd({tournamentRecord:n});const g=`${Qn}.${Zn}`,{timeItem:I}=kr({element:o,itemType:g}),S=(E=I==null?void 0:I.itemValue)==null?void 0:E[Kr];let T;for(const N of r)if((y=S==null?void 0:S.drawIds)==null?void 0:y.includes(N)){T=!0;const C=((b=S.drawIds)==null?void 0:b.filter(U=>U!==N))||[],v={itemType:`${Qn}.${Zn}`,itemValue:{[Kr]:{drawIds:C}}},P=ii({event:o,timeItem:v});if(P.error)return{error:P.error}}if(f.length&&Ht({topic:ha,payload:f}),l.length&&ei({tournamentId:n==null?void 0:n.tournamentId,matchUpIds:l}),r.forEach(N=>{iU({drawId:N})}),PL({event:o,deletedDrawsDetail:u,auditData:s}),t&&T){const N=fu({tournamentRecord:n,event:o,policyDefinitions:e});N.error&&console.log("publish error",N)}return{...$}}function PL({event:t,deletedDrawsDetail:e,auditData:n}){const{extension:r}=xn({name:ju,element:t}),s={...n,deletedDrawsDetail:e},i={name:ju,value:Array.isArray(r==null?void 0:r.value)?r==null?void 0:r.value.concat(s):[s]};ae({element:t,extension:i})}function UL({removeCompletedMatchUps:t,tournamentRecord:e,drawDefinition:n,structureId:r,roundNumber:s,event:i}){if(!e)return{error:et};if(!n)return{error:lt};if(!s)return G({result:{error:Tt},info:"roundNumber required"});const o=Ot({drawDefinition:n,structureId:r});if(o.error)return o;const c=o.structure;return c!=null&&c.structures?{error:Go}:Qr({drawDefinition:n,structure:c})?OL({tournamentId:e.tournamentId,removeCompletedMatchUps:t,eventId:i.eventId,drawDefinition:n,roundNumber:s,structure:c}):(console.log("not implemented"),{...$})}function OL({removeCompletedMatchUps:t,drawDefinition:e,tournamentId:n,roundNumber:r,structure:s,eventId:i}){const o=(s==null?void 0:s.matchUps)??[],c=[];let a=!1;if(o.reduce((l,f)=>{const p=f==null?void 0:f.roundNumber;return p?l.includes(p)?l:l.concat(p):l},[]).sort(Ve).includes(r)){const l=o.filter(f=>{const p=f.roundNumber===r&&(!We.includes(f.matchUpStatus)||t);return p&&c.push(f.matchUpId),!p});c.length&&(ei({matchUpIds:c,drawDefinition:e,tournamentId:n,eventId:i}),l.some(p=>p.roundNumber===r)||(l.forEach(p=>{p.roundNumber>r&&(p.roundNumber-=1,qt({drawDefinition:e,tournamentId:n,eventId:i,matchUp:p}))}),a=!0),s.matchUps=l)}return{deletedMatchUpsCount:c.length,roundRemoved:a,...$}}function ML({tournamentRecord:t,drawDefinition:e,participantId:n,drawPosition:r,structureId:s,qualifier:i,event:o,bye:c}){if(!e)return{error:lt};if(!r)return{error:Wc};if(!s)return{error:En};if(c){const a=Vn({tournamentRecord:t,drawDefinition:e,drawPosition:r,structureId:s,event:o});if(a.error)return a}else{if(i)return{error:bg};{const a=_r({tournamentRecord:t,drawDefinition:e,participantId:n,drawPosition:r,structureId:s,event:o});if(a.error)return a}}return{...$}}function DL({allowDuplicateParticipantIdPairs:t,entryStage:e=As.Main,entryStatus:n=dr,participantIdPairs:r=[],tournamentRecord:s,drawDefinition:i,event:o,uuids:c}){if(!s)return{error:et};if(!o)return{error:Wt};if(o.eventType!==me)return{error:ui};const a=s.participants||[],u=a.filter(E=>E.participantType===xt).map(E=>E.participantId),l=u.filter(E=>!u.includes(E));if(l.length)return{error:gr,invalidParticipantIds:l};const f=r.filter(E=>E.length!==2);if(f.length)return{error:gr,invalidParticipantIdPairs:f};const p=a.filter(E=>E.participantType===_t).map(E=>E.individualParticipantIds),h=r.map(E=>({participantId:(c==null?void 0:c.pop())||Yt(),participantRole:fn,individualParticipantIds:E,participantType:_t})),d=t?h:h.filter(E=>!p.find(y=>qe(y,E.individualParticipantIds).length===2));let m,g=[];if(d){const E=Ss({allowDuplicateParticipantIdPairs:t,participants:d,returnParticipants:!0,tournamentRecord:s});if(E.error)return E;g=E.participants||[],m=E.info}const I=r.map(E=>{const y=g.find(N=>qe(N.individualParticipantIds,E).length===2);if(y)return y;const{participant:b}=Jr({tournamentRecord:s,participantIds:E});return b}).map(E=>E.participantId),S=Fs({participantIds:I,tournamentRecord:s,drawDefinition:i,entryStatus:n,entryStage:e,event:o});d.length&&Ht({payload:{participants:d},topic:yi});const T=d.map(fe);return{...S,info:m,newParticipantIds:T}}function Zb({enforceGender:t=!0,consideredEntries:e,tournamentRecord:n,participants:r,event:s}){if(r=r||(n==null?void 0:n.participants),!r)return{error:Yc};if(!Array.isArray(r))return{error:tt};if(!s)return{error:Wt};const{eventType:i,gender:o}=s,c=i===ds&&se||i===Zu&&_t||xt,a=Object.assign({},...(e||s.entries||[]).map(p=>({[p.participantId]:p.entryStatus}))),u=Object.keys(a),f=r.filter(p=>u.includes(p.participantId)).filter(p=>{var S;const h=a[p.participantId],d=i&&[_n.Doubles,_n.Team].includes(i)&&p.participantType===xt&&(Ri(h)||h===ti),m=p.participantType!==c&&!d,g=(S=p==null?void 0:p.person)==null?void 0:S.sex,I=t&&o&&i===_n.Singles&&[sa.Male,sa.Female].includes(o)&&g!==o;return m||I});if(f.length){const p=f.map(h=>h.participantId);return{error:Y1,invalidParticipantIds:p}}return{...$}}function wL(t){const{provisionalPositioning:e,useExistingSeedLimit:n,tournamentRecord:r,drawDefinition:s,seedingProfile:i,structureId:o,assignments:c,drawId:a,event:u}=t;let l=0;if(!(c!=null&&c.length))return{error:Jm};if(!r)return{error:et};if(!a)return{error:Hn};const f=Mr({provisionalPositioning:e,drawDefinition:s,structureId:o});if(f.error)return f;const{seedAssignments:p,seedLimit:h}=f,d=Object.assign({},...(p||[]).filter(I=>I.seedNumber).map(I=>({[I.seedNumber]:I})));c.forEach(I=>{const{seedNumber:S}=I;h&&S<=h&&(!n||d[S])&&(d[S]=I)});const m=Object.values(d),g=m.map(I=>I==null?void 0:I.participantId).filter(Boolean);if(g.length!==$m(g).length)return{error:F1};for(const I of m){const S=Do({...I,provisionalPositioning:e,tournamentRecord:r,drawDefinition:s,seedingProfile:i,structureId:o,event:u});if(S!=null&&S.error)return S;S!=null&&S.success&&l++}return l?{...$,modifications:l}:{error:zc}}function kL({removePairParticipants:t,tournamentRecord:e,eventIds:n}){if(!e)return{error:et};if(!e.events)return{error:wn};if(!Array.isArray(n))return{error:Tt,info:sn("drawIds")};const r=[],s=[],i=[],o=[];if(e.events=(e.events||[]).filter(c=>{if(n.includes(c.eventId)){const l={action:jy,payload:{events:[c]}};r.push(l),s.push({tournamentId:e.tournamentId,eventName:c.eventName,eventType:c.eventType,category:c.category,eventId:c.eventId,gender:c.gender})}const a=c.eventType===$n?(c.entries||[]).map(({entryStatus:l,participantId:f})=>l!==Or&&f).filter(Boolean):[],u=n.includes(c.eventId);return u?o.push(...a):i.push(...a),!u}),t){const c=o.filter(a=>!i.includes(a));e.participants=e.participants.filter(({participantId:a})=>!c.includes(a))}return cd({tournamentRecord:e}),r.length&&(Ht({topic:ha,payload:r}),_s({tournamentRecord:e,timeItem:{itemType:jy,itemValue:s}})),{...$}}const Xb="COLLEGE_DEFAULT",tN="COLLEGE_JUCO",eN="COLLEGE_D3",_L="DOMINANT_DUO",FL="DOMINANT_DUO_MIXED",LL="LAVER_CUP",RL="TEAM_DOUBLES_3_AGGREGATION",BL="USTA_BREWER_CUP",xL="USTA_OZAKI_CUP",$L="USTA_COLLEGE",VL="USTA_GOLD_TEAM_CHALLENGE",jL="USTA_LEVEL_1",GL="USTA_INTERSECTIONAL",WL="USTA_SECTION_BATTLE",HL="USTA_SOUTHERN_LEVEL_5",qL="USTA_TOC",YL="USTA_WTT_ITT",zL="USTA_ZONAL",nN="STANDARD",rN={[nN]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1},singles:{matchUpCount:6,matchUpValue:1},valueGoal:5},[eN]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1,matchUpFormat:"SET1-S:8/TB7@7"},singles:{matchUpFormat:Kn,matchUpCount:6,matchUpValue:1},tieFormatName:eN,valueGoal:5},[Xb]:{hydrate:!0,doubles:{matchUpCount:3,collectionValue:1,matchUpFormat:Kn},singles:{matchUpCount:6,matchUpValue:1,matchUpFormat:Kn},tieFormatName:Xb,valueGoal:4},[tN]:{hydrate:!0,doubles:{matchUpCount:3,matchUpValue:1,matchUpFormat:"SET1-S:8/TB7"},singles:{matchUpCount:6,matchUpValue:1,matchUpFormat:Kn},tieFormatName:tN,valueGoal:5},[LL]:VS,[_L]:xS,[FL]:$S,[RL]:jS,[BL]:GS,[xL]:WS,[$L]:HS,[VL]:qS,[GL]:YS,[jL]:zS,[WL]:KS,[HL]:JS,[YL]:ZS,[qL]:QS,[zL]:XS},Lo=t=>{const e=t!=null&&t.namedFormat&&Object.keys(rN).includes(t.namedFormat)?t.namedFormat:nN,n=Array.isArray(t==null?void 0:t.uuids)?t==null?void 0:t.uuids:[];let r;const{category:s,gender:i}=(t==null?void 0:t.event)||{},o=pt(rN[e],!1,!0);return o.hydrate?(r={winCriteria:{valueGoal:o.valueGoal},collectionDefinitions:[{collectionId:(n==null?void 0:n.pop())||Yt(),matchUpFormat:Vg,matchUpType:_n.Doubles,collectionName:"Doubles",...o.doubles},{collectionId:(n==null?void 0:n.pop())||Yt(),matchUpType:_n.Singles,matchUpFormat:Kn,collectionName:"Singles",...o.singles}]},o.tieFormatName&&(r.tieFormatName=o.tieFormatName)):(o.collectionDefinitions.forEach(c=>c.collectionId=Yt()),r=o),t!=null&&t.hydrateCollections&&r.collectionDefinitions.forEach(c=>{s&&!c.category&&(c.category=s),i&&!c.gender&&(c.gender=i)}),r};function Ed({suppressNotifications:t,tournamentRecord:e,internalUse:n,event:r}){var a,u,l,f;if(!e)return{error:et};if(e.events||(e.events=[]),!r)return{error:Wt};const{startDate:s,endDate:i}=e;if(!n&&((a=r.entries)!=null&&a.length||(u=r.drawDefinitions)!=null&&u.length)){const p=bt({drawDefinitions:!!((l=r.drawDefinitions)!=null&&l.length),entries:!!((f=r.entries)!=null&&f.length)});return{info:"entries/drawDefinitions cannot exist",error:tt,context:p}}const o=Object.assign({},{drawDefinitions:[],eventType:_n.Singles,entries:[],startDate:s,endDate:i},r);if(r.eventType===_n.Team){if(r.tieFormat){const p=vn({tieFormat:r.tieFormat});if(p.error)return p}else if(r.tieFormatName){if(!tT[r.tieFormatName])return{context:{tieFormatName:r.tieFormatName},error:tt};const p=Lo({namedFormat:r.tieFormatName});o.tieFormat=p}}if(o.eventId||(o.eventId=Yt()),e.events.reduce((p,h)=>p||h.eventId===o.eventId,void 0))return{error:H1};{const p=o;if(e.events.push(p),!t){const{topics:h}=$r();if(h.includes(Pf)){const d=si({event:r}).matchUps||[];Oi({tournamentId:e==null?void 0:e.tournamentId,eventId:r.eventId,matchUps:d})}for(const d of r.drawDefinitions||[])Ba({drawDefinition:d})}return{...$,event:o}}}function KL({tournamentRecord:t,participantId:e,matchUpId:n,matchUp:r,drawId:s}){r&&!s&&({drawId:s}=r),r&&!n&&({matchUpId:n}=r);const{drawDefinition:i}=Je({tournamentRecord:t,drawId:s});if(i){const o=t.participants,c=fh({tournamentParticipants:o,drawDefinition:i,participantId:e,matchUpId:n});if(c.error&&c.error!==ug)return c}else return{error:wn};return{...$}}function JL({tournamentRecord:t,participantId:e,matchUpId:n,matchUp:r,drawId:s}){r&&!s&&({drawId:s}=r),r&&!n&&({matchUpId:n}=r);const{drawDefinition:i}=Je({tournamentRecord:t,drawId:s});if(i){const o=t.participants,c=ph({tournamentParticipants:o,drawDefinition:i,participantId:e,matchUpId:n});if(c.error)return c}else return{error:wn};return{...$}}function QL(t){const{participantId:e}=t;return e&&typeof e!="string"?{error:tt,participantId:e}:sN({...t,participantIds:[e].filter(Boolean)})}function sN({tournamentRecord:t,drawDefinition:e,participantIds:n,stageSequence:r,stage:s=It,eventId:i,event:o}){if(!t)return{error:et};if(!Array.isArray(n))return{error:tt,participantIds:n};if(!o)return{error:Wt};const c="promoteAlternates";if(o){const a=iN({element:o,participantIds:n,stageSequence:r,stage:s});if(a.error)return a}if(e){const a=iN({element:e,participantIds:n,stageSequence:r,stage:s});if(a.error)return i?G({context:{drawPromotionError:a.error,drawId:e.drawId},result:{...$},stack:c}):a}return{...$}}function iN({participantIds:t,stageSequence:e,element:n,stage:r}){const s=(n.entries||[]).filter(f=>f.entryStatus===dr),i=(n.entries||[]).filter(f=>t.includes(f.participantId)),o=s.reduce((f,p)=>{const{entryPosition:h}=p;return isNaN(h)&&f||(!f||h<f.entryPosition)&&p||f},void 0),c=i.length?i:[o].filter(Boolean);if(!(c!=null&&c.length))return{error:dg};const a=c.filter(({entryStatus:f})=>f!==dr);if(a.length)return{error:zd,invalidEntryStatus:a};const u=c.filter(({entryStage:f})=>f&&f!==r);if(u.length)return{error:hv,invalidStage:u};const l=e&&c.filter(f=>f.stageSequence!==e);if(l!=null&&l.length)return{error:mv,invalidStageSequence:l};for(const f of c){f.entryStatus=Ur;const p=f==null?void 0:f.entryPosition;isNaN(p)||n.entries.forEach(d=>{d.entryStatus===dr&&d.entryPosition>p&&(d.entryPosition=d.entryPosition-1)});const h=Math.max(...n.entries.filter(d=>d.entryStatus===Ur&&!isNaN(d.entryPosition)).map(({entryPosition:d})=>vt(d||0)),0);f.entryPosition=h||0}return{...$}}function ZL(t){return Object.assign(t,{entryStatus:ti}),Sd(t)}function XL({luckyLoserParticipantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:s}){return Vh({positionActionName:"luckyLoserDrawPositionAssignment",participantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:s})}function tR(t){return XL(t)}function eR({qualifyingParticipantId:t,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:s}){return Vh({positionActionName:"qualifierDrawPositionAssignment",participantId:t,isQualifierPosition:!0,tournamentRecord:e,drawDefinition:n,drawPosition:r,structureId:s})}function nR(t){return eR(t)}function rR(t){return eb(t)}function sR(t){return fb(t)}function oN(t){return ou(t)}function iR(t){return nb(t)}function oR({tournamentRecord:t,drawDefinition:e,drawPosition:n,structureId:r,event:s}){return Vn({tournamentRecord:t,drawDefinition:e,drawPosition:n,structureId:r,event:s})}function cR({replacementIndividualParticipantId:t,existingIndividualParticipantId:e,tournamentRecord:n,drawDefinition:r,participantId:s,event:i,uuids:o}){var m,g;if(!i)return{error:Wt};if((i==null?void 0:i.eventType)!==$n)return{error:ui};if(o&&!Array.isArray(o))return{error:tt};if(!n)return{error:et};if(![t,e,s].every(I=>typeof I=="string"))return{error:Ce};if(!(((m=i==null?void 0:i.entries)==null?void 0:m.filter(({entryStatus:I})=>[Or,po].includes(I)).map(({participantId:I})=>I))||[]).includes(t))return{error:bs};const a=(n.participants||[]).find(I=>I.participantId===s);if((a==null?void 0:a.participantType)!==_t)return{error:vu,participant:a};const u=a.individualParticipantIds,l=[t,...u.filter(I=>I!==e)],{participant:f}=Jr({participantIds:l,tournamentRecord:n});let p;if(f)p=f.participantId;else{const I={participantId:o==null?void 0:o.pop(),participantRole:fn,individualParticipantIds:l,participantType:_t},S=es({participant:I,returnParticipant:!0,tournamentRecord:n});if(S.error)return S;p=S.participant.participantId}const{flightProfile:h}=be({event:i});if(r){const I=(g=h==null?void 0:h.flights)==null?void 0:g.find(({drawId:S})=>S===r.drawId);I&&(I.drawEntries=I.drawEntries.map(S=>S.participantId===s?{...S,participantId:p}:S)),r.entries=r.entries.map(S=>S.participantId===s?{...S,participantId:p}:S);for(const S of r.structures||[])if(S.positionAssignments)S.positionAssignments=S.positionAssignments.map(T=>T.participantId===s?{...T,participantId:p}:T);else if(S.structures)for(const T of S.structures)T.positionAssignments=T.positionAssignments.map(E=>E.participantId===s?{...E,participantId:p}:E)}i.entries=i.entries.map(I=>I.participantId===s&&{...I,participantId:p}||I.participantId===t&&{...I,participantId:e}||I);const d=n.events.some(({entries:I,eventId:S,drawDefinitions:T})=>i.eventId===S?T.some(({drawId:E,entries:y})=>E===(r==null?void 0:r.drawId)?!1:y==null?void 0:y.find(b=>b.participantId===s)):I==null?void 0:I.find(E=>E.participantId===s));if(!d){const I=Fc({addIndividualParticipantsToEvents:!1,participantIds:[s],tournamentRecord:n});if(I.error)return I}return{...$,participantOtherEntries:d,newPairParticipantId:p}}function aR({autoEntryPositions:t=!0,participantIds:e,drawDefinition:n,drawId:r,stages:s,event:i}){var f;if(!i)return{error:Wt};if(!r)return{error:Hn};if(!(e!=null&&e.length))return{error:Ns};const o=gd({drawDefinition:n,stages:s});if(tn(o,e))return{error:Yo};const a=p=>{const h=p.participantId;return!e.includes(h)},{flightProfile:u}=be({event:i}),l=(f=u==null?void 0:u.flights)==null?void 0:f.find(p=>p.drawId===r);return l!=null&&l.drawEntries&&(l.drawEntries=l.drawEntries.filter(a),t&&(l.drawEntries=pr({entries:l.drawEntries}))),n!=null&&n.entries&&(n.entries=n.entries.filter(a),t&&(n.entries=pr({entries:n.entries}))),{...$}}function uR(t){const e=t.tournamentRecord;if(!e)return{error:et};const n=hd(t);if(n.error)return n;const{playoffStructureNameBase:r,playoffPositions:s,roundNumbers:i,structureId:o}=t,a={itemType:"addPlayoffStructures",itemValue:bt({playoffStructureNameBase:r,playoffPositions:s,roundNumbers:i,structureId:o})};return _s({tournamentRecord:e,timeItem:a}),n}function lR({tournamentRecord:t,drawDefinition:e,participantId:n,structureId:r,seedValue:s,event:i}){return t?(t.participants||[]).find(c=>c.participantId===n)?Mb({tournamentRecord:t,drawDefinition:e,participantId:n,structureId:r,seedValue:s,event:i}):{error:bs}:{error:et}}function dR({tournamentRecord:t,drawDefinition:e,scheduledDates:n,stageSequences:r,matchUpFormat:s,structureIds:i,structureId:o,eventType:c,matchUpId:a,eventIds:u,eventId:l,drawIds:f,stages:p,drawId:h,event:d,force:m}){const g="setMatchUpFormat";if(!t)return{error:et};if(!s)return{error:Vd};if(s&&!nr(s))return G({result:{error:bu,matchUpFormat:s},stack:g});if(n&&!Array.isArray(n))return G({result:{error:tt,scheduledDates:n},stack:g});if(c&&![ls,$n].includes(c))return G({result:{error:ui},stack:g});let I=0;if((o||i)&&!e)return G({result:{error:lt},stack:g});if(h&&a){const T=Gl({tournamentRecord:t,drawDefinition:e,matchUpFormat:s,structureIds:i,structureId:o,matchUpId:a});if(T.error)return T;I+=1}const S=T=>{const E=[];for(const y of T.structures||[]){if(Array.isArray(p)&&!p.includes(y.stage)||Array.isArray(r)&&!r.includes(y.stageSequence)||i.length&&!i.includes(y.structureId))continue;i.length&&y.matchUpFormat!==s&&(y.matchUpFormat=s,E.push(y.structureId),I+=1);const b=(m||n)&&Qt({matchUpFilters:{matchUpStatuses:[pe.ToBePlayed]},structure:y}),N=n&&Qt({matchUpFilters:{matchUpStatuses:[pe.ToBePlayed]},contextFilters:{scheduledDates:n},afterRecoveryTimes:!1,inContext:!0,structure:y});if(b!=null&&b.length){const A=N?N.map(Qe):b.map(Qe);for(const C of b)A.includes(C.matchUpId)&&(C.matchUpFormat=n!=null&&n.length?s:void 0,qt({tournamentId:t==null?void 0:t.tournamentId,eventId:d==null?void 0:d.eventId,context:g,drawDefinition:T,matchUp:C}))}}return!E.length&&T.matchUpFormat!==s&&(T.matchUpFormat=s,I+=1),E};i=i||[o].filter(Boolean),u=u||[l].filter(Boolean),f=f||[h].filter(Boolean);for(const T of t.events||[])if(!(u!=null&&u.length&&!u.includes(T.eventId)||c&&c!==T.eventType||c===we))if(Array.isArray(r)||Array.isArray(p)||i.length||f.length)for(const E of T.drawDefinitions||[]){if(Array.isArray(f)&&!f.includes(E.drawId))continue;const y=S(E);Zt({structureIds:y,drawDefinition:E})}else T.matchUpFormat!==s&&(T.matchUpFormat=s,I+=1);return I?{...$,modificationsCount:I}:{...$,info:zc}}function cN({tournamentRecord:t,drawDefinition:e,participantId:n,entryPosition:r,skipRefresh:s,event:i}){const o="setEntryPositions";if(!t)return{error:et};if(!n)return G({result:{error:Ce},stack:o});if(r!==void 0&&!Number.isSafeInteger(r))return{error:tt,entryPosition:r};((i==null?void 0:i.entries)||[]).forEach(a=>{a.participantId===n&&(a.entryPosition=r)}),((e==null?void 0:e.entries)||[]).forEach(a=>{a.participantId===n&&(a.entryPosition=r)});const c=a=>{a.entries.forEach(u=>{u.entryPosition===r&&u.participantId!==n&&(u.entryPosition+=.1)})};return s||(i!=null&&i.entries&&(c(i),i.entries=pr({entries:i.entries})),e!=null&&e.entries&&(c(e),e.entries=pr({entries:e.entries}))),{...$}}function fR({tournamentRecord:t,entryPositions:e,drawDefinition:n,event:r}){if(!t)return{error:et};if(!Array.isArray(e))return{error:tt};for(const s of e){const{participantId:i,entryPosition:o}=s,c=cN({skipRefresh:!0,tournamentRecord:t,drawDefinition:n,participantId:i,entryPosition:o,event:r});if(c.error)return c}return r!=null&&r.entries&&(r.entries=pr({entries:r.entries})),n!=null&&n.entries&&(n.entries=pr({entries:n.entries})),{...$}}function pR(t){return gb(t)}function aN({scaleAttributes:t,scaledEntries:e,stageEntries:n,seedsCount:r,scaleName:s}){if(!t)return{error:Tt,info:"missing scaleAttributes"};const i=Object.assign({},...(e||[]).slice(0,r).map(({participantId:a},u)=>({[a]:u+1})));s=s||t.scaleName;const o=new Date().toISOString();return{scaleItemsWithParticipantIds:n.map(({participantId:a})=>({scaleItems:[{scaleValue:i[a],eventType:t.eventType,scaleType:br,scaleName:s,scaleDate:o}],participantId:a}))}}function hR(t){return Eb(t)}function mR({tournamentRecord:t,scaleAttributes:e,participantIds:n}){var c;if(!t)return{error:et};if(!n)return{error:Ns};if(!e)return{error:Tt,info:"scaleAttributes required"};const{scaleType:r,eventType:s,scaleName:i}=e,o=[PP,r,s,i].join(".");return(c=t.participants)==null||c.forEach(a=>{n.includes(a.participantId)&&a.timeItems&&(a.timeItems=a.timeItems.filter(u=>u&&(u==null?void 0:u.itemType)!==o))}),{...$}}function uN({tournamentRecord:t,scaleAttributes:e,drawDefinition:n,entryStatuses:r,drawId:s,event:i,stage:o}){var l;if(!i)return{error:Wt};if(r&&!Array.isArray(r))return G({result:{error:tt},info:sn("entryStatus"),stack:"removeScaleValues"});let c=i.entries;if(s){const{flightProfile:f}=be({event:i}),p=(l=f==null?void 0:f.flights)==null?void 0:l.find(h=>h.drawId===s);p?c=p.drawEntries:c=n==null?void 0:n.entries}const u=(c||[]).filter(f=>(!o||!f.entryStage||f.entryStage===o)&&(!r||r.includes(f.entryStatus))).map(fe);return mR({tournamentRecord:t,scaleAttributes:e,participantIds:u})}function bd({tournamentRecord:t,scaleAttributes:e,participantId:n}){if(!t)return{error:et};if(!n)return{error:Ce};const{participant:r}=zs({tournamentRecord:t,participantId:n});return r?Ts({participant:r,scaleAttributes:e}):{error:_e}}function hu({sortDescending:t=!1,tournamentRecord:e,scaleAttributes:n,scaleSortMethod:r,stageSequence:s,entries:i,event:o,stage:c}){if(!e)return{error:et};return i=i||(o==null?void 0:o.entries)||[],{scaledEntries:i.filter(p=>(!c||!p.entryStage||p.entryStage===c)&&(!s||!p.entryStageSequence||p.entryStageSequence===s)&&ps.includes(p.entryStatus)).map(p=>{const{participantId:h}=p,{scaleItem:d}=bd({tournamentRecord:e,scaleAttributes:n,participantId:h});return{...p,...d}}).filter(p=>{const h=p.scaleValue;return!r&&(isNaN(h)||!parseFloat(h))?!1:h}).sort(r||l)};function l(p,h){return t?f(h)-f(p):f(p)-f(h)}function f(p){return parseFloat(p.scaleValue||(t?-1:1e5))}}function gR({tournamentRecord:t,drawDefinition:e,entryStatuses:n,scaleName:r,drawId:s,event:i,stage:o}){var a,u;if(!t)return{error:et};if(!i)return{error:Wt};r=r||((a=i.category)==null?void 0:a.categoryName)||((u=i.category)==null?void 0:u.ageCategoryCode);const c={eventType:i.eventType,scaleType:br,scaleName:r};return uN({tournamentRecord:t,scaleAttributes:c,drawDefinition:e,entryStatuses:n,drawId:s,event:i,stage:o})}function IR({tournamentRecord:t,drawDefinition:e,policyDefinitions:n,scaleAttributes:r,scaleName:s,drawSize:i,drawId:o,event:c,stage:a,sortDescending:u,scaleSortMethod:l}){const f=Jb({policyDefinitions:n,drawDefinition:e,drawSize:i,drawId:o,event:c,stage:a});if(f.error)return f;const{entries:p,seedsCount:h,stageEntries:d}=f;if(!d||!h)return{error:tt};const m=hu({tournamentRecord:t,scaleAttributes:r,scaleSortMethod:l,sortDescending:u,entries:p,stage:a}).scaledEntries??[],{scaleItemsWithParticipantIds:g}=aN({scaleAttributes:r,scaledEntries:m,stageEntries:d,seedsCount:h,scaleName:s});return{scaleItemsWithParticipantIds:g}}function SR({tournamentRecord:t,drawDefinition:e,resetEntries:n,event:r}){var o,c;if(!e)return{error:lt};const s=(o=e.structures)==null?void 0:o.find(a=>a.stage===je);if(!s)return{error:Te};const i=((c=s.matchUps)==null?void 0:c.map(({matchUpId:a})=>a))||[];return s.positionAssignments=[],s.seedAssignments=[],s.matchUps=[],ei({tournamentId:t==null?void 0:t.tournamentId,action:"resetVoluntaryConsolationStructure",matchUpIds:i,drawDefinition:e}),n&&(e.entries=e.entries.filter(a=>a.entryStage!==je)),Zt({tournamentId:t==null?void 0:t.tournamentId,eventId:r==null?void 0:r.eventId,drawDefinition:e,structureIds:[s.structureId]}),{...$}}function TR({autoPublish:t=!0,tournamentRecord:e,auditData:n,event:r}){var i;if(!e)return{error:et};if(!r)return{error:Wt};const{flightProfile:s}=be({event:r});if(s){const o=(i=s.flights)==null?void 0:i.map(({drawId:a})=>a).filter(Boolean),c=om({eventId:r.eventId,tournamentRecord:e,autoPublish:t,auditData:n,drawIds:o,event:r});return c.error?c:Yu({event:r,name:ar})}return{...$}}function lN({event:t,orderedDrawIdsMap:e}){var i,o;if(typeof t!="object")return{error:Wt};if(!e)return{error:Tt,info:"Missing drawIdsOrderMap"};if(typeof e!="object")return{error:tt,info:"orderedDrawIdsMap must be an object"};const n=Object.values(e);if(!n.every(c=>!isNaN(c)))return{error:tt,info:"drawOrder must be numeric"};if(Vt(n).length!==n.length)return{error:tt,info:"drawOrder values must be unique"};if((i=t.drawDefinitions)!=null&&i.length){const c=(t.drawDefinitions||[]).map(({drawId:u})=>u),a=Object.keys(e);if(a!=null&&a.length&&qe(c,a).length!==c.length)return{error:tt,info:"Missing drawIds"};t.drawDefinitions.forEach(u=>{u.drawOrder=e[u.drawId]})}const{flightProfile:s}=be({event:t});return(o=s==null?void 0:s.flights)==null||o.forEach(c=>{c.flightNumber=e[c.drawId]}),{...$}}function dN({tournamentRecord:t,event:e}){var s;if(!t)return{error:et};if(!e)return{error:Wt};const{flightProfile:n}=be({event:e}),r=(n==null?void 0:n.flights)&&Object.assign({},...n.flights.sort((i,o)=>i.flightNumber-o.flightNumber).map((i,o)=>({[i.drawId]:o+1})))||((s=e.drawDefinitions)==null?void 0:s.length)&&Object.assign({},...e.drawDefinitions.sort((i,o)=>i.drawOrder-o.drawOrder).map((i,o)=>({[i.drawId]:o+1})))||void 0;return r?lN({event:e,orderedDrawIdsMap:r}):{...$}}function yR({autoPublish:t=!0,tournamentRecord:e,auditData:n,drawId:r,event:s}){var c,a;if(!e)return{error:et};if(!r)return{error:Hn};if(!s)return{error:Wt};const{flightProfile:i}=be({event:s});if(i&&((c=i.flights)==null?void 0:c.find(l=>l.drawId===r))){const l=i.flights.filter(p=>p.drawId!==r),f={name:ar,value:{...i,flights:l}};Yr({event:s,extension:f})}if((a=s.drawDefinitions)==null?void 0:a.find(u=>u.drawId===r)){const u=om({drawIds:[r],eventId:s.eventId,tournamentRecord:e,autoPublish:t,auditData:n,event:s});if(u.error)return u}return dN({tournamentRecord:e,event:s})}function fN({deleteExisting:t,event:e,flightProfile:n}){var o;const r="attachFlightProfile";if(!n)return G({result:{error:Tt},stack:r});if(!e)return G({result:{error:Wt},stack:r});const{flightProfile:s}=be({event:e});return s&&!t?G({result:{error:Ng},stack:r}):(o=e.drawDefinitions)!=null&&o.length?G({result:{error:D1},stack:r}):(Yr({event:e,extension:{name:ar,value:n}}),{flightProfile:pt(n,!1,!0),...$})}const ER="splitWaterfall",bR="splitShuttle";function NR(t){const{drawNameRoot:e="Flight",attachFlightProfile:n,tournamentRecord:r,scaleAttributes:s,scaleSortMethod:i,deleteExisting:o,sortDescending:c,drawNames:a=[],flightsCount:u,splitMethod:l,uuids:f=[],event:p,stage:h}=t;if(!p)return{error:Wt};const d=p.entries||[],{flightProfile:m}=be({event:p});if(m&&n&&!o)return{error:Ng};const g=t.scaledEntries??hu({tournamentRecord:r,scaleAttributes:s,scaleSortMethod:i,sortDescending:c,event:p,stage:h}).scaledEntries,I=g.map(fe),S=on(d.filter(({participantId:v})=>!I.includes(v)).filter(v=>(!h||!v.entryStage||v.entryStage===h)&&(!v.entryStatus||ho.includes(v.entryStatus)))),T=g.concat(...S),E=T.length,y=Math.ceil(E/u);let b=Ge(T,y);l===ER?b=jm(T,u):l===bR&&(b=jm(T,u,!0));function N(v){return(v||[]).map(({participantId:P,scaleValue:U})=>{const O=d.find(D=>D.participantId===P);return O!=null&&O.scaleValue&&U&&(O.scaleValue=U),O}).sort((P,U)=>P.scaleValue-U.scaleValue).map((P,U)=>(P.scaleValue&&(P.seedNumber=U+1),P))}const A=ht(0,u).map(v=>{const P=v+1;return{flightNumber:P,drawId:(f==null?void 0:f.pop())||Yt(),drawEntries:N(b[v]),drawName:(a==null?void 0:a.length)&&a[v]||`${e} ${P}`}}),C={scaleAttributes:s,splitMethod:l,flights:A};if(n){const v=fN({flightProfile:C,deleteExisting:o,event:p});return{splitEntries:ze()&&b||void 0,...v}}else return{flightProfile:C,...$}}function AR(t){const{tournamentRecord:e}=t;if(!e)return{error:et};const n=e.participants;return qE({participants:n,...t})}function vR(t){return HE(t)}function CR({substituteParticipantId:t,existingParticipantId:e,tournamentRecord:n,drawDefinition:r,sideNumber:s,matchUpId:i,event:o}){var m,g,I;const c="substituteParticipant";if(!r)return{error:lt};if(!i)return{error:$e};if(!e||!t)return G({result:{error:Ce},stack:c});const{matchUp:a}=ie({drawDefinition:r,matchUpId:i,event:o});if(!a)return{error:Ye};if(!a.collectionId)return G({result:{error:qn},stack:c});const u=ln({drawDefinition:r}),{matchUps:l}=xe({tournamentParticipants:n==null?void 0:n.participants,inContext:!0,drawDefinition:r,matchUpsMap:u}),f=l==null?void 0:l.find(S=>S.matchUpId===i),p=l==null?void 0:l.find(S=>S.matchUpId===(f==null?void 0:f.matchUpTieId)),h=(m=p==null?void 0:p.sides)==null?void 0:m.find(S=>S.participant.individualParticipants.some(({participantId:T})=>T===e));return!h||s&&h.sideNumber!==s?{error:bs}:((I=(g=h.participant)==null?void 0:g.individualParticipants)==null?void 0:I.map(fe).filter(S=>S!==e)).includes(t)?Qb({newParticipantId:t,tieMatchUpId:i,existingParticipantId:e,substitution:!0,tournamentRecord:n,drawDefinition:r,event:o}):G({result:{error:bs},stack:c})}function PR(t){return CR(t)}function UR(t){return JE(t)}function pN({tournamentRecord:t,drawDefinition:e,flightProfile:n,drawName:r,drawId:s,event:i}){var c;if(!r||typeof r!="string")return G({result:{error:tt},context:{drawName:r}});n||(n=be({event:i}).flightProfile);const o=(c=n==null?void 0:n.flights)==null?void 0:c.find(a=>a.drawId===s);if(o){o.drawName=r;const a={name:ar,value:{...n,flights:n.flights}};Yr({event:i,extension:a})}return e&&(e.drawName=r,Zt({tournamentId:t==null?void 0:t.tournamentId,drawDefinition:e})),!o&&!e?{error:lt}:{...$,flight:o}}function OR({tournamentRecord:t,drawDefinition:e,drawUpdates:n,drawId:r,event:s}){var a;if(!or(n))return{error:mg};const i=be({event:s}).flightProfile,o=n.drawName&&pN({drawName:n.drawName,tournamentRecord:t,drawDefinition:e,flightProfile:i,drawId:r,event:s});if(o!=null&&o.error)return o==null?void 0:o.error;const c=(o==null?void 0:o.flight)||((a=i==null?void 0:i.flights)==null?void 0:a.find(u=>u.drawId===r));if(!c&&!e)return{error:lt};if(c){const u={name:ar,value:{...i,flights:i.flights}};Yr({event:s,extension:u})}return e&&(n.policyDefinitions&&Td({policyDefinitions:n.policyDefinitions,drawDefinition:e}),Zt({tournamentId:t==null?void 0:t.tournamentId,drawDefinition:e})),{...$}}function MR({tournamentRecord:t,removeScheduling:e,drawDefinition:n}){var o;if(!n)return{error:lt};const r=ln({drawDefinition:n}),s=c=>{var a;return(a=r==null?void 0:r.drawMatchUps)==null?void 0:a.find(u=>u.matchUpId===c)};for(const c of n.structures||[]){const{positionAssignments:a,stage:u,stageSequence:l}=c;a&&(l!==1||![Pt,It].includes(u))&&(c.positionAssignments=a.map(p=>(delete p.participantId,p)),c.seedAssignments=[]);const{matchUps:f}=Qt({afterRecoveryTimes:!1,inContext:!0,matchUpsMap:r,structure:c});for(const p of f){const{matchUpId:h,roundNumber:d,sides:m}=p,g=s(h);if(g){if(delete g.extensions,delete g.notes,g.matchUpStatus!==re&&Object.assign(g,fl),d&&d>1&&g.drawPositions){const I=m==null?void 0:m.map(({drawPosition:T,participantFed:E})=>!E&&T).filter(Boolean),S=g.drawPositions.map(T=>I.includes(T)?void 0:T);g.drawPositions=S}e?delete g.timeItems:(o=g.timeItems)!=null&&o.length&&(g.timeItems=g.timeItems.filter(I=>I.itemType&&![Qs,oo,ga,CP,Ia,Sa].includes(I.itemType))),qt({tournamentId:t==null?void 0:t.tournamentId,context:"resetDrawDefiniton",drawDefinition:n,matchUp:g})}}}const i=(n.structures||[]).map(({structureId:c})=>c);return Zt({drawDefinition:n,structureIds:i}),{...$}}function DR({matchPlayDrawPositions:t=!0,tournamentRecord:e,drawDefinition:n,drawId:r}){var o;if(!e)return{error:et};if(!n)return{error:lt};let s=[];const{drawsAnalysis:i}=rm({tournamentRecord:e});if(i.canBePruned.includes(r)){const c=i.matchPlay.includes(r),a=i.drawAnalysis[r],{structures:[u]}=lr({stageSequence:1,drawDefinition:n,stage:It}),l=a.structuresData.find(({structureId:d})=>u.structureId===d),f=u.matchUps||[];s=f.sort((d,m)=>d.roundPosition-m.roundPosition).filter(({roundNumber:d})=>!l.inactiveRounds.includes(d));const p=s.map(Qe),h=f.map(Qe).filter(d=>!p.includes(d));if(c){const d=s.sort((E,y)=>E.roundPosition-y.roundPosition).filter(({roundNumber:E})=>!l.inactiveRounds.includes(E)).filter(({winningSide:E})=>E),m=d.map(Qe),g=p.filter(E=>!m.includes(E));h.push(...g);const S=d.flatMap(E=>E.drawPositions||[]).filter(Boolean).flat(),T=Object.assign({},...S.map((E,y)=>({[E]:y+1})));if(d.forEach(E=>{t?E.drawPositions=E.drawPositions.map(y=>T[y]):delete E.drawPositions}),t){const E=(o=u==null?void 0:u.positionAssignments)==null?void 0:o.filter(y=>S.includes(y.drawPosition)).map(y=>(y.drawPosition=T[y.drawPosition],y));u.positionAssignments=E}else u.positionAssignments=[];u.matchUps=d,s=d}ei({tournamentId:e==null?void 0:e.tournamentId,matchUpIds:h,drawDefinition:n}),Zt({drawDefinition:n})}return{...$,matchUps:s}}function wR(t){return vb(t)}function kR({entryStatus:t=Ur,unpairedParticipantIds:e=[],participantIdPairs:n=[],entryStage:r=It,tournamentRecord:s,event:i}){if(!s)return{error:et};if(!i)return{error:Wt};const o=s.participants||[],c=o.filter(I=>I.participantType===xt).map(I=>I.participantId),u=e.concat(...n).flat(1/0).filter(I=>!c.includes(I));if(u.length)return{error:gr,invalidParticipantIds:u};const l=n.filter(I=>I.length!==2);if(l.length)return{error:gr,invalidParticipantIdPairs:l};const f=o.filter(I=>I.participantType===_t).map(I=>I.individualParticipantIds),h=n.filter(I=>!f.find(S=>qe(S,I).length===2)).map(I=>({participantType:_t,participantRole:fn,individualParticipantIds:I})),d=Ss({participants:h,tournamentRecord:s});if(d.error)return d;const m=n.map(I=>{const{participant:S}=Jr({tournamentRecord:s,participantIds:I});return S}).map(I=>({participantId:I,entryStatus:t,entryStage:r})),g=e.map(I=>({entryStatus:Or,participantId:I,entryStage:r}));return i.entries=(i.entries||[]).filter(I=>I.entryStage===r),i.entries=i.entries.concat(...m,...g),{...$}}function _R(t){var n;const e=(n=t.tournamentRecord)==null?void 0:n.participants;return Object.assign(t,{tournamentParticipants:e}),Yh(t)}function cm({qualifyingPositions:t,drawEntries:e=[],drawName:n,drawId:r,event:s,stage:i}){var m,g,I;const o="addFlight";if(!s)return G({result:{error:Wt},stack:o});if(!n)return G({result:{error:Tt},stack:o});if(e!=null&&e.length){const S=(s.entries||[]).map(kn("participantId")),T=e.map(kn("participantId"));if(qe(T,S).length!==T.length)return G({result:{error:tt},stack:o})}const c=(m=be({event:s}))==null?void 0:m.flightProfile,a=((I=(g=c==null?void 0:c.flights)==null?void 0:g.map(({flightNumber:S})=>!isNaN(S)&&vt(S)))==null?void 0:I.filter(Boolean))||[],u=Math.max(0,...a)+1,f={drawId:r||Yt(),flightNumber:u,drawEntries:e,drawName:n};if(i&&(f.stage=i),t&&(f.qualifyingPositions=t),((c==null?void 0:c.flights)||[]).find(({drawId:S})=>S===f.drawId))return G({result:{error:kv},stack:o});const h=((c==null?void 0:c.flights)||[]).concat(f),d={name:ar,value:{...c||{},flights:h}};return Yr({event:s,extension:d})}function FR(t){return md(t)}function LR(t){return Rh(t)}function RR(t){return am({...t,itemType:"attachConsolationStructures"})}function BR(t){return am({...t,itemType:"attachPlayoffStructures"})}function am({itemType:t="attachStructures",matchUpModifications:e,tournamentRecord:n,drawDefinition:r,structures:s,links:i}){if(!n)return{error:et};if(!r)return{error:lt};const o=KE({matchUpModifications:e,tournamentRecord:n,drawDefinition:r,structures:s,links:i});if(o.error)return o;const u={itemValue:{structureIds:s==null?void 0:s.map(({structureId:l})=>l),drawId:r.drawId},itemType:t};return _s({tournamentRecord:n,timeItem:u}),o}function hN({tournamentRecord:t,event:e,startDate:n}){if(!t)return{error:et};if(!e)return{error:Wt};if(!Vr.test(n))return{error:bn};const r=gN(t);if(r.error)return r;const{tournamentStartDate:s,tournamentEndDate:i}=r,o=new Date(Bt(n)).getTime();if(!s||!i||o<s||o>i)return{error:bn};const c=e.endDate&&new Date(Bt(e.endDate));return c&&o>c&&(e.endDate=n),e.startDate=n,{...$}}function mN({tournamentRecord:t,event:e,endDate:n}){if(!t)return{error:et};if(!e)return{error:Wt};if(!Vr.test(n))return{error:bn};const r=gN(t);if(r.error)return r;const{tournamentStartDate:s,tournamentEndDate:i}=r,o=new Date(Bt(n)).getTime();if(!s||!i||o<s||o>i)return{error:bn};const c=e.startDate&&new Date(Bt(e.startDate));return c&&o<c&&(e.startDate=n),e.endDate=n,{...$}}function xR({tournamentRecord:t,event:e,startDate:n,endDate:r}){if(!t)return{error:et};if(!e)return{error:Wt};if(!n&&!r)return{error:Tt,info:"missing date"};if(n&&!Vr.test(n))return{error:bn};if(r&&!Vr.test(r))return{error:bn};if(n&&r){const s=new Date(Bt(n)),i=new Date(Bt(r));if(s>i)return{error:tt}}if(n){const s=hN({tournamentRecord:t,event:e,startDate:n});if(s.error)return s}if(r){const s=mN({tournamentRecord:t,event:e,endDate:r});if(s.error)return s}return{...$}}function gN(t){const{startDate:e,endDate:n}=t;return!Vr.test(e)||!Vr.test(n)?G({result:{error:rv},context:{startDate:e,endDate:n}}):{tournamentStartDate:new Date(Bt(e)).getTime(),tournamentEndDate:new Date(Bt(n)).getTime()}}function $R({tournamentRecord:t,drawDefinition:e,drawPosition:n}){return t?e?oe(n)?{...$}:{error:Wo}:{error:lt}:{error:et}}function VR({tournamentRecord:t,drawDefinition:e,matchUpId:n,lineUps:r,event:s}){var m,g,I,S;if(!t)return{error:et};if(!e)return{error:rr};if(typeof n!="string")return{error:qn};if(!Array.isArray(r))return{error:tt,lineUps:r};const i="applyLineUps",o=t.participants||[];let c=ie({tournamentParticipants:o,inContext:!0,drawDefinition:e,matchUpId:n});if(c.error)return c;if(!c.matchUp)return{error:Ye};const{matchUp:a,structure:u}=c,{drawPositions:l,matchUpType:f}=a;if(f!==Jt)return{error:qn};if(!(l!=null&&l.length))return{error:Ld};const p=(m=hn({matchUp:a,drawDefinition:e,structure:u,event:s}))==null?void 0:m.tieFormat,h={};for(const T of r){if(!Array.isArray(T))return{error:tt,lineUp:T};const E={},y=[];for(const v of T){if(typeof v!="object")return{error:tt,lineUpAssignment:v};const{participantId:P,collectionAssignments:U=[]}=v;if(!Array.isArray(U))return{error:tt,collectionAssignments:U};const O=o.find(M=>M.participantId===P);if(!O)return{error:_e};if(O.participantType!==xt)return{error:xr};const D=(I=(g=a.sides)==null?void 0:g.find(M=>{var w,k;return(k=(w=M.participant)==null?void 0:w.individualParticipantIds)==null?void 0:k.includes(P)}))==null?void 0:I.sideNumber;D&&y.push(D);for(const M of U){if(typeof M!="object")return{error:tt,collectionAssignment:M};const{collectionId:w,collectionPosition:k}=M,_=(S=p==null?void 0:p.collectionDefinitions)==null?void 0:S.find(W=>W.collectionId===w);if(!_)return{error:tt,collectionId:w};const F=`${w}-${k}`;E[F]||(E[F]=[]);const L=E[F].length;if(_.matchUpType===Oe&&L||_.matchUpType===me&&L>1)return{info:"Excessive collectionPosition assignments",error:tt};E[F].push(P)}}const b=Object.values(E);for(const v of b)if(v.length===2){const{participant:P}=Jr({tournamentParticipants:o,participantIds:v});if(!P){const O=es({participant:{participantType:_t,participantRole:fn,individualParticipantIds:v},pairOverride:!0,tournamentRecord:t});if(O.error)return O}}const N=Mn(y),A=(N[1]||0)>(N[2]||0)&&1||(N[2]||0)>(N[1]||0)&&2||void 0,C=Object.keys(h).map(v=>parseInt(v));A&&!C.includes(A)&&(h[A]=T)}if(!Object.keys(h).length)return{error:Eg};if(c=ie({drawDefinition:e,matchUpId:n}),c.error)return c;if(!c.matchUp)return{error:Ye};const{matchUp:d}=c;d.sides||(d.sides=[]);for(const T of[1,2]){const E=d.sides.find(b=>b.sideNumber===T),y=h[T];if(y)E?E.lineUp=y:d.sides.push({lineUp:y,sideNumber:T});else continue}return qt({tournamentId:t==null?void 0:t.tournamentId,context:i,drawDefinition:e,matchUp:d}),{...$}}function jR(t){return Xp(t)}function GR(t){return wh(t)}function WR(t){return Mh(t)}function HR(t){const{tournamentRecord:e}=t;if(!e)return{error:et};const n=e.participants;return Fh({participants:n,...t})}function qR({tournamentRecord:t,drawDefinition:e,structure:n,link:r}){if(!t)return{error:et};if(!e)return{error:lt};const s=Lh({tournamentId:t.tournamentId,drawDefinition:e,structure:n,link:r});if(s.error)return s;const o={itemType:"attachQualifyingStructures",itemValue:{structureId:n.structureId,drawId:e.drawId}};return _s({tournamentRecord:t,timeItem:o}),s}function YR(t){const e=t.tournamentRecord;if(!e)return{error:et};const n=YE(t);if(n.error)return n;const{qualifyingRoundNumber:r,qualifyingPositions:s,targetStructureId:i,drawDefinition:o,structureName:c,matchUpType:a,drawSize:u,drawType:l}=t,p={itemType:"addQualifyingStructures",itemValue:bt({drawId:o.drawId,structureName:c,targetStructureId:i,qualifyingPositions:s,qualifyingRoundNumber:r,matchUpType:a,drawSize:u,drawType:l})};return _s({tournamentRecord:e,timeItem:p}),n}function zR(t){const{tournamentRecord:e}=t;if(!e)return{error:et};const n=e.participants;return Ch({participants:n,...t})}function IN(t){let{seedsCount:e}=t;const n=t.preparedStructureIds||[],{provisionalPositioning:r,inContextDrawMatchUps:s,tournamentRecord:i,appliedPolicies:o,qualifyingOnly:c,drawDefinition:a,seedingProfile:u,participants:l,matchUpsMap:f,automated:p,placeByes:h,drawType:d,drawSize:m,entries:g,event:I,enforcePolicyLimits:S=!0,seedAssignmentProfile:T,seedByRanking:E=!0,seededParticipants:y,assignSeedsCount:b,seedingScaleName:N,stageSequence:A=1,roundTarget:C,stage:v}=t,P=I==null?void 0:I.eventType,U=g.filter(H=>{var R,x;const B=(x=(R=Ke({name:Hr,element:H}))==null?void 0:R.extension)==null?void 0:x.value;return(!H.entryStage||H.entryStage===v)&&(!A||!H.entryStageSequence||H.entryStageSequence===A)&&(!C||!B||B===C)&&ho.includes(H.entryStatus)});y&&(e=y.length),e>m&&(e=m),e>U.length&&(e=U.length);const{structures:O}=lr({drawDefinition:a,stageSequence:A,roundTarget:C,stage:v}),D=((O==null?void 0:O.length)||0)>1,M=O==null?void 0:O.find(({structureId:H})=>!n.includes(H));if(!M)return G({result:{error:Te}});const w=M==null?void 0:M.structureId,k=M?Oo({provisionalPositioning:r,appliedPolicies:o,drawDefinition:a,structure:M}):void 0,{seedLimit:_}=tb({participantsCount:U.length,enforcePolicyLimits:S,appliedPolicies:o,drawDefinition:a,seedingProfile:u,structureId:w,seedsCount:e});_&&_<e&&(e=_);const F=g.map(fe);if(y)y.filter(({participantId:H})=>F.includes(H)).filter(H=>!H.seedNumber||H.seedNumber<=y.length).sort((H,B)=>H.seedNumber<B.seedNumber?-1:H.seedNumber<B.seedNumber?1:0).forEach(H=>{const{participantId:B,seedNumber:R,seedValue:x}=H;Do({provisionalPositioning:r,tournamentRecord:i,drawDefinition:a,seedingProfile:u,participantId:B,seedBlockInfo:k,structureId:w,seedNumber:R,seedValue:x,event:I})});else if(I||N){const{categoryName:H,ageCategoryCode:B}=(I==null?void 0:I.category)||{},R={scaleType:br,scaleName:N||H||B||I.eventId,eventType:P};let{scaledEntries:x}=hu({scaleAttributes:R,tournamentRecord:i,stageSequence:A,entries:g,stage:v});!(x!=null&&x.length)&&E&&({scaledEntries:x}=hu({scaleAttributes:{scaleType:Ii,scaleName:H||B,eventType:P},tournamentRecord:i,stageSequence:A,entries:g,stage:v}));const q=(x==null?void 0:x.length)??0;q<e&&(e=q),x==null||x.filter(({participantId:V})=>F.includes(V)).slice(0,b||e).forEach((V,Y)=>{const z=Y+1,{participantId:J,scaleValue:Q}=V,X=(T==null?void 0:T[z])||Q||z;Do({provisionalPositioning:r,tournamentRecord:i,drawDefinition:a,seedingProfile:u,participantId:J,structureId:w,seedNumber:z,seedValue:X,event:I})})}let L=[],W,j;if(p!==!1&&d!==Xn&&!(c&&v!==Pt)){const H=typeof p=="object"&&p.seedsOnly,B=lu({inContextDrawMatchUps:s,multipleStructures:D,tournamentRecord:i,appliedPolicies:o,drawDefinition:a,seedingProfile:u,participants:l,structureId:w,matchUpsMap:f,placeByes:h,seedLimit:_,seedsOnly:H,drawSize:m,drawType:d,event:I});if(B.conflicts&&(L=B==null?void 0:B.conflicts),W=B==null?void 0:B.positionAssignments,j=B==null?void 0:B.positioningReport,B.error)return G({result:B,stack:"prepareStage"})}return{positionAssignments:W,positioningReport:j,stageEntries:U,structureId:w,seedsCount:e,conflicts:L}}function um(t){var q,V,Y,z,J,Q,X,Z,nt,rt,K,it,st,dt,mt,Mt,Nt,St,ct,Et,gt,Ft,yt,wt,Xt,$t,At,Dt;const e="generateDrawDefinition",{considerEventEntries:n=!0,ignoreAllowedDrawTypes:r,voluntaryConsolation:s,hydrateCollections:i,policyDefinitions:o,ignoreStageSpace:c,tournamentRecord:a,qualifyingOnly:u,tieFormatName:l,drawEntries:f,addToEvent:p,placeByes:h,event:d}=t,m=ge({tournamentRecord:a,event:d}).appliedPolicies??{},I=(t.drawTypeCoercion??((q=m==null?void 0:m[pf])==null?void 0:q.drawTypeCoercion)??!0)&&t.drawSize===2&&na.SingleElimination||t.drawType||na.SingleElimination,{tournamentParticipants:S}=dn({tournamentRecord:a,inContext:!0}),T=t.enforceGender??((Y=(V=o==null?void 0:o[Jn])==null?void 0:V.participants)==null?void 0:Y.enforceGender)??((J=(z=m==null?void 0:m[Jn])==null?void 0:z.participants)==null?void 0:J.enforceGender),E=!r&&a&&Kb({tournamentRecord:a,categoryType:(Q=d==null?void 0:d.category)==null?void 0:Q.categoryType,categoryName:(X=d==null?void 0:d.category)==null?void 0:X.categoryName});if(E!=null&&E.length&&!E.includes(I))return G({result:{error:Bd},stack:e});const y=((Z=d==null?void 0:d.entries)==null?void 0:Z.filter(at=>at.entryStatus&&[...tS,ol].includes(at.entryStatus)))??[],b=(u&&[]||f||(n?y:[])).filter(({entryStage:at})=>!at||at===It),N=d&&S&&Zb({consideredEntries:b,enforceGender:T,participants:S,event:d});if(N!=null&&N.error)return G({result:N,stack:e});const C=!t.drawSize&&b.length&&![Xn,va,ic,Pr,Ds].includes(I)&&Vo(b.length)||t.drawSize&&oe(t.drawSize)&&vt(t.drawSize)||!1;if(isNaN(C)&&I!==Xn)return G({result:{error:Eu},stack:e});let v=typeof t.seedsCount!="number"?vt(t.seedsCount??0):t.seedsCount??0;const P=d==null?void 0:d.eventType,U=t.matchUpType??P,O=t.drawId?(nt=d==null?void 0:d.drawDefinitions)==null?void 0:nt.find(at=>at.drawId===t.drawId):void 0;let{tieFormat:D,matchUpFormat:M}=t;if(U===Jt&&P===Jt){const at=(K=(rt=O==null?void 0:O.structures)==null?void 0:rt.find(({stage:ot})=>ot===It))==null?void 0:K.tieFormat;D=D||at||l&&((it=d==null?void 0:d.tieFormat)==null?void 0:it.tieFormatName)===l&&d.tieFormat||l&&Lo({namedFormat:l,hydrateCollections:i,event:d})||(d==null?void 0:d.tieFormat)||Lo({event:d,hydrateCollections:i}),M=void 0}else M||(D=void 0,d!=null&&d.matchUpFormat||(M=Kn));if(D){const at=vn({gender:d==null?void 0:d.gender,enforceGender:T,tieFormat:D});if(at.error)return G({result:at,stack:e})}if(t.drawId&&typeof t.drawId!="string")return G({result:{error:tt},stack:e});O&&I!==O.drawType&&(O.drawType=I);let k=O??wb({drawType:I,drawId:t.drawId});if((M||D)&&!(M&&(d==null?void 0:d.matchUpFormat)===M||(d==null?void 0:d.tieFormat)&&D&&JSON.stringify(d.tieFormat)===JSON.stringify(D))){if(D){const ot=vC(D);if(ot.error)return G({result:ot,stack:e});k.tieFormat=ot.tieFormat??D}else if(M){const ot=Gl({tournamentRecord:a,drawDefinition:k,matchUpFormat:M,event:d});if(ot.error)return{error:ot.error,info:"matchUpFormat or tieFormat error"}}U&&(k.matchUpType=U)}if(o){if(typeof o!="object")return G({result:{info:"policyDefinitions must be an object",error:tt},stack:e});{const at={};for(const ot of Object.keys(o))JSON.stringify(m==null?void 0:m[ot])!==JSON.stringify(o[ot])&&(at[ot]=o[ot]);Object.keys(at).length&&(Td({drawDefinition:k,policyDefinitions:at}),Object.assign(m,at))}}m[tc]||(Td({drawDefinition:k,policyDefinitions:gp}),Object.assign(m,gp));let _=(dt=(st=O==null?void 0:O.structures)==null?void 0:st.find(at=>at.stage===It&&at.stageSequence===1))==null?void 0:dt.structureId;const F=f??y,L=[];let W,j=[];const H=t.qualifyingPlaceholder&&!((mt=t.qualifyingProfiles)!=null&&mt.length)&&!O,B=O?(Mt=O.structures)==null?void 0:Mt.filter(at=>at.stage===Pt):[],R=(B==null?void 0:B.length)===1&&!((Nt=B[0].matchUps)!=null&&Nt.length)&&B[0].structureId;if(R){const at=t.qualifyingProfiles,ot=at!=null&&at.length?UE({idPrefix:t.idPrefix,isMock:t.isMock,uuids:t.uuids,qualifyingProfiles:at,appliedPolicies:m}):void 0;if(ot!=null&&ot.error)return ot;k.structures=(St=k.structures)==null?void 0:St.filter(({structureId:ne})=>ne!==R),k.links=(ct=k.links)==null?void 0:ct.filter(({source:ne})=>ne.structureId!==R);const{qualifiersCount:Lt,qualifyingDrawPositionsCount:ft,qualifyingDetails:Ct}=ot??{};ft&&(ot!=null&&ot.structures&&((Et=k.structures)==null||Et.push(...ot.structures)),ot!=null&&ot.links&&((gt=k.links)==null||gt.push(...ot.links)));const Ut=(Ft=k.structures)==null?void 0:Ft.find(({stage:ne,stageSequence:Ae})=>ne===It&&Ae===1),{qualifiersCount:Kt}=Li({stageSequence:1,drawDefinition:k,structureId:_,stage:It}),ut=Math.max(Lt??0,Kt??0);let Rt=Dh({qualifiersCount:ut,drawDefinition:k,stage:It});if(Rt.error||(Rt=au({drawSize:ft,stage:Pt,drawDefinition:k}),Rt.error))return Rt;for(const ne of(f??[]).filter(({entryStage:Ae})=>Ae===As.Qualifying)){const Ae={...ne,entryStage:ne.entryStage??As.Main,drawDefinition:k};Gh(Ae)}for(const ne of Ct||[]){const{finalQualifyingRoundNumber:Ae,finalQualifyingStructureId:Ee,roundTarget:Un,finishingPositions:Xe,linkType:Lr}=ne,jn=Ut&&((yt=kc({targetStructureId:Ut.structureId,sourceStructureId:Ee,sourceRoundNumber:Ae,finishingPositions:Xe,targetEntryRound:Un,linkType:Lr}))==null?void 0:yt.link);if(jn!=null&&jn.error)return jn;jn&&(k.links||(k.links=[]),k.links.push(jn))}W={drawDefinition:k}}else{if(W=wh({...t,modifyOriginal:!1,tournamentRecord:a,appliedPolicies:m,drawDefinition:k,matchUpFormat:M,matchUpType:U,tieFormat:D,drawSize:C}),W.error)return G({result:W,stack:e});k=W.drawDefinition;for(const ot of F){if(f&&ot.entryStage&&ot.entryStage!==As.Main)continue;const Lt={...ot,ignoreStageSpace:c??I===Xn,entryStage:ot.entryStage??As.Main,drawDefinition:k,drawType:I},ft=Gh(Lt);if(f&&ft.error)return G({result:ft,stack:e})}I===Ci&&(v=0);const at=IN({...W,...t,qualifyingOnly:!C||u,appliedPolicies:m,drawDefinition:k,participants:S,stage:It,seedsCount:v,placeByes:h,drawSize:C,entries:F});if(at.error&&!at.conflicts)return at;if((wt=at.positioningReport)!=null&&wt.length&&L.push({[It]:at.positioningReport}),_=at.structureId,at.conflicts&&(j=at.conflicts),I===Xn&&t.roundsCount){const ot=(Xt=d==null?void 0:d.entries)==null?void 0:Xt.filter(({entryStage:Ct,entryStatus:Ut})=>(!Ct||Ct===It)&&Ut&&ps.includes(Ut)),Lt=ot==null?void 0:ot.map(kn("participantId")),ft=ot?Math.floor(ot.length/2):0;ht(1,t.roundsCount+1).forEach(()=>{var Ct;if(t.automated){const{restrictEntryStatus:Ut,generateMatchUps:Kt,addToStructure:ut,maxIterations:Rt,structureId:ne,matchUpIds:Ae,scaleName:Ee}=t.drawMatic??{};Yh({tournamentRecord:a,participantIds:Lt,drawDefinition:k,eventType:((Ct=t.drawMatic)==null?void 0:Ct.eventType)??U,generateMatchUps:Kt??!0,restrictEntryStatus:Ut,addToStructure:ut,maxIterations:Rt,structureId:ne,matchUpIds:Ae,scaleName:Ee})}else md({addToStructure:!0,tournamentRecord:a,newRound:!0,drawDefinition:k,matchUpsCount:ft})})}}const x=[];if(t.qualifyingProfiles){const at=(Ct,Ut)=>Ct.stageSequence-Ut.stageSequence,ot=(Ct,Ut)=>Ct.roundTarget-Ut.roundTarget,Lt=[];let ft=1;t.qualifyingProfiles.sort(ot);for(const Ct of t.qualifyingProfiles){if(!Array.isArray(Ct.structureProfiles))return G({result:{error:Tt},info:sn("structureProfiles")});ft=Ct.roundTarget||ft;const Ut=(($t=Ct.structureProfiles)==null?void 0:$t.sort(at))||[];let Kt=1;for(const ut of Ut){const{qualifyingRoundNumber:Rt,qualifyingPositions:ne,seededParticipants:Ae,seedingScaleName:Ee,seedsCount:Un=0,seedingProfile:Xe,seedByRanking:Lr,placeByes:jn,drawSize:ue}=ut,he=IN({...W,...t,stageSequence:Kt,qualifyingRoundNumber:Rt,preparedStructureIds:Lt,qualifyingPositions:ne,seededParticipants:Ae,stage:Pt,seedingScaleName:Ee,appliedPolicies:m,drawDefinition:k,qualifyingOnly:u,seedingProfile:Xe,seedByRanking:Lr,participants:S,roundTarget:ft,seedsCount:Un,placeByes:jn,drawSize:ue,entries:F});if(he.error)return he;he.structureId&&Lt.push(he.structureId),Kt+=1,(At=he.conflicts)!=null&&At.length&&x.push(...he.conflicts),(Dt=he.positioningReport)!=null&&Dt.length&&L.push({[Pt]:he.positioningReport})}ft+=1}}else if(_&&H){const at=Ze({structureName:Pt,stage:Pt}),{link:ot}=kc({sourceStructureId:at.structureId,targetStructureId:_,sourceRoundNumber:0,linkType:js.Position});k.structures||(k.structures=[]),k.structures.push(at),k.links||(k.links=[]),k.links.push(ot)}return k.drawName=t.drawName??I,typeof s=="object"&&zR({...s,tournamentRecord:a,appliedPolicies:m,drawDefinition:k,matchUpType:U}),p&&Za({tournamentRecord:a,drawDefinition:k,event:d}),{existingDrawDefinition:!!O,qualifyingConflicts:x,positioningReports:L,drawDefinition:k,structureId:_,...$,conflicts:j}}function KR(t){return ZE(t)}function JR(t){return t.tournamentRecord?hb(t):{error:et}}function QR({tournamentRecord:t}){if(!t)return{error:et};let e=0;for(const n of t.events??[]){const r=n.tieFormats??[],s=u=>{if(!u.tieFormat)return;let l;for(const f of r)Sc({descendant:u.tieFormat,ancestor:f}).different||(l=f.tieFormatId);if(l)u.tieFormatId=l,delete u.tieFormat;else{const f=pt(u.tieFormat,void 0,!0);f.tieFormatId||(f.tieFormatId=Yt()),u.tieFormatId=f.tieFormatId,delete u.tieFormat,r.push(f),e+=1}};s(n);for(const u of n.drawDefinitions??[]){s(u);for(const l of u.structures??[])s(l)}const i=(u,l)=>{var p;const f=(p=c.eventMatchUps)==null?void 0:p.find(h=>h.matchUpId===u);f&&(f.tieFormatId=l,delete f.tieFormat,qt({tournamentId:t==null?void 0:t.tournamentId,eventId:n.eventId,matchUp:f}))},o=u=>{const l=pt(u.tieFormat,void 0,!0);l.tieFormatId||(l.tieFormatId=Yt()),r.push(l),e+=1,i(u.matchUpId,l.tieFormatId)},c=si({matchUpFilters:{matchUpTypes:[yr]},event:n}),a=c.matchUps??[];for(const u of a){let l;for(const f of r)u.tieFormat&&Sc({descendant:u.tieFormat,ancestor:f}).different||(l=f.tieFormatId);l?i(u.matchUpId,l):o(u)}r.length&&(n.tieFormats=r)}return{...$,addedCount:e}}function ZR(t){return t.tournamentRecord?ms(t):{error:et}}function XR(t){return t.tournamentRecord?Nb(t):{error:et}}function tB(t){return t.tournamentRecord?Ab(t):{error:et}}function eB({tournamentRecord:t,eventUpdates:e,eventId:n,event:r}){var p;if(!t)return{error:et};if(!TC(n)||!or(e))return{error:tt};const s=((p=r==null?void 0:r.entries)==null?void 0:p.filter(({entryStatus:h})=>{const d=h;return[...ps,dr].includes(d)}).map(({participantId:h})=>h))||[],i=s?Fi({participantFilters:{participantIds:s},withIndividualParticipants:!0,tournamentRecord:t}).participants||[]:[],o=[],c=i.reduce((h,d)=>{var g,I;const m=(g=d.person)!=null&&g.sex?[d.person.sex]:((I=d.individualParticpants)==null?void 0:I.map(S=>{var T;return(T=S.person)==null?void 0:T.sex}))||[];return o.push(...m),h.includes(d.participantType)?h:h.concat(d.participantType)},[]),a=Vt(o),u=!a.length||[hs,Io].includes(e.gender||"")||a.length===1&&a[0]===e.gender;if(e.gender&&!u)return G({context:{gender:e.gender},result:{error:tt}});const f=(c.includes(we)&&[we]||c.includes(xt)&&[ls]||c.includes(_t)&&[$n]||[$n,ls,we]).includes(e.eventType||"");return e.eventType&&!f?G({context:{participantType:e.eventType},result:{error:tt}}):(e.eventType&&(r.eventType,e.eventType),e.eventName&&(r.eventName=e.eventName),e.gender&&(r.gender=e.gender),{...$})}const nB={generateQualifyingStructure:HR,attachQualifyingStructure:qR,attachPlayoffStructures:BR,addQualifyingStructure:YR,setStructureOrder:QE,attachStructures:am,renameStructures:KR,disableTieAutoCalc:XR,enableTieAutoCalc:tB,validateCollectionDefinition:cf,modifyCollectionDefinition:zl,orderCollectionDefinitions:qp,removeCollectionDefinition:Kl,addCollectionDefinition:Zl,removeCollectionGroup:Kp,addCollectionGroup:Jp,modifyTieFormat:Qp,resetScorecard:jR,resetTieFormat:Zp,setEventStartDate:hN,setEventEndDate:mN,setEventDates:xR,deleteEvents:kL,modifyEvent:eB,addEvent:Ed,removeSeededParticipant:$R,removeScaleValues:uN,checkValidEntries:Zb,addDrawEntries:ob,removeSeeding:gR,autoSeeding:IR,getAvailablePlayoffRounds:oN,getAvailablePlayoffProfiles:oN,deleteDrawDefinitions:om,addPlayoffStructures:uR,modifyDrawDefinition:OR,addDrawDefinition:Za,removeStructure:XE,modifyDrawName:pN,generateAndPopulatePlayoffStructures:_h,generateSeedingScaleItems:aN,setSubOrder:mb,addEventEntries:Fs,promoteAlternate:QL,promoteAlternates:sN,destroyPairEntry:db,destroyPairEntries:S_,setEntryPosition:cN,setEntryPositions:fR,addEventEntryPairs:DL,removeEventEntries:Id,removeDrawEntries:aR,modifyEventEntries:kR,modifyEntriesStatus:jh,modifySeedAssignment:lR,modifyPairAssignment:cR,resetVoluntaryConsolationStructure:SR,deleteFlightProfileAndFlightDraws:TR,deleteFlightAndFlightDraw:yR,generateFlightProfile:NR,refreshEventDrawOrder:dN,attachFlightProfile:fN,resetDrawDefinition:MR,pruneDrawDefinition:DR,updateDrawIdsOrder:lN,getFlightProfile:be,getScaledEntries:hu,generateLineUps:Hb,addFlight:cm,generateAdHocMatchUps:FR,deleteAdHocMatchUps:UR,addAdHocMatchUps:LR,drawMatic:_R,setOrderOfFinish:wR,setDelegatedOutcome:hR,removeDelegatedOutcome:pR,addVoluntaryConsolationStructure:Ch,addVoluntaryConsolationStage:vR,generateVoluntaryConsolation:AR,attachConsolationStructures:RR,bulkMatchUpStatusUpdate:ey,updateTieMatchUpScore:ZR,aggregateTieFormats:QR,setMatchUpFormat:dR,setMatchUpStatus:Qa,assignDrawPosition:ML,assignSeedPositions:wL,assignDrawPositionBye:oR,substituteParticipant:PR,removeRoundMatchUps:UL,swapDrawPositionAssignments:sR,assignMatchUpSideParticipant:AL,removeMatchUpSideParticipant:vL,removeDrawPositionAssignment:Sd,alternateDrawPositionAssignment:rR,withdrawParticipantAtDrawPosition:ZL,setDrawParticipantRepresentativeIds:bL,getDrawParticipantRepresentativeIds:NL,luckyLoserDrawPositionAssignment:tR,qualifierDrawPositionAssignment:nR,setPositionAssignments:iR,automatedPositioning:d_,automatedPlayoffPositioning:pd,checkInParticipant:KL,checkOutParticipant:JL,toggleParticipantCheckInState:Jy,addDrawDefinitionTimeItem:Rb,generateDrawTypeAndModifyDrawDefinition:GR,generateDrawStructuresAndLinks:WR,generateDrawMaticRound:Tb,generateDrawDefinition:um,applyLineUps:VR,assignTieMatchUpParticipantId:em,removeTieMatchUpParticipantId:CL,replaceTieMatchUpParticipantId:Qb,resetMatchUpLineUps:JR,updateTeamLineUp:Uc,validateLineUp:zT,getTeamLineUp:ba};function rB(t){const{entries:e=[],entryStatus:n,stage:r}=t;return Math.max(...e.filter(s=>(!r||r===s.entryStage)&&(!n||s.entryStatus===n)&&!isNaN(s.entryPosition)).map(({entryPosition:s})=>vt(s||0)),0)}function sB(t){var O,D,M,w;let{matchUps:e}=t;const{tournamentRecord:n,drawDefinition:r,excludeMargin:s,exclusionRule:i,zoneDoubling:o,matchUpType:c,scaleName:a,eventId:u,zonePct:l,drawId:f,event:p}=t;if(!n&&!e)return{error:et};if(c&&![Oe,me].includes(c))return{error:tt,info:{matchUpType:c}};if(e&&!cr(e))return{error:tt,context:{matchUps:e}};const h=wr[a],d=(h==null?void 0:h.ascending)??t.ascending??!1,m=(h==null?void 0:h.accessor)??t.valueAccessor,g=Array.isArray(h==null?void 0:h.range)?Math.abs(h.range[0]-h.range[1]):0,I=oe(l)&&g?(l||0/100)*g:t.zoneMargin||g,S={withScaleValues:!0,withCompetitiveness:!0},T={matchUpTypes:c?[c]:[Oe,me]},E=n==null?void 0:n.participants;(O=e==null?void 0:e[0])!=null&&O.hasContext?f?e=e.filter(k=>k.drawId===f):u&&(e=e.filter(k=>k.eventId===u)):e===void 0&&(e=f&&!r&&[]||!f&&u&&!p&&[]||f&&((D=tr({inContext:!0,drawDefinition:r,contextFilters:T,contextProfile:S,participants:E}))==null?void 0:D.matchUps)||!f&&u&&((M=si({inContext:!0,contextFilters:T,contextProfile:S,participants:E,event:p}))==null?void 0:M.matchUps)||((w=He({tournamentRecord:n,contextFilters:T,contextProfile:S}))==null?void 0:w.matchUps)||[]),c&&(e=e.filter(k=>k.matchUpType===c));const y=e.filter(({winningSide:k,score:_,sides:F,matchUpStatus:L})=>![In,te,ce,ia,zn].includes(L||"")&&Be({score:_})&&(F==null?void 0:F.length)===2&&k),b=oB({matchUps:y,excludeMargin:s,exclusionRule:i,valueAccessor:m,ascending:d,scaleName:a}),N=!o||c===Oe?I:(I||0)*2,A=I?y.map(({competitiveProfile:k,matchUpType:_,score:F,sides:L})=>{const W=SN({valueAccessor:m,matchUpType:_,scaleName:a,sides:L}),j=Math.abs(W[0].value-W[1].value);return{competitiveness:k==null?void 0:k.competitiveness,valuesGap:j,score:F}}).filter(({valuesGap:k})=>k<=N):[],C=iB({zoneData:A}),v=C&&[].concat(Object.values(C)).flat().length,P=v&&Object.assign({},...Object.keys(C).map(k=>({[k]:Math.round(1e4*C[k].length/v)/100}))),U=y.length-((A==null?void 0:A.length)||0);return{...$,relevantMatchUps:y,zoneDistribution:P,zoneData:A,accuracy:b,nonZone:U}}function iB({zoneData:t}){const e={[If]:[],[ca]:[],[aa]:[]};for(const n of t){const{competitiveness:r,score:s,valuesGap:i}=n;e[r]&&e[r].push({score:s,valuesGap:i})}return e}function SN({exclusionRule:t,valueAccessor:e,matchUpType:n,scaleName:r,sides:s}){const i=t==null?void 0:t.range.sort(),o=c=>{const a=c==null?void 0:c[t==null?void 0:t.valueAccessor];return{exclude:t&&a>=i[0]&&a<=i[1],exclusionValue:a}};return s.sort((c,a)=>c.sideNumber-a.sideNumber).map(({participant:c})=>{const a=[],u=c==null?void 0:c.individualParticipants;if(u!=null&&u.length){const l=[];let f=0;for(const p of u){const{scaleValue:h,value:d}=TN({valueAccessor:e,participant:p,matchUpType:n,scaleName:r}),{exclude:m,exclusionValue:g}=o(h);m&&a.push(g),l.push(h),d&&!isNaN(f)?f+=d:f=void 0}return{participantName:c.participantName,exclusionValues:a,scaleValues:l,value:f}}else if(c){const{scaleValue:l,value:f}=TN({valueAccessor:e,matchUpType:n,participant:c,scaleName:r}),{exclude:p,exclusionValue:h}=o(l);return p&&a.push(h),{participantName:c.participantName,exclusionValues:a,scaleValue:l,value:f}}else return{}})}function TN({participant:t,valueAccessor:e,matchUpType:n,scaleName:r}){var a,u,l,f,p;const s=(u=(a=t==null?void 0:t.rankings)==null?void 0:a[n])==null?void 0:u.find(h=>h.scaleName===r),o=(p=((f=(l=t==null?void 0:t.ratings)==null?void 0:l[n])==null?void 0:f.find(h=>h.scaleName===r))||s)==null?void 0:p.scaleValue,c=e?o==null?void 0:o[e]:o;return{scaleValue:o,value:c}}function oB({excludeMargin:t,exclusionRule:e,valueAccessor:n,ascending:r,scaleName:s,matchUps:i}){const o={affirmative:[],negative:[],excluded:[]};for(const u of i){const{matchUpType:l,sides:f,score:p,winningSide:h}=u;if(!h)continue;if(e&&(!e.valueAccessor||!e.range))return{info:"exclusionRule requires valueAccessor and range",error:Tt};const d=h-1,m=SN({exclusionRule:e,valueAccessor:n,matchUpType:l,scaleName:s,sides:f});if(e){const y=m.map(({exclusionValues:b})=>b).flat();if(y.length){o.excluded.push({scoreString:p==null?void 0:p.scoreStringSide1,exclusionValues:y,winningSide:h,sideValues:m});continue}}if(m.filter(y=>![void 0,"",null].includes(y.value)).length<2){o.excluded.push({scoreString:p==null?void 0:p.scoreStringSide1,missingValues:!0,winningSide:h,sideValues:m});continue}const g=m[d].value-m[1-d].value,I=parseFloat(t||0),S=I&&Math.abs(g)<I;if(S){o.excluded.push({scoreString:p==null?void 0:p.scoreStringSide1,excludeMargin:t,winningSide:h,excludeGap:S,sideValues:m,valuesGap:g});continue}const T=r?g:g*-1,E=h===1?p==null?void 0:p.scoreStringSide1:p==null?void 0:p.scoreStringSide2;T>0?o.affirmative.push({winningScoreString:E,winningSide:h,sideValues:m,valuesGap:g,score:p}):o.negative.push({winningScoreString:E,winningSide:h,sideValues:m,valuesGap:g,score:p})}const c=o.affirmative.length+o.negative.length,a=c&&o.affirmative.length/c*100;return o.percent=a?Math.round(100*a)/100:0,o}function cB({tournamentRecord:t,drawDefinition:e,structureId:n,matchUpId:r,drawId:s,event:i}){var p;if(!t)return{error:et};if(!s&&!i&&!n&&!r)return G({result:{error:Tt},stack:"getMatchUpFormat"});const o=eu({tournamentRecord:t,drawDefinition:e,matchUpId:r,drawId:s,event:i});if(r&&(o!=null&&o.error))return o;!e&&(o!=null&&o.drawDefinition)&&(e=o==null?void 0:o.drawDefinition);let c=o==null?void 0:o.structure;if(!c&&n&&!r){if(!e)return{error:Hn};const h=Ot({drawDefinition:e,structureId:n});if(h.error)return h;c=h.structure}const a=c==null?void 0:c.matchUpFormat,u=e==null?void 0:e.matchUpFormat,l=i==null?void 0:i.matchUpFormat,f=((p=o==null?void 0:o.matchUp)==null?void 0:p.matchUpFormat)||a||u||l;return{structureDefaultMatchUpFormat:a,eventDefaultMatchUpFormat:l,drawDefaultMatchUpFormat:u,matchUpFormat:f}}function aB({profileBands:t,tournamentRecord:e,matchUps:n}){if(!cr(n))return{error:$s};const r=!t&&Xi({policyType:Hs,tournamentRecord:e}).policy,s=t||(r==null?void 0:r.profileBands)||Sf[Hs].profileBands,i=n.filter(({winningSide:p})=>p),o=i.map(uI),c=(p,h)=>{const d=aI(h,s);return p[d]+=1,p},a=lI(o).reduce((p,h)=>c(p,h),{[If]:0,[ca]:0,[aa]:0,[iI]:0}),u=Object.keys(a).reduce((p,h)=>(a[h]||0)+p,0),l=Object.keys(a).map(p=>{const h=parseFloat((a[p]/u).toFixed(4));return{[p]:h*100}}),f=i.filter(({matchUpStatus:p})=>p===oI).length;return l.push({[oI]:parseFloat((f/u).toFixed(4))*100}),{competitiveBands:Object.assign({},...l),...$}}function uB({tournamentRecord:t,outcomes:e}){var o;if(!t)return{error:et};if(!(e!=null&&e.length))return{error:Tt,info:"Missing outcomes"};const n=e.reduce((c,a)=>{const{drawId:u,eventId:l}=a;return l&&u&&(c[l]?c[l].includes(u)||c[l].push(u):c[l]=[u]),c},{}),r=Object.keys(n);return{publishedEventIds:((o=t.events)==null?void 0:o.filter(c=>r.includes(c.eventId))).filter(c=>{const{timeItem:a}=ws({itemType:`${Qn}.${Zn}`,event:c}),u=a==null?void 0:a.itemValue,{eventId:l}=c;return n[l].filter(p=>{var h,d;return(d=(h=u==null?void 0:u[Kr])==null?void 0:h.drawIds)==null?void 0:d.includes(p)}).length}).map(c=>c.eventId),eventIdPublishedDrawIdsMap:n}}function lB({tournamentRecord:t,participantId:e}){if(!t)return{error:et};if(!e)return{error:Ce};const{participant:n}=zs({tournamentRecord:t,participantId:e});if(!n)return{error:_e};const{timeItem:r}=kr({itemType:Ta,element:n});return r&&r.itemValue===ya&&ya}function dB({tournamentRecord:t,event:e}){var p,h;if(!t)return{error:et};if(!e)return{error:Wt};const n=e.entries||[],r=t.participants||[],s=((p=e.category)==null?void 0:p.categoryName)||((h=e.category)==null?void 0:h.ageCategoryCode),{eventType:i}=e,o=n.map(d=>d.participantId),c=r.filter(d=>o.includes(d.participantId));let a,u,l;return{entryScaleAttributes:c.map(d=>{var b,N,A,C,v,P;const{participantId:m,participantName:g,name:I}=d;let S={scaleType:xI,eventType:i,scaleName:s};const T=(N=(b=Ts({participant:d,scaleAttributes:S}))==null?void 0:b.scaleItem)==null?void 0:N.scaleValue;S={scaleType:OP,eventType:i,scaleName:s};const E=(C=(A=Ts({participant:d,scaleAttributes:S}))==null?void 0:A.scaleItem)==null?void 0:C.scaleValue;S={scaleType:UP,eventType:i,scaleName:s};const y=(P=(v=Ts({participant:d,scaleAttributes:S}))==null?void 0:v.scaleItem)==null?void 0:P.scaleValue;return a=!!(a||T),u=!!(u||E),l=!!(l||y),{participantId:m,participantName:g||I,seed:T,ranking:E,rating:y}}),hasSeededParticipants:a,hasRankedParticipants:u,hasRatedParticipants:l}}function fB(t){return Cn(t)}function pB(t){const{tournamentRecord:e}=t;if(!e)return{error:et};const{tournamentParticipants:n}=dn({tournamentRecord:e,inContext:!0});return Ob({tournamentParticipants:n,...t})}function hB({tournamentRecord:t,drawDefinition:e}){return t?{drawDefinition:pt(e)}:{error:et}}const mB={allTournamentMatchUps:He,tournamentMatchUps:fT,allEventMatchUps:si,getRoundMatchUps:fB,allDrawMatchUps:tr,eventMatchUps:pT,drawMatchUps:vO,credits:sd,getTournamentStructures:LM,getEventStructures:GT,getEvents:uP,getEvent:aP,findDrawDefinitionExtension:Hu,findParticipantExtension:sP,findTournamentExtension:Bn,findEventExtension:Us,findExtension:xn,getTieFormat:Oy,getMatchUpFormat:cB,getDrawDefinition:hB,getEventProperties:dB,getPositionAssignments:im,isValidMatchUpFormat:nr,getMaxEntryPosition:rB,getMatchUpCompetitiveProfile:dI,findVenue:Js,getCourts:vP,getVenuesAndCourts:Of,findCourt:AP,getEventTimeItem:ws,getTournamentTimeItem:El,getParticipantTimeItem:SO,getDrawDefinitionTimeItem:IO,bulkUpdatePublishedEventIds:uB,matchUpActions:gE,positionActions:pB,findMatchUp:BD,participantScheduledMatchUps:cy,getPredictiveAccuracy:sB,getMatchUpsStats:aB,participantScaleItem:Ts,getParticipantScaleItem:bd,getParticipantSignInStatus:lB,getPolicyDefinitions:Zi,getMatchUpScheduleDetails:_f},gB={addVenue:ma,deleteVenue:yh,deleteVenues:ak,modifyVenue:PE,enableCourts:TE,enableVenues:yE,disableCourts:IE,disableVenues:SE,addCourt:Nh,addCourts:Ah,deleteCourt:bE,modifyCourt:bh,modifyCourtAvailability:vE,findVenue:NP};(()=>{const t={getState:o=>gF({convertExtensions:o==null?void 0:o.convertExtensions,removeExtensions:o==null?void 0:o.removeExtensions,tournamentId:os()}),newTournamentRecord:(o={})=>{const c=Jh(o),a=c.tournamentId;return c.error?c:(Dg(c),Zc(a),{...$,tournamentId:a})},setTournamentId:o=>Zc(o),version:()=>Es(),reset:()=>{const o=Xd(os());return e(o)},setState:(o,c,a)=>{Hi(c,a);const u=Qh(o,c);return e(u)},getDevContext:o=>ze(o),executionQueue:(o,c)=>i(o,c),devContext:o=>(zo(o),t)};function e(o){return o!=null&&o.error?(t.error=o.error,t.success=!1):(t.error=void 0,t.success=!0),t}return s([mB,nB,gB,gL,EL,hL,WF,uL,xF]),t;function n(o,c,a,u){var I,S;delete t.success,delete t.error;const l=Date.now(),f=IF(o,a),p=c({...f,tournamentRecord:o}),h=Date.now()-l,d=ze(),m={method:u},g=typeof d.result=="object"&&d.result.error;return![void 0,!1].includes(d.perf)&&(isNaN(d.perf)||h>d.perf)&&(m.elapsed=h),(g||d.params&&!Array.isArray(d.params)||Array.isArray(d.params)&&((I=d.params)!=null&&I.includes(u)))&&(m.params=a),(g||!g&&d.result&&!Array.isArray(d.result)||Array.isArray(d.result)&&((S=d.result)!=null&&S.includes(u)))&&(m.result=p),Object.keys(m).length>1&&console.log("te:",m),d.makeDeepCopy&&(p.deepCopyIterations=nC()),p}function r(o,c,a){const u=os(),l=(c==null?void 0:c.sandBoxRecord)||(c==null?void 0:c.sandboxRecord)||(c==null?void 0:c.sandboxTournament)||Jc(u),f=(c==null?void 0:c.rollbackOnError)&&pt(l,!1,!0),p=n(l,o,c,a);p!=null&&p.error&&f&&Qh(f);const h=(p==null?void 0:p.success)&&(c==null?void 0:c.delayNotify)!==!0&&(c==null?void 0:c.doNotNotify)!==!0,d=Kc(),m=Date.now();return d&&(Dl({tournamentRecord:l,value:{version:Es(),timeStamp:m}}),p.modificationsApplied=!0),h&&Di({directives:[{method:o,params:c}],mutationStatus:d,tournamentId:u,timeStamp:m}),(h||!(p!=null&&p.success)||c!=null&&c.doNotNotify)&&fi(),p}function s(o){o.forEach(c=>{Object.keys(c).forEach(a=>{t[a]=u=>{if(ze())return r(c[a],u,a);try{return r(c[a],u,a)}catch(l){Xc({engineName:"tournamentEngine",methodName:a,params:u,err:l})}}})})}function i(o,c){var m;if(!Array.isArray(o))return{error:tt};const a=os(),u=Jc(a),l=c&&pt(u,!1,!0),f=[];for(const g of o){if(typeof g!="object")return{error:tt};const{method:I,params:S}=g;if(!t[I]){const E={error:vg,methodName:I},y=ze();return(y.result&&!Array.isArray(y.result)||Array.isArray(y.result)&&((m=y.result)!=null&&m.includes(I)))&&console.log("te:",E),E}const T=n(u,t[I],S,I);if(T!=null&&T.error)return l&&Qh(l),{...T,rolledBack:!!l};f.push({...T,methodName:I})}const p=Kc(),h=Date.now();return p&&Dl({tournamentRecord:u,value:{version:Es(),timeStamp:h}}),Di({directives:o,mutationStatus:p,timeStamp:h,tournamentId:a}),fi(),{success:f.every(g=>g.success),results:f}}})();function yN(t,e){var s;if(typeof t!="object")return{error:Ir};const n=((s=t.unifiedTournamentId)==null?void 0:s.tournamentId)||t.tournamentId;if(!n)return{error:is};const r=e!==!1?pt(t):t;return Qc({[n]:r}),Zc(n),r}function IB(t){const{convertExtensions:e,removeExtensions:n,tournamentId:r}=t||{};if(typeof r!="string")return{};const s=Jc(r);return{tournamentRecord:pt(s,e,!1,n)}}function SB(t,e){return t&&e!=null&&e.someParam&&(e={...e}),e}function EN(t,e){return t&&e&&Array.isArray(e)&&e[t-1]||typeof e=="object"&&e[t]}function TB(t){const{participation:e={},awardProfiles:n,startDate:r,eventType:s,drawSize:i,drawType:o,category:c,endDate:a,level:u}=t,{participationOrder:l,flightNumber:f,rankingStage:p}=e,h=m=>!r&&!a||!m.dateRanges?!0:m.dateRanges.some(g=>{const I=!r||!g.startDate||new Date(r)>new Date(g.startDate),S=!a||!g.endDate||new Date(a)<=new Date(g.endDate);return I&&S});return{awardProfile:n.find(m=>{var g,I,S,T,E,y,b,N,A,C;return h(m)&&(!m.maxFlightNumber||f<=m.maxFlightNumber)&&(!((g=m.drawTypes)!=null&&g.length)||((I=m.drawTypes)==null?void 0:I.includes(o)))&&(!((S=m.drawSizes)!=null&&S.length)||m.drawSizes.includes(i))&&(!((T=m.stages)!=null&&T.length)||m.stages.includes(p))&&(!((E=m.levels)!=null&&E.length)||m.levels.includes(u))&&(!m.maxDrawSize||i<=m.maxDrawSize)&&(!m.drawSize||m.drawSize===i)&&(!m.maxLevel||u<=m.maxLevel)&&(!f||!((b=(y=m.flights)==null?void 0:y.flightNumbers)!=null&&b.length)||m.flights.flightNumbers.includes(f))&&(!m.participationOrder||m.participationOrder===l)&&(!((N=m.category)!=null&&N.ageCategoryCodes)||m.category.ageCategoryCodes.includes(c==null?void 0:c.ageCategoryCode))&&(!((A=m.eventTypes)!=null&&A.length)||((C=m.eventTypes)==null?void 0:C.includes(s)))})}}function bN({participantWon:t,flightNumber:e,valueObj:n,drawSize:r,flights:s,level:i}){var d,m;const o=(g,I)=>{if(g){if(Array.isArray(I)){const S=I.find(T=>T.flight===g||T.f===g);return S.value||S.v}if(typeof I=="object"){const S=I.flights||I.f;if(Array.isArray(S))return S[g-1]}}},c=(g,I)=>{const S=(g==null?void 0:g.value)||(g==null?void 0:g.v)||(oe(g)?g:0),T=EN(i,g==null?void 0:g.level);return{value:o(I,T)||oe(T)&&T||S}};let a=0,u,l,f,p;const h=t&&"won"||t===!1&&"lost"||void 0;if(Array.isArray(n)){let g=n.find(T=>{var E;return T.drawSize===r||((E=T.drawSizes)==null?void 0:E.includes(r))}),I=n.find(T=>T.drawSize&&T.threshold&&r>T.drawSize),S=n.find(T=>{var E;return!T.drawSize&&!((E=T.drawSizes)!=null&&E.length)});h!==void 0&&(g=g==null?void 0:g[h],I=I==null?void 0:I[h],S=S==null?void 0:S[h]),l=c(g,e).value,f=c(I,e).value,p=c(S,e).value,a=l||f||p,u=l&&g.requireWin||f&&I.requireWin||(S==null?void 0:S.requireWin)}else if(typeof n=="object"){let g=(d=n==null?void 0:n.drawSizes)==null?void 0:d[r],I=n;h!==void 0&&(g=g==null?void 0:g[h],I=I==null?void 0:I[h]),l=c(g,e).value,p=c(I,e).value,a=l||p,u=l?g.requireWin:I==null?void 0:I.requireWin}else oe(n)&&h===void 0&&(a=n);return e&&((m=s==null?void 0:s.pct)!=null&&m[e])&&(a=Math.round(a*s.pct[e])),{awardPoints:a,requireWin:u}}function yB({participantFilters:t,policyDefinitions:e,tournamentRecord:n,saveRankings:r,level:s}){var S;if(!n)return{error:et};const{policyDefinitions:i}=Zi({policyTypes:[df],tournamentRecord:n}),o=(e==null?void 0:e[df])||(i==null?void 0:i[df]);if(!o)return{error:Au};const c=o.awardProfiles;let a=o.requireWinFirstRound;const u=o.requireWinForPoints,{participants:l,derivedEventInfo:f,derivedDrawInfo:p,mappedMatchUps:h}=Fi({withRankingProfile:!0,participantFilters:t,tournamentRecord:n}),d=l==null?void 0:l.filter(T=>{var E;return(E=T.draws)==null?void 0:E.length}),m={},g={},I={};for(const T of d||[]){const{participantType:E,participantId:y,person:b,draws:N}=T;for(const A of N){const{drawId:C,structureParticipation:v,eventId:P}=A,U=f[P],O=p[C],D=O==null?void 0:O.drawType,{category:M,eventType:w}=U||{},k=A.startDate||U.startDate||n.startDate,_=A.endDate||U.endDate||n.endDate;if(w===ds&&y!==vr)continue;let F;if(c){let L=u,W=0,j=0,H=0,B;for(const R of v){const{finishingPositionRange:x,participationOrder:q,participantWon:V,flightNumber:Y,rankingStage:z,winCount:J}=R;W+=J||0;const Q=O==null?void 0:O.drawSize,{awardProfile:X}=TB({awardProfiles:c,participation:R,eventType:w,startDate:k,category:M,drawSize:Q,drawType:D,endDate:_,level:s});if(X){if(!Q)continue;const Z=Array.isArray(x)&&Math.max(...x),nt=Vt(x||[]).join("-"),rt=Z&&z!==Pt&&(x==null?void 0:x.includes(Q));X.requireWinForPoints!==void 0&&(L=X.requireWinForPoints),X.requireWinFirstRound!==void 0&&(a=X.requireWinFirstRound);const{finishingPositionPoints:K={},finishingPositionRanges:it,finishingRound:st,pointsPerWin:dt,flights:mt}=X,Mt=Array.isArray(X.perWinPoints)?(S=X.perWinPoints)==null?void 0:S.find(gt=>{var Ft;return(Ft=gt.participationOrders)==null?void 0:Ft.includes(q)}):X.perWinPoints,Nt=K.participationOrders;let St=0,ct;if((!Nt||Nt.includes(q))&&it&&Z){const gt=it[Z];gt&&({awardPoints:St,requireWin:ct}=bN({flightNumber:Y,valueObj:gt,drawSize:Q,flights:mt,level:s}))}if(!St&&st&&q===1&&Z){const gt=st[Z];gt&&({awardPoints:St,requireWin:ct}=bN({participantWon:V,flightNumber:Y,valueObj:gt,drawSize:Q,flights:mt,level:s}))}if(rt&&a!==void 0&&(L=a),ct!==void 0&&(L=ct),St>j&&(!L||J)&&(j=St,B=Z),!St&&dt&&J&&(H+=J*dt,B=nt),!St&&J&&Mt){const gt=EN(s,Mt==null?void 0:Mt.level);gt?H+=J*gt:Mt.value&&(H+=J*Mt.value)}}if(F=j+H,E===vr){const Z=(T.matchUps||[]).filter(({structureId:nt})=>nt===R.structureId);for(const{matchUpId:nt}of Z){const rt=h[nt],K=rt.sides.find(it=>it.participantId===y).sideNumber;if(rt.winningSice===K)for(const it of rt.tieMatchUps)it.winningSide}}}if(H||j){const R={winCount:W,positionPoints:j,rangeAccessor:B,perWinPoints:H,eventType:w,drawId:C,points:F},x=b==null?void 0:b.personId;x?(m[x]||(m[x]=[]),m[x].push(R)):E===_t?(I[y]||(I[y]=[]),I[y].push(R)):E===vr&&(g[y]||(g[y]=[]),g[y].push(R))}}}}return r&&ae({element:n,extension:{name:nI,value:{personPoints:m,teamPoints:g,pairPoints:I}}}),{participantsWithOutcomes:d,personPoints:m,pairPoints:I,teamPoints:g,...$}}const EB={getTournamentPoints:yB},bB=t=>250/Math.pow(t+5,.4),NB=()=>1;function AB(t=3,e=2){const n=t/e;return isNaN(n)?Lc.kDefault():n}const Lc={nSpread:400,diffThreshold:.125,kCalc:bB,kMultiplier:AB,kDefault:NB};function NN(t){let{winnerRating:e,loserRating:n,ratingRange:r}=t;const{ratings:s=wr,winnerCountables:i=1,loserCountables:o=0,ratingType:c=No,maxCountables:a,countables:u}=t||{},l=s==null?void 0:s[c];if(!l)return{error:Tt};r=l.range||r,e=e||l.defaultInitialization,n=n||l.defaultInitialization;const f=r[0]>r[1],p=l.decimalsCount||0,h=f?r.slice().reverse():r,d=(k,_)=>parseFloat(_)>=Math.min(...k)&&parseFloat(_)<=Math.max(...k);(!d(r,e)||!d(r,n))&&(d(r,e)||(e=l.defaultInitialization),d(r,n)||(n=l.defaultInitialization));const m=({value:k,sourceRange:_,targetRange:F})=>(k-_[0])*(F[1]-F[0])/(_[1]-_[0])+F[0],g=m({targetRange:wr[No].range,sourceRange:h,value:f?r[0]-e:e}),I=m({targetRange:wr[No].range,sourceRange:h,value:f?r[0]-n:n}),S=(k,_)=>1/(1+Math.pow(10,(_-k)/Lc.nSpread)),T=S(g,I),E=S(I,g),y=Lc.kCalc(i),b=Lc.kCalc(o),N=Lc.kMultiplier(a,u),A=g+N*y*(1-T),C=I+N*b*(0-E),v=m({sourceRange:wr[No].range,value:A,targetRange:h}),P=m({sourceRange:wr[No].range,value:C,targetRange:h}),U=f?r[0]-v:v;let O=parseFloat(parseFloat(U).toFixed(p));const D=f?r[0]-P:P;let M=parseFloat(parseFloat(D).toFixed(p));const w=Math.max(...r)?Math.abs(e-n)/Math.max(...r):0;return(v>P&&w>Lc.diffThreshold||O<0||M<0)&&(O=e,M=n),{newWinnerRating:O,newLoserRating:M}}const vB=t=>(t==null?void 0:t.reduce((e,n)=>(n.winningSide&&(e[n.winningSide-1]+=1),e),[0,0]))||[0,0];function CB({removePriorValues:t=!0,tournamentRecord:e,ratingType:n=No,considerGames:r,matchUpIds:s,asDynamic:i}){var f,p;if(!e)return{error:et};if(!Array.isArray(s))return{error:$s};if(typeof n!="string")return{error:tt,ratingType:n};if(!wr[n])return{error:tt};const o=wr[n],{accessor:c}=o,a={},u=He({matchUpFilters:{matchUpIds:s,matchUpStatuses:We},tournamentRecord:e,inContext:!0}).matchUps||[];for(const h of u.sort(vo)){const{endDate:d,matchUpFormat:m,score:g,sides:I,winningSide:S}=h,T=h.matchUpType,E={eventType:T,scaleName:n,scaleType:to},y=`${n}.${pI}`,b={scaleName:y,eventType:T,scaleType:to},N=Object.assign({},...(I||[]).map(k=>{const{sideNumber:_,participant:F}=k;return _&&{[_]:[F==null?void 0:F.participantId,...(F==null?void 0:F.individualParticipantIds)||[]].filter(Boolean).flat()}})),A=i?y:n,C=Object.assign({},...Object.values(N).flat().map(k=>{const{scaleItem:_}=bd({scaleAttributes:b,tournamentRecord:e,participantId:k}),{scaleItem:F}=bd({tournamentRecord:e,scaleAttributes:E,participantId:k}),L=c?{[c]:void 0}:void 0;return k&&{[k]:_??F??{scaleName:A,eventType:T,scaleDate:d,scaleType:to,scaleValue:L}}})),v=m?yn(m):{},P=(v==null?void 0:v.bestOf)||1,U=(v==null?void 0:v.setsTo)||1,O=r?P&U:P,D=(g==null?void 0:g.sets)&&vB(g.sets)||S===1&&[1,0]||[0,1],M=S?N[S]:[],w=S?N[3-S]:[];for(const k of M){const _=(f=C[k])==null?void 0:f.scaleValue,F=typeof _=="object"?_[c]:_;for(const L of w){const W=(p=C[L])==null?void 0:p.scaleValue,j=typeof W=="object"?W[c]:W,H=S?D[S]:[0,0],B=S?D[3-S]:[0,0],{newWinnerRating:R,newLoserRating:x}=NN({winnerCountables:H,loserCountables:B,maxCountables:O,winnerRating:F,loserRating:j,ratingType:n}),q=c?{..._,[c]:R}:R,V=c?{...W,[c]:x}:x;C[k].scaleValue=q,C[L].scaleValue=V;let Y=du({participantId:k,removePriorValues:t,tournamentRecord:e,scaleItem:{...C[k],scaleName:A}});if(Y.error||(Y=du({participantId:L,removePriorValues:t,tournamentRecord:e,scaleItem:{...C[L],scaleName:A}}),Y.error))return Y}}Object.assign(a,C)}const l=u.map(({matchUpId:h})=>h);return{...$,modifiedScaleValues:a,processedMatchUpIds:l}}const PB={calculateNewRatings:NN,generateDynamicRatings:CB};(()=>{const t={getState:i=>IB({convertExtensions:i==null?void 0:i.convertExtensions,removeExtensions:i==null?void 0:i.removeExtensions,tournamentId:os()}),setTournamentId:i=>Zc(i)};t.version=()=>Es(),t.reset=()=>{const i=Xd(os());return e(i)},t.setState=(i,o,c)=>{Hi(o,c);const a=yN(i,o);return e(a)};function e(i){return i!=null&&i.error?(t.error=i.error,t.success=!1):(t.error=void 0,t.success=!0),t}return s([EB,PB]),t;function n(i,o,c){delete t.success,delete t.error;const a=SB(i,c);return o({...a,tournamentRecord:i})}function r(i,o){const c=(o==null?void 0:o.sandBoxRecord)||(o==null?void 0:o.sandboxRecord)||(o==null?void 0:o.sandboxTournament)||Jc(os()),a=(o==null?void 0:o.rollbackOnError)&&pt(c,!1,!0),u=n(c,i,o);u!=null&&u.error&&a&&yN(a);const l=(u==null?void 0:u.success)&&(o==null?void 0:o.delayNotify)!==!0&&(o==null?void 0:o.doNotNotify)!==!0;return l&&Di(),(l||!(u!=null&&u.success)||o!=null&&o.doNotNotify)&&fi(),u}function s(i){i.forEach(o=>{Object.keys(o).forEach(c=>{t[c]=a=>{if(ze())return r(o[c],a);try{return r(o[c],a)}catch(u){Xc({engineName:"scaleEngine",methodName:c,params:a,err:u})}}})})}})();var UB=["Abbey","Assange","Ahern","Ampleforth","Atreides","Austen","Banks","Barrington","Batty","Bauers","Beals","Beer","Bennett","Berry","Bonaparte","Brockovich","Bukowski","Cassidy","Catton","Calvino","Carson","Chip","Constant","Crane","Crowne","Cummings","Curie","Dallas","Diamond","Deckard","Earhart","Eisenstein","Eldritch","Elliot","Eyre","Faulkner","Fukuoka","Godel","Goldstein","Greer","Hedges","Herbert","Holmgren","Humperdinck","Huxley","Illich","Jeffers","Jensen","Jevons","Johnson","Johnstone","Jovovich","Kingsnorth","Langer","Fernwright","Fuller","Le Guin","Lem","Lovelace","Midgely","Mond","Montoya","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","Wormwood"],OB=["Ada","Amelia","Amelie","America","Anne","Antoina","Aravis","Astrid","Beatrice","Brienne","Buttercup","Caitlin","Cimorene","Cordelia","Desdemona","Ellen","Elizabeth","Emily","Emmie","Erin","Eva","Evelyn","Hermia","Hypatia","Imogen","Jane","Jasmine","Juliana","Juliet","Heather","Helen","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"],MB=["Alan","Aldous","August","Axel","Barda","Bill","Charles","Chris","Darwin","David","Derrick","Edward","Emmanuel","Ernst","Estlin","Fezzik","Filby","Frank","Frito","George","Glen","Helmholtz","Inigo","Italo","Ivan","James","Jared","Joe","Julian","John Michael","Jonathan","Korben","Kirkpatrick","Kurt","Lief","Malachi","Mark","Masanobu","Michael","Mustapha","Neil","Octavio","Palmer","Paul","Pierre","Robinson","Rick","Rincewind","Roy","Sheldon","Stafford","Stanislaw","Stanley","Syme","Thorstein","Tyrone","Vizzini","Walton","Walker","Warren","Wendell","Westley","William","Winston"],DB={lastNames:UB,firstFemale:OB,firstMale:MB};function lm(t){const{count:e=100,sex:n}=t||{};if(!e||n&&![Se,Ne].includes(n))return{personData:[],error:tt};const r=Math.ceil(e*1.3),{lastNames:s,firstFemale:i,firstMale:o}=DB,c=ri.map(({iso:g})=>g).filter(Boolean),a=Math.ceil(r/s.length),u=Math.ceil(r/i.length),l=Math.ceil(r/o.length),f=ht(0,a).flatMap(()=>{const g=pt(s,!1,!0);return ht(0,s.length).map(()=>cn(g))}),p=ht(0,u).flatMap(()=>{const g=pt(i,!1,!0);return ht(0,i.length).map(()=>cn(g))}),h=ht(0,l).flatMap(()=>{const g=pt(o,!1,!0);return ht(0,o.length).map(()=>cn(g))}),d={};for(let g=0;g<r;g++){const I=f.pop(),S=n||Dn([Se,Ne]),T=S===Se?h.pop():p.pop(),E=Dn(c);d[`${T}${I}`]={nationalityCode:E,sex:S,firstName:T,lastName:I}}return{personData:Object.values(d).slice(0,e)}}function AN(t){let e=(t==null?void 0:t.count)||1;const{personExtensions:n,consideredDate:r,isMock:s=!0,gendersCount:i,personData:o,category:c,sex:a}=t||{};if(isNaN(e))return{error:tt};const u=(i==null?void 0:i[Se])||a===Se&&e||0,l=(i==null?void 0:i[Ne])||a===Ne&&e||0;e=Math.max(e,u+l);const f=e-(u+l),p=u&&lm({count:u,sex:Se}).personData||[],h=l&&lm({count:l,sex:Ne}).personData||[],d=[...p,...h,...f&&lm({count:f}).personData||[]];let m=d.filter(A=>!a||u&&l||A.sex===a);const g=[];if(Array.isArray(o)){const A=o.filter(C=>typeof C.firstName!="string"||typeof C.lastName!="string"||C.sex&&![Se,Ne].includes(C.sex)||C.nationalityCode&&(typeof C.nationalityCode!="string"||C.nationalityCode.length>3||!ri.find(({iso:v,ioc:P})=>[v,P].includes(C.nationalityCode)))?!1:(C.nationalityCode&&g.push(C.nationalityCode),!0));if(A.length)m=A;else return{error:tt}}const I=o?m:on(m);if(I.length<e){const{maleFirstNames:A,maleLastNames:C,femaleFirstNames:v,femaleLastNames:P,nationalityCodes:U}=d.reduce((O,D)=>{const{firstName:M,lastName:w,nationalityCode:k}=D;return D.sex===Se?(O.maleFirstNames.includes(M)||O.maleFirstNames.push(M),O.maleLastNames.includes(w)||O.maleLastNames.push(w)):(O.femaleFirstNames.includes(M)||O.femaleFirstNames.push(M),O.femaleLastNames.includes(w)||O.femaleLastNames.push(w)),O.nationalityCodes.includes(k)||O.nationalityCodes.push(k),O},{maleFirstNames:[],maleLastNames:[],femaleFirstNames:[],femaleLastNames:[],nationalityCodes:[]});ht(0,e-I.length).forEach(()=>{const O=a||Dn([Se,Ne]),D=Dn(U),M=Dn(O===Se?A:v),w=Dn(O===Se?C:P),k={firstName:M,lastName:w,sex:O,nationalityCode:D};I.push(k)})}const{ageMinDate:S,ageMaxDate:T}=ST({consideredDate:r,category:c}),E=vt((S==null?void 0:S.slice(0,4))||0)||vt((T==null?void 0:T.slice(0,4))||0)-3,y=vt((T==null?void 0:T.slice(0,4))||0)||vt((S==null?void 0:S.slice(0,4))||0)+3,b=(S||T)&&[E,y],N=I.slice(0,e).map((A,C)=>{const[v,P]=b||[],U=b&&cn(ht(v,P)),O=cn(ht(0,365)),D=U&&IC(U,O);return Object.assign(bt({extensions:n||[{name:"regionCode",value:C+1}],birthDate:D,isMock:s}),A)});return{persons:N.length&&N||I[0],nationalityCodes:g}}function vN(t){const{cities:e,states:n,postalCodes:r,nationalityCode:s,participantIndex:i}=t;return{postalCode:r==null?void 0:r[i],state:n==null?void 0:n[i],city:e==null?void 0:e[i],countryCode:s}}var wB=["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","Sparkle Soul Tribe","Stacked Deck","Cross Stringers","The Emergence","Total Demolition","Touch and Go","Upside Downers","Vertically Challenged","Visual Spectacle"];function dm({nameRoot:t="TEAM",count:e=1}={}){const r=on(wB).slice(0,e);return r.length<e&&ht(0,e-r.length).forEach(s=>r.push(`${t} ${s+1}`)),{names:r}}var kB=[{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"}],_B=["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 CN({count:t=1,participantsCount:e=32}={}){const n=on(_B),r=n.slice(0,t);return{cities:ht(0,e).map(i=>i<Math.min(t,n.length)?r[i]:Dn(r))}}function PN({count:t=1,participantsCount:e=32}={}){const n=on(kB),r=n.slice(0,t).map(i=>Object.keys(i)).flat();return{states:ht(0,e).map(i=>i<Math.min(t,n.length)?r[i]:Dn(r))}}function UN({count:t=1,participantsCount:e=32}={}){const n=ht(0,t).map(()=>ht(0,5).map(()=>Wn(0,9)).join(""));return{postalCodes:ht(0,e).map(s=>s<t?n[s]:Dn(n))}}function FB({keepExtensions:t=[],anonymizeParticipantNames:e=!0,tournamentRecord:n,tournamentName:r,personIds:s=[],tournamentId:i}){var F,L,W,j,H;if(!n)return{error:et};const o=Array.isArray(t)?sI.concat(...t):sI,c=B=>{var R;return Array.isArray(t)?(R=B==null?void 0:B.extensions)==null?void 0:R.filter(x=>o.includes(x.name)):B==null?void 0:B.extensions},a={};n.extensions=c(n);const u=i||Yt();a[n.tournamentId]=u,n.tournamentId=u,n.createdAt=new Date().toISOString(),n.tournamentName=r||`Anonymized: ${Sr(new Date)}`,delete n.parentOrganisation;for(const B of n.participants||[]){const R=Yt();a[B.participantId]=R,B.participantId=R}for(const B of n.participants||[])Array.isArray(B.individualParticipantIds)&&(B.individualParticipantIds=B.individualParticipantIds.map(R=>a[R]));let l=0;for(const B of n.venues||[]){B.extensions=c(B),B.venueName=`Venue #${l}`,B.venueAbbreviation=`V${l}`;const R=Yt();a[B.venueId]=R,l+=1}let f=1;for(const B of n.events||[]){B.extensions=c(B);const R=Yt();a[B.eventId]=R,B.eventId=R;const x=((F=B.category)==null?void 0:F.categoryName)||((L=B.category)==null?void 0:L.ageCategoryCode)||((W=B.category)==null?void 0:W.ratingType)||B.gender;if(B.eventName=`Event ${f} ${x}`,Array.isArray(B.entries))for(const V of B.entries)V.participantId=a[V.participantId];for(const V of B.drawDefinitions||[]){V.extensions=c(V);const Y=Yt();if(a[V.drawId]=Y,V.drawId=Y,Array.isArray(V.entries))for(const J of V.entries)J.participantId=a[J.participantId];const z=J=>{J.extensions=c(J);const Q=Yt();a[J.structureId]=Q,J.structureId=Q;for(const X of J.positionAssignments||[])X.participantId&&(X.participantId=a[X.participantId]);for(const X of J.seedAssignments||[])X.participantId&&(X.participantId=a[X.participantId]);for(const X of J.matchUps||[])for(const Z of X.sides||[])Z.lineUp&&(Z.lineUp=Z.lineUp.map(({participantId:nt,collectionAssignments:rt})=>({participantId:a[nt],collectionAssignments:rt})))};for(const J of V.structures||[])if(z(J),Array.isArray(J.structures))for(const Q of J.structures)z(Q);for(const J of V.links||[])J.source.structureId=a[J.source.structureId],J.target.structureId=a[J.target.structureId]}const{extension:q}=Us({name:ar,event:B});Array.isArray((j=q==null?void 0:q.value)==null?void 0:j.flights)&&((H=q==null?void 0:q.value.flights)==null||H.forEach(V=>{if(V.drawId=a[V.drawId],Array.isArray(V.drawEntries))for(const Y of V.drawEntries)Y.participantId=a[Y.participantId]})),f+=1}const p=n.startDate||Sr(new Date),h=(n.participants||[]).filter(({participantType:B})=>B===xt),d=h.reduce((B,R)=>{var q;const x=(q=R.person)==null?void 0:q.sex;return[Se,Ne].includes(x)?B[x]+=1:B[So]+=1,B},{[Se]:0,[Ne]:0,[So]:0}),m=Object.assign({},...Object.keys(d).map(B=>{var R;return{[B]:((R=AN({category:{ageCategoryCode:"O18"},count:d[B],addressProps:{citiesCount:10},personExtensions:[],consideredDate:p,sex:B}))==null?void 0:R.persons)||[]}})),g={[Se]:0,[Ne]:0,[So]:0},I=h.length,S=h.reduce((B,R)=>{var z,J;const x=((J=(z=R.person)==null?void 0:z.addresses)==null?void 0:J[0])||{},{city:q,state:V,postalCode:Y}=x;return B.cities.includes(q)||B.cities.push(q),B.states.includes(V)||B.states.push(V),B.postalCodes.includes(Y)||B.postalCodes.push(Y),B},{cities:[],postalCodes:[],states:[]}),T=S.postalCodes.length,E=S.cities.length,y=S.states.length,{cities:b}=CN({count:E||I,participantsCount:I}),{states:N}=PN({count:y||I,participantsCount:I}),{postalCodes:A}=UN({count:T||I,participantsCount:I}),C={cities:b,states:N,postalCodes:A};h.forEach((B,R)=>{var J,Q;const x=B==null?void 0:B.person,q=(x==null?void 0:x.sex)||So,V=(J=Bt(x==null?void 0:x.birthDate))==null?void 0:J.split("-")[0],Y=g[q],z=m[q][Y];if(g[q]+=1,V){const[,X,Z]=((Q=z==null?void 0:z.birthDate)==null?void 0:Q.split("-"))||[],nt=[V,X,Z].join("-");z.birthDate=nt}if(x!=null&&x.addresses){const X=vN({...C,participantIndex:R,nationalityCode:z.nationalityCode});z.addresses=[X]}z.personId=(s==null?void 0:s[R])||Yt(),e?(z.standardFamilyName=z.lastName,z.standardGivenName=z.firstName,B.participantName=`${z.standardGivenName} ${z.standardFamilyName}`):(z.standardFamilyName=x==null?void 0:x.standardFamilyName,z.standardGivenName=x==null?void 0:x.standardGivenName),delete z.firstName,delete z.lastName,z.extensions=c(x),B.person=z,a[x==null?void 0:x.personId]=z.personId}),(n.participants||[]).filter(({participantType:B})=>B===_t).forEach(B=>{const{individualParticipantIds:R}=B;B.participantName=LB({individualParticipantIds:R,individualParticipants:h})});const P=(n.participants||[]).filter(({participantType:B})=>B===se),U=P.length,O=dm({count:U}).names;P.forEach((B,R)=>{B.participantName=O[R]});const D=(n.participants||[]).filter(({participantType:B})=>B===Fn),M=D.length,w=dm({count:M,nameRoot:"Group"}).names;D.forEach((B,R)=>{B.participantName=w[R]});const{extension:k}=Bn({name:qs,tournamentRecord:n});Array.isArray(k==null?void 0:k.value)&&(k==null||k.value.forEach(B=>{B.tournamentId=a[B.tournamentId],B.structureId=a[B.structureId],B.eventId=a[B.eventId],B.drawId=a[B.drawId]}));const{extension:_}=Bn({name:nc,tournamentRecord:n});return Array.isArray(_==null?void 0:_.value)&&(_==null||_.value.forEach(B=>{B.personId=a[B.personId]})),{...$}}function LB({individualParticipantIds:t,individualParticipants:e}){let n=e.filter(({participantId:r})=>t.includes(r)).map(({person:r})=>r==null?void 0:r.standardFamilyName).filter(Boolean).sort().join("/");return t.length===1&&(n+="/Unknown"),n}function ON({matchUpStatusProfile:t,completeAllMatchUps:e,randomWinningSide:n,tournamentRecord:r,drawProfiles:s,event:i}){var d,m,g,I;const o=be({event:i}).flightProfile,{eventName:c,eventType:a,category:u}=i,{startDate:l}=r,f=[],p=(u==null?void 0:u.categoryName)||(u==null?void 0:u.ageCategoryCode)||(u==null?void 0:u.ratingType),h=(d=i.drawDefinitions)==null?void 0:d.map(({drawId:S})=>S);if(Array.isArray(o==null?void 0:o.flights))for(const[S,T]of o.flights.entries()){const{drawId:E,stage:y,drawName:b,drawEntries:N}=T;f.push(T.drawId);const A=s[S],{seedsCount:C,generate:v=!0}=A||{};if(v){const P=N.filter(dl).map(fe),U=p||c;if(r&&C&&C<=P.length&&ht(1,C+1).forEach((F,L)=>{const W={scaleValue:F,scaleName:U,scaleType:br,eventType:a,scaleDate:l},j=P[L];du({tournamentRecord:r,participantId:j,scaleItem:W})}),h!=null&&h.includes(E))break;let O=um({...A,matchUpType:a,seedingScaleName:U,tournamentRecord:r,isMock:!0,drawEntries:N,drawName:b,drawId:E,event:i,stage:y});if(O.error)return{error:O.error,drawIds:[]};const{drawDefinition:D}=O;if(!D)return{error:rr};const M=(m=s[S])==null?void 0:m.drawExtensions;if(Array.isArray(M)&&M.filter(ur).forEach(_=>ae({element:D,extension:_})),O=Za({suppressNotifications:!0,tournamentRecord:r,drawDefinition:D,event:i}),O.error)return{error:O.error,drawIds:[]};if(A!=null&&A.withPlayoffs){const _=(g=D.structures)==null?void 0:g[0].structureId,F=hd({idPrefix:A.idPrefix,...A.withPlayoffs,tournamentRecord:r,drawDefinition:D,isMock:!0,structureId:_,event:i});if(F!=null&&F.error)return F}const w=A==null?void 0:A.completionGoal;if(!((A==null?void 0:A.automated)===!1)&&(e||w)){const _=A==null?void 0:A.matchUpFormat,F=pu({completeAllMatchUps:!w&&e,matchUpStatusProfile:t,randomWinningSide:n,tournamentRecord:r,completionGoal:w,drawDefinition:D,matchUpFormat:_,event:i});if(F.error)return{error:F.error,drawIds:[]};const L=F.completedCount;if((A==null?void 0:A.drawType)===Ds){const W=(I=D.structures)==null?void 0:I.find(B=>B.stage===It);if(!W)return{error:Te};let j=pd({structureId:W.structureId,tournamentRecord:r,drawDefinition:D,event:i});if(j.error)return{error:j.error,drawIds:[]};const H=w?w-(L??0):void 0;if(j=pu({completeAllMatchUps:!w&&e,completionGoal:w?H:void 0,matchUpStatusProfile:t,randomWinningSide:n,tournamentRecord:r,drawDefinition:D,matchUpFormat:_,event:i}),j.error)return{error:j.error,drawIds:[]}}}}}return{...$,drawIds:f}}function Nd(t){let{rankingRange:e,scaledParticipantsCount:n}=t;const{ratingsParameters:r=wr,valuesInstanceLimit:s,consideredDate:i,category:o,nationalityCodesCount:c,nationalityCodeType:a,nationalityCodes:u,participantsCount:l=32,participantType:f,personIds:p,idPrefix:h,uuids:d,personExtensions:m,addressProps:g,gendersCount:I,matchUpType:S,personData:T,sex:E,inContext:y,withISO2:b,withIOC:N,scaleAllParticipants:A}=t,C=f===_t||S===Tr,v=f===se||S===se;e&&(!Array.isArray(e)||!e.every(dt=>Me(dt))||e.length!==2)&&(e=void 0),n=A?l:n;const P=1e3,U=n&&n>P?n:P;e=e||[1,U],e[1]+=1;const O=l*(C?2:v?8:1),D=AN({count:O,personExtensions:m,consideredDate:i,gendersCount:I,personData:T,category:o,sex:E});if(D.error)return D;const{nationalityCodes:M,persons:w}=D;let k=[],_=[],F=[],L=[];if(typeof o=="object"){const{categoryName:dt,ageCategoryCode:mt,ratingType:Mt}=o;if((dt||mt)&&!Mt){const[Nt,St]=e||[];if(_=on(ht(Nt,St)).slice(0,n||Wn(20,30)),[_t,se].includes(f)){const[ct,Et]=e||[];k=on(ht(ct,Et)).slice(0,n||Wn(20,30))}}if(Mt&&r[Mt]){const{ratingMax:Nt,ratingMin:St,ratingAttributes:ct}=o,Et=Object.assign({},r[Mt],ct||{}),{attributes:gt={},decimalsCount:Ft,accessors:yt,range:wt,step:Xt}=Et,$t=ft=>{const Ct={};for(const Ut of Object.keys(ft)||{}){const Kt=ft[Ut];if(typeof Kt=="object"&&Kt.generator){const{range:ut}=Kt,[Rt,ne]=ut.slice().sort();Ct[Ut]=Wn(Rt,ne)}else Ct[Ut]=Kt}return Ct},Dt=wt[0]>wt[1]?2:.5,[at,ot]=wt.slice().sort(),Lt=()=>ht(0,2e3).map(()=>_m(at,ot,Dt,Xt,Ft)).filter(ft=>(!Nt||ft<=Nt)&&(!St||ft>=St)).slice(0,n||Wn(20,30)).map(ft=>yt?Object.assign({},...yt.map(Ct=>({[Ct]:ft})),$t(gt)):ft);F=Lt(),[_t,se].includes(f)&&(L=Lt())}}const W=ri.filter(dt=>a==="IOC"&&dt.ioc||dt.iso);function j(dt){const mt=Math.ceil(O/dt);return s&&mt>s?Math.ceil(O/s):dt}const{postalCodesProfile:H,postalCodesCount:B,statesProfile:R,citiesProfile:x,citiesCount:q,statesCount:V}=g||{},Y=dt=>Object.keys(dt).map(mt=>ht(0,R[mt]).map(()=>mt)).flat(),z=x&&Y(x)||(g==null?void 0:g.cities)||CN({count:q||O,participantsCount:O}).cities,J=R&&Y(R)||(g==null?void 0:g.states)||PN({count:V||O,participantsCount:O}).states,Q=H&&Y(H)||(g==null?void 0:g.postalCodes)||UN({count:B||O,participantsCount:O}).postalCodes,X={cities:z,states:J,postalCodes:Q},Z=j(c),nt=Z?on(W).slice(0,c):u?W.filter(dt=>u.includes(dt.iso)):W,rt=on(ht(0,Math.ceil(O/(Z||1))).map(()=>nt).flat(1/0)),K=dm({count:l}).names;return{participants:ht(0,l).map(dt=>{const mt=C?2:v?8:1,Mt=ht(0,mt).map(gt=>{const Ft=dt*mt+gt;return st(Ft)}),Nt=Mt.map(gt=>gt.participantId),St=Mt.map(gt=>gt.person.standardFamilyName).join("/"),ct=C?_t:se,Et={participantId:MN({participantType:ct,idPrefix:h,index:dt,uuids:d}),participantRole:fn,participantName:C?St:K[dt],individualParticipantIds:Nt,participantType:ct};return y&&(Et.individualParticipants=Mt),C||v?[Et,...Mt]:Mt}).flat()};function st(dt){const mt=w[dt],{nationalityCode:Mt,participantExtensions:Nt,participantTimeItems:St,extensions:ct,firstName:Et,birthDate:gt,lastName:Ft,personId:yt,sex:wt}=mt||{},Xt=Et||"GivenName",$t=Ft||"FamilyName",At=`${Xt} ${$t}`,Dt=rt[dt],at=(M==null?void 0:M.length)&&Mt||Dt&&(a==="IOC"?Dt.ioc||Dt.iso:Dt.iso||Dt.ioc)||Mt;rt!=null&&rt.length&&!at&&!Mt&&console.log("%c Invalid Nationality Code",{participantIndex:dt,country:Dt});const ot=vN({...X,participantIndex:dt,nationalityCode:at}),Lt=bt({participantId:MN({participantType:xt,index:dt,idPrefix:h,uuids:d}),extensions:Nt,timeItems:St,participantRole:fn,participantType:xt,participantName:At,person:{addresses:[ot],personId:yt||(p==null?void 0:p.length)&&p[dt]||Yt(),standardFamilyName:$t,standardGivenName:Xt,nationalityCode:at,extensions:ct,birthDate:Yn(gt)?gt:void 0,sex:wt}});if(N&&at){const ft=ri.find(({iso:Ct})=>Ct===at);ft!=null&&ft.ioc&&(Lt.person.iocNationalityCode=ft.ioc),ft!=null&&ft.label&&(Lt.person.countryName=ft.label)}if(b&&at){const ft=ri.find(({iso:Ct})=>Ct===at);ft!=null&&ft.iso2&&(Lt.person.iso2NationalityCode=ft.iso2),ft!=null&&ft.label&&(Lt.person.countryName=ft.label)}if(o){const ft=_[dt],Ct=k[dt];Ad({scaleValue:ft,eventType:WI,scaleType:Ii,participant:Lt,category:o}),Ad({scaleValue:Ct,eventType:Zu,scaleType:Ii,participant:Lt,category:o});const Ut=F[dt],Kt=L[dt];Ad({scaleValue:Ut,eventType:WI,scaleType:to,participant:Lt,category:o}),Ad({scaleValue:Kt,eventType:Zu,scaleType:to,participant:Lt,category:o})}return Lt}}function Ad({scaleValue:t,participant:e,eventType:n,scaleType:r,category:s}){const i=s.categoryName||s.ratingType||s.ageCategoryCode,o=[eo,r,n,i].join("."),c={itemValue:t,itemType:o};i&&t&&(e.timeItems||(e.timeItems=[]),e.timeItems.push(c))}function MN({idPrefix:t,participantType:e,index:n,uuids:r}){return t?`${t}-${e===xt?"I":_t?"P":se?"T":Fn?"G":"X"}-${n}`:(r==null?void 0:r.pop())||Yt()}function DN({alternatesCount:t=0,tieFormatName:e,tieFormat:n,drawSize:r}){var h;let s=0,i=0,o=0,c=0;const a={},u={[Se]:0,[Ne]:0,[hs]:0,[So]:0,[Io]:0};n=typeof n=="object"?n:Lo({namedFormat:e}),(h=n==null?void 0:n.collectionDefinitions)==null||h.filter(Boolean).forEach(d=>{const{category:m,collectionId:g,matchUpType:I,matchUpCount:S,gender:T}=d;if([Se,Ne].includes(T)){const E=S*(I===me?2:1);u[T]<E&&(u[T]=E)}else T===hs&&(u[Se]<S&&(u[Se]=S),u[Ne]<S&&(u[Ne]=S));if(m){const E=JSON.stringify(m);a[E]=m}if(g||(d.collectionId=Yt()),I===me){const E=S;c+=S,s=Math.max(s,E)}if(I===Oe){const E=S;o+=S,i=Math.max(i,E)}});const l=Object.keys(a).length?Math.max(o,c*2):Math.max(i,s*2),f=s*(r+t),p=i*(r+t);return{maxDoublesDraw:f,maxSinglesDraw:p,teamSize:l,genders:u}}function RB({participantsProfile:t,eventProfiles:e,drawProfiles:n}){let{participantsCount:r,participantType:s=xt}=t||{};const i=r||0,o={[Ne]:0,[hs]:0,[So]:0,[Se]:0,[Io]:0};let c=0,a=0,u=0,l=0,f=0;const p=({alternatesCount:d=0,uniqueParticipants:m,tieFormatName:g,drawSize:I=0,eventType:S,tieFormat:T,category:E,gender:y,stage:b})=>{const N=S===$n,A=S===we,C=!!(m||b===Pt||E||y);if(A){l=Math.max(l,I+d),T=typeof T=="object"?T:Lo({namedFormat:g});const{teamSize:v,maxDoublesDraw:P,maxSinglesDraw:U,genders:O}=DN({alternatesCount:d,tieFormatName:g,tieFormat:T,drawSize:I});u=Math.max(u,v),a=Math.max(a,U),C||(c=Math.max(c,P)),Object.keys(O).forEach(D=>o[D]+=O[D])}else if(N)if(C){const v=(I+d)*2;f+=v,y&&(o[y]+=v)}else I+d&&I+d>c&&(c=I+d);else if(C){const v=I+d;y&&(o[y]+=v),f+=v}else I&&I>a&&(a=I+d)};if(e==null||e.forEach(d=>{const{tieFormatName:m,tieFormat:g,drawProfiles:I,eventType:S,category:T,gender:E}=d;if(I)for(const y of I){const{tieFormatName:b,tieFormat:N}=y;p({...y,tieFormatName:b||m,tieFormat:N||g,eventType:S,category:T,gender:E})}}),Array.isArray(n))for(const d of n)p(d);const h=Math.max(l*u,c*2,a);return c&&(s=_t),(r||i)<h&&(r=h),r&&c&&[_t,we].includes(s)&&(a&&Math.floor(a/2)>c?r=Math.floor(a/2):(!a||c*2>=a)&&(r=Math.ceil(r/2))),r===void 0&&(r=!(e!=null&&e.length)&&!(n!=null&&n.length)?32:0),r<i&&(r=i),{uniqueParticipantsCount:f,participantsCount:r,largestTeamDraw:l,largestTeamSize:u,participantType:s,gendersCount:o}}function wN({participantsProfile:t,tournamentRecord:e,eventProfiles:n,drawProfiles:r,startDate:s,uuids:i}){const{participantsCount:o,participantType:c,largestTeamDraw:a,largestTeamSize:u,gendersCount:l}=RB({participantsProfile:t,eventProfiles:n,drawProfiles:r}),f=t==null?void 0:t.teamKey,p=Nd({uuids:i,...t,consideredDate:s,participantsCount:o,participantType:c,gendersCount:l}).participants;let h=0,d=Ss({tournamentRecord:e,participants:p});if(d.error)return d;if(h+=d.addedCount,f){const I=Fb({tournamentRecord:e,...f});if(I.error)return I}const m=p.filter(({participantType:I})=>I===xt).map(fe),g=ht(0,a).map(I=>{const S=m.slice(I*u,(I+1)*u);return{participantName:`Team ${I+1}`,participantRole:fn,participantType:se,participantId:Yt(),individualParticipantIds:S}});return d=Ss({participants:g,tournamentRecord:e}),d.error?d:(h+=d.addedCount,{addedCount:h,...$})}function kN(t){var N,A;const{participantsProfile:e={},uniqueParticipantsCount:n,ratingsParameters:r,tournamentRecord:s,eventProfile:i,eventIndex:o,event:c,uuids:a}=t,{category:u,gender:l,eventType:f}=c,p=f===ls&&xt||f===$n&&_t||f,h=n[It]||0,d=n[Pt]||0,m=(N=i.drawProfiles)!=null&&N.length?h+d:((A=i.participantsProfile)==null?void 0:A.participantsCount)??0,g=[Se,Ne].includes(l)?l:void 0,I=e!=null&&e.idPrefix?`E-${o}-${e==null?void 0:e.idPrefix}`:void 0,{participants:S}=Nd({uuids:i.uuids||a,...e,scaledParticipantsCount:i.scaledParticipantsCount,consideredDate:s==null?void 0:s.startDate,rankingRange:i.rankingRange,participantType:p,participantsCount:m,ratingsParameters:r,category:u,idPrefix:I,sex:g}),E=Ss({tournamentRecord:s,participants:S});if(E.error)return E;const y=S==null?void 0:S.filter(({participantType:C})=>C===p),b=S==null?void 0:S.map(fe);return{uniqueDrawParticipants:y,uniqueParticipantIds:b}}function _N({drawProfiles:t,category:e,gender:n}){const r={},s=t==null?void 0:t.reduce((o,c)=>{const{qualifyingPositions:a=0,participantsCount:u=0,uniqueParticipants:l,stage:f=It,drawSize:p=0}=c||{};Object.keys(o).includes(f)||(o[f]=0);const h=(u||p)-a;return l||n||e||f===Pt?(Object.keys(r).includes(f)||(r[f]=0),r[f]+=h):o[f]=Math.max(o[f],h),o},{}),i=Object.keys(r);return i.forEach(o=>s[o]+=r[o]),{stageParticipantsCount:s,uniqueParticipantsCount:r,uniqueParticipantStages:i}}function FN({allUniqueParticipantIds:t,stageParticipantsCount:e,eventParticipantType:n,targetParticipants:r}){const s=e[It]||0,i=e[Pt]||0;return{stageParticipants:{QUALIFYING:r.filter(({participantType:c})=>c===n).filter(({participantId:c})=>!t.includes(c)).slice(0,i),MAIN:r.filter(({participantType:c})=>c===n).filter(({participantId:c})=>!t.includes(c)).slice(i,i+s)}}}function BB({autoEntryPositions:t,tournamentRecord:e,drawParticipants:n,drawProfile:r,event:s}){const{drawType:i=Ms,qualifyingPositions:o=0,stage:c=It,drawSize:a=0,drawName:u,drawId:l}=r,f=a-o,p=n.slice(0,f).map(fe);if(p.length){const m=Fs({participantIds:p,autoEntryPositions:t,tournamentRecord:e,stage:c,event:s});if(m.error)return m}const h=p.map(m=>({entryStatus:Ur,entryStage:c,participantId:m})),d=cm({drawName:u||i,qualifyingPositions:o,drawEntries:h,drawId:l,event:s,stage:c});return d.error?d:{...$}}function LN({uniqueDrawParticipants:t,autoEntryPositions:e,stageParticipants:n,tournamentRecord:r,drawProfiles:s,category:i,gender:o,event:c}){let a=0;for(const u of s){const{qualifyingPositions:l=0,uniqueParticipants:f,stage:p=It,drawSize:h=0}=u,d=h-l,m=f||o||i||p===Pt,g=m?t.slice(a,a+d):n[p||It]||[];m&&(a+=d);const I=BB({autoEntryPositions:e,drawParticipants:g,tournamentRecord:r,drawProfile:u,event:c});if(I.error)return I}return{...$}}function RN(t){var q;const{allUniqueParticipantIds:e,matchUpStatusProfile:n,participantsProfile:r,completeAllMatchUps:s,autoEntryPositions:i,hydrateCollections:o,randomWinningSide:c,ratingsParameters:a,tournamentRecord:u,eventProfile:l,eventIndex:f,publish:p,uuids:h}=t;let d=l.gender,m=l.eventName;const{eventType:g=ls,policyDefinitions:I,drawProfiles:S=[],eventExtensions:T,surfaceCategory:E,tieFormatName:y,discipline:b,eventLevel:N,timeItems:A,ballType:C,category:v}=l,P=l.eventId||Yt(),U=l.tieFormat||(g===we?Lo({namedFormat:y,event:{eventId:P,category:v,gender:d},hydrateCollections:o}):void 0),O=u.participants;for(const V of S)!d&&V.gender&&(d=V==null?void 0:V.gender);const{stageParticipantsCount:D,uniqueParticipantsCount:M,uniqueParticipantStages:w}=_N({drawProfiles:S,category:v,gender:d}),k=g===ls&&xt||g===$n&&_t||g,{uniqueDrawParticipants:_=[],uniqueParticipantIds:F=[]}=w?kN({event:{eventType:g,category:v,gender:d},uniqueParticipantsCount:M,participantsProfile:r,ratingsParameters:a,tournamentRecord:u,eventProfile:l,eventIndex:f,uuids:h}):{};let{eventAttributes:L}=l;typeof L!="object"&&(L={});const W=(v==null?void 0:v.categoryName)||(v==null?void 0:v.ageCategoryCode)||(v==null?void 0:v.ratingType);m=m||W||"Generated Event";const j={...L,surfaceCategory:E,discipline:b,eventLevel:N,eventName:m,eventType:g,tieFormat:U,ballType:C,category:v,eventId:P,gender:d};if(T!=null&&T.length&&Array.isArray(T)){const V=T.filter(ur);V!=null&&V.length&&Object.assign(j,{extensions:V})}if(Array.isArray(A)&&A.forEach(V=>ii({event:R,timeItem:V})),typeof I=="object")for(const V of Object.keys(I))nE({policyDefinitions:{[V]:I[V]},event:j});j.category&&(j.category.categoryName=W);let H;const B=Ed({suppressNotifications:!1,internalUse:!0,tournamentRecord:u,event:j});if(B.error)return B;const R=B==null?void 0:B.event,{stageParticipants:x}=FN({allUniqueParticipantIds:e,stageParticipantsCount:D,eventParticipantType:k,targetParticipants:O});if(S!=null&&S.length){const V=LN({uniqueDrawParticipants:_,autoEntryPositions:i,stageParticipants:x,tournamentRecord:u,drawProfiles:S,category:v,gender:d,event:R});if(V.error)return V;const Y=ON({matchUpStatusProfile:n,completeAllMatchUps:s,randomWinningSide:c,tournamentRecord:u,drawProfiles:S,event:R});if(Y.error)return Y;H=Y.drawIds}else if((q=l==null?void 0:l.participantsProfile)!=null&&q.participantsCount){const V=_.map(kn("participantId"));if(V.length){const Y=Fs({participantIds:V,autoEntryPositions:i,tournamentRecord:u,stage:It,event:R});if(Y.error)return Y}}return p&&fu({tournamentRecord:u,event:R}),{drawIds:H,eventId:P,uniqueParticipantIds:F}}function fm(t){var Nt,St;const{allUniqueParticipantIds:e=[],participantsProfile:n={},matchUpStatusProfile:r,completeAllMatchUps:s,autoEntryPositions:i,hydrateCollections:o,randomWinningSide:c,ratingsParameters:a,tournamentRecord:u,isMock:l=!0,drawProfile:f,startDate:p,drawIndex:h,uuids:d}=t,m=pt(f,!1,!0),{excessParticipantAlternates:g=!0,matchUpFormat:I=Kn,drawType:S=Ms,tournamentAlternates:T=0,alternatesCount:E=0,qualifyingPositions:y,qualifyingProfiles:b,generate:N=!0,eventExtensions:A,drawExtensions:C,completionGoal:v,tieFormatName:P,seedsCount:U,timeItems:O,drawName:D,category:M,idPrefix:w,publish:k,gender:_,stage:F}=m,L=m.drawSize||(m.ignoreDefaults?void 0:32),W=m.eventId||Yt(),j=f.eventType||f.matchUpType||ls,H=j===$n?_t:xt,B=typeof f.tieFormat=="object"&&f.tieFormat||j===se&&Lo({namedFormat:P,event:{eventId:W,category:M,gender:_},hydrateCollections:o})||void 0,R=(M==null?void 0:M.categoryName)||(M==null?void 0:M.ageCategoryCode)||(M==null?void 0:M.ratingType),x=f.eventName||R||`Generated ${j}`;let q=(u==null?void 0:u.participants)||[];const V=((b==null?void 0:b.map(ct=>ct.structureProfiles||[]).flat().reduce((ct,Et)=>{const gt=!Et.participantsCount||Et.participantsCount>Et.drawSize?Et.drawSize:Et.participantsCount||0;return ct+gt},0))||0)*(H===_t?2:1),Y=(!f.participantsCount||f.participantsCount>L?L:f.participantsCount)||0,z={eventName:x,eventType:j,tieFormat:B,category:M,eventId:W,gender:_};Array.isArray(O)&&O.forEach(ct=>ii({event:z,timeItem:ct}));let{eventAttributes:J}=f;if(typeof J!="object"&&(J={}),Object.assign(z,J),A!=null&&A.length&&Array.isArray(A)){const ct=A.filter(ur);ct!=null&&ct.length&&Object.assign(z,{extensions:ct})}const Q=[];if(V||f.uniqueParticipants||!u||_||M){const ct=(Y||0)+E+V;let Et=ct;const gt={[Se]:0,[Ne]:0};let Ft,yt;j===se&&({teamSize:Ft,genders:yt}=DN({alternatesCount:E,tieFormatName:P,tieFormat:B,drawSize:L}),Object.keys(yt).forEach(At=>{[Se,Ne].includes(At)&&yt[At]&&(gt[At]=L*yt[At])}),Et=Ft*((L||0)+V));const wt=n!=null&&n.idPrefix?`D-${h}-${n==null?void 0:n.idPrefix}`:void 0,$t=Nd({...n,scaledParticipantsCount:f.scaledParticipantsCount||n.scaledParticipantsCount,participantsCount:Et,consideredDate:u==null?void 0:u.startDate,sex:_||(n==null?void 0:n.sex),rankingRange:f.rankingRange,uuids:f.uuids||d,ratingsParameters:a,participantType:H,gendersCount:gt,idPrefix:wt,category:M}).participants;if(z.category&&(z.category.categoryName=R),u){const At=Ss({participants:$t,tournamentRecord:u});if(At.error)return At}if($t.forEach(({participantId:At})=>Q.push(At)),q=$t,j===se){const At=yt[Se]?$t.filter(({participantType:ut,person:Rt})=>ut===xt&&(Rt==null?void 0:Rt.sex)===Se).map(fe):[],Dt=yt[Ne]?$t.filter(({participantType:ut,person:Rt})=>ut===xt&&(Rt==null?void 0:Rt.sex)===Ne).map(fe):[],at=$t.filter(({participantType:ut})=>ut===xt).map(fe).filter(ut=>!At.includes(ut)&&!Dt.includes(ut)),ot=Ft-(yt[Se]+yt[Ne]);let Lt=0,ft=0,Ct=0;const Ut=ht(0,ct).map(ut=>{const Rt=Dt.slice(Lt,Lt+yt[Ne]),ne=At.slice(ft,ft+yt[Se]),Ae=at.slice(Ct,Ct+ot);return Lt+=yt[Ne],ft+=yt[Se],Ct+=ot,{individualParticipantIds:[...Rt,...ne,...Ae],participantOtherName:`TM${ut+1}`,participantName:`Team ${ut+1}`,participantRole:fn,participantType:se,participantId:Yt()}}),Kt=Ss({participants:Ut,tournamentRecord:u});if(!Kt.success)return Kt;q=Ut}}const X=ct=>{const{participantType:Et}=ct;return j===ls&&Et===xt||j===$n&&Et===_t?!0:j===se&&Et===se},Z=ct=>{var Et,gt;return!f.gender||((Et=ct.person)==null?void 0:Et.sex)===f.gender?!0:(gt=ct.individualParticipantIds)==null?void 0:gt.some(Ft=>{const yt=q.find(wt=>wt.participantId===Ft);return yt&&Z(yt)})},nt=q.filter(X).filter(Z).filter(({participantId:ct})=>!e.includes(ct)),rt=nt.slice(0,Y).map(ct=>ct.participantId);if(l&&(rt!=null&&rt.length)){const ct=Fs({autoEntryPositions:i,entryStage:F,tournamentRecord:u,participantIds:rt,event:z});if(ct.error)return ct}const K=V?nt.slice(Y,Y+V).map(ct=>ct.participantId):0;if(l&&(K!=null&&K.length)){let ct=0,Et=1;const gt=(yt,wt)=>yt.stageSequence-wt.stageSequence,Ft=(yt,wt)=>yt.roundTarget-wt.roundTarget;for(const yt of b.sort(Ft)){Et=yt.roundTarget||Et;let wt=1,Xt;for(const $t of yt.structureProfiles.sort(gt)){const Dt=($t.drawSize||_d($t.participantsCount))-(Xt||0),at=K.slice(ct,ct+Dt),ot=Fs({entryStage:Pt,entryStageSequence:wt,autoEntryPositions:i,tournamentRecord:u,participantIds:at,roundTarget:Et,event:z});if(ot.error)return ot;Xt=$t.qualifyingPositions,ct+=Dt,wt+=1}Et+=1}}const it=g&&((Nt=u==null?void 0:u.participants)==null?void 0:Nt.filter(({participantId:ct})=>!rt.includes(ct)).filter(X).filter(Z).slice(0,E||L-Y||T).map(ct=>ct.participantId));if(l&&(it!=null&&it.length)){const ct=Fs({participantIds:it,autoEntryPositions:!1,entryStatus:dr,tournamentRecord:u,event:z});if(ct.error)return ct.error}const st=R||x;u&&U&&U<=rt.length&&ht(1,U+1).forEach((Et,gt)=>{const Ft={scaleName:st,scaleDate:p,scaleType:xI,scaleValue:Et,eventType:j},yt=rt[gt];du({tournamentRecord:u,participantId:yt,scaleItem:Ft})});const dt=um({...pt(f,!1,!0),tournamentRecord:u,seedingScaleName:st,matchUpFormat:I,eventId:W,isMock:l,event:z});if(dt.error)return dt;if(!dt.drawDefinition)return{error:rr};const{drawDefinition:mt}=dt,Mt=mt.drawId;if(Array.isArray(C)&&C.filter(ur).forEach(ct=>ae({element:mt,extension:ct})),N){if(Za({drawDefinition:mt,event:z,suppressNotifications:!0}),f.withPlayoffs){const Et=(St=mt.structures)==null?void 0:St[0].structureId,gt=hd({...f.withPlayoffs,tournamentRecord:u,drawDefinition:mt,structureId:Et,idPrefix:w,isMock:l,event:z});if(gt!=null&&gt.error)return gt}const ct=f.automated===!1;if(l&&!ct){const Et=gt=>{var wt;const Ft=pu({completeAllMatchUps:gt.completeAllMatchUps,completionGoal:gt.completionGoal,matchUpStatusProfile:r,randomWinningSide:c,tournamentRecord:u,drawDefinition:mt,matchUpFormat:I,event:z});if(Ft.error)return Ft;const yt=Ft.completedCount;if(S===Ds){const Xt=(wt=mt.structures)==null?void 0:wt.find(Dt=>Dt.stage===It);if(!Xt)return{error:Te};pd({structureId:Xt.structureId,tournamentRecord:u,drawDefinition:mt,event:z});const $t=v?v-(yt??0):void 0,At=pu({completionGoal:v?$t:void 0,matchUpStatusProfile:r,completeAllMatchUps:s,randomWinningSide:c,tournamentRecord:u,drawDefinition:mt,matchUpFormat:I,event:z});if(At.error)return At}};if(v&&Et({completionGoal:v}),f.outcomes){const{matchUps:gt}=tr({inContext:!0,drawDefinition:mt,event:z});for(const Ft of f.outcomes){const{matchUpStatus:yt=De,matchUpStatusCodes:wt,stageSequence:Xt=1,matchUpIndex:$t=0,structureOrder:At,matchUpFormat:Dt,drawPositions:at,roundPosition:ot,stage:Lt=It,roundNumber:ft,winningSide:Ct,scoreString:Ut}=Ft,Kt=(gt==null?void 0:gt.reduce((Ee,Un)=>{const{structureId:Xe,matchUpId:Lr}=Un;return Ee[Xe]?Ee[Xe].push(Lr):Ee[Xe]=[Lr],Ee},{}))??[],ut=Object.assign({},...Object.keys(Kt).map((Ee,Un)=>({[Ee]:Un+1}))),Rt=gt==null?void 0:gt.filter(Ee=>(!Lt||Ee.stage===Lt)&&(!Xt||Ee.stageSequence===Xt)&&(!ft||Ee.roundNumber===ft)&&(!ot||Ee.roundPosition===ot)&&(!At||ut[Ee.structureId]===At)&&(!at||qe(at,Ee.drawPositions).length===2)),ne=Rt==null?void 0:Rt[$t],Ae=zb({matchUpStatusCodes:wt,tournamentRecord:u,drawDefinition:mt,targetMatchUp:ne,matchUpFormat:Dt,matchUpStatus:yt,scoreString:Ut,winningSide:Ct});if(Ae!=null&&Ae.error)return Ae}}s&&Et({completeAllMatchUps:s})}k&&fu({tournamentRecord:u,event:z})}else{const ct=cm({drawEntries:mt.entries,drawName:D||S,qualifyingPositions:y,drawId:Mt,event:z,stage:F});if(ct.error)return ct}return{...$,event:bt(z),uniqueParticipantIds:Q,targetParticipants:q,drawDefinition:mt,eventId:W,drawId:Mt}}function BN({tournamentRecord:t,venueProfiles:e,uuids:n}){const{startDate:r,endDate:s}=t,i=[];for(const[o,c]of e.entries()){const{venueAbbreviation:a,venueId:u=(n==null?void 0:n.pop())||Yt(),dateAvailability:l,startTime:f="07:00",endTime:p="19:00",courtTimings:h,courtsCount:d,courtNames:m,venueName:g,idPrefix:I,courtIds:S}=c,T={venueName:g||`Venue ${o+1}`,venueAbbreviation:a,venueId:u},E=ma({tournamentRecord:t,venue:T});if(E.error)return E;i.push(u);const y=ef(r,s),b=!Array.isArray(l)&&[{startTime:f,endTime:p}].concat(y.map(A=>({date:Sr(A),startTime:f,endTime:p}))),N=Ah({dateAvailability:l||b,tournamentRecord:t,courtTimings:h,courtsCount:d,courtNames:m,startTime:f,idPrefix:I,courtIds:S,endTime:p,venueId:u,dates:y});if(N.error)return N}return i}function xB(t){var A,C,v;const{ratingsParameters:e=wr,participantsProfile:n={},matchUpStatusProfile:r,completeAllMatchUps:s,autoEntryPositions:i,hydrateCollections:o,randomWinningSide:c,schedulingProfile:a,tournamentRecord:u,eventProfiles:l,venueProfiles:f,autoSchedule:p,drawProfiles:h,uuids:d}=t;if(!u)return{error:et};const m=[],g=[],I=[];l==null||l.forEach(P=>{var O;const U=(O=u.events)==null?void 0:O.find((D,M)=>P.eventIndex!==void 0&&M===P.eventIndex||P.eventName&&D.eventName===P.eventName||P.eventId&&D.eventId===P.eventId);U!=null&&U.gender&&(P.gender=U.gender)});const S=((A=u.participants)==null?void 0:A.length)||void 0;S&&(n!=null&&n.idPrefix)&&(n.idPrefix=`${n.idPrefix}-${S}`);const T=wN({startDate:u.startDate,participantsProfile:n,tournamentRecord:u,eventProfiles:l,drawProfiles:h,uuids:d});if(!T.success)return T;if(l){let P=((C=u.events)==null?void 0:C.length)||0;for(const U of l){const{ratingsParameters:O}=U,D=(v=u.events)==null?void 0:v.find((M,w)=>U.eventIndex!==void 0&&w===U.eventIndex||U.eventName&&M.eventName===U.eventName||U.eventId&&M.eventId===U.eventId);if(D){const{gender:M,category:w,eventType:k}=D,{drawProfiles:_,publish:F}=U,L=k===ls&&xt||k===$n&&_t||k;if(_){const{stageParticipantsCount:W,uniqueParticipantsCount:j,uniqueParticipantStages:H}=_N({drawProfiles:_,category:w,gender:M}),{uniqueDrawParticipants:B=[],uniqueParticipantIds:R=[]}=H?kN({event:{eventType:k,category:w,gender:M},uniqueParticipantsCount:j,participantsProfile:n,ratingsParameters:O,tournamentRecord:u,eventProfile:U,uuids:d}):{};m.push(...R);const{stageParticipants:x}=FN({targetParticipants:u.participants||[],allUniqueParticipantIds:m,stageParticipantsCount:W,eventParticipantType:L});let q=LN({uniqueDrawParticipants:B,autoEntryPositions:i,stageParticipants:x,tournamentRecord:u,drawProfiles:_,category:w,gender:M,event:D});if(q.error||(q=ON({matchUpStatusProfile:r,completeAllMatchUps:s,randomWinningSide:c,tournamentRecord:u,drawProfiles:_,event:D}),q.error))return q;I.push(...q.drawIds)}F&&fu({tournamentRecord:u,event:D})}else{const M=RN({startDate:u.startDate,allUniqueParticipantIds:m,matchUpStatusProfile:r,participantsProfile:n,completeAllMatchUps:s,autoEntryPositions:i,randomWinningSide:c,ratingsParameters:O,tournamentRecord:u,eventProfile:U,eventIndex:P,uuids:d});if(M.error)return M;const{eventId:w,drawIds:k,uniqueParticipantIds:_}=M;k&&I.push(...k),g.push(w),_!=null&&_.length&&m.push(..._),P+=1}}}if(h){let P=(u.events||[]).map(U=>{var O;return((O=U.drawDefinitions)==null?void 0:O.map(()=>1))||[]}).flat().reduce((U,O)=>U+O,0);for(const U of h){let O=fm({startDate:u.startDate,allUniqueParticipantIds:m,matchUpStatusProfile:r,participantsProfile:n,completeAllMatchUps:s,autoEntryPositions:i,hydrateCollections:o,randomWinningSide:c,ratingsParameters:e,tournamentRecord:u,drawProfile:U,drawIndex:P,uuids:d});if(O.error)return O;const{drawId:D,eventId:M,event:w,uniqueParticipantIds:k}=O;if(O=Ed({tournamentRecord:u,event:w,internalUse:!0}),O.error)return O;D&&I.push(D),g.push(M),k!=null&&k.length&&m.push(...k),P+=1}}const E=f!=null&&f.length?BN({tournamentRecord:u,venueProfiles:f}):[];let y,b={};if(a!=null&&a.length){const P={[u.tournamentId]:u},U=nu({tournamentRecords:P,schedulingProfile:a});if(U.error)return U;if(p){const{tournamentId:O}=u,D={[O]:u};b=dh({tournamentRecords:D})}}return{totalParticipantsCount:u.participants.length,scheduledRounds:y,schedulerResult:b,...$,eventIds:g,venueIds:E,drawIds:I}}const $B={anonymizeTournamentRecord:FB,modifyTournamentRecord:xB};function VB({schedulingProfile:t,tournamentRecord:e}){if(typeof t!="object")return{error:tt};const n=Nc({tournamentRecord:e}).containedStructures,r=He({tournamentRecord:e}).matchUps||[],{tournamentId:s}=e,i=[];for(const o of t){const{scheduleDate:c,venues:a=[]}=o;for(const u of a){const{rounds:l,venueId:f}=u;for(const p of l){const{drawId:h,winnerFinishingPositionRange:d,roundSegment:m}=p,I=r.filter(S=>{var y;const T=(d==null?void 0:d.indexOf("-"))>0&&d.split("-").map(b=>+b),E=(y=S.finishingPositionRange)==null?void 0:y.winner;return S.drawId===h&&(!p.roundNumber||S.roundNumber===p.roundNumber)&&(!E||!T||qe(E,T).length===2||Vt(E).length===Vt(T).length&&qe(E,T).length===Vt(E).length)})[0];if(I){const{eventId:S,roundNumber:T,drawName:E,structureName:y,roundName:b}=I;let N=I.structureId;T&&!d&&(N=Object.keys(n).find(v=>n[v].includes(N))||N);const A={tournamentId:s,structureId:N,roundNumber:T,roundSegment:m,eventId:S,drawId:h},C=Ry({tournamentRecords:{[s]:e},round:A,scheduleDate:c,venueId:f});if(C.error)return C;i.push({structureName:y,roundName:b,drawName:E,...A})}}}}return{scheduledRounds:i}}const jB=["Mock Tournament","CourtHive Challenge","Racket Rally","Generated Tournament","Factory Follies","Open Competition"];function GB(t){let{tournamentAttributes:e,startDate:n,endDate:r}=t;const{tournamentName:s=cn(jB),ratingsParameters:i=wr,scheduleCompletedMatchUps:o,tournamentExtensions:c,matchUpStatusProfile:a,completeAllMatchUps:u,participantsProfile:l,autoEntryPositions:f,hydrateCollections:p,randomWinningSide:h,policyDefinitions:d,schedulingProfile:m,autoSchedule:g,eventProfiles:I,venueProfiles:S,drawProfiles:T,uuids:E}=t;if(n&&!Yn(n)||r&&!Yn(r))return{error:bn};if(I&&!Array.isArray(I))return{error:tt};if(!n){const O=new Date;n=Sr(r??O),r=Sr(O.setDate(O.getDate()+7))}if(!r){const O=new Date(n);r=Sr(O.setDate(O.getDate()+7))}typeof e!="object"&&(e={});const y=Jh({...e,tournamentName:s,startDate:n,endDate:r});if(c!=null&&c.length&&Array.isArray(c)){const O=c.filter(D=>ur({extension:D}));O!=null&&O.length&&Object.assign(y,{extensions:O,isMock:!0})}if(typeof d=="object")for(const O of Object.keys(d))gh({policyDefinitions:{[O]:d[O]},tournamentRecord:y});const b=wN({participantsProfile:l,tournamentRecord:y,eventProfiles:I,drawProfiles:T,startDate:n,uuids:E});if(!b.success)return b;const N=[],A=[],C=[];if(Array.isArray(T)){let O=0;for(const D of T){let M=fm({allUniqueParticipantIds:N,matchUpStatusProfile:a,participantsProfile:l,completeAllMatchUps:u,autoEntryPositions:f,hydrateCollections:p,randomWinningSide:h,ratingsParameters:i,tournamentRecord:y,isMock:!0,drawProfile:D,startDate:n,drawIndex:O,uuids:E});if(M.error)return M;const{drawId:w,eventId:k,event:_,uniqueParticipantIds:F}=M;if(M=Ed({suppressNotifications:!1,internalUse:!0,tournamentRecord:y,event:_}),M.error)return M;w&&C.push(w),A.push(k),F!=null&&F.length&&N.push(...F),O+=1}}if(I){let O=0;for(const D of I){const M=RN({allUniqueParticipantIds:N,matchUpStatusProfile:a,participantsProfile:l,completeAllMatchUps:u,autoEntryPositions:f,hydrateCollections:p,randomWinningSide:h,ratingsParameters:i,tournamentRecord:y,eventProfile:D,eventIndex:O,startDate:n,uuids:E});if(M.error)return M;const{eventId:w,drawIds:k,uniqueParticipantIds:_}=M;k&&C.push(...k),A.push(w),_!=null&&_.length&&N.push(..._),O+=1}}const v=S!=null&&S.length?BN({tournamentRecord:y,venueProfiles:S,uuids:E}):[];let P,U={};if(m){const O=VB({schedulingProfile:m,tournamentRecord:y});if(O.error)return O;if(P=O.scheduledRounds,g){const{tournamentId:D}=y,M={[D]:y};U=dh({scheduleCompletedMatchUps:o,tournamentRecords:M})}}return Kc(),bt({...$,tournamentRecord:y,scheduledRounds:P,schedulerResult:U,eventIds:A,venueIds:v,drawIds:C})}const WB={generateOutcomeFromScoreString:qb,generateTournamentRecord:GB,generateEventWithDraw:fm,generateParticipants:Nd,parseScoreString:vl,generateOutcome:Yb,credits:sd};let pm=!1;(()=>{const t={version:()=>Es(),setDeepCopy:(r,s)=>(Hi(r,s),t),devContext:r=>(zo(r),pm=!0,t)};return n([$B,WB]),t;function e(r,s){const i=r({...s});return i!=null&&i.error||Di(),fi(),pm&&(zo(!1),pm=!1),i}function n(r){r.forEach(s=>{Object.keys(s).forEach(i=>{t[i]=o=>{try{return e(s[i],o)}catch(c){let a;typeof c=="string"?a=c.toUpperCase():c instanceof Error&&(a=c.message),console.log("ERROR",{params:JSON.stringify(o),method:i,error:a})}}})})}})();const hm={hasAttributeValues:EC,extractAttributes:kn,structureSort:Pi,matchUpSort:vo,tidyScore:mM,generateScoreString:gs,calculateWinCriteria:gc,compareTieFormats:Sc,parseScoreString:vl,scoreHasValue:Be,getScaleValues:sc,proConflicts:hT,addExtension:ae,chunkArray:Ge,countValues:N1,dateRange:ef,dateTime:SC,roundRobinGroups:RO,definedAttributes:bt,dehydrateMatchUps:PO,findExtension:Ke,garman:kO,getTimeItem:kr,generateHashCode:bC,generateRange:ht,generateTimeCode:Lg,instanceCount:Mn,intersection:qe,isNumeric:Me,isConvertableInteger:oe,isPowerOf2:mr,JSON2CSV:NC,flattenJSON:of,makeDeepCopy:pt,nearestPowerOf2:Fd,nextPowerOf2:Vo,numericSort:Ve,overlap:tn,parseAgeCategoryCode:ST,randomMember:Dn,randomPop:cn,shuffleArray:on,isAdHoc:Qr,unique:Vt,UUID:Yt,UUIDS:AC,validateTieFormat:vn},HB=zt({WebkitBoxSizing:"border-box",marginInlineEnd:".3em",display:"inline-block",boxSizing:"border-box",position:"relative",borderRadius:2,variants:{variant:{doubles:{width:".75rem"},singles:{width:"1rem"}}}});function qB({matchUp:t,individualParticipant:e,spacer:n}){var c,a,u;const r=((c=e==null?void 0:e.person)==null?void 0:c.iso2NationalityCode)||"",s=r?(a=gO.countryToFlag(r))==null?void 0:a.slice(0,4):"",i=document.createElement("span"),o=(u=t==null?void 0:t.matchUpType)==null?void 0:u.toLowerCase();return n||(i.className=HB({variant:o})),i.innerHTML=n?"":s,i}function mm({individualParticipant:t,composition:e,className:n,matchUp:r,spacer:s,side:i,type:o}){if(o==="scale")return f1({individualParticipant:t,composition:e,className:n,matchUp:r,spacer:s});const c=(e==null?void 0:e.configuration)||{},a=document.createElement("div");return o==="flag"&&c.flags&&qB({className:n,matchUp:r,individualParticipant:t,spacer:s})||o==="seeding"&&l1({className:n,composition:e,matchUp:r,side:i})||a}const YB=zt({willChange:"opacity",position:"fixed",zIndex:9998,bottom:0,right:0,left:0,top:0}),zB=zt({display:"block"}),KB=zt({position:"fixed",right:0,left:0}),JB=zt({paddingRight:"15px",alignItems:"center",margin:"30px auto",paddingLeft:"15px",position:"fixed",height:"100vh",display:"flex",width:"100%",zIndex:9999,bottom:0,right:0,left:0,top:0}),QB=zt({boxShadow:"0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23)",backgroundColor:"white",position:"relative",borderRadius:"3px",minHeight:"auto",width:"100%"}),ZB=zt({borderBottom:"1px solid rgba(0, 0, 0, 0.1)",alignItems:"center",position:"relative",display:"flex"}),XB=zt({fontWeight:"600",fontSize:"20px"}),xN=zt({borderTop:"1px solid rgba(0, 0, 0, 0.1)",justifyContent:"right",alignItems:"center",position:"relative",display:"flex"}),$N="Nothing to see here";function Fr(t){return typeof t=="function"}function vd(t){return typeof t=="string"}function VN(t){return Array.isArray(t)}function gm(t){return typeof t=="object"&&!Array.isArray(t)}function t2(t){if(t)for(;t.firstChild;)t.removeChild(t.firstChild)}const Im=(()=>{const t=KB(),e={},n=".5";let r=[],s,i=[],o=[],c;const a=I=>{if(I){let S;o=o.filter(T=>(T.id===I&&(S=T),T.id!==I)),S&&document.body.removeChild(S)}else{const S=o.pop();S&&document.body.removeChild(S)}},u=()=>{c&&(c.style.opacity=0,c.style.display="none")},l=I=>{const S=o.length;if(I&&e[S]===!1)return;const T=i.pop(),E=r.pop();Fr(T)&&T({content:E}),document.body.classList.remove(t),document.body.style.top=null,window.scrollTo({top:s,behavior:"instant"}),u(),a()},f=()=>{c=document.createElement("div"),c.className=YB(),c.id="cmdl-backdrop",c.onclick=()=>l(!0),document.body.appendChild(c)},p=({config:I})=>{s=window.scrollY,document.body.classList.add(t),document.body.style.top=`-${s}px`,c||f(),c.style.display="",(I==null?void 0:I.backdrop)!==!1&&(c.style.backgroundColor="rgba(0, 0, 0, 0.2)",c.style.transition="opacity 0.15s linear",c.style.opacity=1)},h=({config:I,attr:S})=>{if(!vd(S))return;const T=S.split(".");for(const E of T)if(I=I==null?void 0:I[E],!I)return;return I},d=({config:I,attr:S,attrs:T,unit:E="em",value:y})=>{var N;let b;return vd(S)?b=h({config:I,attr:S}):VN(T)&&(b=(N=T.map(A=>h({config:I,attr:A})).filter(Boolean))==null?void 0:N[0]),b!==void 0&&(y=b),isNaN(y)?y:`${y}${E}`},m=({buttons:I,config:S,modalNumber:T})=>{var b,N;const E=document.createElement("div");E.className=xN(),E.style.padding=d({config:S,attrs:["footer.padding","padding"],value:n});const y={label:((b=S==null?void 0:S.dictionary)==null?void 0:b.close)||"Close",onClick:Im.close,intent:"is-info"};for(const A of I){if(A.hide)continue;const C=Object.assign({},y);gm(A)&&Object.assign(C,A);const v=document.createElement("button");C.disabled!==void 0&&(v.disabled=C.disabled),C.id&&(v.id=C.id),v.className=((N=C==null?void 0:C.footer)==null?void 0:N.className)||"button font-medium",v.classList.add(C.intent),v.style="margin-right: .5em;",v.innerHTML=C.label||C.text,v.onclick=P=>{P.stopPropagation(),Fr(C.onClick)&&C.onClick({e:P,content:r[T]}),C.close!==!1&&(Fr(C.close)&&C.close(),Im.close())},E.appendChild(v)}return E};return{close:l,open:({title:I="",content:S,buttons:T,footer:E,config:y,onClose:b}={})=>{p({config:y}),i.push(b);const N=o.length+1;e[N]=y==null?void 0:y.clickAway;const A=document.createElement("section"),C=`cmdl-${N}`;A.className=zB(),A.role="dialog",A.tabIndex=-1,A.id=C;const v=document.createElement("div");v.className=JB(),v.style.maxWidth=`${(y==null?void 0:y.maxWidth)||450}px`,v.onclick=()=>l(!0);const P=document.createElement("div");P.className=QB(),P.onclick=W=>W.stopPropagation();const U=document.createElement("div"),O=document.createElement("div");U.appendChild(O),P.appendChild(U);const D=({title:W,config:j})=>{U.className=W?ZB():"",U.style.padding=d({config:j,attrs:["title.padding","padding"],value:n}),O.className=W?XB():"",O.innerHTML=W};I&&D({title:I});const M=document.createElement("div");P.appendChild(M);const w=({content:W,config:j})=>{M.style.fontSize=d({config:j,attr:"fontSize",value:"15px"}),M.style.position="relative",M.style.padding=d({config:j,attrs:["content.padding","padding"],value:n}),Fr(W)?r[N]=W(M):gm(W)?M.appendChild(W):vd(W)?M.innerHTML=W:M.innerHTML=$N};if(w({content:S,config:y}),VN(T))E=m({buttons:T,config:y,modalNumber:N}),P.appendChild(E);else if(E){const W=document.createElement("div");W.className=xN(),W.style.padding=d({config:y,attrs:["footer.padding","padding"]}),gm(E)?W.appendChild(E):vd(E)?W.innerHTML=E:W.innerHTML=$N,P.appendChild(W)}v.appendChild(P),A.appendChild(v),document.body.appendChild(A),o.push(A);const k=({content:W,config:j})=>{r[N]=void 0,t2(M),w({content:W,config:j})},_=({buttons:W,config:j})=>{P.removeChild(E),E=m({buttons:W,config:j,modalNumber:N}),P.appendChild(E)},F=({onClose:W})=>{i.length=0,i.push(W)};return{setContent:k,setButtons:_,update:({content:W,buttons:j,title:H,config:B,onClose:R})=>{y=B||y,W&&k({content:W,config:y}),j&&_({buttons:j,config:y}),R&&F({onClose:R}),H&&D({title:H,config:y})}}}}})(),e2="Qualifier",n2="BYE",r2="TBD";function jN(t){var T;const{isWinningSide:e,side:n,sideNumber:r,individualParticipant:s,matchUp:i,composition:o}=t||{},c=e?"winner":void 0,a=t.eventHandlers||{},u=o==null?void 0:o.configuration,l=s==null?void 0:s.participantName,f=E=>{Fr(a==null?void 0:a.participantClick)&&(E.stopPropagation(),a.participantClick({individualParticipant:s,pointerEvent:E,matchUp:i,side:n}))},p=document.createElement("div");p.classList.add("tmx-i"),p.setAttribute("sideNumber",r),p.setAttribute("id",s==null?void 0:s.participantId),p.onclick=f;const h=document.createElement("div");h.className=XA({variant:c});const m=(u==null?void 0:u.flags)&&mm({...t,type:"flag"});if(m)h.appendChild(m);else{const E=mm({type:"scale",...t});E&&h.appendChild(E)}const g=document.createElement("div");if(g.className=t1({variant:c}),l){const E=document.createElement("span");if(e&&(u!=null&&u.winnerColor))E.style.color=typeof u.winnerColor=="string"?u.winnerColor:"green";else if(u!=null&&u.genderColor){const y=(T=s==null?void 0:s.person)==null?void 0:T.sex,b=y==="MALE"&&"#2E86C1"||y==="FEMALE"&&"#AA336A"||"";E.style.color=typeof u.genderColor=="string"?u.genderColor:b}E.innerHTML=l,g.appendChild(E)}else{const E=document.createElement("abbr");E.className=ZA({variant:u.showAddress?"showAddress":""}),E.innerHTML=(n==null?void 0:n.bye)&&n2||(n==null?void 0:n.qualifier)&&e2||r2,g.appendChild(E)}const I=mm({...t,className:u1(),type:"seeding"});I&&g.appendChild(I),h.appendChild(g),p.appendChild(h);const S=a1(t);return p.appendChild(S),{element:p}}const s2=zt({width:"auto",display:"inline-block",textTransform:"uppercase",fontFamily:"Sharp Sans, Arial, sans-serif",fontSize:"0.625rem",lineHeight:"1rem",marginInline:"0.25rem 0.25rem",paddingInline:"0.25rem 0.25rem",fontWeight:700,borderRadius:"4px",color:"#fff",textAlign:"center",whiteSpace:"nowrap",variants:{variant:{defaulted:{backgroundColor:"#df164c"},retired:{backgroundColor:"#df164c"},walkover:{backgroundColor:"black"},double_walkover:{backgroundColor:"black"}}}});function i2({matchUpStatus:t}){const e=t==null?void 0:t.toLowerCase(),n=["WALKOVER","DOUBLE_WALKOVER"].includes(t)?"WO":(t==null?void 0:t.slice(0,3))||"",r=document.createElement("div");r.className=s2({variant:e});const s=document.createElement("abbr");return s.setAttribute("title",t),s.style.textDecoration="none",s.style.borderBottom="none",s.innerHTML=n,r.appendChild(s),r}const o2=zt({marginInlineEnd:".5rem",backgroundColor:"pink",marginInlineStart:2,height:40,width:40});function c2({teamLogo:t}){console.log({teamLogo:t});const e=document.createElement("div");return e.className=o2(),e}const a2=zt({flexDirection:"column",position:"relative",display:"flex"}),u2=zt({alignItems:"stretch",display:"flex"}),l2=zt({marginInlineEnd:".25rem",color:"green"});function d2({dim:t="20px"}={}){const e=l2();return`
27
27
  <div style="line-height: 0;">
28
28
  <svg height="${t}" viewBox="0 0 18 24" width="${t}" xmlns="http://www.w3.org/2000/svg" class="${e}" style="fill: currentcolor;">
29
29
  <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"></path>
30
30
  </svg>
31
31
  </div>
32
- `}function GN({eventHandlers:t,sideContainer:e,composition:n,participant:r,placeholder:s,sideNumber:i,matchUp:o}){var v,P,U;const{winningSide:c,matchUpType:a,isRoundRobin:u,matchUpStatus:l}=o||{},f=n==null?void 0:n.configuration;let p;const h=i?(v=o==null?void 0:o.sides)==null?void 0:v.find(O=>O.sideNumber===i):void 0;r||(r=h==null?void 0:h.participant,p=f!=null&&f.allDrawPositions||f!=null&&f.drawPositions&&(h!=null&&h.drawPosition)&&((o==null?void 0:o.roundNumber)===1||h!=null&&h.participantFed||u)?h==null?void 0:h.drawPosition:"");const d=a==="DOUBLES",m=d?(P=r==null?void 0:r.individualParticipants)==null?void 0:P[0]:r,g=d&&((U=r==null?void 0:r.individualParticipants)==null?void 0:U[1]),I=i===c||l==="BYE"&&r,S=(f==null?void 0:f.winnerChevron)&&I,T=f==null?void 0:f.teamLogo,E=["RETIRED","DOUBLE_WALKOVER","WALKOVER","DEFAULTED"].includes(l)&&!I,y=f==null?void 0:f.gameScoreOnly,b=document.createElement("div");if(b.className=e&&n1({drawPosition:p,sideNumber:i}),b.classList.add("tmx-p"),r!=null&&r.participantId&&b.setAttribute("id",r.participantId),T){const O=c2({teamLogo:T});b.appendChild(O)}const N=document.createElement("div");N.className=e1({variant:d?"doubles":"singles"});const A=document.createElement("div");A.className=r1({winnerChevron:S,isDoubles:d});const C=jN({individualParticipant:m,eventHandlers:t,isWinningSide:I,composition:n,sideNumber:i,matchUp:o,side:h}).element;if(A.appendChild(C),g){const O=jN({individualParticipant:g,eventHandlers:t,isWinningSide:I,composition:n,sideNumber:i,matchUp:o,side:h}).element;A.appendChild(O)}else d&&s&&A.appendChild(s);if(N.appendChild(A),b.appendChild(N),e){const O=document.createElement("div");if(I&&!y){const D=d2();typeof D=="string"?O.innerHTML=D:O.appendChild(D)}else if(E){const D=i2({matchUpStatus:l});O.appendChild(D)}b.appendChild(O)}return b}const f2=zt({borderBottom:"solid 1px black",marginInlineStart:"16px",marginInlineEnd:"16px",fontWeight:"bold",width:"460px",height:"1.5em"});function WN({eventHandlers:t,roundMatchUps:e,roundProfile:n,roundNumber:r,context:s}){var l;const i=document.createElement("div");i.className=f2(),i.classList.add("tmx-rh"),i.setAttribute("roundNumber",r);const o=Fr(t==null?void 0:t.roundHeaderClick);o&&(i.onclick=f=>t.roundHeaderClick({roundNumber:r,roundProfile:n,roundMatchUps:e,context:s,pointerEvent:f}));const c=o?"⋮":"",a=(l=n==null?void 0:n[r])==null?void 0:l.roundName,u=a&&` <div style="display: flex; flex-direction: row; justify-content: space-between">
32
+ `}function GN({eventHandlers:t,sideContainer:e,composition:n,participant:r,placeholder:s,sideNumber:i,matchUp:o}){var v,P,U;const{winningSide:c,matchUpType:a,isRoundRobin:u,matchUpStatus:l}=o||{},f=n==null?void 0:n.configuration;let p;const h=i?(v=o==null?void 0:o.sides)==null?void 0:v.find(O=>O.sideNumber===i):void 0;r||(r=h==null?void 0:h.participant,p=f!=null&&f.allDrawPositions||f!=null&&f.drawPositions&&(h!=null&&h.drawPosition)&&((o==null?void 0:o.roundNumber)===1||h!=null&&h.participantFed||u)?h==null?void 0:h.drawPosition:"");const d=a==="DOUBLES",m=d?(P=r==null?void 0:r.individualParticipants)==null?void 0:P[0]:r,g=d&&((U=r==null?void 0:r.individualParticipants)==null?void 0:U[1]),I=i===c||l==="BYE"&&r,S=(f==null?void 0:f.winnerChevron)&&I,T=f==null?void 0:f.teamLogo,E=["RETIRED","DOUBLE_WALKOVER","WALKOVER","DEFAULTED"].includes(l)&&!I,y=f==null?void 0:f.gameScoreOnly,b=document.createElement("div");if(b.className=e&&n1({drawPosition:p,sideNumber:i}),b.classList.add("tmx-p"),b.setAttribute("id",r==null?void 0:r.participantId),T){const O=c2({teamLogo:T});b.appendChild(O)}const N=document.createElement("div");N.className=e1({variant:d?"doubles":"singles"});const A=document.createElement("div");A.className=r1({winnerChevron:S,isDoubles:d});const C=jN({individualParticipant:m,eventHandlers:t,isWinningSide:I,composition:n,sideNumber:i,matchUp:o,side:h}).element;if(A.appendChild(C),g){const O=jN({individualParticipant:g,eventHandlers:t,isWinningSide:I,composition:n,sideNumber:i,matchUp:o,side:h}).element;A.appendChild(O)}else d&&s&&A.appendChild(s);if(N.appendChild(A),b.appendChild(N),e){const O=document.createElement("div");if(I&&!y){const D=d2();typeof D=="string"?O.innerHTML=D:O.appendChild(D)}else if(E){const D=i2({matchUpStatus:l});O.appendChild(D)}b.appendChild(O)}return b}const f2=zt({borderBottom:"solid 1px black",marginInlineStart:"16px",marginInlineEnd:"16px",fontWeight:"bold",width:"460px",height:"1.5em"});function WN({eventHandlers:t,roundMatchUps:e,roundProfile:n,roundNumber:r,context:s}){var l;const i=document.createElement("div");i.className=f2(),i.classList.add("tmx-rh"),i.setAttribute("roundNumber",r);const o=Fr(t==null?void 0:t.roundHeaderClick);o&&(i.onclick=f=>t.roundHeaderClick({roundNumber:r,roundProfile:n,roundMatchUps:e,context:s,pointerEvent:f}));const c=o?"⋮":"",a=(l=n==null?void 0:n[r])==null?void 0:l.roundName,u=a&&` <div style="display: flex; flex-direction: row; justify-content: space-between">
33
33
  <div>${a}</div>
34
34
  <div style="font-weight: bold">${c}</div>
35
35
  </div>
36
- `;return i.innerHTML=u||"",i}const HN=zt({flexDirection:"column",display:"flex"}),p2=zt({flexDirection:"row",display:"flex"}),qN=zt({justifyContent:"space-around",marginInlineStart:"16px",marginInlineEnd:"16px",flexDirection:"column",height:"100%",display:"flex",width:"460px",variants:{variant:{adHoc:{justifyContent:"flex-start"}}}}),h2=zt({borderTop:"solid 1px black",marginRight:"-1em",marginLeft:"-1em",paddingTop:".5em",marginTop:".2em",variants:{variant:{0:{marginTop:"1em",borderTop:"none",paddingTop:"0px"}},roundOrder:{first:{marginLeft:"0em"},last:{marginRight:"0em"}}}}),m2=zt({fontWeight:"bold",color:"blue",height:"1em"}),YN=zt({width:"$score$setWidth",display:"inline-block",fontSize:9,variants:{variant:{set:{textAlign:"center"},points:{marginInlineEnd:3}}}}),g2=zt({transform:"translateY(-50%)",textTransform:"uppercase",backgroundColor:"#fff",position:"absolute",textAlign:"center",top:"calc(50%)",color:"#bbb",fontSize:0,right:4});function I2(){return zt({backgroundColor:"magenta",position:"absolute",opacity:"0.2",height:"100%",width:"100%",top:0})}const S2=zt({});function T2({configuration:t}){const e={backgroundColor:"$matchUpBackgroundColor",WebkitTransition:"all 0.30s linear",boxShadow:"$matchUp$boxShadow",transition:"all 0.30s linear",border:"solid $border",marginBottom:"$space$1",marginTop:"$space$1",position:"relative",display:"grid",width:"100%",borderInlineStartWidth:"$borderWidths$borderInlineStart"};if(t!=null&&t.matchUpHover){const n=typeof t.matchUpHover=="string"?t.matchUpHover:"cyan";e["&:hover"]={backgroundColor:n}}else e["&:hover"]={borderColor:"$borderHover"};return zt(e)}function y2({variant:t}){return zt({borderBottom:"solid 1px lightgray",backgroundColor:"$matchUp",position:"relative",width:"100%",height:"$lineHeights$centerInfo",variants:{variant:{1:{borderBottom:"solid 1px black"},2:{borderBottom:"solid 1px lightgray"}}}})({variant:t})}const E2=zt({justifyContent:"center",alignContent:"center",flexDirection:"column",height:"100%",display:"flex"}),b2=zt({fontFamily:"Lato,Arial,Helvetica,sans-serif",WebkitFontSmooting:"antialiased",marginInlineStart:"calc(20%)",WebkitBoxOrient:"horizontal",WebKitBoxDirection:"normal",WebkitBoxPack:"center",boxSizing:"inherit",flexDirection:"row",display:"flex"}),zN=zt({alignContent:"center",boxSizing:"inherit",fontFamily:"Lato",fontWeight:900,fontSize:9});function N2({eventHandlers:t,entryStatus:e,sideNumber:n,className:r,matchUp:s}){const i=document.createElement("div");Fr(t==null?void 0:t.centerInfoClick)&&(i.onclick=l=>t.centerInfoClick({matchUp:s,sideNumber:n,pointerEvent:l})),i.className=ji(y2({variant:n}),r),i.classList.add("tmx-ci"),i.setAttribute("sideNumber",n);const o=document.createElement("div");o.className=E2();const c=document.createElement("div");c.className=b2();const a=document.createElement("div");a.className=zN(),a.innerHTML=e?"Entry status:&nbsp;":"",c.appendChild(a);const u=document.createElement("div");return u.className=zN(),u.innerHTML=e||"",c.appendChild(u),o.appendChild(c),i.appendChild(o),{element:i}}const mu={scheduleInfo:1.8,centerInfo:1.5,gameScore:2};function A2({composition:t,isDoubles:e,roundFactor:n=1}){const r=parseInt(window.getComputedStyle(document.body).getPropertyValue("font-size")),s=(t==null?void 0:t.configuration)||{},i=(s==null?void 0:s.connectorWidth)||16,o=s.centerInfo?mu.centerInfo*r:0,c=s.scheduleInfo?mu.scheduleInfo*r:0,u=(60+(s.showAddress?r:0))*(e?1.3:1)+o,l=u*n,f=(u+c)*n;return zt({"&::before":{borderBlockStart:"$borderWidths$matchUp solid #999",left:-i,width:i,position:"absolute",borderRadius:2,top:-1},"&::after":{width:i,position:"absolute",borderRadius:2,left:"100%"},"&::after, &::before":{borderWidth:"$borderWidths$matchUp",borderColor:"$connector",display:"block",content:""},variants:{isFirstRound:{true:{"&::before":{height:0,width:0,borderWidth:0}}},link:{m1:{"&::after":{borderInlineEnd:"$borderWidths$matchUp solid $connector",borderTopStyle:"solid",height:l,top:-1}},m2:{"&::after":{bottom:"calc(100%)",borderInlineEnd:"$borderWidths$matchUp solid $connector",borderBottomStyle:"solid",height:f}},m0:{"&::after":{borderTopStyle:"solid",borderColor:"$connector",top:-1}},mr:{"&::before":{height:0,width:0,borderWidth:0},"&::after":{height:0,width:0,borderWidth:0}},noProgression:{true:{"&::after":{height:0,width:0,borderWidth:0}}}}}})}const KN=t=>zt({display:"flex",alignItems:"center",height:t,justifyContent:"flex-end",backgroundColor:"$matchUp",variants:{sideNumber:{1:{borderBottom:"1px solid $internalDividers"}},fontSize:{small:{fontSize:"smaller",paddingRight:"1em",color:"blue"}}}}),v2=zt({lineHeight:"0.75rem",fontSize:"0.625rem",left:"1.1rem",top:".4rem"}),JN=zt({lineHeight:"$lineHeights$gameScore",justifyContent:"center",width:"$score$setWidth",position:"relative",textAlign:"center",cursor:"pointer",fontWeight:500,fontSize:"$1",display:"flex",margin:0,variants:{variant:{winner:{color:"$winner!important",fontWeight:700},loser:{color:"$loser!important"}}}}),C2=zt({marginInlineEnd:"$space$gameMarginInlineEnd",justifyContent:"flex-end",alignItems:"center",display:"flex"});function P2({value:t}={}){const e=document.createElement("input");return e.onclick=n=>n.target.select(),e.className=JN(),e.value=t,e}function U2({gameScoreOnly:t,scoreStripes:e,set:n,sideNumber:r}){const i=r===(n==null?void 0:n.winningSide)||n!=null&&n.winningSide?"loser":void 0,o=r===2?n.side2Score:n.side1Score,c=n.side2TiebreakScore||n.side1TiebreakScore,a=r===2?n.side2TiebreakScore:n.side1TiebreakScore,u=o===void 0&&a,l=u||o,f=e&&n.setNumber%2?"lightgray":"transparent",h=n.editing?n.editing===r:void 0;let d;if(h)d=P2({value:l});else if(d=document.createElement("p"),d.className=JN({variant:i}),d.classList.add("tmx-st"),d.setAttribute("setNumber",n.setNumber),d.style.backgroundColor=f,d.innerHTML=isNaN(l)?"":l,!t){const m=document.createElement("span");m.className=v2(),m.innerHTML=c&&!u?a:"",d.appendChild(m)}return d}function O2({participantHeight:t,eventHandlers:e,composition:n,sideNumber:r,matchUp:s}){var d,m,g,I;const i=(d=n==null?void 0:n.configuration)==null?void 0:d.winnerChevron,o=(m=n==null?void 0:n.configuration)==null?void 0:m.gameScoreOnly,c=((g=s==null?void 0:s.score)==null?void 0:g.sets)||[],a=(I=n==null?void 0:n.configuration)==null?void 0:I.scoreBox,u=r===2?t:t-1,l=KN(u),f=S=>{Fr(e==null?void 0:e.scoreClick)&&(S.stopPropagation(),e.scoreClick({pointerEvent:S,matchUp:s}))},p=document.createElement("div");p.className=l({sideNumber:!a&&r,fontSize:"5px"}),p.classList.add("sideScore"),p.classList.add("tmx-scr"),p.onclick=f;const h=document.createElement("div");h.className=C2();for(const S of c||[]){const T=U2({gameScoreOnly:o,scoreStripes:i,sideNumber:r,set:S});h.appendChild(T)}return p.appendChild(h),p}const M2=zt({height:"$lineHeights$scheduleInfo",borderBottom:"1px solid darkgray",justifyContent:"space-between",backgroundColor:"#F8F9F9",boxSizing:"border-box",paddingRight:"0.2rem",paddingLeft:"0.5rem",alignItems:"center",cursor:"pointer",color:"#7F8080",display:"flex",width:"100%"});var QN={exports:{}};(function(t,e){(function(n,r){t.exports=r()})(s1,function(){var n=1e3,r=6e4,s=36e5,i="millisecond",o="second",c="minute",a="hour",u="day",l="week",f="month",p="quarter",h="year",d="date",m="Invalid Date",g=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,I=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,S={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(D){var M=["th","st","nd","rd"],w=D%100;return"["+D+(M[(w-20)%10]||M[w]||M[0])+"]"}},T=function(D,M,w){var k=String(D);return!k||k.length>=M?D:""+Array(M+1-k.length).join(w)+D},E={s:T,z:function(D){var M=-D.utcOffset(),w=Math.abs(M),k=Math.floor(w/60),_=w%60;return(M<=0?"+":"-")+T(k,2,"0")+":"+T(_,2,"0")},m:function D(M,w){if(M.date()<w.date())return-D(w,M);var k=12*(w.year()-M.year())+(w.month()-M.month()),_=M.clone().add(k,f),F=w-_<0,L=M.clone().add(k+(F?-1:1),f);return+(-(k+(w-_)/(F?_-L:L-_))||0)},a:function(D){return D<0?Math.ceil(D)||0:Math.floor(D)},p:function(D){return{M:f,y:h,w:l,d:u,D:d,h:a,m:c,s:o,ms:i,Q:p}[D]||String(D||"").toLowerCase().replace(/s$/,"")},u:function(D){return D===void 0}},y="en",b={};b[y]=S;var N="$isDayjsObject",A=function(D){return D instanceof U||!(!D||!D[N])},C=function D(M,w,k){var _;if(!M)return y;if(typeof M=="string"){var F=M.toLowerCase();b[F]&&(_=F),w&&(b[F]=w,_=F);var L=M.split("-");if(!_&&L.length>1)return D(L[0])}else{var W=M.name;b[W]=M,_=W}return!k&&_&&(y=_),_||!k&&y},v=function(D,M){if(A(D))return D.clone();var w=typeof M=="object"?M:{};return w.date=D,w.args=arguments,new U(w)},P=E;P.l=C,P.i=A,P.w=function(D,M){return v(D,{locale:M.$L,utc:M.$u,x:M.$x,$offset:M.$offset})};var U=function(){function D(w){this.$L=C(w.locale,null,!0),this.parse(w),this.$x=this.$x||w.x||{},this[N]=!0}var M=D.prototype;return M.parse=function(w){this.$d=function(k){var _=k.date,F=k.utc;if(_===null)return new Date(NaN);if(P.u(_))return new Date;if(_ instanceof Date)return new Date(_);if(typeof _=="string"&&!/Z$/i.test(_)){var L=_.match(g);if(L){var W=L[2]-1||0,j=(L[7]||"0").substring(0,3);return F?new Date(Date.UTC(L[1],W,L[3]||1,L[4]||0,L[5]||0,L[6]||0,j)):new Date(L[1],W,L[3]||1,L[4]||0,L[5]||0,L[6]||0,j)}}return new Date(_)}(w),this.init()},M.init=function(){var w=this.$d;this.$y=w.getFullYear(),this.$M=w.getMonth(),this.$D=w.getDate(),this.$W=w.getDay(),this.$H=w.getHours(),this.$m=w.getMinutes(),this.$s=w.getSeconds(),this.$ms=w.getMilliseconds()},M.$utils=function(){return P},M.isValid=function(){return this.$d.toString()!==m},M.isSame=function(w,k){var _=v(w);return this.startOf(k)<=_&&_<=this.endOf(k)},M.isAfter=function(w,k){return v(w)<this.startOf(k)},M.isBefore=function(w,k){return this.endOf(k)<v(w)},M.$g=function(w,k,_){return P.u(w)?this[k]:this.set(_,w)},M.unix=function(){return Math.floor(this.valueOf()/1e3)},M.valueOf=function(){return this.$d.getTime()},M.startOf=function(w,k){var _=this,F=!!P.u(k)||k,L=P.p(w),W=function(Y,z){var J=P.w(_.$u?Date.UTC(_.$y,z,Y):new Date(_.$y,z,Y),_);return F?J:J.endOf(u)},j=function(Y,z){return P.w(_.toDate()[Y].apply(_.toDate("s"),(F?[0,0,0,0]:[23,59,59,999]).slice(z)),_)},H=this.$W,B=this.$M,R=this.$D,x="set"+(this.$u?"UTC":"");switch(L){case h:return F?W(1,0):W(31,11);case f:return F?W(1,B):W(0,B+1);case l:var q=this.$locale().weekStart||0,V=(H<q?H+7:H)-q;return W(F?R-V:R+(6-V),B);case u:case d:return j(x+"Hours",0);case a:return j(x+"Minutes",1);case c:return j(x+"Seconds",2);case o:return j(x+"Milliseconds",3);default:return this.clone()}},M.endOf=function(w){return this.startOf(w,!1)},M.$set=function(w,k){var _,F=P.p(w),L="set"+(this.$u?"UTC":""),W=(_={},_[u]=L+"Date",_[d]=L+"Date",_[f]=L+"Month",_[h]=L+"FullYear",_[a]=L+"Hours",_[c]=L+"Minutes",_[o]=L+"Seconds",_[i]=L+"Milliseconds",_)[F],j=F===u?this.$D+(k-this.$W):k;if(F===f||F===h){var H=this.clone().set(d,1);H.$d[W](j),H.init(),this.$d=H.set(d,Math.min(this.$D,H.daysInMonth())).$d}else W&&this.$d[W](j);return this.init(),this},M.set=function(w,k){return this.clone().$set(w,k)},M.get=function(w){return this[P.p(w)]()},M.add=function(w,k){var _,F=this;w=Number(w);var L=P.p(k),W=function(B){var R=v(F);return P.w(R.date(R.date()+Math.round(B*w)),F)};if(L===f)return this.set(f,this.$M+w);if(L===h)return this.set(h,this.$y+w);if(L===u)return W(1);if(L===l)return W(7);var j=(_={},_[c]=r,_[a]=s,_[o]=n,_)[L]||1,H=this.$d.getTime()+w*j;return P.w(H,this)},M.subtract=function(w,k){return this.add(-1*w,k)},M.format=function(w){var k=this,_=this.$locale();if(!this.isValid())return _.invalidDate||m;var F=w||"YYYY-MM-DDTHH:mm:ssZ",L=P.z(this),W=this.$H,j=this.$m,H=this.$M,B=_.weekdays,R=_.months,x=_.meridiem,q=function(z,J,Q,X){return z&&(z[J]||z(k,F))||Q[J].slice(0,X)},V=function(z){return P.s(W%12||12,z,"0")},Y=x||function(z,J,Q){var X=z<12?"AM":"PM";return Q?X.toLowerCase():X};return F.replace(I,function(z,J){return J||function(Q){switch(Q){case"YY":return String(k.$y).slice(-2);case"YYYY":return P.s(k.$y,4,"0");case"M":return H+1;case"MM":return P.s(H+1,2,"0");case"MMM":return q(_.monthsShort,H,R,3);case"MMMM":return q(R,H);case"D":return k.$D;case"DD":return P.s(k.$D,2,"0");case"d":return String(k.$W);case"dd":return q(_.weekdaysMin,k.$W,B,2);case"ddd":return q(_.weekdaysShort,k.$W,B,3);case"dddd":return B[k.$W];case"H":return String(W);case"HH":return P.s(W,2,"0");case"h":return V(1);case"hh":return V(2);case"a":return Y(W,j,!0);case"A":return Y(W,j,!1);case"m":return String(j);case"mm":return P.s(j,2,"0");case"s":return String(k.$s);case"ss":return P.s(k.$s,2,"0");case"SSS":return P.s(k.$ms,3,"0");case"Z":return L}return null}(z)||L.replace(":","")})},M.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},M.diff=function(w,k,_){var F,L=this,W=P.p(k),j=v(w),H=(j.utcOffset()-this.utcOffset())*r,B=this-j,R=function(){return P.m(L,j)};switch(W){case h:F=R()/12;break;case f:F=R();break;case p:F=R()/3;break;case l:F=(B-H)/6048e5;break;case u:F=(B-H)/864e5;break;case a:F=B/s;break;case c:F=B/r;break;case o:F=B/n;break;default:F=B}return _?F:P.a(F)},M.daysInMonth=function(){return this.endOf(f).$D},M.$locale=function(){return b[this.$L]},M.locale=function(w,k){if(!w)return this.$L;var _=this.clone(),F=C(w,k,!0);return F&&(_.$L=F),_},M.clone=function(){return P.w(this.$d,this)},M.toDate=function(){return new Date(this.valueOf())},M.toJSON=function(){return this.isValid()?this.toISOString():null},M.toISOString=function(){return this.$d.toISOString()},M.toString=function(){return this.$d.toUTCString()},D}(),O=U.prototype;return v.prototype=O,[["$ms",i],["$s",o],["$m",c],["$H",a],["$W",u],["$M",f],["$y",h],["$D",d]].forEach(function(D){O[D[1]]=function(M){return this.$g(M,D[0],D[1])}}),v.extend=function(D,M){return D.$i||(D(M,U,v),D.$i=!0),v},v.locale=C,v.isDayjs=A,v.unix=function(D){return v(1e3*D)},v.en=b[y],v.Ls=b,v.p={},v})})(QN);var D2=QN.exports;const w2=Om(D2);function k2({matchUp:t,eventHandlers:e}){const{scheduledTime:n,scheduledDate:r,venueAbbreviation:s,courtName:i}=(t==null?void 0:t.schedule)||{},{dateTime:{extractDate:o,extractTime:c}}=hm,a=c(n);let l=o(r),f="ddd D MMMM";a&&(f+=", hh:mm A",l+=`T${a}`);const p=r?w2(l).format(f):"Not scheduled",h=s&&(i==null?void 0:i.toString().startsWith(s))&&i||s&&i&&`${s} ${i}`||i||s||"",d=document.createElement("div");d.className=M2(),d.classList.add("tmx-sch"),Fr(e==null?void 0:e.scheduleClick)&&(d.onclick=T=>e.scheduleClick({matchUp:t,pointerEvent:T}));const m=document.createElement("div");m.innerHTML=p,d.append(m);const g=T=>{Fr(e==null?void 0:e.venueClick)&&(T.stopPropagation(),e.venueClick({pointerEvent:T,matchUp:t}))},I=document.createElement("div");I.style="display: flex; flex-direction: row";const S=document.createElement("div");if(S.style.paddingRight=".2rem",S.onclick=g,S.innerHTML=h,I.append(S),d.append(I),d.onclick){const T=document.createElement("div");T.innerHTML="⋮",I.append(T)}return d}function ZN({eventHandlers:t,composition:e,sideNumber:n,className:r,matchUp:s}){var h,d;const i=(e==null?void 0:e.configuration)||{},o=i==null?void 0:i.scheduleInfo,c=(h=s==null?void 0:s.score)==null?void 0:h.scoreStringSide1,a=((d=e==null?void 0:e.configuration)==null?void 0:d.scoreBox)&&c,u=(s==null?void 0:s.readyToScore)&&(t==null?void 0:t.scoreClick)&&!hm.scoreHasValue({matchUp:s}),l=document.createElement("div");if(l.className=ji(a2(),r),l.classList.add("tmx-sd"),l.setAttribute("sideNumber",n),o&&n===1){const m=k2({matchUp:s,eventHandlers:t});l.appendChild(m)}const f=document.createElement("div");f.className=u2();const p=GN({sideContainer:!0,eventHandlers:t,composition:e,sideNumber:n,matchUp:s});if(f.appendChild(p),a){const m=document.createElement("div");m.style.border="1px solid lightgray",f.appendChild(m)}if(c){const m=O2({eventHandlers:t,composition:e,sideNumber:n,matchUp:s});f.appendChild(m)}if(u){const m=KN(),g=S=>{Fr(t==null?void 0:t.scoreClick)&&(event.stopPropagation(),t.scoreClick({pointerEvent:S,matchUp:s}))},I=document.createElement("div");I.className=m({sideNumber:!a&&n,fontSize:"small"}),I.onclick=g,I.innerHTML="[Score]",f.appendChild(I)}return l.appendChild(f),l}function XN(t){const{composition:e,matchUp:n,moeity:r,selectedMatchUpId:s,searchActive:i}=t,{roundFactor:o,roundNumber:c,finishingRound:a,matchUpType:u,preFeedRound:l,stage:f}=n,p=f==="QUALIFYING",h=t.isFinalRound||parseInt(a)===1,d=f==="QUALIFYING"&&h,m=!p&&h,g=parseInt(c)===1,I=u==="DOUBLES",S=(i||n.isRoundRobin||n.collectionId||t.isLucky||t.isAdHoc)&&"mr"||m&&"noProgression"||(d||l)&&"m0"||r&&"m1"||"m2",T=A2({composition:e,isDoubles:I,roundFactor:o})({isFirstRound:g,link:S}),E=(e==null?void 0:e.configuration)||{},{resultsInfo:y,centerInfo:b}=E||{},N=t.eventHandlers||{},A=D=>{Fr(N==null?void 0:N.matchUpClick)&&N.matchUpClick({pointerEvent:D,matchUp:n})},C=document.createElement("div");C.className=ji(e.theme,t==null?void 0:t.className,"matchup",S2()),C.classList.add("tmx-m"),n!=null&&n.matchUpId&&C.setAttribute("id",n.matchUpId),C.onclick=A;const v=document.createElement("div");v.className=T2({configuration:E});const P=({sideNumber:D})=>{var k,_,F;const M=(F=(_=(k=n==null?void 0:n.sides.find(L=>L.sideNumber===D))==null?void 0:k.participant)==null?void 0:_.entryStatus)==null?void 0:F.replace("_"," ");return N2({eventHandlers:N,entryStatus:M,sideNumber:D,className:D===2&&T,matchUp:n})},U=ZN({sideNumber:1,eventHandlers:N,composition:e,matchUp:n}),O=ZN({className:!b&&T,sideNumber:2,eventHandlers:N,composition:e,matchUp:n});if(v.appendChild(U),b){const D=P({sideNumber:1}),M=P({sideNumber:2});v.appendChild(D.element),v.appendChild(M.element)}if(v.appendChild(O),y){const D=_2({score:n.score});v.appendChild(D)}if(C.appendChild(v),s===n.matchUpId){const D=document.createElement("div");D.className=I2(),C.appendChild(D)}return C}function _2({score:t}){var i;const e=(i=t==null?void 0:t.sets)==null?void 0:i.filter(Boolean).sort((o,c)=>(o.setNumber||0)-(c.setNumber||0)),n=e==null?void 0:e[e.length-1],r=(n==null?void 0:n.side1PointsScore)||(n==null?void 0:n.side2PointsScore),s=document.createElement("div");if(s.className=g2(),r){const o=document.createElement("div");o.className=YN({variant:"points"}),o.innerHTML="PTS",s.appendChild(o)}for(const o of e||[]){const c=document.createElement("div");c.setAttribute("key",o.setNumber),c.className=YN({variant:"set"}),c.innerHTML=o.setNumber,s.appendChild(c)}return s}function tA({selectedMatchUpId:t,eventHandlers:e,isFinalRound:n,isRoundRobin:r,searchActive:s,composition:i,roundFactor:o,roundNumber:c,roundProfile:a,matchUps:u,context:l,isLucky:f}){const p=u.filter(A=>A.roundNumber===c).sort((A,C)=>(A.roundPosition||0)-(C.roundPosition||0)),h=p.every(({roundPosition:A,drawPositions:C})=>!A&&!C),d=(i==null?void 0:i.configuration)||{},m=document.createElement("div");if(m.className=HN(),m.classList.add("tmx-rd"),m.setAttribute("roundNumber",c),d.roundHeader){const A=WN({roundProfile:a,roundMatchUps:p,roundNumber:c,eventHandlers:e,context:l});m.appendChild(A)}const g=document.createElement("div");g.className=qN({variant:h?"adHoc":void 0});let I,S,T;if(r){const A=v=>v.reduce((P,U)=>U+P,0);p.sort((v,P)=>{const U=A(v.drawPositions)-A(P.drawPositions),O=Math.min(...v.drawPositions??[])-Math.min(...P.drawPositions??[]);return U||O});const C=p.reduce((v,P)=>(v[P.structureId]=P.structureName,v),{});I=Object.values(C),S=Object.keys(C),T=Object.keys(hm.instanceCount(p.map(({structureId:v})=>v))).length}else h&&p.sort((A,C)=>(A.roundOrder??0)-(C.roundOrder??0));const E=T&&p.length/T,y=Object.keys(a).map(A=>parseInt(A)),b=y.indexOf(c),N=b===0&&"first"||b===y.length-1&&"last";return p.forEach((A,C)=>{const v=E&&!(C%E),P=E&&Math.floor(C/E),U=E&&I[P];if(v){const M=document.createElement("div");M.className=h2({variant:P,roundOrder:N}),g.appendChild(M);const w=document.createElement("div");if(w.className=m2(),Fr(e==null?void 0:e.groupHeaderClick)){const{drawId:k,containerStructureId:_}=p[0];g.onclick=F=>e.groupHeaderClick({drawId:k,structureId:S[P],containerStructureId:_,pointerEvent:F})}c===1&&(w.innerHTML=U),g.appendChild(w)}const O=C%2===0;o&&(A.roundFactor=o);const D=XN({selectedMatchUpId:t,eventHandlers:e,isFinalRound:n,searchActive:s,composition:i,isAdHoc:h,isLucky:f,matchUp:A,moeity:O});g.appendChild(D)}),m.appendChild(g),m}function F2({selectedMatchUpId:t,eventHandlers:e,searchActive:n,composition:r,structureId:s,finalColumn:i,matchUps:o,context:c}){var g;const{roundNumbers:a,roundProfile:u,hasOddMatchUpsCount:l,isNotEliminationStructure:f}=X_.getRoundMatchUps({matchUps:o});s=s||(c==null?void 0:c.structureId)||((g=o==null?void 0:o[0])==null?void 0:g.structureId);const p=o.some(({isRoundRobin:I})=>I),h=l||f,d=document.createElement("div");d.className=p2(),d.classList.add("tmx-str"),s&&d.setAttribute("id",s);const m=Math.max(...a);for(const I of a){const T=tA({selectedMatchUpId:t,eventHandlers:e,isFinalRound:I===m,isRoundRobin:p,searchActive:n,composition:r,roundNumber:I,roundProfile:u,matchUps:o,context:c,isLucky:h});d.appendChild(T)}if(i){const I=document.createElement("div");I.className=HN();const S=document.createElement("div");S.className=qN(),S.appendChild(i),I.appendChild(S),d.appendChild(I)}return d}const eA=zt({backgroundColor:"$colors$backgroundColor",color:"$colors$color",overflowX:"auto",height:1e3});function L2({content:t,theme:e}){const n=document.createElement("div");return n.className=e?ji(eA(),e):eA(),e&&n.classList.add(e),typeof t=="string"?n.innerHTML=t:n.appendChild(t),n}const{createTheme:Ro}=Pm({theme:{lineHeights:{scheduleInfo:`${mu.scheduleInfo}rem`,centerInfo:`${mu.centerInfo}rem`,gameScore:`${mu.gameScore}rem`},borderWidths:{matchUpInline:"1px 1px",matchUp:"1px"},space:{1:"10px",2:"0.375rem",gameMarginInlineEnd:"0.25rem"},fontSizes:{1:"0.875rem"},colors:{internalDividers:"lightgray",backgroundColor:"white",connector:"lightgray",border:"darkgray",color:"black"},participant:{textTransform:"capitalize",minHeight:"2rem",seed:"gray"},score:{setWidth:"1.3rem"}}}),nA=Ro("australian-theme",{colors:{borderHover:"#0091d2",connector:"#999"}}),R2=Ro("wimbledon-theme",{borderWidths:{borderInlineStart:"10px"},colors:{connector:"transparent",borderHover:"darkgrey",border:"#00703c",matchUp:"#fff"},participant:{textTransform:"uppercase"}}),B2=Ro("french-theme",{colors:{winnerName:"#01503d!important",winner:"#01503d!important",borderHover:"#0091d2",border:"#F8F9F9"},matchUp:{boxShadow:"0 0 30px 0 hsla(0,0%,89%,9)"}}),x2=Ro("usopen-theme",{colors:{matchUpBackgroundColor:"#F8F9F9",internalDividers:"darkgray",borderHover:"#0091d2",connector:"#999"}}),rA=Ro("basic-theme",{colors:{internalDividers:"transparent",winner:"#50B649!important",loser:"#E61A1A!important",connector:"#999"},space:{gameMarginInlineEnd:"0.75rem"},participant:{seed:"transparent"},fontSizes:{1:"1.5rem"}}),$2=Ro("dark-theme",{colors:{backgroundColor:"#333333",borderHover:"#0091d2",color:"white"},participant:{seed:"cyan"}}),V2=Ro("itf-theme",{colors:{borderHover:"#0091d2",connector:"#999",matchUp:"#fff"},participant:{textTransform:"uppercase",seed:"gray"}}),j2={Australian:{configuration:{flags:!0},theme:nA},Basic:{configuration:{gameScoreOnly:!0,teamLogo:!1,roundHeader:!0},theme:rA},DrawPositions:{configuration:{gameScoreOnly:!0,drawPositions:!0,teamLogo:!1},theme:rA},French:{configuration:{bracketedSeeds:!0,flags:!0},theme:B2},Wimbledon:{configuration:{resultsInfo:!0,flags:!0},theme:R2},"US Open":{configuration:{scoreBox:!0,flags:!0},theme:x2},ITF:{configuration:{winnerChevron:!0,centerInfo:!0,flags:!0,roundHeader:!0},theme:V2},National:{configuration:{bracketedSeeds:"square",allDrawPositions:!0,drawPositions:!0,scheduleInfo:!0,roundHeader:!0,showAddress:!0,scaleAttributes:{scaleColor:"red",scaleType:"RATING",scaleName:"WTN",accessor:"wtnRating"}},theme:nA},Night:{configuration:{flags:!0},theme:$2}};hr.cModal=Im,hr.compositions=j2,hr.renderContainer=L2,hr.renderMatchUp=XN,hr.renderParticipant=GN,hr.renderRound=tA,hr.renderRoundHeader=WN,hr.renderStructure=F2,Object.defineProperty(hr,Symbol.toStringTag,{value:"Module"})});
36
+ `;return i.innerHTML=u||"",i}const HN=zt({flexDirection:"column",display:"flex"}),p2=zt({flexDirection:"row",display:"flex"}),qN=zt({justifyContent:"space-around",marginInlineStart:"16px",marginInlineEnd:"16px",flexDirection:"column",height:"100%",display:"flex",width:"460px",variants:{variant:{adHoc:{justifyContent:"flex-start"}}}}),h2=zt({borderTop:"solid 1px black",marginRight:"-1em",marginLeft:"-1em",paddingTop:".5em",marginTop:".2em",variants:{variant:{0:{marginTop:"1em",borderTop:"none",paddingTop:"0px"}},roundOrder:{first:{marginLeft:"0em"},last:{marginRight:"0em"}}}}),m2=zt({fontWeight:"bold",color:"blue",height:"1em"}),YN=zt({width:"$score$setWidth",display:"inline-block",fontSize:9,variants:{variant:{set:{textAlign:"center"},points:{marginInlineEnd:3}}}}),g2=zt({transform:"translateY(-50%)",textTransform:"uppercase",backgroundColor:"#fff",position:"absolute",textAlign:"center",top:"calc(50%)",color:"#bbb",fontSize:0,right:4});function I2(){return zt({backgroundColor:"magenta",position:"absolute",opacity:"0.2",height:"100%",width:"100%",top:0})}const S2=zt({});function T2({configuration:t}){const e={backgroundColor:"$matchUpBackgroundColor",WebkitTransition:"all 0.30s linear",boxShadow:"$matchUp$boxShadow",transition:"all 0.30s linear",border:"solid $border",marginBottom:"$space$1",marginTop:"$space$1",position:"relative",display:"grid",width:"100%",borderInlineStartWidth:"$borderWidths$borderInlineStart"};if(t!=null&&t.matchUpHover){const n=typeof t.matchUpHover=="string"?t.matchUpHover:"cyan";e["&:hover"]={backgroundColor:n}}else e["&:hover"]={borderColor:"$borderHover"};return zt(e)}function y2({variant:t}){return zt({borderBottom:"solid 1px lightgray",backgroundColor:"$matchUp",position:"relative",width:"100%",height:"$lineHeights$centerInfo",variants:{variant:{1:{borderBottom:"solid 1px black"},2:{borderBottom:"solid 1px lightgray"}}}})({variant:t})}const E2=zt({justifyContent:"center",alignContent:"center",flexDirection:"column",height:"100%",display:"flex"}),b2=zt({fontFamily:"Lato,Arial,Helvetica,sans-serif",WebkitFontSmooting:"antialiased",marginInlineStart:"calc(20%)",WebkitBoxOrient:"horizontal",WebKitBoxDirection:"normal",WebkitBoxPack:"center",boxSizing:"inherit",flexDirection:"row",display:"flex"}),zN=zt({alignContent:"center",boxSizing:"inherit",fontFamily:"Lato",fontWeight:900,fontSize:9});function N2({eventHandlers:t,entryStatus:e,sideNumber:n,className:r,matchUp:s}){const i=document.createElement("div");Fr(t==null?void 0:t.centerInfoClick)&&(i.onclick=l=>t.centerInfoClick({matchUp:s,sideNumber:n,pointerEvent:l})),i.className=ji(y2({variant:n}),r),i.classList.add("tmx-ci"),i.setAttribute("sideNumber",n);const o=document.createElement("div");o.className=E2();const c=document.createElement("div");c.className=b2();const a=document.createElement("div");a.className=zN(),a.innerHTML=e?"Entry status:&nbsp;":"",c.appendChild(a);const u=document.createElement("div");return u.className=zN(),u.innerHTML=e||"",c.appendChild(u),o.appendChild(c),i.appendChild(o),{element:i}}const mu={scheduleInfo:1.8,centerInfo:1.5,gameScore:2};function A2({composition:t,isDoubles:e,roundFactor:n=1}){const r=parseInt(window.getComputedStyle(document.body).getPropertyValue("font-size")),s=(t==null?void 0:t.configuration)||{},i=(s==null?void 0:s.connectorWidth)||16,o=s.centerInfo?mu.centerInfo*r:0,c=s.scheduleInfo?mu.scheduleInfo*r:0,u=(60+(s.showAddress?r:0))*(e?1.3:1)+o,l=u*n,f=(u+c)*n;return zt({"&::before":{borderBlockStart:"$borderWidths$matchUp solid #999",left:-i,width:i,position:"absolute",borderRadius:2,top:-1},"&::after":{width:i,position:"absolute",borderRadius:2,left:"100%"},"&::after, &::before":{borderWidth:"$borderWidths$matchUp",borderColor:"$connector",display:"block",content:""},variants:{isFirstRound:{true:{"&::before":{height:0,width:0,borderWidth:0}}},link:{m1:{"&::after":{borderInlineEnd:"$borderWidths$matchUp solid $connector",borderTopStyle:"solid",height:l,top:-1}},m2:{"&::after":{bottom:"calc(100%)",borderInlineEnd:"$borderWidths$matchUp solid $connector",borderBottomStyle:"solid",height:f}},m0:{"&::after":{borderTopStyle:"solid",borderColor:"$connector",top:-1}},mr:{"&::before":{height:0,width:0,borderWidth:0},"&::after":{height:0,width:0,borderWidth:0}},noProgression:{true:{"&::after":{height:0,width:0,borderWidth:0}}}}}})}const KN=t=>zt({display:"flex",alignItems:"center",height:t,justifyContent:"flex-end",backgroundColor:"$matchUp",variants:{sideNumber:{1:{borderBottom:"1px solid $internalDividers"}},fontSize:{small:{fontSize:"smaller",paddingRight:"1em",color:"blue"}}}}),v2=zt({lineHeight:"0.75rem",fontSize:"0.625rem",left:"1.1rem",top:".4rem"}),JN=zt({lineHeight:"$lineHeights$gameScore",justifyContent:"center",width:"$score$setWidth",position:"relative",textAlign:"center",cursor:"pointer",fontWeight:500,fontSize:"$1",display:"flex",margin:0,variants:{variant:{winner:{color:"$winner!important",fontWeight:700},loser:{color:"$loser!important"}}}}),C2=zt({marginInlineEnd:"$space$gameMarginInlineEnd",justifyContent:"flex-end",alignItems:"center",display:"flex"});function P2({value:t}={}){const e=document.createElement("input");return e.onclick=n=>n.target.select(),e.className=JN(),e.value=t,e}function U2({gameScoreOnly:t,scoreStripes:e,set:n,sideNumber:r}){const i=r===(n==null?void 0:n.winningSide)||n!=null&&n.winningSide?"loser":void 0,o=r===2?n.side2Score:n.side1Score,c=n.side2TiebreakScore||n.side1TiebreakScore,a=r===2?n.side2TiebreakScore:n.side1TiebreakScore,u=o===void 0&&a,l=u||o,f=e&&n.setNumber%2?"lightgray":"transparent",h=n.editing?n.editing===r:void 0;let d;if(h)d=P2({value:l});else if(d=document.createElement("p"),d.className=JN({variant:i}),d.classList.add("tmx-st"),d.setAttribute("setNumber",n.setNumber),d.style.backgroundColor=f,d.innerHTML=isNaN(l)?"":l,!t){const m=document.createElement("span");m.className=v2(),m.innerHTML=c&&!u?a:"",d.appendChild(m)}return d}function O2({participantHeight:t,eventHandlers:e,composition:n,sideNumber:r,matchUp:s}){var d,m,g,I;const i=(d=n==null?void 0:n.configuration)==null?void 0:d.winnerChevron,o=(m=n==null?void 0:n.configuration)==null?void 0:m.gameScoreOnly,c=((g=s==null?void 0:s.score)==null?void 0:g.sets)||[],a=(I=n==null?void 0:n.configuration)==null?void 0:I.scoreBox,u=r===2?t:t-1,l=KN(u),f=S=>{Fr(e==null?void 0:e.scoreClick)&&(S.stopPropagation(),e.scoreClick({pointerEvent:S,matchUp:s}))},p=document.createElement("div");p.className=l({sideNumber:!a&&r,fontSize:"5px"}),p.classList.add("sideScore"),p.classList.add("tmx-scr"),p.onclick=f;const h=document.createElement("div");h.className=C2();for(const S of c||[]){const T=U2({gameScoreOnly:o,scoreStripes:i,sideNumber:r,set:S});h.appendChild(T)}return p.appendChild(h),p}const M2=zt({height:"$lineHeights$scheduleInfo",borderBottom:"1px solid darkgray",justifyContent:"space-between",backgroundColor:"#F8F9F9",boxSizing:"border-box",paddingRight:"0.2rem",paddingLeft:"0.5rem",alignItems:"center",cursor:"pointer",color:"#7F8080",display:"flex",width:"100%"});var QN={exports:{}};(function(t,e){(function(n,r){t.exports=r()})(s1,function(){var n=1e3,r=6e4,s=36e5,i="millisecond",o="second",c="minute",a="hour",u="day",l="week",f="month",p="quarter",h="year",d="date",m="Invalid Date",g=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,I=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,S={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(D){var M=["th","st","nd","rd"],w=D%100;return"["+D+(M[(w-20)%10]||M[w]||M[0])+"]"}},T=function(D,M,w){var k=String(D);return!k||k.length>=M?D:""+Array(M+1-k.length).join(w)+D},E={s:T,z:function(D){var M=-D.utcOffset(),w=Math.abs(M),k=Math.floor(w/60),_=w%60;return(M<=0?"+":"-")+T(k,2,"0")+":"+T(_,2,"0")},m:function D(M,w){if(M.date()<w.date())return-D(w,M);var k=12*(w.year()-M.year())+(w.month()-M.month()),_=M.clone().add(k,f),F=w-_<0,L=M.clone().add(k+(F?-1:1),f);return+(-(k+(w-_)/(F?_-L:L-_))||0)},a:function(D){return D<0?Math.ceil(D)||0:Math.floor(D)},p:function(D){return{M:f,y:h,w:l,d:u,D:d,h:a,m:c,s:o,ms:i,Q:p}[D]||String(D||"").toLowerCase().replace(/s$/,"")},u:function(D){return D===void 0}},y="en",b={};b[y]=S;var N="$isDayjsObject",A=function(D){return D instanceof U||!(!D||!D[N])},C=function D(M,w,k){var _;if(!M)return y;if(typeof M=="string"){var F=M.toLowerCase();b[F]&&(_=F),w&&(b[F]=w,_=F);var L=M.split("-");if(!_&&L.length>1)return D(L[0])}else{var W=M.name;b[W]=M,_=W}return!k&&_&&(y=_),_||!k&&y},v=function(D,M){if(A(D))return D.clone();var w=typeof M=="object"?M:{};return w.date=D,w.args=arguments,new U(w)},P=E;P.l=C,P.i=A,P.w=function(D,M){return v(D,{locale:M.$L,utc:M.$u,x:M.$x,$offset:M.$offset})};var U=function(){function D(w){this.$L=C(w.locale,null,!0),this.parse(w),this.$x=this.$x||w.x||{},this[N]=!0}var M=D.prototype;return M.parse=function(w){this.$d=function(k){var _=k.date,F=k.utc;if(_===null)return new Date(NaN);if(P.u(_))return new Date;if(_ instanceof Date)return new Date(_);if(typeof _=="string"&&!/Z$/i.test(_)){var L=_.match(g);if(L){var W=L[2]-1||0,j=(L[7]||"0").substring(0,3);return F?new Date(Date.UTC(L[1],W,L[3]||1,L[4]||0,L[5]||0,L[6]||0,j)):new Date(L[1],W,L[3]||1,L[4]||0,L[5]||0,L[6]||0,j)}}return new Date(_)}(w),this.init()},M.init=function(){var w=this.$d;this.$y=w.getFullYear(),this.$M=w.getMonth(),this.$D=w.getDate(),this.$W=w.getDay(),this.$H=w.getHours(),this.$m=w.getMinutes(),this.$s=w.getSeconds(),this.$ms=w.getMilliseconds()},M.$utils=function(){return P},M.isValid=function(){return this.$d.toString()!==m},M.isSame=function(w,k){var _=v(w);return this.startOf(k)<=_&&_<=this.endOf(k)},M.isAfter=function(w,k){return v(w)<this.startOf(k)},M.isBefore=function(w,k){return this.endOf(k)<v(w)},M.$g=function(w,k,_){return P.u(w)?this[k]:this.set(_,w)},M.unix=function(){return Math.floor(this.valueOf()/1e3)},M.valueOf=function(){return this.$d.getTime()},M.startOf=function(w,k){var _=this,F=!!P.u(k)||k,L=P.p(w),W=function(Y,z){var J=P.w(_.$u?Date.UTC(_.$y,z,Y):new Date(_.$y,z,Y),_);return F?J:J.endOf(u)},j=function(Y,z){return P.w(_.toDate()[Y].apply(_.toDate("s"),(F?[0,0,0,0]:[23,59,59,999]).slice(z)),_)},H=this.$W,B=this.$M,R=this.$D,x="set"+(this.$u?"UTC":"");switch(L){case h:return F?W(1,0):W(31,11);case f:return F?W(1,B):W(0,B+1);case l:var q=this.$locale().weekStart||0,V=(H<q?H+7:H)-q;return W(F?R-V:R+(6-V),B);case u:case d:return j(x+"Hours",0);case a:return j(x+"Minutes",1);case c:return j(x+"Seconds",2);case o:return j(x+"Milliseconds",3);default:return this.clone()}},M.endOf=function(w){return this.startOf(w,!1)},M.$set=function(w,k){var _,F=P.p(w),L="set"+(this.$u?"UTC":""),W=(_={},_[u]=L+"Date",_[d]=L+"Date",_[f]=L+"Month",_[h]=L+"FullYear",_[a]=L+"Hours",_[c]=L+"Minutes",_[o]=L+"Seconds",_[i]=L+"Milliseconds",_)[F],j=F===u?this.$D+(k-this.$W):k;if(F===f||F===h){var H=this.clone().set(d,1);H.$d[W](j),H.init(),this.$d=H.set(d,Math.min(this.$D,H.daysInMonth())).$d}else W&&this.$d[W](j);return this.init(),this},M.set=function(w,k){return this.clone().$set(w,k)},M.get=function(w){return this[P.p(w)]()},M.add=function(w,k){var _,F=this;w=Number(w);var L=P.p(k),W=function(B){var R=v(F);return P.w(R.date(R.date()+Math.round(B*w)),F)};if(L===f)return this.set(f,this.$M+w);if(L===h)return this.set(h,this.$y+w);if(L===u)return W(1);if(L===l)return W(7);var j=(_={},_[c]=r,_[a]=s,_[o]=n,_)[L]||1,H=this.$d.getTime()+w*j;return P.w(H,this)},M.subtract=function(w,k){return this.add(-1*w,k)},M.format=function(w){var k=this,_=this.$locale();if(!this.isValid())return _.invalidDate||m;var F=w||"YYYY-MM-DDTHH:mm:ssZ",L=P.z(this),W=this.$H,j=this.$m,H=this.$M,B=_.weekdays,R=_.months,x=_.meridiem,q=function(z,J,Q,X){return z&&(z[J]||z(k,F))||Q[J].slice(0,X)},V=function(z){return P.s(W%12||12,z,"0")},Y=x||function(z,J,Q){var X=z<12?"AM":"PM";return Q?X.toLowerCase():X};return F.replace(I,function(z,J){return J||function(Q){switch(Q){case"YY":return String(k.$y).slice(-2);case"YYYY":return P.s(k.$y,4,"0");case"M":return H+1;case"MM":return P.s(H+1,2,"0");case"MMM":return q(_.monthsShort,H,R,3);case"MMMM":return q(R,H);case"D":return k.$D;case"DD":return P.s(k.$D,2,"0");case"d":return String(k.$W);case"dd":return q(_.weekdaysMin,k.$W,B,2);case"ddd":return q(_.weekdaysShort,k.$W,B,3);case"dddd":return B[k.$W];case"H":return String(W);case"HH":return P.s(W,2,"0");case"h":return V(1);case"hh":return V(2);case"a":return Y(W,j,!0);case"A":return Y(W,j,!1);case"m":return String(j);case"mm":return P.s(j,2,"0");case"s":return String(k.$s);case"ss":return P.s(k.$s,2,"0");case"SSS":return P.s(k.$ms,3,"0");case"Z":return L}return null}(z)||L.replace(":","")})},M.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},M.diff=function(w,k,_){var F,L=this,W=P.p(k),j=v(w),H=(j.utcOffset()-this.utcOffset())*r,B=this-j,R=function(){return P.m(L,j)};switch(W){case h:F=R()/12;break;case f:F=R();break;case p:F=R()/3;break;case l:F=(B-H)/6048e5;break;case u:F=(B-H)/864e5;break;case a:F=B/s;break;case c:F=B/r;break;case o:F=B/n;break;default:F=B}return _?F:P.a(F)},M.daysInMonth=function(){return this.endOf(f).$D},M.$locale=function(){return b[this.$L]},M.locale=function(w,k){if(!w)return this.$L;var _=this.clone(),F=C(w,k,!0);return F&&(_.$L=F),_},M.clone=function(){return P.w(this.$d,this)},M.toDate=function(){return new Date(this.valueOf())},M.toJSON=function(){return this.isValid()?this.toISOString():null},M.toISOString=function(){return this.$d.toISOString()},M.toString=function(){return this.$d.toUTCString()},D}(),O=U.prototype;return v.prototype=O,[["$ms",i],["$s",o],["$m",c],["$H",a],["$W",u],["$M",f],["$y",h],["$D",d]].forEach(function(D){O[D[1]]=function(M){return this.$g(M,D[0],D[1])}}),v.extend=function(D,M){return D.$i||(D(M,U,v),D.$i=!0),v},v.locale=C,v.isDayjs=A,v.unix=function(D){return v(1e3*D)},v.en=b[y],v.Ls=b,v.p={},v})})(QN);var D2=QN.exports;const w2=Om(D2);function k2({matchUp:t,eventHandlers:e}){const{scheduledTime:n,scheduledDate:r,venueAbbreviation:s,courtName:i}=(t==null?void 0:t.schedule)||{},{dateTime:{extractDate:o,extractTime:c}}=hm,a=c(n);let l=o(r),f="ddd D MMMM";a&&(f+=", hh:mm A",l+=`T${a}`);const p=r?w2(l).format(f):"Not scheduled",h=s&&(i==null?void 0:i.toString().startsWith(s))&&i||s&&i&&`${s} ${i}`||i||s||"",d=document.createElement("div");d.className=M2(),d.classList.add("tmx-sch"),Fr(e==null?void 0:e.scheduleClick)&&(d.onclick=T=>e.scheduleClick({matchUp:t,pointerEvent:T}));const m=document.createElement("div");m.innerHTML=p,d.append(m);const g=T=>{Fr(e==null?void 0:e.venueClick)&&(T.stopPropagation(),e.venueClick({pointerEvent:T,matchUp:t}))},I=document.createElement("div");I.style="display: flex; flex-direction: row";const S=document.createElement("div");if(S.style.paddingRight=".2rem",S.onclick=g,S.innerHTML=h,I.append(S),d.append(I),d.onclick){const T=document.createElement("div");T.innerHTML="⋮",I.append(T)}return d}function ZN({eventHandlers:t,composition:e,sideNumber:n,className:r,matchUp:s}){var h,d;const i=(e==null?void 0:e.configuration)||{},o=i==null?void 0:i.scheduleInfo,c=(h=s==null?void 0:s.score)==null?void 0:h.scoreStringSide1,a=((d=e==null?void 0:e.configuration)==null?void 0:d.scoreBox)&&c,u=(s==null?void 0:s.readyToScore)&&(t==null?void 0:t.scoreClick)&&!hm.scoreHasValue({matchUp:s}),l=document.createElement("div");if(l.className=ji(a2(),r),l.classList.add("tmx-sd"),l.setAttribute("sideNumber",n),o&&n===1){const m=k2({matchUp:s,eventHandlers:t});l.appendChild(m)}const f=document.createElement("div");f.className=u2();const p=GN({sideContainer:!0,eventHandlers:t,composition:e,sideNumber:n,matchUp:s});if(f.appendChild(p),a){const m=document.createElement("div");m.style.border="1px solid lightgray",f.appendChild(m)}if(c){const m=O2({eventHandlers:t,composition:e,sideNumber:n,matchUp:s});f.appendChild(m)}if(u){const m=KN(),g=S=>{Fr(t==null?void 0:t.scoreClick)&&(event.stopPropagation(),t.scoreClick({pointerEvent:S,matchUp:s}))},I=document.createElement("div");I.className=m({sideNumber:!a&&n,fontSize:"small"}),I.onclick=g,I.innerHTML="[Score]",f.appendChild(I)}return l.appendChild(f),l}function XN(t){const{composition:e,matchUp:n,moeity:r,selectedMatchUpId:s,searchActive:i}=t,{roundFactor:o,roundNumber:c,finishingRound:a,matchUpType:u,preFeedRound:l,stage:f}=n,p=f==="QUALIFYING",h=t.isFinalRound||parseInt(a)===1,d=f==="QUALIFYING"&&h,m=!p&&h,g=parseInt(c)===1,I=u==="DOUBLES",S=(i||n.isRoundRobin||n.collectionId||t.isLucky||t.isAdHoc)&&"mr"||m&&"noProgression"||(d||l)&&"m0"||r&&"m1"||"m2",T=A2({composition:e,isDoubles:I,roundFactor:o})({isFirstRound:g,link:S}),E=(e==null?void 0:e.configuration)||{},{resultsInfo:y,centerInfo:b}=E||{},N=t.eventHandlers||{},A=D=>{Fr(N==null?void 0:N.matchUpClick)&&N.matchUpClick({pointerEvent:D,matchUp:n})},C=document.createElement("div");C.className=ji(e.theme,t==null?void 0:t.className,"matchup",S2()),C.classList.add("tmx-m"),C.setAttribute("id",n==null?void 0:n.matchUpId),C.onclick=A;const v=document.createElement("div");v.className=T2({configuration:E});const P=({sideNumber:D})=>{var k,_,F;const M=(F=(_=(k=n==null?void 0:n.sides.find(L=>L.sideNumber===D))==null?void 0:k.participant)==null?void 0:_.entryStatus)==null?void 0:F.replace("_"," ");return N2({eventHandlers:N,entryStatus:M,sideNumber:D,className:D===2&&T,matchUp:n})},U=ZN({sideNumber:1,eventHandlers:N,composition:e,matchUp:n}),O=ZN({className:!b&&T,sideNumber:2,eventHandlers:N,composition:e,matchUp:n});if(v.appendChild(U),b){const D=P({sideNumber:1}),M=P({sideNumber:2});v.appendChild(D.element),v.appendChild(M.element)}if(v.appendChild(O),y){const D=_2({score:n.score});v.appendChild(D)}if(C.appendChild(v),s===n.matchUpId){const D=document.createElement("div");D.className=I2(),C.appendChild(D)}return C}function _2({score:t}){var i;const e=(i=t==null?void 0:t.sets)==null?void 0:i.filter(Boolean).sort((o,c)=>(o.setNumber||0)-(c.setNumber||0)),n=e==null?void 0:e[e.length-1],r=(n==null?void 0:n.side1PointsScore)||(n==null?void 0:n.side2PointsScore),s=document.createElement("div");if(s.className=g2(),r){const o=document.createElement("div");o.className=YN({variant:"points"}),o.innerHTML="PTS",s.appendChild(o)}for(const o of e||[]){const c=document.createElement("div");c.setAttribute("key",o.setNumber),c.className=YN({variant:"set"}),c.innerHTML=o.setNumber,s.appendChild(c)}return s}function tA({selectedMatchUpId:t,eventHandlers:e,isFinalRound:n,isRoundRobin:r,searchActive:s,composition:i,roundFactor:o,roundNumber:c,roundProfile:a,matchUps:u,context:l,isLucky:f}){const p=u.filter(A=>A.roundNumber===c).sort((A,C)=>(A.roundPosition||0)-(C.roundPosition||0)),h=p.every(({roundPosition:A,drawPositions:C})=>!A&&!C),d=(i==null?void 0:i.configuration)||{},m=document.createElement("div");if(m.className=HN(),m.classList.add("tmx-rd"),m.setAttribute("roundNumber",c),d.roundHeader){const A=WN({roundProfile:a,roundMatchUps:p,roundNumber:c,eventHandlers:e,context:l});m.appendChild(A)}const g=document.createElement("div");g.className=qN({variant:h?"adHoc":void 0});let I,S,T;if(r){const A=v=>v.reduce((P,U)=>U+P,0);p.sort((v,P)=>{const U=A(v.drawPositions)-A(P.drawPositions),O=Math.min(...v.drawPositions??[])-Math.min(...P.drawPositions??[]);return U||O});const C=p.reduce((v,P)=>(v[P.structureId]=P.structureName,v),{});I=Object.values(C),S=Object.keys(C),T=Object.keys(hm.instanceCount(p.map(({structureId:v})=>v))).length}else h&&p.sort((A,C)=>(A.roundOrder??0)-(C.roundOrder??0));const E=T&&p.length/T,y=Object.keys(a).map(A=>parseInt(A)),b=y.indexOf(c),N=b===0&&"first"||b===y.length-1&&"last";return p.forEach((A,C)=>{const v=E&&!(C%E),P=E&&Math.floor(C/E),U=E&&I[P];if(v){const M=document.createElement("div");M.className=h2({variant:P,roundOrder:N}),g.appendChild(M);const w=document.createElement("div");if(w.className=m2(),Fr(e==null?void 0:e.groupHeaderClick)){const{drawId:k,containerStructureId:_}=p[0];g.onclick=F=>e.groupHeaderClick({drawId:k,structureId:S[P],containerStructureId:_,pointerEvent:F})}c===1&&(w.innerHTML=U),g.appendChild(w)}const O=C%2===0;o&&(A.roundFactor=o);const D=XN({selectedMatchUpId:t,eventHandlers:e,isFinalRound:n,searchActive:s,composition:i,isAdHoc:h,isLucky:f,matchUp:A,moeity:O});g.appendChild(D)}),m.appendChild(g),m}function F2({selectedMatchUpId:t,eventHandlers:e,searchActive:n,composition:r,structureId:s,finalColumn:i,matchUps:o,context:c}){var g;const{roundNumbers:a,roundProfile:u,hasOddMatchUpsCount:l,isNotEliminationStructure:f}=X_.getRoundMatchUps({matchUps:o});s=s||(c==null?void 0:c.structureId)||((g=o==null?void 0:o[0])==null?void 0:g.structureId);const p=o.some(({isRoundRobin:I})=>I),h=l||f,d=document.createElement("div");d.className=p2(),d.classList.add("tmx-str"),d.setAttribute("id",s);const m=Math.max(...a);for(const I of a){const T=tA({selectedMatchUpId:t,eventHandlers:e,isFinalRound:I===m,isRoundRobin:p,searchActive:n,composition:r,roundNumber:I,roundProfile:u,matchUps:o,context:c,isLucky:h});d.appendChild(T)}if(i){const I=document.createElement("div");I.className=HN();const S=document.createElement("div");S.className=qN(),S.appendChild(i),I.appendChild(S),d.appendChild(I)}return d}const eA=zt({backgroundColor:"$colors$backgroundColor",color:"$colors$color",overflowX:"auto",height:1e3});function L2({content:t,theme:e}){const n=document.createElement("div");return n.className=e?ji(eA(),e):eA(),e&&n.classList.add(e),typeof t=="string"?n.innerHTML=t:n.appendChild(t),n}const{createTheme:Ro}=Pm({theme:{lineHeights:{scheduleInfo:`${mu.scheduleInfo}rem`,centerInfo:`${mu.centerInfo}rem`,gameScore:`${mu.gameScore}rem`},borderWidths:{matchUpInline:"1px 1px",matchUp:"1px"},space:{1:"10px",2:"0.375rem",gameMarginInlineEnd:"0.25rem"},fontSizes:{1:"0.875rem"},colors:{internalDividers:"lightgray",backgroundColor:"white",connector:"lightgray",border:"darkgray",color:"black"},participant:{textTransform:"capitalize",minHeight:"2rem",seed:"gray"},score:{setWidth:"1.3rem"}}}),nA=Ro("australian-theme",{colors:{borderHover:"#0091d2",connector:"#999"}}),R2=Ro("wimbledon-theme",{borderWidths:{borderInlineStart:"10px"},colors:{connector:"transparent",borderHover:"darkgrey",border:"#00703c",matchUp:"#fff"},participant:{textTransform:"uppercase"}}),B2=Ro("french-theme",{colors:{winnerName:"#01503d!important",winner:"#01503d!important",borderHover:"#0091d2",border:"#F8F9F9"},matchUp:{boxShadow:"0 0 30px 0 hsla(0,0%,89%,9)"}}),x2=Ro("usopen-theme",{colors:{matchUpBackgroundColor:"#F8F9F9",internalDividers:"darkgray",borderHover:"#0091d2",connector:"#999"}}),rA=Ro("basic-theme",{colors:{internalDividers:"transparent",winner:"#50B649!important",loser:"#E61A1A!important",connector:"#999"},space:{gameMarginInlineEnd:"0.75rem"},participant:{seed:"transparent"},fontSizes:{1:"1.5rem"}}),$2=Ro("dark-theme",{colors:{backgroundColor:"#333333",borderHover:"#0091d2",color:"white"},participant:{seed:"cyan"}}),V2=Ro("itf-theme",{colors:{borderHover:"#0091d2",connector:"#999",matchUp:"#fff"},participant:{textTransform:"uppercase",seed:"gray"}}),j2={Australian:{configuration:{flags:!0},theme:nA},Basic:{configuration:{gameScoreOnly:!0,teamLogo:!1,roundHeader:!0},theme:rA},DrawPositions:{configuration:{gameScoreOnly:!0,drawPositions:!0,teamLogo:!1},theme:rA},French:{configuration:{bracketedSeeds:!0,flags:!0},theme:B2},Wimbledon:{configuration:{resultsInfo:!0,flags:!0},theme:R2},"US Open":{configuration:{scoreBox:!0,flags:!0},theme:x2},ITF:{configuration:{winnerChevron:!0,centerInfo:!0,flags:!0,roundHeader:!0},theme:V2},National:{configuration:{bracketedSeeds:"square",allDrawPositions:!0,drawPositions:!0,scheduleInfo:!0,roundHeader:!0,showAddress:!0,scaleAttributes:{scaleColor:"red",scaleType:"RATING",scaleName:"WTN",accessor:"wtnRating"}},theme:nA},Night:{configuration:{flags:!0},theme:$2}};hr.cModal=Im,hr.compositions=j2,hr.renderContainer=L2,hr.renderMatchUp=XN,hr.renderParticipant=GN,hr.renderRound=tA,hr.renderRoundHeader=WN,hr.renderStructure=F2,Object.defineProperty(hr,Symbol.toStringTag,{value:"Module"})});