### sc2ts Development Setup and Commands Source: https://github.com/kanghyojun/sc2ts/blob/main/README.md This section outlines the steps required to set up the sc2ts development environment, including cloning the repository, installing dependencies, building the library, and running tests. It also highlights the use of pnpm for package management and Husky for Git hooks. ```bash # Clone the repository git clone cd sc2ts # Install dependencies (this also sets up Git hooks via Husky) pnpm install # Build the library pnpm run build # Run tests pnpm run test # Watch mode for development pnpm run dev ``` -------------------------------- ### sc2ts CLI: Complete Workflow Example Source: https://github.com/kanghyojun/sc2ts/blob/main/README.md Demonstrates a typical workflow for analyzing an SC2 replay file using the sc2ts CLI. It involves first getting basic information and player details, then listing available files, and finally extracting specific game data. ```bash # 1. First, examine the replay file sc2ts info replay.SC2Replay --players # Output: Shows game info, players, duration, etc. # 2. See what files are available sc2ts list replay.SC2Replay --details # Output: Lists all extractable files with sizes # 3. Extract specific game data sc2ts extract replay.SC2Replay --files "replay.details,replay.game.events" --pretty ``` -------------------------------- ### Example TDD Process for MpqArchive Class Source: https://github.com/kanghyojun/sc2ts/blob/main/CLAUDE.md Illustrates the Test-Driven Development (TDD) cycle, starting with writing a failing test, implementing minimal code to pass, and then refactoring. This example focuses on testing the constructor of the MpqArchive class for invalid MPQ signatures. ```typescript // Step 1: Write failing test describe("MpqArchive", () => { it("should throw MpqInvalidFormatError for corrupted headers", () => { const corruptedBuffer = Buffer.from([0x00, 0x00, 0x00, 0x00]); // Invalid signature expect(() => new MpqArchive(corruptedBuffer)).toThrow(MpqInvalidFormatError); }); }); // Step 3: Implement minimal code to pass test export class MpqArchive { constructor(buffer: Buffer) { if (buffer.readUInt32LE(0) !== 0x1a51504d) { // 'MPQ\x1A' throw new MpqInvalidFormatError("Invalid MPQ signature"); } // ... rest of implementation } } ``` -------------------------------- ### Install SC2TS Package Source: https://github.com/kanghyojun/sc2ts/blob/main/docs/SC2TS_DOCUMENTATION.md Installs the SC2TS library using npm, pnpm, or yarn. This is the initial step to begin using the library in your TypeScript project. ```bash npm install sc2ts # or pnpm install sc2ts # or yarn add sc2ts ``` -------------------------------- ### Install SC2TS CLI Globally Source: https://github.com/kanghyojun/sc2ts/blob/main/docs/SC2TS_DOCUMENTATION.md Installs the SC2TS command-line interface tool globally on your system. This allows you to use SC2TS commands directly from your terminal for replay analysis. ```bash npm install -g sc2ts ``` -------------------------------- ### Install sc2ts CLI Globally or Use with npx Source: https://github.com/kanghyojun/sc2ts/blob/main/README.md Installs the sc2ts command-line interface globally, allowing you to use the 'sc2ts' command directly in your terminal. Alternatively, you can use 'npx' to run the CLI commands without a global installation. ```bash # Install globally for CLI access npm install -g sc2ts # Or use directly with npx npx sc2ts --help ``` -------------------------------- ### CLI Development and Usage Example Source: https://github.com/kanghyojun/sc2ts/blob/main/docs/SC2TS_DOCUMENTATION.md Shows bash commands for running the Command Line Interface (CLI) in development mode and provides an example of parsing a replay file with specific options. This is useful for debugging and testing CLI features. ```bash # Run CLI in development mode pnpm run dev:cli [command] [options] # Example: Parse a replay in development pnpm run dev:cli parse "replays/example.SC2Replay" --json --pretty ``` -------------------------------- ### Testing CLI Commands with Sample Replay Source: https://github.com/kanghyojun/sc2ts/blob/main/CLAUDE.md Provides an example of how to test CLI commands, specifically the parse command, using a sample replay file located in the 'replays/' directory. It emphasizes using `pnpm run dev:cli` for development and testing. ```bash # Test with sample replay pnpm run dev:cli parse "replays/a.SC2Replay" --json --verbose ``` -------------------------------- ### Install sc2ts Package using npm, pnpm, or yarn Source: https://github.com/kanghyojun/sc2ts/blob/main/README.md Installs the sc2ts library to your project dependencies. This command is used to add the library to your project, making its features available for use in your TypeScript code. ```bash npm install sc2ts # or pnpm add sc2ts # or yarn add sc2ts ``` -------------------------------- ### Logging Configuration Source: https://github.com/kanghyojun/sc2ts/blob/main/README.md Information on how to configure logging for sc2ts using LogTape, including basic setup, log categories, and production vs. development settings. ```APIDOC ## Logging Configuration (Optional) sc2ts uses [LogTape](https://logtape.org/) for structured logging. Following LogTape's best practices for library authors, **sc2ts does not configure logging itself** - it's up to your application to configure logging if you want to see debug output. ### Basic Logging Setup If you want to see debug logs from sc2ts in your application: ```typescript import { configure, getConsoleSink } from '@logtape/logtape'; import { SC2Replay } from 'sc2ts'; // Configure LogTape in your application (not in the library) await configure({ sinks: { console: getConsoleSink(), }, loggers: [ // Configure sc2ts logging { category: ['sc2ts'], lowestLevel: 'debug', // Show all debug logs sinks: ['console'], }, ], }); // Now sc2ts will log debug information const replay = await SC2Replay.fromFile('replay.SC2Replay'); // Logs will show: MPQ header parsing, file extraction, decompression, etc. ``` ### Log Categories sc2ts uses these log categories (all under the `sc2ts` namespace): - `['sc2ts', 'mpq-archive']` - MPQ archive parsing and file extraction - `['sc2ts', 'mpq-reader']` - Low-level binary reading and decryption - `['sc2ts', 'sc2-replay']` - SC2 replay parsing - `['sc2ts', 'protocol']` - Protocol decoder and event parsing - `['sc2ts', 'cli']` - CLI command execution - `['sc2ts', 'cli-extractor']` - CLI file extraction - `['sc2ts', 'cli-formatter']` - CLI output formatting ### Production vs Development ```typescript await configure({ sinks: { console: getConsoleSink(), }, loggers: [ { category: ['sc2ts'], // Only show warnings and errors in production lowestLevel: process.env.NODE_ENV === 'production' ? 'warning' : 'debug', sinks: ['console'], }, ], }); ``` ### Disabling Logs If you don't configure LogTape, sc2ts will not produce any log output. This is intentional - libraries should not force logging configuration on applications. ### Custom Logger Access If you're building tools on top of sc2ts and want to use the same logger: ```typescript import { getScLogger } from 'sc2ts'; // Create a logger for your module (will be under ['sc2ts', 'your-module']) const logger = getScLogger('your-module'); logger.info('Processing replay batch', { count: 10 }); logger.debug('Detailed processing info', { fileSize: 1024 }); ``` For more information about LogTape configuration, see the [LogTape documentation](https://logtape.org/). ``` -------------------------------- ### Error Handling Example Source: https://github.com/kanghyojun/sc2ts/blob/main/README.md Example demonstrating how to handle potential errors during MPQ or replay parsing using try-catch blocks and specific error types. ```APIDOC ## Error Handling ```typescript import { MpqError, MpqInvalidFormatError, SC2Replay } from 'sc2ts'; try { const replay = await SC2Replay.fromBuffer(buffer); console.log('Replay parsed successfully'); } catch (error) { if (error instanceof MpqInvalidFormatError) { console.error('Invalid MPQ format:', error.message); } else if (error instanceof MpqError) { console.error('MPQ parsing error:', error.message); } else { console.error('Unexpected error:', error); } } ``` ``` -------------------------------- ### Example Good Commit Sequence (Bash) Source: https://github.com/kanghyojun/sc2ts/blob/main/CLAUDE.md Presents a sequence of well-formed Git commit messages that tell a coherent development story. This example demonstrates the use of clear prefixes (feat, test, fix, refactor, docs) and logical progression of changes, contributing to a clean and bisectable commit history. ```bash # Good commit sequence that tells a story: feat: implement basic MPQ archive reading functionality test: add comprehensive tests for MPQ header parsing fix: handle corrupted MPQ signatures gracefully refactor: optimize memory usage in large file processing docs: document MPQ archive API with usage examples ``` -------------------------------- ### Atomic Git Commit Examples (Bash) Source: https://github.com/kanghyojun/sc2ts/blob/main/CLAUDE.md This section provides examples of correct and incorrect Git commit messages. It emphasizes the importance of atomic commits, clear descriptions, and specific prefixes like 'feat', 'fix', 'refactor', and 'test'. Good examples use an imperative mood and stay within character limits. ```bash # โŒ BAD Examples: git commit -m "Add new feature, fix bug, and update docs" git commit -m "Add new function" # (missing tests, types, etc.) git commit -m "update code" git commit -m "changes" # โœ… GOOD Examples: git commit -m "feat: add MPQ hash table parsing with encryption support" git commit -m "fix: correct hash table name1/name2 calculation for SC2 replays" git commit -m "refactor: extract binary reading logic into separate utility functions" git commit -m "test: add comprehensive hash table parsing regression tests" ``` -------------------------------- ### Example Git Commit Workflow (Bash) Source: https://github.com/kanghyojun/sc2ts/blob/main/CLAUDE.md Illustrates a typical Git commit workflow for the sc2ts project. It highlights staging specific changes, committing with a clear message, and the automatic execution of pre-commit hooks for linting, type checking, and testing. Separate commits are made for distinct logical changes. ```bash # Make changes to hash table parsing git add src/mpq-reader.ts src/__tests__/mpq-reader.test.ts # Commit - pre-commit hook runs automatically git commit -m "fix: correct endianness handling in hash table parsing" # Hook output: # ๐Ÿ” Running pre-commit checks... # ๐Ÿ“ Running ESLint with auto-fix... # ๐Ÿ”Ž Running TypeScript type check... # ๐Ÿงช Running tests... # โœ… All pre-commit checks passed! # Make separate commit for type improvements git add src/types.ts git commit -m "refactor: improve type definitions for MpqHashTableEntry" # Make separate commit for documentation git add README.md git commit -m "docs: add hash table parsing examples to README" ``` -------------------------------- ### Development Build and Test Commands Source: https://github.com/kanghyojun/sc2ts/blob/main/docs/SC2TS_DOCUMENTATION.md Provides essential bash commands for developing the sc2ts project. This includes installing dependencies, building the library, running tests, linting code, and performing type checking. These commands are fundamental for maintaining code quality and functionality. ```bash # Install dependencies pnpm install # Build the library pnpm run build # Run tests pnpm run test # Lint code pnpm run lint # Type checking pnpm run typecheck ``` -------------------------------- ### CLI Parse Command Examples Source: https://github.com/kanghyojun/sc2ts/blob/main/CLAUDE.md Demonstrates how to use the 'parse' command of the project's CLI to extract data from an SC2 replay file. It shows options for human-readable output, JSON output to the console, and saving JSON output to a file. The '--pretty' flag enhances JSON readability. ```bash # Human-readable output pnpm run dev:cli parse "replay.SC2Replay" # JSON output to console pnpm run dev:cli parse "replay.SC2Replay" --json --pretty # JSON output to file pnpm run dev:cli parse "replay.SC2Replay" --json --pretty -o "output.json" ``` -------------------------------- ### Low-Level MPQ Reader Usage Source: https://github.com/kanghyojun/sc2ts/blob/main/README.md Example of how to use the MpqReader class for low-level MPQ archive reading, including accessing header information and tables. ```APIDOC ## Low-Level MPQ Reader Usage ```typescript import { MpqReader } from 'sc2ts'; const reader = new MpqReader(buffer); // Read MPQ header information const header = reader.readMpqHeader(); console.log('MPQ Format Version:', header.formatVersion); console.log('Archive Size:', header.archiveSize); // Access hash and block tables const hashTable = reader.readHashTable(header); const blockTable = reader.readBlockTable(header); console.log('Hash entries:', hashTable.length); console.log('Block entries:', blockTable.length); ``` ``` -------------------------------- ### Configure SC2Replay Parsing Options with sc2ts TypeScript API Source: https://github.com/kanghyojun/sc2ts/blob/main/README.md This TypeScript example shows how to customize the parsing of StarCraft II replay data using the `SC2Replay.fromBuffer` method with an options object. It demonstrates how to selectively enable or disable the parsing of different event types (game events, message events, tracker events, init data) for performance optimization. The example also includes a snippet to iterate through parsed message events to find chat messages. ```typescript import { SC2Replay } from 'sc2ts'; const replay = await SC2Replay.fromBuffer(buffer, { // Enable/disable specific event parsing for performance decodeGameEvents: true, // Parse gameplay events (default: true) decodeMessageEvents: true, // Parse chat messages (default: true) decodeTrackerEvents: true, // Parse detailed tracking events (default: true) decodeInitData: false // Parse initialization data (default: false) }); // Access different types of events console.log('Game events:', replay.gameEvents.length); console.log('Message events:', replay.messageEvents.length); console.log('Tracker events:', replay.trackerEvents.length); // Example: Find all chat messages replay.messageEvents.forEach(msg => { if (msg._event === 'NNet.Game.SChatMessage') { console.log(`Player ${msg.m_userId}: ${msg.m_string}`); } }); ``` -------------------------------- ### SC2Replay Usage Examples (TypeScript) Source: https://github.com/kanghyojun/sc2ts/blob/main/docs/SC2TS_DOCUMENTATION.md Illustrates various ways to use the SC2Replay class for parsing StarCraft II replay files. Examples include basic parsing, selective parsing for performance optimization by disabling certain event decoders, parsing from a Buffer, and accessing key properties like game duration, winner, and event counts. ```typescript // Basic parsing with all events const replay = await SC2Replay.fromFile('replay.SC2Replay'); // Selective parsing for performance const replay = await SC2Replay.fromFile('replay.SC2Replay', { decodeGameEvents: false, // Skip player actions decodeMessageEvents: true, // Include chat messages decodeTrackerEvents: true, // Include unit tracking decodeInitData: false // Skip initialization data }); // Parse from buffer (useful for browser/stream) const buffer = fs.readFileSync('replay.SC2Replay'); const replay = SC2Replay.fromBuffer(buffer); // Access data console.log('Game duration:', replay.duration, 'seconds'); console.log('Total loops:', replay.gameLength); console.log('Winner:', replay.winner?.name); console.log('Chat messages:', replay.messageEvents.length); console.log('Unit events:', replay.trackerEvents.filter(e => e.eventType?.includes('SUnitBorn') ).length); ``` -------------------------------- ### Handling Pre-commit Hook Failures (Bash) Source: https://github.com/kanghyojun/sc2ts/blob/main/CLAUDE.md Provides an example of how to handle a scenario where a Git pre-commit hook fails, specifically due to failing tests. It shows the expected hook output indicating the failure and advises on the necessary steps to fix the issue before retrying the commit. ```bash # Example: Commit blocked by failing test git commit -m "fix: some change" # Hook output: # ๐Ÿ” Running pre-commit checks... # ๐Ÿ“ Running ESLint with auto-fix... # ๐Ÿ”Ž Running TypeScript type check... # ๐Ÿงช Running tests... # โŒ Tests failed. Please fix the failing tests. # Fix the issue, then try again git commit -m "fix: some change" ``` -------------------------------- ### Example Debug Script Structure in Node.js Source: https://github.com/kanghyojun/sc2ts/blob/main/CLAUDE.md Shows a basic structure for Node.js debug scripts intended for the `.debug/` directory. It includes comments for explanation, helper functions, and a main analysis section, promoting self-contained and documented debugging tools. ```javascript // .debug/analyze-issue.js const fs = require("fs"); // Helper functions function helperFunction() { // Implementation } // Main analysis console.log("Starting analysis..."); // Analysis code here console.log("Analysis complete."); ``` -------------------------------- ### TDD Workflow Example: Parse Hash Table Source: https://github.com/kanghyojun/sc2ts/blob/main/CLAUDE.md Demonstrates the correct Test-Driven Development (TDD) workflow by writing a test case for the `parseHashTable` function before implementing the function itself. This ensures that tests define expected behavior and are run before code implementation. ```typescript // Correct: Write test first it("should parse hash table with correct name1/name2 values", () => { const testBuffer = Buffer.from([ /* test data */ ]); const expectedEntries = [ { filename: "replay.details", name1: 0xd383c29c, name2: 0xef402e92 }, { filename: "replay.initData", name1: 0x12345678, name2: 0x87654321 }, ]; const entries = parseHashTable(testBuffer); expect(entries).toHaveLength(2); expect(entries[0]).toEqual(expectedEntries[0]); expect(entries[1]).toEqual(expectedEntries[1]); }); // Then implement the function function parseHashTable(buffer: Buffer): MpqHashTableEntry[] { // Implementation to make the test pass } ``` -------------------------------- ### Bash: sc2ts CLI for SC2 Replay File Operations Source: https://context7.com/kanghyojun/sc2ts/llms.txt Showcases the command-line interface (CLI) for the sc2ts project, enabling extraction, listing, and parsing of StarCraft II replay files without writing custom code. Commands support various options for output format, specific file selection, and detailed information retrieval. No external dependencies beyond the installed 'sc2ts' CLI tool. ```bash # Extract all files as JSON sc2ts extract replay.SC2Replay # Extract to specific directory with pretty printing sc2ts extract replay.SC2Replay --output ./extracted --pretty # Extract specific files only sc2ts extract replay.SC2Replay --files "replay.details,replay.game.events,replay.initData" # Extract as raw binary files sc2ts extract replay.SC2Replay --format raw --output ./raw # Verbose extraction with detailed progress sc2ts extract replay.SC2Replay --verbose --pretty # List all files in archive sc2ts list replay.SC2Replay # List files with detailed information sc2ts list replay.SC2Replay --details # Filter files by name pattern sc2ts list replay.SC2Replay --filter "events" --details # Show replay information sc2ts info replay.SC2Replay # Show replay info with player details sc2ts info replay.SC2Replay --players # Show replay info with event statistics sc2ts info replay.SC2Replay --events # Output replay info as JSON sc2ts info replay.SC2Replay --json --players --events # Parse replay with human-readable output sc2ts parse replay.SC2Replay # Parse and output as JSON sc2ts parse replay.SC2Replay --json --pretty # Parse and save to file sc2ts parse replay.SC2Replay --json --pretty --output parsed.json # Batch processing multiple replays for replay in *.SC2Replay; do sc2ts info "$replay" --json --players > "${replay%.SC2Replay}_info.json" sc2ts extract "$replay" --files "replay.details" --output "./details/" done ``` -------------------------------- ### Configure sc2ts Logging with LogTape Source: https://github.com/kanghyojun/sc2ts/blob/main/README.md Illustrates how to configure LogTape for sc2ts to enable debug logging. This involves setting up sinks and specifying loggers with desired categories and levels. It's designed for application-level setup, not within the library itself. ```typescript import { configure, getConsoleSink } from '@logtape/logtape'; import { SC2Replay } from 'sc2ts'; // Configure LogTape in your application (not in the library) await configure({ sinks: { console: getConsoleSink(), }, loggers: [ // Configure sc2ts logging { category: ['sc2ts'], lowestLevel: 'debug', // Show all debug logs sinks: ['console'], }, ], }); // Now sc2ts will log debug information const replay = await SC2Replay.fromFile('replay.SC2Replay'); // Logs will show: MPQ header parsing, file extraction, decompression, etc. ``` -------------------------------- ### Configure Production vs Development Logging Levels Source: https://github.com/kanghyojun/sc2ts/blob/main/README.md Provides an example of conditionally setting the logging level for sc2ts based on the environment variable NODE_ENV. In production, only warnings and errors are logged, while in development, all debug messages are shown. This requires LogTape configuration. ```typescript await configure({ sinks: { console: getConsoleSink(), }, loggers: [ { category: ['sc2ts'], // Only show warnings and errors in production lowestLevel: process.env.NODE_ENV === 'production' ? 'warning' : 'debug', sinks: ['console'], }, ], }); ``` -------------------------------- ### Example Regression Test for Hash Table Parsing Source: https://github.com/kanghyojun/sc2ts/blob/main/CLAUDE.md Provides an example of a regression test designed to prevent the recurrence of issues related to incorrect hash table name1/name2 values during SC2 replay parsing. It emphasizes using known good data for validation. ```typescript // Regression test for issue #123: Hash table parsing returns incorrect name1/name2 it("should correctly parse hash table name1/name2 values (regression test)", () => { // This test prevents regression of hash table parsing bug found in a.SC2Replay const expectedEntries = [ { filename: "replay.details", name1: 0xd383c29c, name2: 0xef402e92 }, // ... more expected values from known good data ]; // Validate that parsing produces expected hash values // ... test implementation }); ``` -------------------------------- ### MpqArchive Class Documentation Source: https://github.com/kanghyojun/sc2ts/blob/main/README.md Documentation for the MpqArchive class, which is the main class for working with MPQ archives. It includes static methods for opening archives, constructor details, properties, and methods for file manipulation. ```APIDOC ## MpqArchive Class The main class for working with MPQ archives. ### Static Methods ```typescript MpqArchive.fromBuffer(buffer: Buffer, options?: MpqParseOptions): Promise MpqArchive.open(filepath: string, options?: MpqParseOptions): Promise ``` ### Constructor (Advanced) ```typescript new MpqArchive(reader: MpqReader) ``` ### Properties (Getters) - `fileCount` (number) - Number of files in the archive - `archiveHeader` (MpqHeader | null) - MPQ archive header information ### Methods - `listFiles(): string[]` - Get list of all file paths - `getFile(filename: string): Promise` - Extract file content and metadata (async) - `hasFile(filename: string): boolean` - Check if file exists - `getUserDataContent(): Buffer | null` - Get user data content from SC2 replays ``` -------------------------------- ### sc2ts CLI Testing Commands Source: https://github.com/kanghyojun/sc2ts/blob/main/README.md After building the sc2ts project, these bash commands demonstrate how to test the command-line interface (CLI) for various functionalities, such as displaying help information, extracting replay data, listing game details, and showing player information. ```bash # Build the project pnpm run build # Test CLI commands ./bin/run.mjs --help ./bin/run.mjs extract replay.SC2Replay ./bin/run.mjs list replay.SC2Replay --details ./bin/run.mjs info replay.SC2Replay --players ``` -------------------------------- ### Incorrect TDD Workflow Example Source: https://github.com/kanghyojun/sc2ts/blob/main/CLAUDE.md Illustrates an incorrect Test-Driven Development (TDD) workflow where the implementation code is written before the corresponding test case. This is explicitly discouraged in the project's TDD guidelines. ```typescript // Wrong: Writing implementation first function parseHashTable(buffer: Buffer): MpqHashTableEntry[] { // Implementation code here... return entries; } // Then writing tests afterwards it("should parse hash table", () => { // Test written after implementation }); ``` -------------------------------- ### SC2Replay Class Static Methods Source: https://github.com/kanghyojun/sc2ts/blob/main/docs/SC2TS_DOCUMENTATION.md Methods for creating SC2Replay instances from a file path or a buffer. ```APIDOC ## SC2Replay Class Main class for parsing StarCraft II replay files. ### Static Methods #### `SC2Replay.fromFile(filePath: string, options?: ReplayOptions): Promise` Creates an `SC2Replay` instance by parsing a replay file from the given file path. - **filePath** (string) - Required - The path to the replay file. - **options** (ReplayOptions) - Optional - Configuration options for parsing. #### `SC2Replay.fromBuffer(buffer: Buffer, options?: ReplayOptions): SC2Replay` Creates an `SC2Replay` instance by parsing a replay from a Buffer. - **buffer** (Buffer) - Required - The replay data as a Buffer. - **options** (ReplayOptions) - Optional - Configuration options for parsing. ### Request Example ```typescript // Create SC2Replay from file path const replay = await SC2Replay.fromFile('replay.SC2Replay'); // Create SC2Replay from buffer const buffer = fs.readFileSync('replay.SC2Replay'); const replay = SC2Replay.fromBuffer(buffer); ``` ### Response Example ```json { "replayHeader": { ... }, "replayDetails": { ... }, "players": [ ... ] } ``` ``` -------------------------------- ### Development Testing Commands Source: https://github.com/kanghyojun/sc2ts/blob/main/docs/SC2TS_DOCUMENTATION.md Lists bash commands for running tests during development of the sc2ts project. It covers running all tests, executing tests in watch mode for continuous feedback, and generating code coverage reports. ```bash # Run all tests pnpm run test # Run tests in watch mode pnpm run test:watch # Run with coverage pnpm run test:coverage ``` -------------------------------- ### TypeScript: Generate Build Order for Each Player Source: https://github.com/kanghyojun/sc2ts/blob/main/docs/SC2TS_DOCUMENTATION.md Defines a function `getBuildOrder` that retrieves the first N units/buildings produced by a specified player, ordered by their appearance time in the game. It formats the output to include unit type, time in seconds, and game time. Requires `unitBirths` and `loopsPerSecond`. Outputs arrays of build order items for each player. ```typescript // Get first 10 units/buildings for each player function getBuildOrder(playerId: number, limit: number = 10) { return unitBirths .filter(event => (event as any).m_controlPlayerId === playerId && event.loop > 0) .sort((a, b) => a.loop - b.loop) .slice(0, limit) .map(event => ({ unit: (event as any).m_unitTypeName, time: Math.floor(event.loop / loopsPerSecond), gameTime: `${Math.floor(event.loop / loopsPerSecond / 60)}:${(Math.floor(event.loop / loopsPerSecond) % 60).toString().padStart(2, '0')}` })); } const player1BuildOrder = getBuildOrder(1); const player2BuildOrder = getBuildOrder(2); console.log('Player 1 build order:', player1BuildOrder); console.log('Player 2 build order:', player2BuildOrder); ``` -------------------------------- ### SC2Replay Class Documentation Source: https://github.com/kanghyojun/sc2ts/blob/main/README.md Documentation for the SC2Replay class, used for parsing StarCraft II replay files. It includes static methods for creating SC2Replay objects from buffers or files. ```APIDOC ## SC2Replay Class Parser for StarCraft II replay files. ### Static Methods ```typescript SC2Replay.fromBuffer(buffer: Buffer, options?: ReplayOptions): Promise SC2Replay.fromFile(filepath: string, options?: ReplayOptions): Promise ``` ``` -------------------------------- ### SC2TS CLI: Info Command Source: https://github.com/kanghyojun/sc2ts/blob/main/docs/SC2TS_DOCUMENTATION.md Displays basic information about a StarCraft II replay file using the `sc2ts info` command. Options include showing player details and formatting the output as JSON. ```bash # Basic info sc2ts info "replay.SC2Replay" # Include player details sc2ts info "replay.SC2Replay" --players # JSON format sc2ts info "replay.SC2Replay" --json ``` -------------------------------- ### TypeScript: Logging Configuration with LogTape and sc2ts Source: https://context7.com/kanghyojun/sc2ts/llms.txt Illustrates how to integrate optional structured logging with LogTape for the sc2ts library. This snippet shows different configuration strategies, including setting global log levels, configuring specific categories, and creating custom loggers. ```typescript import { configure, getConsoleSink } from '@logtape/logtape'; import { SC2Replay, getScLogger } from 'sc2ts'; // Configure logging in your application await configure({ sinks: { console: getConsoleSink(), }, loggers: [ { category: ['sc2ts'], lowestLevel: 'debug', // Show all sc2ts logs sinks: ['console'], }, ], }); // Now sc2ts will emit debug logs const replay = await SC2Replay.fromFile('replay.SC2Replay'); // Logs show: MPQ header parsing, file extraction, decompression, etc. // Production configuration (warnings and errors only) await configure({ sinks: { console: getConsoleSink(), }, loggers: [ { category: ['sc2ts'], lowestLevel: process.env.NODE_ENV === 'production' ? 'warning' : 'debug', sinks: ['console'], }, ], }); // Selective logging by category await configure({ sinks: { console: getConsoleSink(), }, loggers: [ // Only log MPQ archive operations { category: ['sc2ts', 'mpq-archive'], lowestLevel: 'debug', sinks: ['console'], }, // Only errors for protocol operations { category: ['sc2ts', 'protocol'], lowestLevel: 'error', sinks: ['console'], }, ], }); // Create custom logger for your module const logger = getScLogger('my-module'); logger.info('Starting batch processing', { count: 10 }); logger.debug('Processing file', { filename: 'replay.SC2Replay' }); logger.warn('Slow processing detected', { duration: 5000 }); logger.error('Processing failed', { error: 'Invalid format' }); // Available log categories: // - ['sc2ts', 'mpq-archive'] - MPQ archive operations // - ['sc2ts', 'mpq-reader'] - Binary reading/decryption // - ['sc2ts', 'sc2-replay'] - SC2 replay parsing // - ['sc2ts', 'protocol'] - Protocol decoder // - ['sc2ts', 'cli'] - CLI command execution // - ['sc2ts', 'cli-extractor'] - CLI file extraction // - ['sc2ts', 'cli-formatter'] - CLI output formatting ``` -------------------------------- ### HET Table Signature (C++) Source: https://github.com/kanghyojun/sc2ts/blob/main/docs/references/mpq.md Defines the signature for the HET (Hash Entry Table) table, which starts with 'HET\x1A'. This table is present in MPQ format version 3 and later, potentially replacing the traditional hash table. ```cpp // Common header, for both HET and BET tables DWORD dwSignature; // 'HET\x1A' ``` -------------------------------- ### SC2Replay Static Methods for Parsing (TypeScript) Source: https://github.com/kanghyojun/sc2ts/blob/main/docs/SC2TS_DOCUMENTATION.md Provides static methods for the SC2Replay class to parse StarCraft II replay files. `fromFile` creates an SC2Replay object from a file path, while `fromBuffer` creates one from a Buffer object. Both methods support optional `ReplayOptions` for fine-tuning the parsing process. ```typescript // Create SC2Replay from file path static async fromFile(filePath: string, options?: ReplayOptions): Promise // Create SC2Replay from buffer static fromBuffer(buffer: Buffer, options?: ReplayOptions): SC2Replay ``` -------------------------------- ### SC2TS CLI Info Command Usage Source: https://github.com/kanghyojun/sc2ts/blob/main/CLAUDE.md Displays detailed information about SC2 replay files using the info command. Options include showing basic info, player details, event information, and JSON output. This command provides insights into game details, players, and archive metadata. ```bash # Basic info pnpm run dev:cli info "replay.SC2Replay" # Include player details pnpm run dev:cli info "replay.SC2Replay" --players # Include event information pnpm run dev:cli info "replay.SC2Replay" --events # JSON output pnpm run dev:cli info "replay.SC2Replay" --json ``` -------------------------------- ### TypeScript: Custom MPQ Error Handling with sc2ts Source: https://context7.com/kanghyojun/sc2ts/llms.txt Demonstrates comprehensive error handling for MPQ parsing failures using custom error classes provided by the sc2ts library. It includes catching specific errors like invalid format, decryption, decompression, and file not found, along with a safe file extraction example. ```typescript import { MpqError, MpqInvalidFormatError, MpqDecryptionError, MpqDecompressionError, MpqFileNotFoundError, SC2Replay, MpqArchive } from 'sc2ts'; try { // Attempt to parse replay const replay = await SC2Replay.fromFile('replay.SC2Replay'); console.log('Replay parsed successfully'); // Access data safely const details = replay.replayDetails; if (!details) { throw new Error('No replay details found'); } console.log('Map:', details.title); console.log('Players:', replay.players.length); } catch (error) { if (error instanceof MpqInvalidFormatError) { console.error('Invalid MPQ format:', error.message); console.error('File may be corrupted or not an MPQ archive'); } else if (error instanceof MpqDecryptionError) { console.error('Decryption failed:', error.message); console.error('File may use unsupported encryption'); } else if (error instanceof MpqDecompressionError) { console.error('Decompression failed:', error.message); console.error('File may use unsupported compression format'); } else if (error instanceof MpqFileNotFoundError) { console.error('File not found in archive:', error.message); console.error('Available files:', error.availableFiles); } else if (error instanceof MpqError) { console.error('MPQ parsing error:', error.message); console.error('Stack:', error.stack); } else { console.error('Unexpected error:', error); } } // Example: Safe file extraction with error handling async function safeExtractFile(archive, filename) { try { const file = await archive.getFile(filename); return { success: true, data: file.data, size: file.fileSize }; } catch (error) { if (error instanceof MpqFileNotFoundError) { return { success: false, error: `File '${filename}' not found`, alternatives: error.availableFiles?.filter(f => f.includes(filename.split('.')[0]) ) }; } throw error; } } // Usage const archive = await MpqArchive.open('replay.SC2Replay'); const result = await safeExtractFile(archive, 'replay.details'); if (result.success) { console.log('Extracted:', result.size, 'bytes'); } else { console.log('Error:', result.error); console.log('Did you mean:', result.alternatives); } ``` -------------------------------- ### Extract SC2 Replay Files as Raw Binaries using sc2ts CLI Source: https://github.com/kanghyojun/sc2ts/blob/main/README.md This command extracts all files from a StarCraft II replay file in their raw binary format. The `--format raw` option is used for this purpose, and the `--output` flag specifies the directory where the extracted files will be saved. This is useful for advanced analysis or processing with external tools. ```bash sc2ts extract replay.SC2Replay --format raw --output ./raw_data ``` -------------------------------- ### Batch Process SC2 Replays with sc2ts CLI Source: https://github.com/kanghyojun/sc2ts/blob/main/README.md This script demonstrates batch processing of multiple StarCraft II replay files using a shell loop. For each replay, it extracts basic information into a JSON file and then extracts the 'replay.details' file into a dedicated directory. This allows for systematic analysis and data collection from a collection of replays. ```bash # Process multiple replays (using shell scripting) for replay in *.SC2Replay; do echo "Processing $replay..." sc2ts info "$replay" --json > "${replay%.SC2Replay}_info.json" sc2ts extract "$replay" --files "replay.details" --output "./details/" done ``` -------------------------------- ### sc2ts CLI: Display SC2 Replay Information Source: https://github.com/kanghyojun/sc2ts/blob/main/README.md Displays comprehensive information about SC2 replay files, including basic metadata, detailed player information, and event statistics. The output can be formatted as JSON, and verbose options provide technical details. ```bash # Basic replay information sc2ts info replay.SC2Replay # Show detailed player information sc2ts info replay.SC2Replay --players # Show event statistics sc2ts info replay.SC2Replay --events # Output as JSON sc2ts info replay.SC2Replay --json # All options combined sc2ts info replay.SC2Replay --players --events --json --verbose ``` -------------------------------- ### Browser Usage with File API Source: https://github.com/kanghyojun/sc2ts/blob/main/docs/SC2TS_DOCUMENTATION.md Demonstrates how to use the sc2ts library in a browser environment using the File API. It shows how to handle file input changes, read the file as an ArrayBuffer, and load the replay data using `SC2Replay.fromBuffer`. ```typescript // Browser usage with File API const fileInput = document.querySelector('input[type="file"]'); fileInput.addEventListener('change', async (event) => { const file = event.target.files[0]; const buffer = await file.arrayBuffer(); const replay = await SC2Replay.fromBuffer(Buffer.from(buffer)); console.log('Replay loaded:', replay.replayDetails.title); }); ``` -------------------------------- ### TypeScript: Define MpqArchive Class for MPQ File Handling Source: https://github.com/kanghyojun/sc2ts/blob/main/docs/SC2TS_DOCUMENTATION.md Defines the `MpqArchive` class for low-level interaction with MPQ archive files. It includes methods for retrieving a file list and accessing individual files within the archive. Dependencies include the `Buffer` type. It exposes archive header information and a map of files. ```typescript class MpqArchive { constructor(input: string | Buffer) // Methods getFileList(): string[] getFile(filename: string): MpqFile | null // Properties archiveHeader: MpqArchiveHeader files: Map } ``` -------------------------------- ### TypeScript: BitPackedBuffer for SC2 Binary Data Reading Source: https://context7.com/kanghyojun/sc2ts/llms.txt Demonstrates how to use the BitPackedBuffer class from the 'sc2ts' library to read data at a bit level from SC2 replay files. It covers creating buffers, reading bits, checking for exhaustion, byte alignment, and handling different endianness. Dependencies include the 'sc2ts' library and Node.js Buffer. ```typescript import { BitPackedBuffer } from 'sc2ts'; // Create bit-packed buffer (big-endian by default) const buffer = Buffer.from([0x12, 0x34, 0x56, 0x78]); const bitBuffer = new BitPackedBuffer(buffer, 'big'); // Read bits const value1 = bitBuffer.readBits(4); // Read 4 bits console.log('First 4 bits:', value1.toString(16)); const value2 = bitBuffer.readBits(8); // Read 8 bits console.log('Next 8 bits:', value2.toString(16)); // Check if buffer is exhausted if (!bitBuffer.done()) { const value3 = bitBuffer.readBits(12); console.log('Next 12 bits:', value3.toString(16)); } // Get used bits count console.log('Used bits:', bitBuffer.usedBits()); // Byte align (skip to next byte boundary) bitBuffer.byteAlign(); // Read aligned bytes const aligned = bitBuffer.readAlignedBytes(2); console.log('Aligned bytes:', aligned); // Example: Parse custom bit-packed structure const data = Buffer.from([0xFF, 0xAA, 0x55, 0x00]); const reader = new BitPackedBuffer(data); // Read header (3 bits) const header = reader.readBits(3); console.log('Header:', header); // Read flags (5 bits) const flags = reader.readBits(5); console.log('Flags:', flags.toString(2).padStart(5, '0')); // Read counter (8 bits) const counter = reader.readBits(8); console.log('Counter:', counter); // Little-endian example const leBuffer = new BitPackedBuffer(buffer, 'little'); const leValue = leBuffer.readBits(16); console.log('Little-endian 16 bits:', leValue.toString(16)); ``` -------------------------------- ### Working with MPQ Archives using SC2TS Source: https://github.com/kanghyojun/sc2ts/blob/main/docs/SC2TS_DOCUMENTATION.md Demonstrates how to interact with MPQ archive files using the MpqArchive class from the sc2ts library. It shows how to open an archive, list its contents, and extract specific files. The extracted file data includes its raw byte array. ```typescript import { MpqArchive } from 'sc2ts'; // Open an MPQ archive const archive = new MpqArchive('path/to/archive.mpq'); // List files in the archive const files = archive.getFileList(); console.log('Files in archive:', files); // Extract a specific file const fileData = archive.getFile('replay.details'); if (fileData) { console.log('File size:', fileData.data.length); } ``` -------------------------------- ### Running ESLint Commands Source: https://github.com/kanghyojun/sc2ts/blob/main/CLAUDE.md Provides the commands to check code style and automatically fix issues using ESLint with the project's configuration. These commands are typically executed via a package manager like pnpm. ```bash # Check code style pnpm run lint # Auto-fix issues pnpm run lint:fix ``` -------------------------------- ### sc2ts CLI: List Files in an SC2 Archive Source: https://github.com/kanghyojun/sc2ts/blob/main/README.md Lists all files contained within an SC2 replay archive. You can choose to display simple file names, detailed file information (like size and compression), or filter the list based on a pattern. Verbose output provides additional information. ```bash # Simple file listing sc2ts list replay.SC2Replay # Show detailed file information sc2ts list replay.SC2Replay --details # Filter files by name sc2ts list replay.SC2Replay --filter "events" # Verbose output sc2ts list replay.SC2Replay --verbose ``` -------------------------------- ### MpqArchive.open - Load MPQ archive from file path Source: https://context7.com/kanghyojun/sc2ts/llms.txt Loads an MPQ archive directly from a file path. This method reads the file from disk and parses it automatically. ```APIDOC ## MpqArchive.open - Load MPQ archive from file path ### Description Load an MPQ archive directly from a file path. This method reads the file from disk and parses it automatically. ### Method `MpqArchive.open` ### Parameters #### Path Parameters - **filePath** (string) - Required - The path to the MPQ archive file. #### Query Parameters - **options** (object) - Optional - Configuration options for opening the archive. - **listFile** (string) - Optional - A string containing file list, separated by newlines. ### Request Example ```typescript import { MpqArchive } from 'sc2ts'; const archive = await MpqArchive.open('example.mpq', { listFile: 'replay.details\nreplay.game.events\nreplay.initData' }); ``` ### Response #### Success Response (200) - **archive** (MpqArchive) - An instance of MpqArchive representing the loaded archive. #### Response Example ```typescript console.log('Archive loaded with', archive.fileCount, 'files'); const files = await Promise.all([ archive.getFile('replay.details'), archive.getFile('replay.game.events'), archive.getFile('replay.initData') ]); files.forEach(file => { console.log(`${file.filename}: ${file.fileSize} bytes`); }); ``` ``` -------------------------------- ### Load and List Files from MPQ Archive using sc2ts TypeScript API Source: https://github.com/kanghyojun/sc2ts/blob/main/README.md This TypeScript code demonstrates how to use the `sc2ts` library to interact with MPQ archives. It shows two methods for loading an archive (from a buffer or file path), listing all files within it, extracting a specific file's data, and checking for the existence of a file. This is useful for manipulating archive contents programmatically. ```typescript import { MpqArchive } from 'sc2ts'; import { readFileSync } from 'fs'; // Method 1: Load from buffer (async) const buffer = readFileSync('example.mpq'); const archive = await MpqArchive.fromBuffer(buffer); // Method 2: Load from file path (async) const archive2 = await MpqArchive.open('example.mpq'); // List all files in the archive const files = archive.listFiles(); console.log('Files in archive:', files); // Extract a specific file (async) const fileData = await archive.getFile('path/to/file.txt'); console.log('File content:', fileData.data.toString()); console.log('Original size:', fileData.fileSize); console.log('Compressed size:', fileData.compressedSize); // Check if file exists if (archive.hasFile('some/file.dat')) { console.log('File exists!'); } // Get archive information console.log('Archive has', archive.fileCount, 'files'); ```