### Install Brackets Manager Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/quick-start.md Install the necessary packages for brackets-manager.js using npm. ```bash npm install brackets-manager brackets-json-db ``` -------------------------------- ### Round Robin Standings Options Example Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/types.md Example of configuring `RoundRobinFinalStandingsOptions` with a custom ranking formula based on wins and draws, and setting a limit for qualified participants. ```typescript const options: RoundRobinFinalStandingsOptions = { rankingFormula: (item) => 3 * item.wins + 1 * item.draws, maxQualifiedParticipantsPerGroup: 2 }; ``` -------------------------------- ### Example ParticipantSlot Usage Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/types.md Shows examples of defining a seeded participant slot, a to-be-determined slot, and a bye. ```typescript const slot: ParticipantSlot = { id: 5, position: 1 }; const bye: ParticipantSlot = null; const tbd: ParticipantSlot = { id: null, position: 2 }; ``` -------------------------------- ### Example Usage of IdMapping Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/types.md Demonstrates how to create and use an IdMapping object for ID normalization. ```typescript const idMap: IdMapping = { "1": "0", "2": "1", "3": "2" }; ``` -------------------------------- ### Example Usage of Ordering Methods Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/types.md Shows how to import and use various ordering methods from the 'brackets-manager' library to transform seed arrays. ```javascript const ordering = require('brackets-manager').ordering; const seeds = [1, 2, 3, 4, 5, 6, 7, 8]; const natural = ordering.natural(seeds); // [1, 2, 3, 4, 5, 6, 7, 8] const reversed = ordering.reverse(seeds); // [8, 7, 6, 5, 4, 3, 2, 1] const shifted = ordering.half_shift(seeds); // [5, 6, 7, 8, 1, 2, 3, 4] const grouped = ordering['groups.seed_optimized'](seeds, 2); ``` -------------------------------- ### Round Robin Final Standings Item Usage Example Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/types.md Example of creating a `RoundRobinFinalStandingsItem` object, showing how to populate fields like group ID, rank, points, wins, draws, and losses. ```typescript const item: RoundRobinFinalStandingsItem = { id: 1, name: 'Alice', groupId: 1, rank: 1, points: 9, wins: 3, draws: 0, losses: 0 }; ``` -------------------------------- ### Example Side Usage Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/types.md Illustrates assigning sides to winner/loser and updating match results. ```typescript const winner: Side = 'opponent1'; const loser: Side = 'opponent2'; match.opponent1 = { score: 10, result: 'win' }; match.opponent2 = { score: 5, result: 'loss' }; ``` -------------------------------- ### Cancel Match Game Example Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/types.md Example of how to cancel a match game using the `update.cancelMatchGame` method with specific cancellation options. ```typescript await manager.update.cancelMatchGame(gameId, { mode: 'spent_game' }); ``` -------------------------------- ### Example Duel Usage Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/types.md Demonstrates how to define a duel with two seeded participants. ```typescript const duel: Duel = [ { id: 1, position: 1 }, { id: 2, position: 2 } ]; ``` -------------------------------- ### Types Reference Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/GENERATION_SUMMARY.txt Documentation for all exported types, including usage examples. ```APIDOC ## Types Reference ### Description Details all exported type definitions used within the brackets-manager.js library. ### Usage Each type includes usage examples to demonstrate how to integrate them into your application. ``` -------------------------------- ### Follow Participant's Path Through Matches Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/api-reference-find.md Traces a participant's progression through a series of matches, starting from a given match. This is useful for understanding a participant's history within a tournament bracket. Requires an initialized BracketsManager, a starting match, and a participant ID. ```typescript const manager = new BracketsManager(storage); let currentMatches = [startingMatch]; const path: Match[] = []; while (currentMatches.length > 0) { path.push(...currentMatches); // Find next matches for participant const nextMatches: Match[] = []; for (const match of currentMatches) { const next = await manager.find.nextMatches(match.id, participantId); nextMatches.push(...next); } currentMatches = nextMatches; } console.log(`Participant played ${path.length} matches`); ``` -------------------------------- ### Configure JsonDatabase with Custom Path Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/configuration.md Initialize the JsonDatabase storage with a custom path for storing tournament data. This example demonstrates setting up the database before creating the BracketsManager. ```typescript import { JsonDatabase } from 'brackets-json-db'; const storage = new JsonDatabase({ path: './tournament-data.json' }); const manager = new BracketsManager(storage); ``` -------------------------------- ### Example Scores Usage Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/types.md Demonstrates defining cumulative scores for a match series. ```typescript const scores: Scores = { opponent1: 2, // Won 2 games opponent2: 1 // Won 1 game }; ``` -------------------------------- ### Example Error Handling for Stage Creation Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/api-reference-manager.md Demonstrates how to catch errors when creating a stage, specifically when a required field like 'name' is missing. ```typescript try { await manager.create.stage({ tournamentId: 1, type: 'single_elimination', seeding: ['A', 'B'], // Missing name! }); } catch (error) { console.error('Stage creation failed:', error.message); } ``` -------------------------------- ### Get Module Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/GENERATION_SUMMARY.txt Provides methods for retrieving bracket data. ```APIDOC ## Module: Get ### Description Handles the retrieval of bracket information. ### Methods - **getBracket(id)**: Retrieves a specific bracket by its unique identifier. ``` -------------------------------- ### Final Standings Usage Example Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/types.md Demonstrates how to structure an array of `FinalStandingsItem` objects for displaying tournament rankings. ```typescript const standings: FinalStandingsItem[] = [ { id: 1, name: 'Alice', rank: 1 }, { id: 2, name: 'Bob', rank: 2 }, { id: 3, name: 'Charlie', rank: 3 } ]; ``` -------------------------------- ### Standard Bracket Results Usage Example Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/types.md Example of structuring `StandardBracketResults` to show the tournament winner and the participants eliminated in the semi-final and final rounds. ```typescript const results: StandardBracketResults = { winner: { id: 1 }, losers: [ [{ id: 4 }, { id: 3 }], // Semi-final losers [{ id: 2 }] // Final loser ] }; ``` -------------------------------- ### Example Usage of ParitySplit Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/types.md Illustrates the structure of a ParitySplit object, showing how elements are divided into 'even' and 'odd' indexed arrays. ```typescript const split: ParitySplit = { even: [1, 3, 5], odd: [2, 4] }; ``` -------------------------------- ### Example ChildGameResults Usage Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/types.md Shows how to define detailed results for child games, including spent games and forfeits. ```typescript const results: ChildGameResults = { opponent1: 2, opponent2: 0, spent: 1, // One game was cancelled doubleForfeit: false }; ``` -------------------------------- ### Initialize Brackets Manager and Create Stage Source: https://github.com/drarig29/brackets-manager.js/blob/main/README.md Initializes the JsonDatabase and BracketsManager, then creates a new double-elimination stage for a tournament. This is a common starting point for setting up tournament structures. ```javascript const { JsonDatabase } = require('brackets-json-db'); const { BracketsManager } = require('brackets-manager'); const storage = new JsonDatabase(); const manager = new BracketsManager(storage); // Create an elimination stage for tournament `3`. await manager.create.stage({ tournamentId: 3, name: 'Elimination stage', type: 'double_elimination', seeding: ['Team 1', 'Team 2', 'Team 3', 'Team 4'], settings: { grandFinal: 'double' }, }); ``` -------------------------------- ### DeepPartial Usage Example Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/types.md Illustrates the usage of DeepPartial for creating objects with only a subset of properties defined, including nested objects. ```typescript const partialMatch: DeepPartial = { id: 5, opponent1: { score: 10 } // Other fields are optional }; ``` -------------------------------- ### Example Usage of RoundPositionalInfo Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/types.md Demonstrates the creation of a RoundPositionalInfo object, specifying the current round's number and the total rounds in its group. ```typescript const position: RoundPositionalInfo = { roundNumber: 3, roundCount: 8 }; ``` -------------------------------- ### Get Module Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/INDEX.md Module for querying tournament data and computing standings, providing methods to retrieve stage data, tournament data, groups, rounds, matches, and more. ```APIDOC ## Get Module ### Description Queries tournament data and computes standings. ### Access `manager.get` ### Key Methods - `stageData(stageId): Promise` - All data for one stage - `tournamentData(tournamentId): Promise` - All data for entire tournament - `groups(filter?): Promise>` - Query groups - `rounds(filter?): Promise>` - Query rounds - `matches(filter?): Promise>` - Query matches - `matchGames(matches): Promise>` - Get child games for matches - `currentStage(tournamentId): Promise` - Active incomplete stage - `currentRound(stageId): Promise` - Active incomplete round - `currentMatches(stageId): Promise>` - Matches ready to play - `seeding(stageId): Promise>` - Initial bracket seeding - `finalStandings(stageId, options?): Promise>` - Final rankings ``` -------------------------------- ### Handle Next Matches Errors Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/errors.md This example shows how to catch and handle specific errors when calling the `nextMatches` method, such as when a match is not stale or a participant does not belong to the match. ```typescript try { const next = await manager.find.nextMatches(matchId, participantId); } catch (error) { if (error.message.includes('not stale')) { console.error('Match must be completed first'); } else if (error.message === 'The participant does not belong to this match.') { console.error('Participant was not in this match'); } } ``` -------------------------------- ### Get Next Matches Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/api-reference-find.md Returns the matches that follow a specified match. Supports tracking a specific participant's advancement path. ```typescript const manager = new BracketsManager(storage); // Get all possible next matches const nextMatches = await manager.find.nextMatches(10); // Get next match for a specific participant (single elimination) const participantNext = await manager.find.nextMatches(10, 5); // Returns winner bracket match if participant won, [] if they lost // Get next match in double elimination (loser goes to lower bracket) const doubleEliminationNext = await manager.find.nextMatches(10, 5); // Returns winner bracket match if won, loser bracket match if lost ``` -------------------------------- ### Import and Export Tournament Data Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/quick-start.md Use `export` to get all tournament data, which can be saved to a file. Use `import` to load previously exported data back into the manager. ```typescript // Export all tournament data const data = await manager.export(); fs.writeFileSync('backup.json', JSON.stringify(data, null, 2)); // Import tournament data const backup = JSON.parse(fs.readFileSync('backup.json', 'utf8')); await manager.import(backup); ``` -------------------------------- ### Handle Final Standings Configuration Errors Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/errors.md This example demonstrates how to catch potential errors when retrieving final standings, such as missing round-robin options for round-robin stages or unsupported options for elimination stages. Ensure proper options are provided based on the stage type. ```typescript try { const standings = await manager.get.finalStandings(1); // If stage 1 is round-robin, this throws: // "Round-robin options are required for round-robin stages." } catch (error) { console.error('Need ranking formula:', error.message); } ``` -------------------------------- ### Simple Round-Robin Stage Creation Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/stage-creation.md Create a simple round-robin stage where each team plays every other team once. This example sets up 8 teams into 2 groups of 4. ```typescript const manager = new BracketsManager(storage); // 8 teams in 2 groups of 4, each plays once const stage = await manager.create.stage({ tournamentId: 1, name: 'Group Stage', type: 'round_robin', seeding: [ 'Team A', 'Team B', 'Team C', 'Team D', 'Team E', 'Team F', 'Team G', 'Team H' ], settings: { groupCount: 2, roundRobinMode: 'simple' } }); console.log(`Created ${stage.id} with ${stage.name}`); ``` -------------------------------- ### Handle Errors During Stage Creation Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/stage-creation.md Use a try-catch block to gracefully handle errors that may occur when creating a stage. This example shows how to log the error message and check for specific error conditions like seeding or stage type issues. ```typescript try { const stage = await manager.create.stage({ tournamentId: 1, name: 'Main', type: 'single_elimination', seeding: ['A', 'B'], settings: {} }); } catch (error) { console.error(`Failed to create stage: ${error.message}`); if (error.message.includes('seeding')) { console.error('Seeding validation failed'); } else if (error.message.includes('stage type')) { console.error('Invalid stage type'); } } ``` -------------------------------- ### Handling Chained Operations with Fallback Logic Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/errors.md When performing a sequence of operations, implement fallback logic for intermediate steps. This example shows attempting a reset and using an alternative method if the primary reset fails due to specific conditions. ```typescript async function resetAndUpdate(matchId, newData) { try { // Try to reset await manager.reset.matchResults(matchId); } catch (error) { if (error.message.includes('child games')) { console.log('Resetting individual games instead...'); // Alternative approach for parent matches with child games } else { throw error; } } // Update match await manager.update.match({ id: matchId, ...newData }); } ``` -------------------------------- ### Create Standard Double Elimination Stage Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/stage-creation.md Example of creating a standard double elimination stage with a simple grand final. The winner bracket follows standard elimination, the loser bracket accommodates losers, and the grand final pits the winner bracket champion against the loser bracket champion. ```typescript const stage = await manager.create.stage({ tournamentId: 1, name: 'Main Draw', type: 'double_elimination', seeding: [ 'P1', 'P2', 'P3', 'P4', 'P5', 'P6', 'P7', 'P8' ], settings: { grandFinal: 'simple', seedOrdering: ['inner_outer', 'natural'] } }); ``` -------------------------------- ### Get Final Standings with Error Handling Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/api-reference-get.md Demonstrates how to retrieve final standings using the get.finalStandings method and catch potential errors. Ensure the manager object is properly initialized before use. ```typescript try { const standings = await manager.get.finalStandings(999); } catch (error) { console.error('Could not get standings:', error.message); } ``` -------------------------------- ### Retrieve Tournament Data Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/quick-start.md Examples of retrieving various tournament data points, including full stage data, specific entities like matches or rounds, current state information, seeding, and final standings. Use stageId or tournamentId as needed. ```typescript // Get all data for display const stageData = await manager.get.stageData(stageId); // Query specific entities const matches = await manager.get.matches({ stage_id: stageId }); const rounds = await manager.get.rounds({ stage_id: stageId }); const groups = await manager.get.groups({ stage_id: stageId }); // Get current state const currentStage = await manager.get.currentStage(tournamentId); const currentRound = await manager.get.currentRound(stageId); const currentMatches = await manager.get.currentMatches(stageId); // Get seeding const seeding = await manager.get.seeding(stageId); // Get rankings const standings = await manager.get.finalStandings(stageId); ``` -------------------------------- ### BracketsManager (Main Entry Point) Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/INDEX.md The main entry point for orchestrating all tournament management operations. It requires a storage interface and optionally accepts a verbose flag. ```APIDOC ## BracketsManager (main entry point) ### Description Orchestrates all tournament management operations. It requires a storage interface and optionally accepts a verbose flag. ### Constructor `constructor(storageInterface, verbose?) ### Methods - `import(data, normalizeIds?): Promise` - `export(): Promise ### Properties - `storage: Storage` - Underlying data layer - `create: Create` - Stage creation module - `get: Get` - Data querying module - `update: Update` - Result recording module - `find: Find` - Bracket navigation module - `reset: Reset` - Data reset module - `delete: Delete` - Data deletion module ### Events - `'entity.changed'` - Fired after storage mutations ``` -------------------------------- ### Configuration Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/GENERATION_SUMMARY.txt Documentation for all configuration options available for the library. ```APIDOC ## Configuration ### Description Explains all available configuration options for customizing the behavior of the brackets-manager.js library. ### Options All configuration options are documented, including their purpose, default values, and usage. ``` -------------------------------- ### getLoser Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/helpers.md Gets the loser of a completed match. ```APIDOC ## getLoser(match: Match): ParticipantSlot ### Description Gets the loser of a completed match. ### Parameters #### Path Parameters - **match** (Match) - Required - The match object to retrieve the loser from. ### Response - **ParticipantSlot** - The loser of the match. ### Example ```typescript const loser = helpers.getLoser(match); if (loser?.id) { console.log(`Loser is participant ${loser.id}`); } ``` ``` -------------------------------- ### getWinner Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/helpers.md Gets the winner of a completed match. ```APIDOC ## getWinner(match: Match): ParticipantSlot ### Description Gets the winner of a completed match. ### Parameters #### Path Parameters - **match** (Match) - Required - The match object to retrieve the winner from. ### Response - **ParticipantSlot** - The winner of the match, or null if the match is unresolved. ### Example ```typescript const winner = helpers.getWinner(match); if (winner?.id) { console.log(`Winner is participant ${winner.id}`); } ``` ``` -------------------------------- ### Initialize Brackets Manager and Create Tournament Stages Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/configuration.md This snippet demonstrates initializing the Brackets Manager with a JsonDatabase and creating multiple tournament stages with different configurations. It covers round-robin groups, double elimination brackets, and single elimination brackets with custom settings. ```typescript import { BracketsManager } from 'brackets-manager'; import { JsonDatabase } from 'brackets-json-db'; // Initialize manager with verbose logging const storage = new JsonDatabase(); const manager = new BracketsManager(storage, true); // Create tournament with multiple stages // Stage 1: Round-robin groups await manager.create.stage({ tournamentId: 1, name: 'Group Stage', type: 'round_robin', seeding: [ 'Team A', 'Team B', 'Team C', 'Team D', 'Team E', 'Team F', 'Team G', 'Team H' ], settings: { roundRobinMode: 'double', // Home and away matches groupCount: 2 // Two groups of 4 } }); // Stage 2: Double elimination with best-of-3 await manager.create.stage({ tournamentId: 1, name: 'Main Tournament', type: 'double_elimination', seeding: [ 'Winner A1', 'Winner B1', 'Runner A1', 'Runner B1', 'Winner A2', 'Winner B2', 'Runner A2', 'Runner B2' ], settings: { grandFinal: 'double', // Grand final can be reset matchesChildCount: 3, // Best-of-3 matches seedOrdering: ['inner_outer', 'natural', 'pair_flip'] } }); // Stage 3: Single elimination with consolation await manager.create.stage({ tournamentId: 1, name: 'Final Bracket', type: 'single_elimination', seeding: ['Finalist 1', 'Finalist 2', 'Finalist 3', 'Finalist 4'], settings: { consolationFinal: true, // 3rd place match matchesChildCount: 5 // Best-of-5 finals } }); ``` -------------------------------- ### Create Module Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/GENERATION_SUMMARY.txt Handles the creation of new brackets, including different types and configurations. ```APIDOC ## Module: Create ### Description Provides functionality for creating new tournament brackets. ### Methods - **createBracket(options)**: A detailed method for creating brackets with various configurations. ``` -------------------------------- ### isMatchOngoing Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/helpers.md Checks if a match is currently playable (ready or running). ```APIDOC ## isMatchOngoing(match: Match): boolean ### Description Checks if a match is currently playable (ready or running). ### Parameters #### Path Parameters - **match** (Match) - Required - The match object to check. ### Response - **boolean** - True if the match is ongoing, false otherwise. ### Example ```typescript const match = await manager.get.matches({ round_id: 1 }); for (const m of match) { if (helpers.isMatchOngoing(m)) { console.log(`Match ${m.id} can be played now`); } } ``` ``` -------------------------------- ### Get All Matches in a Stage Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/quick-start.md Retrieve all matches for a given stage and filter them by status. ```typescript const stageData = await manager.get.stageData(stageId); const allMatches = stageData.match; // Filter by status const completedMatches = allMatches.filter(m => m.status >= Status.Completed); const pendingMatches = allMatches.filter(m => m.status < Status.Running); ``` -------------------------------- ### Initialize Brackets Manager Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/README.md Instantiate the BracketsManager with a storage implementation. This is the main entry point for using the library. ```typescript import { BracketsManager } from 'brackets-manager'; import { JsonDatabase } from 'brackets-json-db'; const manager = new BracketsManager(new JsonDatabase()); ``` -------------------------------- ### Stage Creation with Padding vs. Power of 2 Bracket Size Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/stage-creation.md Illustrates the difference between creating a stage with a seeding count that requires padding and a seeding count that perfectly fits a power-of-2 bracket size. Using a power of 2 minimizes unnecessary byes. ```typescript // Not ideal: 5 participants with padding await manager.create.stage({ seeding: ['A', 'B', 'C', 'D', 'E'], // Will be padded to 8, creating 3 byes }); ``` ```typescript // Better: Use power of 2 if possible await manager.create.stage({ seeding: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'], // Perfect bracket, no unnecessary byes }); ``` -------------------------------- ### Get Final Standings Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/quick-start.md Retrieve the final standings for a stage, with options for custom ranking formulas. ```typescript // Elimination stage const standings = await manager.get.finalStandings(stageId); // Round-robin stage (requires formula) const roundRobinStandings = await manager.get.finalStandings(stageId, { rankingFormula: (item) => 3 * item.wins + 1 * item.draws, maxQualifiedParticipantsPerGroup: 2 }); ``` -------------------------------- ### Initialize Brackets Manager and Storage Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/quick-start.md Initialize the JsonDatabase for storage and then create an instance of BracketsManager, passing the storage instance to its constructor. ```typescript import { BracketsManager } from 'brackets-manager'; import { JsonDatabase } from 'brackets-json-db'; // Initialize storage and manager const storage = new JsonDatabase(); const manager = new BracketsManager(storage); ``` -------------------------------- ### Get Previous Matches Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/api-reference-find.md Returns the matches that feed into a specified match. Can optionally filter by a specific participant. ```typescript const manager = new BracketsManager(storage); // Get all sources for a match const sources = await manager.find.previousMatches(10); console.log(`This match has ${sources.length} source(s)`); // Get sources from a specific participant's perspective const participantSources = await manager.find.previousMatches(10, 5); // Returns matches from participant 5's previous rounds ``` -------------------------------- ### Implement Custom Storage Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/configuration.md Implement the CrudInterface for custom storage solutions. Ensure all required methods are defined. ```typescript class MyDatabase implements CrudInterface { async select(table, filter) { ... } async insert(table, data) { ... } async update(table, id, data) { ... } async delete(table, filter) { ... } } const storage = new MyDatabase(); ``` -------------------------------- ### Catching BracketsManager Initialization Errors Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/errors.md Demonstrates how to catch and log specific error messages when creating a stage with missing required configuration, such as the stage name. ```typescript try { const stage = await manager.create.stage({ // Missing name tournamentId: 1, type: 'single_elimination', seeding: ['A', 'B', 'C', 'D'] }); } catch (error) { console.error(error.message); // "You must provide a name for the stage." } ``` -------------------------------- ### Get Loser Bracket Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/api-reference-find.md Retrieves the lower/loser bracket for a given stage ID. This method is only available for double elimination stages. ```typescript const manager = new BracketsManager(storage); const loserBracket = await manager.find.loserBracket(1); console.log(`Loser bracket ID: ${loserBracket.id}`); ``` -------------------------------- ### Helpers Module Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/GENERATION_SUMMARY.txt Documentation for utility functions provided by the library. ```APIDOC ## Module: Helpers ### Description Contains various utility functions that can be used alongside the main BracketsManager class. ### Functions Over 35 utility functions are documented, covering common tasks and patterns. ``` -------------------------------- ### Backup and Restore Configuration Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/configuration.md Backup manager state before making significant configuration changes. Restore the state if an error occurs during the changes. ```typescript // Backup before configuration changes const backup = await manager.export(); try { // Make changes await manager.delete.stage(1); // ... other changes } catch (error) { // Restore on error await manager.import(backup); } ``` -------------------------------- ### Get Match Loser Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/helpers.md Retrieves the loser of a completed match. Returns the ParticipantSlot of the loser, or null if the match outcome is not yet determined. ```typescript const loser = helpers.getLoser(match); if (loser?.id) { console.log(`Loser is participant ${loser.id}`); } ``` -------------------------------- ### Get Match Winner Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/helpers.md Retrieves the winner of a completed match. Returns the ParticipantSlot of the winner, or null if the match outcome is not yet determined. ```typescript const winner = helpers.getWinner(match); if (winner?.id) { console.log(`Winner is participant ${winner.id}`); } ``` -------------------------------- ### Get Upper Bracket Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/api-reference-find.md Retrieves the upper or winner bracket for a given stage ID. Applicable to both single and double elimination tournaments. ```typescript const manager = new BracketsManager(storage); // Single elimination const bracket = await manager.find.upperBracket(1); console.log(`Upper bracket ID: ${bracket.id}`); // Double elimination - returns winner bracket const winnerBracket = await manager.find.upperBracket(2); console.log(`Winner bracket ID: ${winnerBracket.id}`); ``` -------------------------------- ### Find Bracket and Match Information Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/quick-start.md Use `find` methods to retrieve bracket information (upper and loser) and navigate through matches. You can find previous, next, or a participant's next match. ```typescript // Get bracket information const winnerBracket = await manager.find.upperBracket(stageId); const loserBracket = await manager.find.loserBracket(stageId); // Navigate matches const previous = await manager.find.previousMatches(matchId); const next = await manager.find.nextMatches(matchId); // Follow participant's path const nextMatchForParticipant = await manager.find.nextMatches(matchId, participantId); ``` -------------------------------- ### makeRoundRobinMatches(participants: T[], mode?: 'simple' | 'double'): [T, T][][] Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/helpers.md Generates all matches for a round-robin tournament. Supports simple (one round) or double (home and away) modes. ```APIDOC ## makeRoundRobinMatches(participants: T[], mode?: 'simple' | 'double'): [T, T][][] ### Description Generates all matches for a round-robin tournament. The `mode` parameter determines if each pair plays once ('simple') or twice ('double' with home/away). ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **participants** (T[]) - Required - List of participants - **mode** ('simple' | 'double') - Optional - Defaults to 'simple'. Determines if matches are played once or twice (home/away). ### Returns - **[T, T][][]** — Array of rounds, where each round contains match pairs. ### Example ```typescript const teams = ['Team A', 'Team B', 'Team C']; const matches = helpers.makeRoundRobinMatches(teams); const matchesWithAwayGames = helpers.makeRoundRobinMatches(teams, 'double'); ``` ``` -------------------------------- ### Create Module Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/INDEX.md Module for creating tournament stages, supporting various types like round-robin, single elimination, and double elimination. ```APIDOC ## Create Module ### Description Creates tournament stages. Supports round-robin (with grouping and distribution), single elimination (with optional consolation final), and double elimination (with simple or double grand final). ### Access `manager.create` ### Methods - `stage(data: InputStage): Promise` ``` -------------------------------- ### Get Current Stage Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/api-reference-get.md Retrieves the first stage in a tournament that is not yet completed. Returns null if the tournament is fully completed. Requires an initialized BracketsManager instance. ```typescript const manager = new BracketsManager(storage); const current = await manager.get.currentStage(3); if (current) { console.log(`Current stage: ${current.name}`); } else { console.log('Tournament is complete'); } ``` -------------------------------- ### Initialize BracketsManager Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/INDEX.md Instantiate the BracketsManager with a storage interface and an optional verbose flag. ```typescript new BracketsManager(storageInterface: CrudInterface, verbose?: boolean) ``` -------------------------------- ### Get Stage Seeding Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/api-reference-get.md Retrieves the initial seeding for a stage, returning only the participant ID and their position. Handles BYEs represented as null. Requires an initialized BracketsManager instance. ```typescript const manager = new BracketsManager(storage); const seeding = await manager.get.seeding(1); seeding.forEach((slot, index) => { if (slot === null) { console.log(`Position ${index}: BYE`); } else { console.log(`Position ${index}: Participant ${slot.id}`); } }); ``` -------------------------------- ### Create Tournament Rankings and Standings Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/helpers.md Shows how to calculate tournament rankings based on a custom scoring formula and then build final standings from the ranked teams. This is essential for determining tournament outcomes. ```typescript // Scoring example const formula = (item) => 3 * item.wins + 1 * item.draws; const ranking = helpers.getRanking(matches, formula); // Build final standings const grouped = [ [ranking[0]], // Champion [ranking[1]], // Runner-up [ranking[2]], // Third place ]; const standings = helpers.makeFinalStandings(grouped); console.log(standings); ``` -------------------------------- ### Instantiate BracketsManager Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/api-reference-manager.md Create a new instance of BracketsManager, optionally enabling verbose logging. Requires a storage interface implementation. ```typescript import { BracketsManager } from 'brackets-manager'; import { JsonDatabase } from 'brackets-json-db'; const storage = new JsonDatabase(); const manager = new BracketsManager(storage); // Enable verbose logging const verboseManager = new BracketsManager(storage, true); ``` -------------------------------- ### Find Upper Bracket and Get Rounds/Matches Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/api-reference-find.md Demonstrates how to find a specific upper bracket and then retrieve all its rounds and associated matches. Requires an initialized BracketsManager and a stage ID. ```typescript const manager = new BracketsManager(storage); // Get stage data const stage = await manager.get.stageData(stageId); // Find specific bracket const winnerBracket = await manager.find.upperBracket(stageId); // Get all rounds in bracket const rounds = await manager.get.rounds({ group_id: winnerBracket.id }); // For each round, get matches for (const round of rounds) { const matches = await manager.get.matches({ round_id: round.id }); for (const match of matches) { console.log(`Match ${match.number}: ${match.status}`); } } ``` -------------------------------- ### makeRoundRobinDistribution(participants: T[]): [T, T][][] Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/helpers.md Distributes participants into rounds for a round-robin tournament, ensuring each participant plays exactly once per round. ```APIDOC ## makeRoundRobinDistribution(participants: T[]): [T, T][][] ### Description Distributes participants into rounds for a round-robin tournament. This function ensures that in each generated round, every participant is paired up exactly once. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **participants** (T[]) - Required - List of participants ### Returns - **[T, T][][]** — An array of rounds, where each round is an array of paired matches. ### Example ```typescript const distribution = helpers.makeRoundRobinDistribution([1, 2, 3, 4]); ``` ``` -------------------------------- ### Check if Match is Ongoing Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/helpers.md Use this function to determine if a match is currently playable, meaning it is either ready to start or already in progress. It requires a Match object as input. ```typescript const match = await manager.get.matches({ round_id: 1 }); for (const m of match) { if (helpers.isMatchOngoing(m)) { console.log(`Match ${m.id} can be played now`); } } ``` -------------------------------- ### Helpers Module Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/INDEX.md Utility functions for tournament data processing, including array manipulation, round-robin functions, seeding utilities, scoring, and match queries. ```APIDOC ## Helpers Module ### Description Utility functions for tournament data processing. ### Export `import { helpers } from 'brackets-manager'` ### Key Functions - **Array manipulation:** `splitBy()`, `splitByParity()`, `makeGroups()` - **Round-robin:** `makeRoundRobinMatches()`, `makeRoundRobinDistribution()` - **Seeding:** `balanceByes()`, `convertMatchesToSeeding()` - **Scoring:** `getRanking()`, `makeFinalStandings()` - **Match queries:** `isMatchOngoing()`, `isMatchStale()`, `getWinner()`, `getLoser()` - **Participant queries:** `findParticipant()`, `getLosers()` - **Utilities:** `setArraySize()`, `uniqueBy()`, `getNonNull()`, `isRoundRobin()` ``` -------------------------------- ### Handle Stage Deletion Errors Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/errors.md Catch and inspect errors during stage deletion. This example checks for generic 'Could not delete' messages, often indicating foreign key constraints. ```typescript try { await manager.delete.stage(stageId); } catch (error) { if (error.message.includes('Could not delete')) { console.error('Deletion failed - check foreign key constraints'); } } ``` -------------------------------- ### Build Match Schedule Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/quick-start.md Generate a match schedule organized by rounds for a given stage. ```typescript async function getMatchSchedule(stageId) { const stageData = await manager.get.stageData(stageId); return stageData.round.map(round => ({ roundNumber: round.number, matches: stageData.match .filter(m => m.round_id === round.id) .map(m => ({ id: m.id, opponent1: m.opponent1?.id, opponent2: m.opponent2?.id, status: m.status })) })); } const schedule = await getMatchSchedule(stageId); ``` -------------------------------- ### Retrieve Match Games for Matches Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/api-reference-get.md Returns all match games for a given list of matches, processing only those with child_count > 0. Use this to get detailed game information for a set of matches. ```typescript const manager = new BracketsManager(storage); const matches = await manager.get.matches({ stage_id: 1 }); const games = await manager.get.matchGames(matches); console.log(`Total games: ${games.length}`); ``` -------------------------------- ### Handle Match Results Reset Errors Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/errors.md Catch and handle specific errors when resetting match results. This example shows how to differentiate between errors related to child games and locked matches. ```typescript try { await manager.reset.matchResults(matchId); } catch (error) { if (error.message.includes('child games')) { console.error('Use reset.matchGameResults() for child games'); // Reset individual games instead } else if (error.message === 'The match is locked.') { console.error('Dependent matches prevent reset'); } } ``` -------------------------------- ### Backup and Restore Stage Creation Operations Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/stage-creation.md Implement a backup and restore mechanism before performing complex stage creation operations. This ensures data integrity by allowing a rollback in case of errors. ```typescript // Before creating large stages const backup = await manager.export(); try { const stage = await manager.create.stage({...}); } catch (error) { await manager.import(backup); throw error; } ``` -------------------------------- ### Generate and Validate Round-Robin Matches Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/helpers.md Demonstrates how to generate round-robin matches for a given set of teams and then validate the generated rounds. This is useful for setting up tournament schedules. ```typescript const { helpers } = require('brackets-manager'); // Round-robin scenario const teams = ['Team A', 'Team B', 'Team C', 'Team D']; // Generate matches const rounds = helpers.makeRoundRobinMatches(teams, 'double'); console.log(`Generated ${rounds.length} rounds with home/away games`); // Validate try { helpers.assertRoundRobin([0, 1, 2, 3], rounds); console.log('Round-robin is valid'); } catch (error) { console.error('Invalid distribution'); } ``` -------------------------------- ### Modify Stage Properties After Creation Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/stage-creation.md Demonstrates updating various properties of an existing stage. Seeding can be updated if matches have not yet started. Other updatable properties include the number of matches and seed ordering. ```typescript const manager = new BracketsManager(storage); // Create initial stage const stage = await manager.create.stage({...}); // Later: update seeding (if matches haven't started) await manager.update.seeding(stage.id, ['New Seed 1', 'New Seed 2']); // Update game count await manager.update.matchChildCount('stage', stage.id, 3); // Update seed ordering await manager.update.ordering(stage.id, ['natural']); ``` -------------------------------- ### Get Final Standings (Elimination) Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/api-reference-get.md Retrieves the final rankings for an elimination stage (single or double elimination). Returns an array of participants with their ID, name, and final rank. Requires an initialized BracketsManager instance. ```typescript const manager = new BracketsManager(storage); const standings = await manager.get.finalStandings(1); for (const item of standings) { console.log(`${item.rank}. ${item.name}`); } ``` -------------------------------- ### Get Current Matches Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/api-reference-get.md Retrieves matches that can be played in parallel within a stage. Currently only implemented for 'single_elimination' stages. Throws an error for other stage types or if the stage is not found. Requires an initialized BracketsManager instance. ```typescript const manager = new BracketsManager(storage); const currentMatches = await manager.get.currentMatches(1); for (const match of currentMatches) { console.log(`Match ${match.id} is ready to play`); } ``` -------------------------------- ### BracketsManager Constructor Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/api-reference-manager.md Initializes a new instance of the BracketsManager class. It requires a storage interface for data persistence and optionally accepts a verbose flag for logging. ```APIDOC ## Constructor BracketsManager ### Description Creates an instance of BracketsManager to handle all tournament management operations. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | storageInterface | CrudInterface | Yes | — | An implementation of CrudInterface that handles data persistence | | verbose | boolean | No | false | If true, logs all CRUD operations to console | ### Returns BracketsManager instance ### Request Example ```typescript import { BracketsManager } from 'brackets-manager'; import { JsonDatabase } from 'brackets-json-db'; const storage = new JsonDatabase(); const manager = new BracketsManager(storage); // Enable verbose logging const verboseManager = new BracketsManager(storage, true); ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Get Current Round Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/api-reference-get.md Retrieves the first round in a stage that is not yet completed. Returns null if all rounds in the stage are completed. Note that final rounds might be in different groups. Requires an initialized BracketsManager instance. ```typescript const manager = new BracketsManager(storage); const currentStage = await manager.get.currentStage(3); if (currentStage) { const round = await manager.get.currentRound(currentStage.id); if (round) { console.log(`Current round: ${round.number}`); } } ``` -------------------------------- ### Double Round-Robin Stage Creation Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/stage-creation.md Create a double round-robin stage where each team plays every other team twice (home and away). This example uses the same teams and group configuration as the simple round-robin but sets 'roundRobinMode' to 'double'. ```typescript // Same teams, but play each other twice (home and away) const stage = await manager.create.stage({ tournamentId: 1, name: 'Full Group Stage', type: 'round_robin', seeding: [ 'Team A', 'Team B', 'Team C', 'Team D', 'Team E', 'Team F', 'Team G', 'Team H' ], settings: { groupCount: 2, roundRobinMode: 'double' // Each team plays 6 matches (3 opponents × 2) } }); ``` -------------------------------- ### import(data: Database, normalizeIds?: boolean): Promise Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/api-reference-manager.md Imports complete tournament data into the database. This is a destructive operation that clears all existing entities before importing. ```APIDOC ## POST /import ### Description Imports complete tournament data into the database. This is a destructive operation that clears all existing entities before importing. ### Method POST ### Endpoint /import ### Parameters #### Path Parameters None #### Query Parameters - **normalizeIds** (boolean) - Optional - If true, remaps all IDs to consecutive integers starting from 0 #### Request Body - **data** (Database) - Required - Complete tournament data structure containing all tables ### Request Example ```typescript const manager = new BracketsManager(storage); const tournamentData = { participant: [...], stage: [...], group: [...], round: [...], match: [...], match_game: [...] }; await manager.import(tournamentData); ``` ### Response #### Success Response (200) None #### Response Example None ### Throws - Error if any table insertion fails or if participant/stage/group/round/match/match_game tables cannot be cleared ``` -------------------------------- ### Backup and Restore Tournament Data Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/api-reference-reset-delete.md Use this snippet to back up the entire tournament state before making modifications and restore it if necessary. Ensure you have a mechanism to save and load the backup data. ```typescript const manager = new BracketsManager(storage); // Backup before modifications const backup = await manager.export(); saveToFile('tournament-backup.json', backup); // Make modifications await manager.update.match({ id: 0, opponent1: { score: 10 } }); // If something goes wrong, restore const restoreData = loadFromFile('tournament-backup.json'); await manager.import(restoreData); ``` -------------------------------- ### Get Round-Robin Final Standings with Custom Ranking Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/api-reference-get.md Use this snippet to retrieve the final standings for a round-robin stage. It allows for a custom ranking formula to be provided in the options, enabling flexible point calculation based on match outcomes. ```typescript const manager = new BracketsManager(storage); const standings = await manager.get.finalStandings(1, { rankingFormula: (item) => 3 * item.wins + 1 * item.draws, maxQualifiedParticipantsPerGroup: 2 }); for (const item of standings) { console.log(`${item.rank}. ${item.name} (${item.points} points)`); } ``` -------------------------------- ### Error Handling for Reset Operations Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/api-reference-reset-delete.md Demonstrates how to catch and handle specific errors that may occur during reset operations, such as when a match has child games or is locked. This allows for graceful handling of common issues. ```typescript try { await manager.reset.matchResults(matchId); } catch (error) { if (error.message.includes('child games')) { console.log('Use matchGameResults() instead'); // Reset individual games } else if (error.message === 'The match is locked.') { console.log('Next matches must be reset first'); } } ``` -------------------------------- ### makeFinalStandings Source: https://github.com/drarig29/brackets-manager.js/blob/main/_autodocs/helpers.md Converts grouped participants into ranked final standings. It takes a 2D array of participants grouped by rank and returns an array of final standings items. ```APIDOC ## makeFinalStandings(grouped: Participant[][]): FinalStandingsItem[] ### Description Converts grouped participants into ranked final standings. ### Parameters #### Path Parameters - **grouped** (Participant[][]) - Required - Participants grouped by rank ### Returns `FinalStandingsItem[]` — Ranked with rank numbers ### Example ```typescript const grouped = [ [aliceParticipant], // 1st place [bobParticipant], // 2nd place [charlieParticipant, davidParticipant] // Tied 3rd place ]; const standings = helpers.makeFinalStandings(grouped); ``` ```