UNPKG

brackets-viewer

Version:

A simple library to display tournament brackets (round-robin, single elimination, double elimination)

1 lines 166 kB
!function(){var t={3886:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.isMatchGame=e.isMatch=e.getRanking=e.rankingHeader=e.isMajorRound=e.getOriginAbbreviation=e.completeWithBlankMatches=e.findRoot=e.sortBy=e.splitByWithLeftovers=e.splitBy=void 0;const o=n(1491);function r(t,e,n,o){if(!n||null===n.id)return;const r=t[n.id]||{rank:0,id:0,played:0,wins:0,draws:0,losses:0,forfeits:0,scoreFor:0,scoreAgainst:0,scoreDifference:0,points:0};r.id=n.id,(n.forfeit||n.result)&&r.played++,"win"===n.result&&r.wins++,"draw"===n.result&&r.draws++,"loss"===n.result&&r.losses++,n.forfeit&&r.forfeits++,r.scoreFor+=n.score||0,r.scoreAgainst+=o&&o.score||0,r.scoreDifference=r.scoreFor-r.scoreAgainst,r.points=e(r),t[n.id]=r}function i(t){return"child_count"in t}e.splitBy=function(t,e){const n={};for(const o of t){const t=o[e];n[t]||(n[t]=[]),n[t].push(o)}return Object.values(n)},e.splitByWithLeftovers=function(t,e){var n;const o={};for(const r of t){const t=null!==(n=r[e])&&void 0!==n?n:"-1";o[t]||(o[t]=[]),o[t].push(r)}const r=[...Object.entries(o).filter((([t])=>"-1"!==t)).map((([t,e])=>e))];return r[-1]=o[-1],r},e.sortBy=function(t,e){return[...t].sort(((t,n)=>t[e]-n[e]))},e.findRoot=function(t){const e=document.querySelectorAll(t||".brackets-viewer");if(0===e.length)throw Error("Root not found. You must have at least one root element.");if(e.length>1)throw Error("Multiple possible roots were found. Please use `config.selector` to choose a specific root.");const n=e[0];if(!n.classList.contains("brackets-viewer"))throw Error("The selected root must have a `.brackets-viewer` class.");return n},e.completeWithBlankMatches=function(t,e,n){if(!n)return{matches:e,fromToornament:!1};let o=[];return"single_bracket"!==t&&"winner_bracket"!==t||(o=n.map((t=>{var e,n;return[(null===(e=t.opponent1)||void 0===e?void 0:e.position)||null,(null===(n=t.opponent2)||void 0===n?void 0:n.position)||null]})).flat()),"loser_bracket"===t&&(o=n.map((t=>{var e;return(null===(e=t.opponent2)||void 0===e?void 0:e.position)||null}))),0===o.filter((t=>null!==t)).length?{matches:e,fromToornament:!1}:{matches:o.map((t=>t&&e.find((e=>e.number===t))||null)),fromToornament:!0}},e.getOriginAbbreviation=function(t,e,n,r){return n=n||-1,e&&"loser_bracket"===t&&1===n||"single_bracket"===t||"winner_bracket"===t&&1===n?(0,o.t)("abbreviations.seed"):"loser_bracket"===t&&n%2==0&&"opponent1"===r?(0,o.t)("abbreviations.position"):null},e.isMajorRound=function(t){return 1===t||t%2==0},e.rankingHeader=function(t){return(0,o.t)(`ranking.${t}`,{returnObjects:!0})},e.getRanking=function(t,e){e=e||(t=>3*t.wins+1*t.draws+0*t.losses);const n={};for(const o of t)r(n,e,o.opponent1,o.opponent2),r(n,e,o.opponent2,o.opponent1);return function(t){const e=Object.values(t).sort(((t,e)=>t.points!==e.points?e.points-t.points:e.played-t.played)),n={value:0,lastPoints:-1};for(const t of e)t.rank=n.lastPoints!==t.points?++n.value:n.value,n.lastPoints=t.points;return e}(n)},e.isMatch=i,e.isMatchGame=function(t){return!i(t)}},1491:function(t,e,n){"use strict";var o=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.getLoserBracketRoundName=e.getWinnerBracketRoundName=e.getRoundName=e.getBracketName=e.getGroupName=e.getMatchStatus=e.getFinalMatchLabel=e.getMatchLabel=e.getFinalOriginHint=e.getOriginHint=e.toI18nKey=e.t=e.addLocale=e.locales=void 0;const r=o(n(6073)),i=o(n(13)),a=n(7021),s=n(3886),u=o(n(9583)),l=o(n(8159));function c(t,e){return r.default.t(t,e)}function d(t){return t.replace("_","-")}e.locales={en:u.default,fr:l.default},r.default.use(i.default).init({fallbackLng:"en",debug:!1,resources:{en:{translation:e.locales.en},fr:{translation:e.locales.fr}}}),e.addLocale=async function(t,e){r.default.addResourceBundle(t,"translation",e,!0,!0),await r.default.changeLanguage()},e.t=c,e.toI18nKey=d,e.getOriginHint=function(t,e,n,o){if(1===t){if("single_bracket"===o)return t=>c("origin-hint.seed",{position:t});if("winner_bracket"===o)return t=>c("origin-hint.seed",{position:t});if("loser_bracket"===o&&n)return t=>c("origin-hint.seed",{position:t})}if((0,s.isMajorRound)(t)&&"loser_bracket"===o){if(t===e-2)return t=>c("origin-hint.winner-bracket-semi-final",{position:t});if(t===e)return()=>c("origin-hint.winner-bracket-final");const o=Math.ceil((t+1)/2);return n?t=>c("origin-hint.winner-bracket",{round:o-1,position:t}):t=>c("origin-hint.winner-bracket",{round:o,position:t})}},e.getFinalOriginHint=function(t,e,n){return"single_elimination"===t?t=>c("origin-hint.consolation-final",{position:t}):"grand_final"===e?1===n?()=>c("origin-hint.grand-final"):void 0:t=>c(1===t?"origin-hint.double-elimination-consolation-final-opponent-1":"origin-hint.double-elimination-consolation-final-opponent-2")},e.getMatchLabel=function(t,e,n,o){if(void 0===e||void 0===n||void 0===o)return c("match-label.default",{matchNumber:t});const r=c("winner_bracket"===o?"match-label.winner-bracket":"loser_bracket"===o?"match-label.loser-bracket":"match-label.standard-bracket"),i=e===n-1,a=e===n;if("single_bracket"===o){if(i)return c("match-label.standard-bracket-semi-final",{matchNumber:t});if(a)return c("match-label.standard-bracket-final")}return i?c("match-label.double-elimination-semi-final",{matchPrefix:r,matchNumber:t}):a?c("match-label.double-elimination-final",{matchPrefix:r}):c("match-label.double-elimination",{matchPrefix:r,roundNumber:e,matchNumber:t})},e.getFinalMatchLabel=function(t,e,n){return"consolation_final"===t?c("match-label.consolation-final"):1===n?c("match-label.grand-final-single"):c("match-label.grand-final",{roundNumber:e})},e.getMatchStatus=function(t){switch(t){case a.Status.Locked:return c("match-status.locked");case a.Status.Waiting:return c("match-status.waiting");case a.Status.Ready:return c("match-status.ready");case a.Status.Running:return c("match-status.running");case a.Status.Completed:return c("match-status.completed");case a.Status.Archived:return c("match-status.archived");default:return"Unknown status"}},e.getGroupName=function(t){return c("common.group-name",{groupNumber:t})},e.getBracketName=function(t,e){switch(e){case"winner_bracket":case"loser_bracket":return c(`common.group-name-${d(e)}`,{stage:t});default:return}},e.getRoundName=function({roundNumber:t,roundCount:e},n){return t===e?n("common.round-name-final"):n("common.round-name",{roundNumber:t})},e.getWinnerBracketRoundName=function({roundNumber:t,roundCount:e},n){return t===e?n("common.round-name-winner-bracket-final"):n("common.round-name-winner-bracket",{roundNumber:t})},e.getLoserBracketRoundName=function({roundNumber:t,roundCount:e},n){return t===e?n("common.round-name-loser-bracket-final"):n("common.round-name-loser-bracket",{roundNumber:t})}},945:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.BaseGetter=void 0;const o=n(4487);e.BaseGetter=class{constructor(t){this.storage=t}async getOrderedRounds(t){if(!(null==t?void 0:t.settings.size))throw Error("The stage has no size.");return"single_elimination"===t.type?this.getOrderedRoundsSingleElimination(t.id):this.getOrderedRoundsDoubleElimination(t.id)}async getOrderedRoundsSingleElimination(t){return[await this.getUpperBracketFirstRound(t)]}async getOrderedRoundsDoubleElimination(t){const e=await this.storage.select("round",{stage_id:t});if(!e)throw Error("Error getting rounds.");const n=await this.getLoserBracket(t);if(!n)throw Error("Loser bracket not found.");const r=e[0],i=e.filter((t=>t.group_id===n.id));return[r,...i.filter((t=>o.isOrderingSupportedLoserBracket(t.number,i.length)))]}async getRoundPositionalInfo(t){const e=await this.storage.select("round",t);if(!e)throw Error("Round not found.");const n=await this.storage.select("round",{group_id:e.group_id});if(!n)throw Error("Error getting rounds.");return{roundNumber:e.number,roundCount:n.length}}async getPreviousMatches(t,e,n,o){return"loser_bracket"===e?this.getPreviousMatchesLB(t,n,o):"final_group"===e?this.getPreviousMatchesFinal(t,n,o):1===o?[]:this.getMatchesBeforeMajorRound(t,o)}async getPreviousMatchesFinal(t,e,n){return"single_elimination"===e.type?this.getPreviousMatchesFinalSingleElimination(t,e):this.getPreviousMatchesFinalDoubleElimination(t,n)}async getPreviousMatchesFinalSingleElimination(t,e){const n=await this.getUpperBracket(t.stage_id),r=o.getUpperBracketRoundCount(e.settings.size),i=await this.storage.selectFirst("round",{group_id:n.id,number:r-1});if(!i)throw Error("Semi finals round not found.");const a=await this.storage.select("match",{round_id:i.id});if(!a)throw Error("Error getting semi final matches.");return a}async getPreviousMatchesFinalDoubleElimination(t,e){if(e>1)return[await this.findMatch(t.group_id,e-1,1)];const n=await this.getUpperBracket(t.stage_id),o=await this.getLastRound(n.id),r=await this.storage.selectFirst("match",{round_id:o.id,number:1});if(!r)throw Error("Match not found.");const i=await this.getLoserBracket(t.stage_id);if(!i)throw Error("Loser bracket not found.");const a=await this.getLastRound(i.id),s=await this.storage.selectFirst("match",{round_id:a.id,number:1});if(!s)throw Error("Match not found.");return[r,s]}async getPreviousMatchesLB(t,e,n){if(e.settings.skipFirstRound&&1===n)return[];if(o.hasBye(t))return[];const r=await this.getUpperBracket(t.stage_id),i=Math.ceil((n+1)/2),a=e.settings.skipFirstRound?i-1:i;return 1===n?this.getMatchesBeforeFirstRoundLB(t,r.id,a):n%2==0?this.getMatchesBeforeMinorRoundLB(t,r.id,n,a):this.getMatchesBeforeMajorRound(t,n)}async getMatchesBeforeMajorRound(t,e){return[await this.findMatch(t.group_id,e-1,2*t.number-1),await this.findMatch(t.group_id,e-1,2*t.number)]}async getMatchesBeforeFirstRoundLB(t,e,n){return[await this.findMatch(e,n,o.getOriginPosition(t,"opponent1")),await this.findMatch(e,n,o.getOriginPosition(t,"opponent2"))]}async getMatchesBeforeMinorRoundLB(t,e,n,r){const i=o.getOriginPosition(t,"opponent1");return[await this.findMatch(e,r,i),await this.findMatch(t.group_id,n-1,t.number)]}async getNextMatches(t,e,n,o,r){switch(e){case"single_bracket":return this.getNextMatchesUpperBracket(t,n.type,o,r);case"winner_bracket":return this.getNextMatchesWB(t,n,o,r);case"loser_bracket":return this.getNextMatchesLB(t,n.type,o,r);case"final_group":return this.getNextMatchesFinal(t,o,r);default:throw Error("Unknown bracket kind.")}}async getNextMatchesWB(t,e,n,r){const i=await this.getLoserBracket(t.stage_id);if(null===i)return[];const a=e.settings.skipFirstRound?n+1:n,s=a>1?2*(a-1):1,u=e.settings.size,l=o.getLoserOrdering(e.settings.seedOrdering,s),c=o.findLoserMatchNumber(u,s,t.number,l);return[...await this.getNextMatchesUpperBracket(t,e.type,n,r),await this.findMatch(i.id,s,c)]}async getNextMatchesUpperBracket(t,e,n,o){return"single_elimination"===e?this.getNextMatchesUpperBracketSingleElimination(t,e,n,o):"double_elimination"===e&&n===o?[await this.getFirstMatchFinal(t,e)]:[await this.getDiagonalMatch(t.group_id,n,t.number)]}async getNextMatchesUpperBracketSingleElimination(t,e,n,o){if(n===o-1){const o=await this.getFirstMatchFinal(t,e);return[await this.getDiagonalMatch(t.group_id,n,t.number),...o?[o]:[]]}return n===o?[]:[await this.getDiagonalMatch(t.group_id,n,t.number)]}async getNextMatchesLB(t,e,n,o){if(n===o){const n=await this.getFirstMatchFinal(t,e);return n?[n]:[]}return n%2==1?this.getMatchAfterMajorRoundLB(t,n):this.getMatchAfterMinorRoundLB(t,n)}async getFirstMatchFinal(t,e){const n=await this.getFinalGroupId(t.stage_id,e);return null===n?null:this.findMatch(n,1,1)}async getNextMatchesFinal(t,e,n){return e===n?[]:[await this.findMatch(t.group_id,e+1,1)]}async getMatchAfterMajorRoundLB(t,e){return[await this.getParallelMatch(t.group_id,e,t.number)]}async getMatchAfterMinorRoundLB(t,e){return[await this.getDiagonalMatch(t.group_id,e,t.number)]}static getSeedingOrdering(t,e){return"round_robin"===t?e.getRoundRobinOrdering():e.getStandardBracketFirstRoundOrdering()}async getSeedingMatches(t,e){if("round_robin"===e)return this.storage.select("match",{stage_id:t});try{const e=await this.getUpperBracketFirstRound(t);return this.storage.select("match",{round_id:e.id})}catch{return[]}}async getUpperBracketFirstRound(t){const e=await this.storage.selectFirst("round",{stage_id:t,number:1},!1);if(!e)throw Error("Round not found.");return e}async getLastRound(t){const e=await this.storage.selectLast("round",{group_id:t},!1);if(!e)throw Error("Error getting rounds.");return e}async getFinalGroupId(t,e){const n="single_elimination"===e?2:3,o=await this.storage.selectFirst("group",{stage_id:t,number:n});return o?o.id:null}async getUpperBracket(t){const e=await this.storage.selectFirst("group",{stage_id:t,number:1});if(!e)throw Error("Winner bracket not found.");return e}async getLoserBracket(t){return this.storage.selectFirst("group",{stage_id:t,number:2})}async getDiagonalMatch(t,e,n){return this.findMatch(t,e+1,o.getDiagonalMatchNumber(n))}async getParallelMatch(t,e,n){return this.findMatch(t,e+1,n)}async findMatch(t,e,n){const o=await this.storage.selectFirst("round",{group_id:t,number:e});if(!o)throw Error("Round not found.");const r=await this.storage.selectFirst("match",{round_id:o.id,number:n});if(!r)throw Error("Match not found.");return r}async findMatchGame(t){if(void 0!==t.id){const e=await this.storage.select("match_game",t.id);if(!e)throw Error("Match game not found.");return e}if(void 0!==t.parent_id&&t.number){const e=await this.storage.selectFirst("match_game",{parent_id:t.parent_id,number:t.number});if(!e)throw Error("Match game not found.");return e}throw Error("No match game id nor parent id and number given.")}}},4267:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.StageCreator=e.create=void 0;const o=n(2644),r=n(4487);e.create=async function(t){return new i(this.storage,t).run()};class i{constructor(t,e){if(this.storage=t,this.stage=e,this.stage.settings=this.stage.settings||{},this.seedOrdering=this.stage.settings.seedOrdering||[],this.updateMode=!1,this.enableByesInUpdate=!1,!this.stage.name)throw Error("You must provide a name for the stage.");if(void 0===this.stage.tournamentId)throw Error("You must provide a tournament id for the stage.");"round_robin"===e.type&&(this.stage.settings.roundRobinMode=this.stage.settings.roundRobinMode||"simple"),"single_elimination"===e.type&&(this.stage.settings.consolationFinal=this.stage.settings.consolationFinal||!1),"double_elimination"===e.type&&(this.stage.settings.grandFinal=this.stage.settings.grandFinal||"none"),this.stage.settings.matchesChildCount=this.stage.settings.matchesChildCount||0}async run(){let t;switch(this.stage.type){case"round_robin":t=await this.roundRobin();break;case"single_elimination":t=await this.singleElimination();break;case"double_elimination":t=await this.doubleElimination();break;default:throw Error("Unknown stage type.")}if(-1===t.id)throw Error("Something went wrong when creating the stage.");return await this.ensureSeedOrdering(t.id),t}setExisting(t,e){this.updateMode=!0,this.currentStageId=t,this.enableByesInUpdate=e}async roundRobin(){const t=await this.getRoundRobinGroups(),e=await this.createStage();for(let n=0;n<t.length;n++)await this.createRoundRobinGroup(e.id,n+1,t[n]);return e}async singleElimination(){var t,e;if(Array.isArray(null===(t=this.stage.settings)||void 0===t?void 0:t.seedOrdering)&&1!==(null===(e=this.stage.settings)||void 0===e?void 0:e.seedOrdering.length))throw Error("You must specify one seed ordering method.");const n=await this.getSlots(),r=await this.createStage(),i=this.getStandardBracketFirstRoundOrdering(),a=o.ordering[i](n),{losers:s}=await this.createStandardBracket(r.id,1,a);return await this.createConsolationFinal(r.id,s),r}async doubleElimination(){var t;if(this.stage.settings&&Array.isArray(this.stage.settings.seedOrdering)&&this.stage.settings.seedOrdering.length<1)throw Error("You must specify at least one seed ordering method.");const e=await this.getSlots(),n=await this.createStage(),r=this.getStandardBracketFirstRoundOrdering(),i=o.ordering[r](e);return(null===(t=this.stage.settings)||void 0===t?void 0:t.skipFirstRound)?await this.createDoubleEliminationSkipFirstRound(n.id,i):await this.createDoubleElimination(n.id,i),n}async createDoubleEliminationSkipFirstRound(t,e){var n;const{even:o,odd:i}=r.splitByParity(e),{losers:a,winner:s}=await this.createStandardBracket(t,1,o);if(r.isDoubleEliminationNecessary(null===(n=this.stage.settings)||void 0===n?void 0:n.size)){const e=await this.createLowerBracket(t,2,[i,...a]);await this.createGrandFinal(t,s,e)}}async createDoubleElimination(t,e){var n;const{losers:o,winner:i}=await this.createStandardBracket(t,1,e);if(r.isDoubleEliminationNecessary(null===(n=this.stage.settings)||void 0===n?void 0:n.size)){const e=await this.createLowerBracket(t,2,o);await this.createGrandFinal(t,i,e)}}async createRoundRobinGroup(t,e,n){var o;const i=await this.insertGroup({stage_id:t,number:e});if(-1===i)throw Error("Could not insert the group.");const a=r.makeRoundRobinMatches(n,null===(o=this.stage.settings)||void 0===o?void 0:o.roundRobinMode);for(let e=0;e<a.length;e++)await this.createRound(t,i,e+1,a[0].length,a[e])}async createStandardBracket(t,e,n){const o=r.getUpperBracketRoundCount(n.length),i=await this.insertGroup({stage_id:t,number:e});if(-1===i)throw Error("Could not insert the group.");let a=r.makePairs(n),s=1;const u=[];for(let e=o-1;e>=0;e--){const n=Math.pow(2,e);a=this.getCurrentDuels(a,n),u.push(a.map(r.byeLoser)),await this.createRound(t,i,s++,n,a)}return{losers:u,winner:r.byeWinner(a[0])}}async createLowerBracket(t,e,n){var i;const a=null===(i=this.stage.settings)||void 0===i?void 0:i.size,s=r.getRoundPairCount(a);let u=0;const l=this.getMajorOrdering(a),c=o.ordering[l](n[u++]),d=await this.insertGroup({stage_id:t,number:e});if(-1===d)throw Error("Could not insert the group.");let p=r.makePairs(c),g=1;for(let e=0;e<s;e++){const o=Math.pow(2,s-e-1);p=this.getCurrentDuels(p,o,!0),await this.createRound(t,d,g++,o,p);const r=this.getMinorOrdering(a,e,s);p=this.getCurrentDuels(p,o,!1,n[u++],r),await this.createRound(t,d,g++,o,p)}return r.byeWinnerToGrandFinal(p[0])}async createUniqueMatchBracket(t,e,n){const o=await this.insertGroup({stage_id:t,number:e});if(-1===o)throw Error("Could not insert the group.");for(let e=0;e<n.length;e++)await this.createRound(t,o,e+1,1,[n[e]])}async createRound(t,e,n,o,r){const i=this.getMatchesChildCount(),a=await this.insertRound({number:n,stage_id:t,group_id:e});if(-1===a)throw Error("Could not insert the round.");for(let n=0;n<o;n++)await this.createMatch(t,e,a,n+1,r[n],i)}async createMatch(t,e,n,o,i,a){const s=r.toResultWithPosition(i[0]),u=r.toResultWithPosition(i[1]);if("round_robin"===this.stage.type&&null===s&&null===u)return;let l=null,c=r.getMatchStatus(i);if(this.updateMode){l=await this.storage.selectFirst("match",{round_id:n,number:o});const t=null==l?void 0:l.child_count;if(a=void 0===t?a:t,l){const t=r.getMatchStatus(l);t>c&&(c=t)}}const d=await this.insertMatch({number:o,stage_id:t,group_id:e,round_id:n,child_count:a,status:c,opponent1:s,opponent2:u},l);if(-1===d)throw Error("Could not insert the match.");for(let e=0;e<a;e++)if(-1===await this.insertMatchGame({number:e+1,stage_id:t,parent_id:d,status:c,opponent1:r.toResult(i[0]),opponent2:r.toResult(i[1])}))throw Error("Could not insert the match game.")}getCurrentDuels(t,e,n,o,i){return void 0!==n&&!n||t.length!==e?void 0===n||n?r.transitionToMajor(t):r.transitionToMinor(t,o,i):t}async getSlots(t){var e;let n=this.stage.seedingIds||this.stage.seeding;const o=(null===(e=this.stage.settings)||void 0===e?void 0:e.size)||(null==n?void 0:n.length)||0;if(r.ensureValidSize(this.stage.type,o),o&&!n)return Array.from(Array(o),((t,e)=>({id:null,position:e+1})));if(!n)throw Error("Either size or seeding must be given.");return this.stage.settings={...this.stage.settings,size:o},r.ensureNoDuplicates(n),n=r.fixSeeding(n,o),"round_robin"!==this.stage.type&&this.stage.settings.balanceByes&&(n=r.balanceByes(n,this.stage.settings.size)),this.stage.seeding=n,void 0!==this.stage.seedingIds||r.isSeedingWithIds(n)?this.getSlotsUsingIds(n,t):this.getSlotsUsingNames(n,t)}async getSlotsUsingNames(t,e){const n=r.extractParticipantsFromSeeding(this.stage.tournamentId,t);if(!await this.registerParticipants(n))throw Error("Error registering the participants.");const o=await this.storage.select("participant",{tournament_id:this.stage.tournamentId});if(!o)throw Error("Error getting registered participant.");return r.mapParticipantsNamesToDatabase(t,o,e)}async getSlotsUsingIds(t,e){const n=await this.storage.select("participant",{tournament_id:this.stage.tournamentId});if(!n)throw Error("No available participants.");return r.mapParticipantsIdsToDatabase(t,n,e)}async getStageNumber(){const t=await this.storage.select("stage",{tournament_id:this.stage.tournamentId}),e=null==t?void 0:t.map((t=>{var e;return null!==(e=t.number)&&void 0!==e?e:0}));if(void 0!==this.stage.number){if(null==e?void 0:e.includes(this.stage.number))throw Error("The given stage number already exists.");return this.stage.number}return(null==e?void 0:e.length)?Math.max(...e)+1:1}getMatchesChildCount(){var t;return(null===(t=this.stage.settings)||void 0===t?void 0:t.matchesChildCount)?this.stage.settings.matchesChildCount:0}getOrdering(t,e,n){var o;if(!(null===(o=this.stage.settings)||void 0===o?void 0:o.seedOrdering))return this.seedOrdering.push(n),n;const r=this.stage.settings.seedOrdering[t];if(!r)return this.seedOrdering.push(n),n;if("elimination"===e&&r.match(/^groups\./))throw Error("You must specify a seed ordering method without a 'groups' prefix");if("groups"===e&&"natural"!==r&&!r.match(/^groups\./))throw Error("You must specify a seed ordering method with a 'groups' prefix");return r}async getRoundRobinGroups(){var t,e,n,i,a;if(void 0===(null===(t=this.stage.settings)||void 0===t?void 0:t.groupCount)||!Number.isInteger(this.stage.settings.groupCount))throw Error("You must specify a group count for round-robin stages.");if(this.stage.settings.groupCount<=0)throw Error("You must provide a strictly positive group count.");if(null===(e=this.stage.settings)||void 0===e?void 0:e.manualOrdering){if((null===(n=this.stage.settings)||void 0===n?void 0:n.manualOrdering.length)!==(null===(i=this.stage.settings)||void 0===i?void 0:i.groupCount))throw Error("Group count in the manual ordering does not correspond to the given group count.");const t=null===(a=this.stage.settings)||void 0===a?void 0:a.manualOrdering.flat(),e=await this.getSlots(t);return r.makeGroups(e,this.stage.settings.groupCount)}if(Array.isArray(this.stage.settings.seedOrdering)&&1!==this.stage.settings.seedOrdering.length)throw Error("You must specify one seed ordering method.");const s=this.getRoundRobinOrdering(),u=await this.getSlots(),l=o.ordering[s](u,this.stage.settings.groupCount);return r.makeGroups(l,this.stage.settings.groupCount)}getRoundRobinOrdering(){return this.getOrdering(0,"groups","groups.effort_balanced")}getStandardBracketFirstRoundOrdering(){return this.getOrdering(0,"elimination","inner_outer")}getMajorOrdering(t){var e;return this.getOrdering(1,"elimination",(null===(e=o.defaultMinorOrdering[t])||void 0===e?void 0:e[0])||"natural")}getMinorOrdering(t,e,n){var r;if(e!==n-1)return this.getOrdering(2+e,"elimination",(null===(r=o.defaultMinorOrdering[t])||void 0===r?void 0:r[1+e])||"natural")}async insertStage(t){let e=null;if(this.updateMode){if(e=await this.storage.select("stage",this.currentStageId),!e)throw Error("Stage not found.");const n={...e,...t,settings:{...e.settings,...t.settings}};if(!await this.storage.update("stage",this.currentStageId,n))throw Error("Could not update the stage.")}return e?e.id:this.storage.insert("stage",t)}async insertGroup(t){let e=null;return this.updateMode&&(e=await this.storage.selectFirst("group",{stage_id:t.stage_id,number:t.number})),e?e.id:this.storage.insert("group",t)}async insertRound(t){let e=null;return this.updateMode&&(e=await this.storage.selectFirst("round",{group_id:t.group_id,number:t.number})),e?e.id:this.storage.insert("round",t)}async insertMatch(t,e){if(!e)return this.storage.insert("match",t);const n=r.getUpdatedMatchResults(t,e,this.enableByesInUpdate);if(!await this.storage.update("match",e.id,n))throw Error("Could not update the match.");return e.id}async insertMatchGame(t){let e=null;if(this.updateMode&&(e=await this.storage.selectFirst("match_game",{parent_id:t.parent_id,number:t.number})),!e)return this.storage.insert("match_game",t);const n=r.getUpdatedMatchResults(t,e,this.enableByesInUpdate);if(!await this.storage.update("match_game",e.id,n))throw Error("Could not update the match game.");return e.id}async registerParticipants(t){const e=await this.storage.select("participant",{tournament_id:this.stage.tournamentId});if(!e||0===e.length)return this.storage.insert("participant",t);for(const n of t)if(!e.some((t=>t.name===n.name))&&-1===await this.storage.insert("participant",n))return!1;return!0}async createStage(){const t=await this.getStageNumber(),e={tournament_id:this.stage.tournamentId,name:this.stage.name,type:this.stage.type,number:t,settings:this.stage.settings||{}},n=await this.insertStage(e);if(-1===n)throw Error("Could not insert the stage.");return{...e,id:n}}async createConsolationFinal(t,e){var n;if(!(null===(n=this.stage.settings)||void 0===n?void 0:n.consolationFinal))return;const o=e[e.length-2];await this.createUniqueMatchBracket(t,2,[o])}async createGrandFinal(t,e,n){var o;const r=null===(o=this.stage.settings)||void 0===o?void 0:o.grandFinal;if("none"===r)return;const i=[[e,n]];"double"===r&&i.push([{id:null},{id:null}]),await this.createUniqueMatchBracket(t,3,i)}async ensureSeedOrdering(t){var e,n;if((null===(n=null===(e=this.stage.settings)||void 0===e?void 0:e.seedOrdering)||void 0===n?void 0:n.length)===this.seedOrdering.length)return;const o=await this.storage.select("stage",t);if(!o)throw Error("Stage not found.");const r={...o,settings:{...o.settings,seedOrdering:this.seedOrdering}};if(!await this.storage.update("stage",t,r))throw Error("Could not update the stage.")}}e.StageCreator=i},3517:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.BaseUpdater=void 0;const o=n(7021),r=n(2644),i=n(4267),a=n(945),s=n(3576),u=n(4487);class l extends a.BaseGetter{async updateSeeding(t,{seeding:e,seedingIds:n}){var o,s;const u=await this.storage.select("stage",t);if(!u)throw Error("Stage not found.");const c=null!==(s=null===(o=n||e)||void 0===o?void 0:o.length)&&void 0!==s?s:0,d=new i.StageCreator(this.storage,{name:u.name,tournamentId:u.tournament_id,type:u.type,settings:{...u.settings,...0===c?{}:{size:c}},...n?{seedingIds:n}:{seeding:null!=e?e:void 0}});d.setExisting(t,!1);const p=a.BaseGetter.getSeedingOrdering(u.type,d),g=await d.getSlots(),f=await this.getSeedingMatches(u.id,u.type);if(!f)throw Error("Error getting matches associated to the seeding.");const h=r.ordering[p](g);l.assertCanUpdateSeeding(f,h),await d.run()}async confirmCurrentSeeding(t){const e=await this.storage.select("stage",t);if(!e)throw Error("Stage not found.");const n=new s.Get(this.storage),o=await n.seeding(t),r=u.convertSlotsToSeeding(o.map(u.convertTBDtoBYE)),a=new i.StageCreator(this.storage,{name:e.name,tournamentId:e.tournament_id,type:e.type,settings:e.settings,seeding:r});a.setExisting(t,!0),await a.run()}async updateParentMatch(t,e){const n=await this.storage.select("match",t);if(!n)throw Error("Parent not found.");const o=await this.storage.select("match_game",{parent_id:t});if(!o)throw Error("No match games.");const r=u.getChildGamesResults(o),i=u.getParentMatchResults(n,r);u.setParentMatchCompleted(i,n.child_count,e),await this.updateMatch(n,i,!0)}static assertCanUpdateSeeding(t,e){var n,r;let i=0;for(const a of t){if(a.status===o.Status.Archived)throw Error("A match of round 1 is archived, which means round 2 was started.");const t=e[i++],s=e[i++];if(u.isMatchParticipantLocked(a)&&((null===(n=a.opponent1)||void 0===n?void 0:n.id)!==(null==t?void 0:t.id)||(null===(r=a.opponent2)||void 0===r?void 0:r.id)!==(null==s?void 0:s.id)))throw Error("A match is locked.")}}async updateRelatedMatches(t,e,n){const{roundNumber:o,roundCount:r}=await this.getRoundPositionalInfo(t.round_id),i=await this.storage.select("stage",t.stage_id);if(!i)throw Error("Stage not found.");const a=await this.storage.select("group",t.group_id);if(!a)throw Error("Group not found.");const s=u.getMatchLocation(i.type,a.number);e&&await this.updatePrevious(t,s,i,o),n&&await this.updateNext(t,s,i,o,r)}async updateMatch(t,e,n){if(!n&&u.isMatchUpdateLocked(t))throw Error("The match is locked.");const o=await this.storage.select("stage",t.stage_id);if(!o)throw Error("Stage not found.");const r=u.isRoundRobin(o),{statusChanged:i,resultChanged:a}=u.setMatchResults(t,e,r);await this.applyMatchUpdate(t),(i||a)&&(u.isRoundRobin(o)||await this.updateRelatedMatches(t,i,a))}async updateMatchGame(t,e){if(u.isMatchUpdateLocked(t))throw Error("The match game is locked.");const n=await this.storage.select("stage",t.stage_id);if(!n)throw Error("Stage not found.");const o=u.isRoundRobin(n);if(u.setMatchResults(t,e,o),!await this.storage.update("match_game",t.id,t))throw Error("Could not update the match game.");await this.updateParentMatch(t.parent_id,o)}async applyMatchUpdate(t){if(!await this.storage.update("match",t.id,t))throw Error("Could not update the match.");if(0===t.child_count)return;const e={opponent1:u.toResult(t.opponent1),opponent2:u.toResult(t.opponent2)};if((t.status<=o.Status.Ready||t.status===o.Status.Archived)&&(e.status=t.status),!await this.storage.update("match_game",{parent_id:t.id},e))throw Error("Could not update the match game.")}async updatePrevious(t,e,n,r){const i=await this.getPreviousMatches(t,e,n,r);0!==i.length&&(t.status>=o.Status.Running?await this.archiveMatches(i):await this.resetMatchesStatus(i))}async archiveMatches(t){for(const e of t)e.status!==o.Status.Archived&&(e.status=o.Status.Archived,await this.applyMatchUpdate(e))}async resetMatchesStatus(t){for(const e of t)e.status=u.getMatchStatus(e),await this.applyMatchUpdate(e)}async updateNext(t,e,n,r,i){const a=await this.getNextMatches(t,e,n,r,i);if(0===a.length)return void(t.status===o.Status.Completed&&await this.archiveMatches([t]));const s=u.getMatchResult(t),l=n.settings.skipFirstRound&&"winner_bracket"===e?r+1:r;s?await this.applyToNextMatches(u.setNextOpponent,t,e,l,i,a,s):await this.applyToNextMatches(u.resetNextOpponent,t,e,l,i,a)}async applyToNextMatches(t,e,n,o,r,i,a){if("final_group"===n){if(!i[0])throw Error("First next match is null.");return t(i[0],"opponent1",e,"opponent1"),t(i[0],"opponent2",e,"opponent2"),void await this.applyMatchUpdate(i[0])}const s=u.getNextSide(e.number,o,r,n);if(i[0]&&(t(i[0],s,e,a),await this.propagateByeWinners(i[0])),2===i.length){if(!i[1])throw Error("Second next match is null.");if("single_bracket"===n)t(i[1],s,e,a&&u.getOtherSide(a)),await this.applyMatchUpdate(i[1]);else{const n=u.getNextSideLoserBracket(e.number,i[1],o);t(i[1],n,e,a&&u.getOtherSide(a)),await this.propagateByeWinners(i[1])}}}async propagateByeWinners(t){u.setMatchResults(t,t,!1),await this.applyMatchUpdate(t),u.hasBye(t)&&await this.updateRelatedMatches(t,!0,!0)}}e.BaseUpdater=l},9765:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Create=void 0;const o=n(4267);e.Create=class{constructor(t){this.storage=t}async stage(t){return new o.StageCreator(this.storage,t).run()}}},4378:function(t,e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Delete=void 0,e.Delete=class{constructor(t){this.storage=t}async stage(t){if(!await this.storage.delete("match_game",{stage_id:t}))throw Error("Could not delete match games.");if(!await this.storage.delete("match",{stage_id:t}))throw Error("Could not delete matches.");if(!await this.storage.delete("round",{stage_id:t}))throw Error("Could not delete rounds.");if(!await this.storage.delete("group",{stage_id:t}))throw Error("Could not delete groups.");if(!await this.storage.delete("stage",{id:t}))throw Error("Could not delete the stage.")}async tournament(t){const e=await this.storage.select("stage",{tournament_id:t});if(!e)throw Error("Error getting the stages.");for(const t of e)await this.stage(t.id)}}},4063:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Find=void 0;const o=n(945),r=n(4487);class i extends o.BaseGetter{async upperBracket(t){const e=await this.storage.select("stage",t);if(!e)throw Error("Stage not found.");switch(e.type){case"round_robin":throw Error("Round-robin stages do not have an upper bracket.");case"single_elimination":case"double_elimination":return this.getUpperBracket(t);default:throw Error("Unknown stage type.")}}async loserBracket(t){const e=await this.storage.select("stage",t);if(!e)throw Error("Stage not found.");switch(e.type){case"round_robin":throw Error("Round-robin stages do not have a loser bracket.");case"single_elimination":throw Error("Single elimination stages do not have a loser bracket.");case"double_elimination":const e=await this.getLoserBracket(t);if(!e)throw Error("Loser bracket not found.");return e;default:throw Error("Unknown stage type.")}}async previousMatches(t,e){const n=await this.storage.select("match",t);if(!n)throw Error("Match not found.");const o=await this.storage.select("stage",n.stage_id);if(!o)throw Error("Stage not found.");const i=await this.storage.select("group",n.group_id);if(!i)throw Error("Group not found.");const a=await this.storage.select("round",n.round_id);if(!a)throw Error("Round not found.");const s=r.getMatchLocation(o.type,i.number),u=await this.getPreviousMatches(n,s,o,a.number);return void 0!==e?u.filter((t=>r.isParticipantInMatch(t,e))):u}async nextMatches(t,e){const n=await this.storage.select("match",t);if(!n)throw Error("Match not found.");const o=await this.storage.select("stage",n.stage_id);if(!o)throw Error("Stage not found.");const i=await this.storage.select("group",n.group_id);if(!i)throw Error("Group not found.");const{roundNumber:a,roundCount:s}=await this.getRoundPositionalInfo(n.round_id),u=r.getMatchLocation(o.type,i.number),l=r.getNonNull(await this.getNextMatches(n,u,o,a,s));if(void 0!==e){const t=r.getLoser(n);if("single_elimination"===o.type&&(null==t?void 0:t.id)===e)return[];if("double_elimination"===o.type){const[o,i]=l;if((null==t?void 0:t.id)===e)return i?[i]:[];const a=r.getWinner(n);if((null==a?void 0:a.id)===e)return[o];throw Error("The participant does not belong to this match.")}}return l}async match(t,e,n){return this.findMatch(t,e,n)}async matchGame(t){return this.findMatchGame(t)}}e.Find=i},3576:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Get=void 0;const o=n(7021),r=n(945),i=n(4487);class a extends r.BaseGetter{async stageData(t){const e=await this.getStageSpecificData(t),n=await this.storage.select("participant",{tournament_id:e.stage.tournament_id});if(!n)throw Error("Error getting participants.");return{stage:[e.stage],group:e.groups,round:e.rounds,match:e.matches,match_game:e.matchGames,participant:n}}async tournamentData(t){const e=await this.storage.select("stage",{tournament_id:t});if(!e)throw Error("Error getting stages.");const n=await Promise.all(e.map((t=>this.getStageSpecificData(t.id)))),o=await this.storage.select("participant",{tournament_id:t});if(!o)throw Error("Error getting participants.");return{stage:e,group:n.reduce(((t,e)=>[...t,...e.groups]),[]),round:n.reduce(((t,e)=>[...t,...e.rounds]),[]),match:n.reduce(((t,e)=>[...t,...e.matches]),[]),match_game:n.reduce(((t,e)=>[...t,...e.matchGames]),[]),participant:o}}async matchGames(t){const e=t.filter((t=>t.child_count>0)),n=await Promise.all(e.map((t=>this.storage.select("match_game",{parent_id:t.id}))));if(n.some((t=>null===t)))throw Error("Error getting match games.");return i.getNonNull(n).flat()}async currentStage(t){const e=await this.storage.select("stage",{tournament_id:t});if(!e)throw Error("Error getting stages.");for(const t of e){const e=await this.storage.select("match",{stage_id:t.id});if(!e)throw Error("Error getting matches.");if(!e.every((t=>t.status>=o.Status.Completed)))return t}return null}async currentRound(t){const e=await this.storage.select("match",{stage_id:t});if(!e)throw Error("Error getting matches.");const n=i.splitBy(e,"round_id");for(const t of n){if(t.every((t=>t.status>=o.Status.Completed)))continue;const e=await this.storage.select("round",t[0].round_id);if(!e)throw Error("Round not found.");return e}return null}async currentMatches(t){const e=await this.storage.select("stage",t);if(!e)throw Error("Stage not found.");if("single_elimination"!==e.type)throw Error("Not implemented for round robin and double elimination. Ask if needed.");const n=await this.storage.select("match",{stage_id:t});if(!n)throw Error("Error getting matches.");const o=i.splitBy(n,"round_id"),r=i.getUpperBracketRoundCount(e.settings.size);let a=-1;const s=[];for(const t of o){if(a++,e.settings.consolationFinal&&a===r-1){const[e]=t,[n]=o[a+1],r=[e,n];return r.every((t=>!i.isMatchOngoing(t)))?[]:r.filter((t=>i.isMatchOngoing(t)))}t.every((t=>!i.isMatchOngoing(t)))||s.push(...t.filter((t=>i.isMatchOngoing(t))))}return s}async seeding(t){const e=await this.storage.select("stage",t);if(!e)throw Error("Stage not found.");const n=t=>{if(null===t)return null;const{id:e,position:n}=t;return{id:e,position:n}};return"round_robin"===e.type?(await this.roundRobinSeeding(e)).map(n):(await this.eliminationSeeding(e)).map(n)}async finalStandings(t){const e=await this.storage.select("stage",t);if(!e)throw Error("Stage not found.");switch(e.type){case"round_robin":throw Error("A round-robin stage does not have standings.");case"single_elimination":return this.singleEliminationStandings(t);case"double_elimination":return this.doubleEliminationStandings(t);default:throw Error("Unknown stage type.")}}async roundRobinSeeding(t){if(void 0===t.settings.size)throw Error("The size of the seeding is undefined.");const e=await this.storage.select("match",{stage_id:t.id});if(!e)throw Error("Error getting matches.");const n=i.convertMatchesToSeeding(e);if(n.length<t.settings.size){const e=t.settings.size-n.length;for(let t=0;t<e;t++)n.push(null)}const o=i.uniqueBy(n,(t=>t&&t.position));return i.setArraySize(o,t.settings.size,null)}async eliminationSeeding(t){const e=await this.storage.selectFirst("round",{stage_id:t.id,number:1},!1);if(!e)throw Error("Error getting the first round.");const n=await this.storage.select("match",{round_id:e.id});if(!n)throw Error("Error getting matches.");return i.convertMatchesToSeeding(n)}async singleEliminationStandings(t){var e;const n=[],{stage:o,group:r,match:a,participant:u}=await this.stageData(t),[l]=o,[c,d]=r,p=a.filter((t=>t.group_id===c.id)).pop();if(!p)throw Error("Final not found.");n[0]=[i.findParticipant(u,s(p))];const g=i.getLosers(u,a.filter((t=>t.group_id===c.id)));if(n.push(...g.reverse()),null===(e=l.settings)||void 0===e?void 0:e.consolationFinal){const t=a.filter((t=>t.group_id===d.id)).pop();if(!t)throw Error("Consolation final not found.");const e=i.findParticipant(u,s(t)),o=i.findParticipant(u,i.getLoser(t));n.splice(2,1,[e],[o])}return i.makeFinalStandings(n)}async doubleEliminationStandings(t){var e,n;const o=[],{stage:r,group:a,match:u,participant:l}=await this.stageData(t),[c]=r,[d,p,g]=a;if("none"===(null===(e=c.settings)||void 0===e?void 0:e.grandFinal)){const t=u.filter((t=>t.group_id===d.id)).pop();if(!t)throw Error("WB final not found.");const e=u.filter((t=>t.group_id===p.id)).pop();if(!e)throw Error("LB final not found.");o[0]=[i.findParticipant(l,s(t))],o[1]=[i.findParticipant(l,s(e))]}else{const t=u.filter((t=>t.group_id===g.id)),e=i.getGrandFinalDecisiveMatch((null===(n=c.settings)||void 0===n?void 0:n.grandFinal)||"none",t);o[0]=[i.findParticipant(l,s(e))],o[1]=[i.findParticipant(l,i.getLoser(e))]}const f=i.getLosers(l,u.filter((t=>t.group_id===p.id)));return o.push(...f.reverse()),i.makeFinalStandings(o)}async getStageSpecificData(t){const e=await this.storage.select("stage",t);if(!e)throw Error("Stage not found.");const n=await this.storage.select("group",{stage_id:t});if(!n)throw Error("Error getting groups.");const o=await this.storage.select("round",{stage_id:t});if(!o)throw Error("Error getting rounds.");const r=await this.storage.select("match",{stage_id:t});if(!r)throw Error("Error getting matches.");return{stage:e,groups:n,rounds:o,matches:r,matchGames:await this.matchGames(r)}}}e.Get=a;const s=t=>{const e=i.getWinner(t);if(!e)throw Error("The final match does not have a winner.");return e}},4487:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.getOriginPosition=e.getOpponentId=e.setExtraFields=e.resetMatchResults=e.setMatchResults=e.getMatchStatus=e.hasBye=e.isMatchParticipantLocked=e.isMatchUpdateLocked=e.isMatchByeCompleted=e.isMatchWinCompleted=e.isMatchDrawCompleted=e.isMatchResultCompleted=e.isMatchForfeitCompleted=e.isMatchOngoing=e.isMatchCompleted=e.isMatchStarted=e.isMatchPending=e.getOtherSide=e.getSide=e.isParticipantInMatch=e.findPosition=e.getMatchResult=e.byeLoser=e.byeWinnerToGrandFinal=e.byeWinner=e.getLoser=e.getWinner=e.toResultWithPosition=e.toResult=e.convertTBDtoBYE=e.ensureNotTied=e.ensureValidSize=e.fixSeeding=e.ensureEquallySized=e.ensureNoDuplicates=e.ensureEvenSized=e.makePairs=e.setArraySize=e.normalizeParticipant=e.makeNormalizedIdMapping=e.normalizeIds=e.balanceByes=e.makeGroups=e.assertRoundRobin=e.makeRoundRobinDistribution=e.makeRoundRobinMatches=e.splitByParity=e.splitBy=e.isDefined=void 0,e.isRoundCompleted=e.ensureNotRoundRobin=e.isRoundRobin=e.minScoreToWinBestOfX=e.getNearestPowerOfTwo=e.getDiagonalMatchNumber=e.getLowerBracketRoundCount=e.getLoserOrdering=e.getLoserRoundLoserCount=e.getLoserRoundMatchCount=e.findLoserMatchNumber=e.isDoubleEliminationNecessary=e.getRoundPairCount=e.getUpperBracketRoundCount=e.isOrderingSupportedLoserBracket=e.isOrderingSupportedUpperBracket=e.ensureOrderingSupported=e.getSeedCount=e.getSeeds=e.getChildGamesResults=e.getUpdatedMatchResults=e.getParentMatchResults=e.setParentMatchCompleted=e.transitionToMinor=e.transitionToMajor=e.uniqueBy=e.getNonNull=e.sortSeeding=e.convertSlotsToSeeding=e.convertMatchesToSeeding=e.mapParticipantsToDatabase=e.mapParticipantsIdsToDatabase=e.mapParticipantsNamesToDatabase=e.extractParticipantsFromSeeding=e.isSeedingWithIds=e.setForfeits=e.setResults=e.setCompleted=e.setScores=e.invertOpponents=e.handleGivenStatus=e.handleOpponentsInversion=e.resetNextOpponent=e.setNextOpponent=e.getNextSideLoserBracket=e.getNextSide=e.findParticipant=e.getGrandFinalDecisiveMatch=e.makeFinalStandings=e.getLosers=void 0,e.getFractionOfFinal=e.getMatchLocation=e.isFinalGroup=e.isLoserBracket=e.isWinnerBracket=void 0;const o=n(7021),r=n(2644);function i(t){return null!=t}function a(t){const e=t.length,n=e%2==0?e:e+1,o=n-1,r=n/2,i=[];for(let a=0;a<o;a++){const o=[];for(let i=0;i<r;i++){if(0===i&&e%2==1)continue;const r=[(a-i-1+n)%(n-1),0===i?n-1:(a+i)%(n-1)];o.push([t[r[0]],t[r[1]]])}i.push(o)}return i}function s(t){let e=0;return t.reduce(((t,n)=>({...t,[n.id]:e++})),{})}function u(t,e){return null===t?null:{...t,id:null!==t.id?e[t.id]:null}}function l(t,e,n){return Array.from(Array(e),((e,o)=>t[o]||n))}function c(t){const e=p(t);return e?t[f(e)]:null}function d(t){return null===t[0]&&null===t[1]?null:null===t[0]&&null!==t[1]?{id:t[1].id}:null!==t[0]&&null===t[1]?{id:t[0].id}:{id:null}}function p(t){var e,n;if(!m(t))return null;if(y(t))return null;if(null===t.opponent1&&null===t.opponent2)return null;let o=null;if(("win"===(null===(e=t.opponent1)||void 0===e?void 0:e.result)||null===t.opponent2||t.opponent2.forfeit)&&(o="opponent1"),"win"===(null===(n=t.opponent2)||void 0===n?void 0:n.result)||null===t.opponent1||t.opponent1.forfeit){if(null!==o)throw Error("There are two winners.");o="opponent2"}return o}function g(t){return t%2==1?"opponent1":"opponent2"}function f(t){return"opponent1"===t?"opponent2":"opponent1"}function h(t){var e,n;return void 0!==(null===(e=t.opponent1)||void 0===e?void 0:e.score)||void 0!==(null===(n=t.opponent2)||void 0===n?void 0:n.score)}function m(t){return _(t)||v(t)||b(t)}function v(t){var e,n;return void 0!==(null===(e=t.opponent1)||void 0===e?void 0:e.forfeit)||void 0!==(null===(n=t.opponent2)||void 0===n?void 0:n.forfeit)}function b(t){return y(t)||w(t)}function y(t){var e,n;return"draw"===(null===(e=t.opponent1)||void 0===e?void 0:e.result)&&"draw"===(null===(n=t.opponent2)||void 0===n?void 0:n.result)}function w(t){var e,n,o,r;return"win"===(null===(e=t.opponent1)||void 0===e?void 0:e.result)||"win"===(null===(n=t.opponent2)||void 0===n?void 0:n.result)||"loss"===(null===(o=t.opponent1)||void 0===o?void 0:o.result)||"loss"===(null===(r=t.opponent2)||void 0===r?void 0:r.result)}function _(t){var e,n;return null===t.opponent1&&null!==(null===(e=t.opponent2)||void 0===e?void 0:e.id)||null===t.opponent2&&null!==(null===(n=t.opponent1)||void 0===n?void 0:n.id)||null===t.opponent1&&null===t.opponent2}function k(t){return null===t.opponent1||null===t.opponent2}function S(t){var e,n,r,i;const a=Array.isArray(t)?{opponent1:t[0],opponent2:t[1]}:t;return k(a)||null===(null===(e=a.opponent1)||void 0===e?void 0:e.id)&&null===(null===(n=a.opponent2)||void 0===n?void 0:n.id)?o.Status.Locked:null===(null===(r=a.opponent1)||void 0===r?void 0:r.id)||null===(null===(i=a.opponent2)||void 0===i?void 0:i.id)?o.Status.Waiting:m(a)?o.Status.Completed:h(a)?o.Status.Running:o.Status.Ready}function O(t){t.opponent1&&(t.opponent1.forfeit=void 0,t.opponent1.result=void 0),t.opponent2&&(t.opponent2.forfeit=void 0,t.opponent2.result=void 0),t.status=S(t)}function x(t,e){const n=(t,e,n)=>{t&&e&&Object.keys(e).filter((t=>!n.includes(t))).forEach((n=>{t[n]=e[n]}))},o=["id","score","position","forfeit","result"];n(t,e,["id","number","stage_id","group_id","round_id","status","opponent1","opponent2","child_count","parent_id"]),n(t.opponent1,e.opponent1,o),n(t.opponent2,e.opponent2,o)}function E(t,e){const n=t[e];return n&&n.id}function M(t,e){if(!e)throw Error("Cannot find a BYE participant.");const n=t.find((t=>t.id===(null==e?void 0:e.id)));if(!n)throw Error("Participant not found.");return n}function R(t,e){var n,o,r,a;const s=null===(n=e.opponent1)||void 0===n?void 0:n.id,u=null===(o=e.opponent2)||void 0===o?void 0:o.id,l=null===(r=t.opponent1)||void 0===r?void 0:r.id,c=null===(a=t.opponent2)||void 0===a?void 0:a.id;if(i(s)&&s!==l&&s!==c)throw Error("The given opponent1 ID does not exist in this match.");if(i(u)&&u!==l&&u!==c)throw Error("The given opponent2 ID does not exist in this match.");(i(s)&&s===c||i(u)&&u===l)&&C(e)}function P(t,e){var n,r,i,a;if(e.status===o.Status.Running)null===(n=t.opponent1)||void 0===n||delete n.result,null===(r=t.opponent2)||void 0===r||delete r.result,t.status=o.Status.Running;else if(e.status===o.Status.Completed){if(void 0===(null===(i=e.opponent1)||void 0===i?void 0:i.score)||void 0===(null===(a=e.opponent2)||void 0===a?void 0:a.score))return;e.opponent1.score>e.opponent2.score?e.opponent1.result="win":e.opponent2.score>e.opponent1.score?e.opponent2.result="win":(e.opponent1.result="draw",e.opponent2.result="draw"),t.status=o.Status.Completed}}function C(t){[t.opponent1,t.opponent2]=[t.opponent2,t.opponent1]}function N(t,e){var n,r,i,a;if((null===(n=e.opponent1)||void 0===n?void 0:n.score)===(null===(r=t.opponent1)||void 0===r?void 0:r.score)&&(null===(i=e.opponent2)||void 0===i?void 0:i.score)===(null===(a=t.opponent2)||void 0===a?void 0:a.score))return!1;const s=t.status;return t.status=o.Status.Running,e.opponent1&&t.opponent1&&(t.opponent1.score=e.opponent1.score),e.opponent2&&t.opponent2&&(t.opponent2.score=e.opponent2.score),t.status!==s}function L(t,e,n){t.status=o.Status.Completed,j(t,e,"win","loss",n),j(t,e,"loss","win",n),j(t,e,"draw","draw",n),t.opponent1&&!t.opponent2&&(t.opponent1.result="win"),!t.opponent1&&t.opponent2&&(t.opponent2.result="win"),B(t,e)}function j(t,e,n,o,r){var i,a;if(e.opponent1&&e.opponent2){if("win"===e.opponent1.result&&"win"===e.opponent2.result)throw Error("There are two winners.");if("loss"===e.opponent1.result&&"loss"===e.opponent2.result)throw Error("There are two losers.");if(!r&&!0===e.opponent1.forfeit&&!0===e.opponent2.forfeit)throw Error("There are two forfeits.")}(null===(i=e.opponent1)||void 0===i?void 0:i.result)===n&&(t.opponent1?t.opponent1.result=n:t.opponent1={id:null,result:n},t.opponent2?t.opponent2.result=o:t.opponent2={id:null,result:o}),(null===(a=e.opponent2)||void 0===a?void 0:a.result)===n&&(t.opponent2?t.opponent2.result=n:t.opponent2={id:null,result:n},t.opponent1?t.opponent1.result=o:t.opponent1={id:null,result:o})}function B(t,e){var n,o,r,i;if(!0===(null===(n=e.opponent1)||void 0===n?void 0:n.forfeit)&&!0===(null===(o=e.opponent2)||void 0===o?void 0:o.forfeit))return t.opponent1&&(t.opponent1.forfeit=!0),void(t.opponent2&&(t.opponent2.forfeit=!0));!0===(null===(r=e.opponent1)||void 0===r?void 0:r.forfeit)&&(t.opponent1&&(t.opponent1.forfeit=!0),t.opponent2?t.opponent2.result="win":t.opponent2={id:null,result:"win"}),!0===(null===(i=e.opponent2)||void 0===i?void 0:i.forfeit)&&(t.opponent2&&(t.opponent2.forfeit=!0),t.opponent1?t.opponent1.result="win":t.opponent1={id:null,result:"win"})}function F(t,e,n,o){const r=e.map(((e,o)=>{if(null===e)return null;const r=n.find((n=>"object"==typeof e?n[t]===e[t]:n[t]===e));if(!r)throw Error(`Participant ${t} not found in database.`);return{id:r.id,position:o+1}}));if(!o)return r;if(o.length!==r.length)throw Error("Not enough seeds in at least one group of the manual ordering.");return o.map((t=>r[t-1]))}function I(t){const e=t.filter((t=>null!==t));if(e.sort(((t,e)=>t.position-e.position)),e.length===t.length)return e;const n=Object.fromEntries(e.map((t=>[t.position-1,t])));return Array.from({length:t.length},((t,e)=>n[e]||null))}function D(t){return t.filter((t=>null!==t))}function T(t,e,n,o){return