Documentation

Complete reference for the bz2api.js library.

Installation

Include the library in your project:

CDN (jsDelivr)
<script src="https://cdn.jsdelivr.net/gh/sevsunday/bz2api.js@1.0.0/bz2api.min.js"></script>
Download (Local)
<script src="bz2api.js"></script>
Node.js (CommonJS)
const BZ2API = require('./bz2api.js');

Quick Start

// Basic usage - fetch all sessions
const result = await BZ2API.fetchSessions();
console.log(result.sessions);

// With enrichment options
const enriched = await BZ2API.fetchSessions({
  enrichMaps: true,     // Fetch map images/names
  enrichVsrMaps: true  // Add VSR map metadata
});

// Access session data
enriched.sessions.forEach(session => {
  console.log(session.name, session.state);
  console.log(session.players.map(p => p.name));
});

fetchSessions(options?)

Fetches and parses all active multiplayer sessions.

Parameters
Option Type Default Description
enrichMaps boolean false Fetch map metadata (images, descriptions, team names)
enrichVsrMaps boolean false Add VSR map data (pools, loose scrap, author)
vsrMapData array undefined Custom VSR map data to override/merge with built-in data
vsrMapDataMode string undefined Required with vsrMapData: 'replace' or 'merge'
corsProxies array Built-in list Custom CORS proxy URLs (browser only)
Returns
{
  sessions: Session[],      // Parsed session objects
  timestamp: "ISO string",  // Fetch timestamp
  rawResponse: Object,      // Original API response
  dataCache: Object,        // Consolidated player/mod data
  enrichedMaps: boolean,    // Whether map enrichment was used
  enrichedVsrMaps: boolean  // Whether VSR enrichment was used
}

fetchRaw(options?)

Fetches raw API data without parsing. Useful for debugging or custom parsing.

const raw = await BZ2API.fetchRaw();
console.log(raw.GET); // Array of raw session objects

fetchMapData(mapFile, modId)

Fetches metadata for a specific map from the external assets API.

const mapData = await BZ2API.fetchMapData('rckcnynvsr', '1325933293');
// Returns: { name, description, image, teamNames, modNames }

Session Object

Each session in the sessions array contains these fields:

Field Type Description
idstringRakNet session ID
guidstringDecoded session GUID (hex)
namestringSession name
versionstringGame version
statestring"PreGame", "InGame", or "PostGame"
stateDetailstring"waiting", "playing", "loading"
gameTypestring"DM" or "STRAT"
gameTypeNamestring"Deathmatch" or "Strategy"
gameModestring"DM", "STRAT", or "MPI"
gameModeNamestringFull mode name (e.g., "Team Strategy")
isTeamGamebooleanWhether teams are used
mapFilestringMap filename without extension
mapNamestringEnriched map title (if available)
mapImageUrlstringEnriched map preview image URL
playersPlayer[]Array of player objects
playerCountnumberCurrent player count
maxPlayersnumberMaximum allowed players
commandersstring[]Names of commanders in the game
hiddenPlayersstring[]Names of hidden/lurking players
modsMod[]Array of mod objects
primaryModstringMain mod ID
isStockbooleanWhether using stock (no mods)
gameBalancestring"Stock" or "VSR"
hasPasswordbooleanPassword protected
isLockedbooleanSession locked
natobjectNAT type info (id, name, canDirectConnect)
steamJoinUrlstringSteam protocol join URL
tpsnumberTicks per second
maxPingnumberMaximum allowed ping (ms)
gameTimeMinutesnumberGame time elapsed
timeLimitMinutesnumberTime limit (null if none)
killLimitnumberKill limit (null if none)

VSR-specific fields (when enrichVsrMaps: true):

Field Type Description
vsrPoolsnumber|nullNumber of biometal pools
vsrLoosenumber|nullAmount of loose scrap
vsrAuthorstring|nullMap author
vsrMapSizenumber|nullMap dimensions
vsrBaseToBasenumber|nullDistance between bases

Player Object

Field Type Description
namestringPlayer display name
rawIdstringRaw ID from API (e.g., "S76561198...")
steamIdstring|nullSteam ID (if Steam user)
gogIdstring|nullGOG Galaxy ID (if GOG user)
platformstring"Steam" or "GOG"
profileUrlstring|nullLink to player's profile
killsnumber|nullKill count
deathsnumber|nullDeath count
scorenumber|nullScore
teamnumber|nullTeam number (1 or 2)
isHostbooleanIs the session host
isTeamLeaderbooleanIs a team leader
isCommanderbooleanIs the commander
isHiddenbooleanIs hidden/lurking

Data Cache

The dataCache object consolidates unique players and mods across all sessions:

{
  players: {
    "76561198...": {
      steamId: "76561198...",
      profileUrl: "https://..."
    }
  },
  mods: {
    "1325933293": {
      id: "1325933293",
      name: "Vet Strat Recycler Variant",
      workshopUrl: "https://..."
    }
  }
}

Configuration Options

All options can be passed to fetchSessions() or fetchRaw():

const result = await BZ2API.fetchSessions({
  // Map enrichment (external API calls)
  enrichMaps: true,
  
  // VSR map metadata (built-in data)
  enrichVsrMaps: true,
  
  // Custom VSR data (must specify mode)
  vsrMapData: myCustomData,
  vsrMapDataMode: 'merge',  // or 'replace'
  
  // Custom CORS proxies (browser only)
  corsProxies: [
    'https://myproxy.com/?url='
  ]
});

CORS Proxies

In browsers, the library automatically handles CORS by trying direct fetch first, then falling back to public proxies:

// Default proxies (used in order)
const CORS_PROXIES = [
  'https://corsproxy.io/?',
  'https://api.allorigins.win/raw?url=',
  'https://api.codetabs.com/v1/proxy?quest='
];

// Override with custom proxies
BZ2API.fetchSessions({
  corsProxies: ['https://my-proxy.com/?url=']
});
Note: Server-side (Node.js) doesn't need CORS proxies. The library will make direct requests automatically.

Server-Side Usage

The library works in Node.js 18+ (native fetch) or with a fetch polyfill.

Basic Example
const BZ2API = require('./bz2api.js');

(async () => {
  const result = await BZ2API.fetchSessions();
  
  console.log(`Found ${result.sessions.length} sessions`);
  
  result.sessions.forEach(s => {
    console.log(`- ${s.name}: ${s.playerCount} players`);
  });
})();

Steam/GOG Data Enrichment

The library generates profile URLs for Steam and GOG players, but does not fetch avatars, nicknames, or other profile data. This is intentional:

  • Steam Web API requires an API key that must remain secret
  • GOG Galaxy API has similar restrictions
  • Exposing API keys in client-side code is a security risk

The recommended architecture is to run bz2api.js on your server, enrich with Steam/GOG APIs, and expose your own endpoint:

[Rebellion API] → [Your Server] → [Your Client]

                  [Steam API]
Express.js with Steam Enrichment
const express = require('express');
const BZ2API = require('./bz2api.js');

const STEAM_API_KEY = process.env.STEAM_API_KEY;

async function getSteamPlayerSummaries(steamIds) {
  if (steamIds.length === 0) return {};
  const url = `https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v2/?key=${STEAM_API_KEY}&steamids=${steamIds.join(',')}`;
  const response = await fetch(url);
  const data = await response.json();
  
  const players = {};
  for (const player of data.response.players || []) {
    players[player.steamid] = {
      nickname: player.personaname,
      avatar: player.avatarfull
    };
  }
  return players;
}

const app = express();

app.get('/api/sessions', async (req, res) => {
  try {
    // Fetch and parse sessions
    const result = await BZ2API.fetchSessions({ enrichMaps: true });
    
    // Collect all unique Steam IDs
    const steamIds = new Set();
    for (const session of result.sessions) {
      for (const player of session.players) {
        if (player.steamId) steamIds.add(player.steamId);
      }
    }
    
    // Fetch Steam data in bulk and enrich players
    const steamData = await getSteamPlayerSummaries([...steamIds]);
    for (const session of result.sessions) {
      for (const player of session.players) {
        if (player.steamId && steamData[player.steamId]) {
          Object.assign(player, steamData[player.steamId]);
        }
      }
    }
    
    res.json(result);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

app.listen(3000, () => console.log('Server running'));
Plain Node.js with Steam Enrichment
const http = require('http');
const BZ2API = require('./bz2api.js');

const STEAM_API_KEY = process.env.STEAM_API_KEY;

async function getSteamPlayerSummaries(steamIds) {
  if (steamIds.length === 0) return {};
  const url = `https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v2/?key=${STEAM_API_KEY}&steamids=${steamIds.join(',')}`;
  const response = await fetch(url);
  const data = await response.json();
  
  const players = {};
  for (const player of data.response.players || []) {
    players[player.steamid] = {
      nickname: player.personaname,
      avatar: player.avatarfull
    };
  }
  return players;
}

const server = http.createServer(async (req, res) => {
  if (req.url === '/api/sessions' && req.method === 'GET') {
    try {
      const result = await BZ2API.fetchSessions({ enrichMaps: true });
      
      // Collect and fetch Steam data
      const steamIds = new Set();
      for (const session of result.sessions) {
        for (const player of session.players) {
          if (player.steamId) steamIds.add(player.steamId);
        }
      }
      
      const steamData = await getSteamPlayerSummaries([...steamIds]);
      for (const session of result.sessions) {
        for (const player of session.players) {
          if (player.steamId && steamData[player.steamId]) {
            Object.assign(player, steamData[player.steamId]);
          }
        }
      }
      
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify(result));
    } catch (err) {
      res.writeHead(500, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ error: err.message }));
    }
  } else {
    res.writeHead(404);
    res.end('Not Found');
  }
});

server.listen(3000, () => console.log('Server running'));
Why Node.js? The bz2api.js library handles complex parsing including Windows-1252 character decoding, RakNet GUID unpacking, game mode bit fields, and team slot mapping. Using Node.js lets you leverage all this parsing directly. Other languages would require reimplementing this logic.

Exported Constants

The library exports several constants for advanced use:

BZ2API.API_URL          // Rebellion API endpoint
BZ2API.CORS_PROXIES     // Default proxy list
BZ2API.MAP_API_BASE     // Map assets API base URL
BZ2API.VSR_MOD_ID       // VSR mod Steam ID
BZ2API.VSR_MAP_DATA_RAW // Built-in VSR map data array