All files / utils assetConfig.ts

100% Statements 7/7
100% Branches 4/4
100% Functions 3/3
100% Lines 7/7

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57                                    1x                   17x             5x                           5x   5x 2x   3x    
/**
 * Asset path configuration for Black Trigram library consumers.
 *
 * By default, all asset URLs are root-relative (e.g. /assets/audio/*).
 * Library consumers who host assets at a different path can call
 * {@link setAssetBasePath} to prefix all asset URLs.
 *
 * @example
 * ```ts
 * import { setAssetBasePath } from 'blacktrigram';
 * // Serve assets from a CDN
 * setAssetBasePath('https://cdn.example.com');
 * ```
 *
 * @module utils
 * @category Utilities
 */
 
let assetBasePath = "";
 
/**
 * Set the base path for all game assets.
 * Call this before initializing any game components.
 *
 * @param basePath - The base URL/path prefix (e.g. `"https://cdn.example.com"` or `"/my-app"`)
 */
export function setAssetBasePath(basePath: string): void {
  // Remove trailing slash for consistency
  assetBasePath = basePath.replace(/\/+$/, "");
}
 
/**
 * Get the current asset base path.
 */
export function getAssetBasePath(): string {
  return assetBasePath;
}
 
/**
 * Resolve an asset path by prepending the configured base path.
 *
 * Accepts paths with or without a leading slash — both are normalized
 * to root-relative before the base path (if any) is prepended.
 *
 * @param path - Asset path, e.g. /assets/audio/music/intro_theme.mp3 or assets/audio/music/intro_theme.mp3
 * @returns The resolved URL with the configured base path prepended
 */
export function resolveAssetPath(path: string): string {
  // Ensure path starts with / for correct concatenation
  const normalizedPath = path.startsWith("/") ? path : `/${path}`;
 
  if (!assetBasePath) {
    return normalizedPath;
  }
  return `${assetBasePath}${normalizedPath}`;
}