All files / shared-utils/src core.ts

98.39% Statements 245/249
96.79% Branches 181/187
100% Functions 33/33
98.72% Lines 233/236

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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515                                  138x 138x 138x     138x 133x       229026x       5x       3804258x 3804258x 3797637x   6621x       341852x 3x   341849x 341849x       344831x 3x   344828x 344828x       344766x 2x     344764x 344764x 132398x     212366x 212366x 212363x 212363x         212366x 212366x 4x   212362x       4331x 4331x 4331x 8597x 8597x 8597x   4331x       1923x 1x   1922x                 5x 1x     4x 4x 4x 1x   3x 1x     2x 2x 2x 1x   1x 1x           281x 281x 281x 281x 1555x 1555x 3x   1552x 214x 1338x 1337x   1x   1552x   281x 281x 68x     213x 211x 360x 360x 360x 7x 7x   360x     988x     213x 213x 213x 1339x 1339x 5x   1334x 1334x 1334x   213x 213x                                     755x 755x 393x 393x 755x 755x 599x 1204x 1204x 1204x 1204x 606x     755x                             663x             3724x 3x   3721x 352x   3369x 3369x               62x 62x           170x 165x 102x       394x 388x                             60x 60x 60x 60x 60x 60x 60x 158x 158x 139x   19x 19x 18x   1x     158x 158x   60x       25x 25x 25x 25x 24x       3369x 3369x 3369x 3250x   119x 119x 184x 184x 183x     119x 119x       1x     663x             780786x 780786x 780786x 1209898x 1209898x 1209898x 949259x   260639x     780786x               41379x 41379x 41379x 289799x 289799x 289799x 140639x   149160x     41379x               390x 390x 390x 405x 405x 405x 249x   156x     390x       12285x 12285x 12285x 42905x 42905x 18448x   24457x     12285x       23507732x 20829928x   2677804x 2677804x 2677791x   13x                       519304x 90547x   428757x 214363x   214394x 214384x   10x                                       3617x 1x   3616x 4x   3612x 13x   3599x 5x   3594x     3594x 4914x 7x     3587x             663x     5067x 39x 39x 39x 164x 17x   147x 10x 10x   137x   39x       988x 988x 988x       960x 960x 960x          
import { throwIfAborted } from './abort.ts';
 
/**
 * Browser-safe equivalent of `node:path.extname`. Returns the trailing-dot suffix of `path` (including the dot
 * itself) or an empty string when the path has no extension. Matches Node's behavior for the cases the
 * audio-renderer / chart loader feed in:
 *
 * - `'foo.wav'` → `'.wav'`
 * - `'foo/bar.ogg'` → `'.ogg'`
 * - `'foo'` → `''`
 * - `'foo.tar.gz'` → `'.gz'` (only the last segment)
 * - `'.bashrc'` → `''` (a leading dot on the basename isn't an extension, per Node)
 *
 * Lives in `core.ts` rather than `path.ts` so it stays browser-safe — `path.ts` re-exports `node:fs/promises`
 * helpers that aren't reachable from the web bundle.
 */
export function extname(path: string): string {
  const lastSlash = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'));
  const basenameStart = lastSlash + 1;
  const lastDot = path.lastIndexOf('.');
  // `lastDot <= basenameStart` covers both "no dot at all in the basename" and "dot is the FIRST char of the
  // basename" (the dotfile case Node treats as no-extension).
  if (lastDot <= basenameStart) return '';
  return path.slice(lastDot);
}
 
export function clamp(value: number, min: number, max: number): number {
  return value <= min ? min : value >= max ? max : value;
}
 
export function clampSignedUnit(value: number): number {
  return value <= -1 ? -1 : value >= 1 ? 1 : value;
}
 
export function floatToInt16(value: number): number {
  const clamped = value <= -1 ? -1 : value >= 1 ? 1 : value;
  if (clamped >= 0) {
    return Math.round(clamped * 32767);
  }
  return Math.round(clamped * 32768);
}
 
export function normalizeNonNegativeInt(value: number, fallback = 0): number {
  if (value !== value || value === Number.POSITIVE_INFINITY || value === Number.NEGATIVE_INFINITY) {
    return fallback;
  }
  const normalized = Math.trunc(value);
  return normalized >= 0 ? normalized : 0;
}
 
export function normalizePositiveInt(value: number, fallback = 1): number {
  if (value <= 0 || value !== value || value === Number.POSITIVE_INFINITY || value === Number.NEGATIVE_INFINITY) {
    return fallback;
  }
  const normalized = Math.trunc(value);
  return normalized >= 1 ? normalized : 1;
}
 
export function normalizeFractionNumerator(value: number, denominator: number, fallback = 0): number {
  if (value !== value || value === Number.POSITIVE_INFINITY || value === Number.NEGATIVE_INFINITY) {
    return fallback;
  }
 
  const normalized = Math.trunc(value);
  if (normalized <= 0) {
    return 0;
  }
 
  let safeDenominator = 1;
  if (denominator > 0 && denominator === denominator && denominator !== Number.POSITIVE_INFINITY) {
    safeDenominator = Math.trunc(denominator);
    Iif (safeDenominator < 1) {
      safeDenominator = 1;
    }
  }
 
  const maxNumerator = safeDenominator - 1;
  if (normalized > maxNumerator) {
    return maxNumerator;
  }
  return normalized;
}
 
export function gcd(left: number, right: number): number {
  let a = Math.abs(left);
  let b = Math.abs(right);
  while (b !== 0) {
    const next = a % b;
    a = b;
    b = next;
  }
  return a;
}
 
export function lcm(left: number, right: number): number {
  if (left === 0 || right === 0) {
    return 0;
  }
  return Math.abs((left * right) / gcd(left, right));
}
 
export function compareFractions(
  leftNumerator: number,
  leftDenominator: number,
  rightNumerator: number,
  rightDenominator: number,
): number {
  if (leftDenominator === rightDenominator) {
    return leftNumerator - rightNumerator;
  }
 
  const leftScaled = leftNumerator * rightDenominator;
  const rightScaled = rightNumerator * leftDenominator;
  if (leftScaled === rightScaled) {
    return 0;
  }
  if (Number.isSafeInteger(leftScaled) && Number.isSafeInteger(rightScaled)) {
    return leftScaled < rightScaled ? -1 : 1;
  }
 
  const leftScaledBigInt = BigInt(leftNumerator) * BigInt(rightDenominator);
  const rightScaledBigInt = BigInt(rightNumerator) * BigInt(leftDenominator);
  if (leftScaledBigInt < rightScaledBigInt) {
    return -1;
  }
  Eif (leftScaledBigInt > rightScaledBigInt) {
    return 1;
  }
  return 0;
}
 
export function normalizeSortedUniqueNonNegativeIntegers(values: ReadonlyArray<number>): number[] {
  const normalized: number[] = [];
  normalized.length = values.length;
  let normalizedLength = 0;
  for (let index = 0; index < values.length; index += 1) {
    const value = values[index]!;
    if (value === Number.POSITIVE_INFINITY || value === Number.NEGATIVE_INFINITY || value !== value) {
      continue;
    }
    if (value <= 0) {
      normalized[normalizedLength] = 0;
    } else if (value < 0x8000_0000) {
      normalized[normalizedLength] = value | 0;
    } else {
      normalized[normalizedLength] = Math.floor(value);
    }
    normalizedLength += 1;
  }
  normalized.length = normalizedLength;
  if (normalizedLength <= 1) {
    return normalized;
  }
 
  if (normalizedLength <= 16) {
    for (let index = 1; index < normalizedLength; index += 1) {
      const current = normalized[index]!;
      let insertIndex = index - 1;
      while (insertIndex >= 0 && normalized[insertIndex]! > current) {
        normalized[insertIndex + 1] = normalized[insertIndex]!;
        insertIndex -= 1;
      }
      normalized[insertIndex + 1] = current;
    }
  } else {
    normalized.sort((left, right) => left - right);
  }
 
  let writeIndex = 1;
  let previous = normalized[0]!;
  for (let readIndex = 1; readIndex < normalized.length; readIndex += 1) {
    const current = normalized[readIndex]!;
    if (current === previous) {
      continue;
    }
    normalized[writeIndex] = current;
    writeIndex += 1;
    previous = current;
  }
  normalized.length = writeIndex;
  return normalized;
}
 
export interface RunWithConcurrencyOptions {
  signal?: AbortSignal;
}
 
/**
 * Runs `task` against each item with a bounded number of workers.
 *
 * This is intentionally small and dependency-free because browser drop loaders, theme readers, and terminal BGA
 * preloaders all need the same "saturate I/O without fanning out unbounded Promises" primitive.
 */
export async function runWithConcurrency<T>(
  items: ReadonlyArray<T>,
  limit: number,
  task: (item: T, index: number) => Promise<void>,
  options: RunWithConcurrencyOptions = {},
): Promise<void> {
  const total = items.length;
  if (total === 0) return;
  let nextIndex = 0;
  const safeLimit = Number.isFinite(limit) ? Math.max(1, Math.trunc(limit)) : 1;
  const workerCount = Math.min(safeLimit, total);
  const worker = async (): Promise<void> => {
    while (true) {
      throwIfAborted(options.signal);
      const index = nextIndex;
      nextIndex += 1;
      if (index >= total) return;
      await task(items[index]!, index);
    }
  };
  await Promise.all(Array.from({ length: workerCount }, worker));
}
 
export interface AssetInputFile {
  readonly name: string;
  readonly webkitRelativePath?: string;
  arrayBuffer(): Promise<ArrayBuffer>;
}
 
export type AssetFileEntry<TFile extends AssetInputFile = AssetInputFile> = Uint8Array | TFile;
 
export interface FindCaseInsensitiveMapPathOptions {
  rejectCandidate?: (candidate: string) => boolean;
}
 
const caseInsensitivePathIndexCache: WeakMap<ReadonlyMap<string, unknown>, ReadonlyMap<string, string>> = new WeakMap();
 
export function findCaseInsensitiveMapPath<T>(
  files: ReadonlyMap<string, T>,
  candidate: string,
  options: FindCaseInsensitiveMapPathOptions = {},
): string | undefined {
  if (options.rejectCandidate?.(candidate)) {
    return undefined;
  }
  if (files.has(candidate)) {
    return candidate;
  }
  const index = getCaseInsensitivePathIndex(files);
  return index.get(candidate.toLowerCase());
}
 
export function lookupCaseInsensitiveMapEntry<T>(
  files: ReadonlyMap<string, T>,
  candidate: string,
  options: FindCaseInsensitiveMapPathOptions = {},
): T | undefined {
  const key = findCaseInsensitiveMapPath(files, candidate, options);
  return key === undefined ? undefined : files.get(key);
}
 
export async function loadFileEntryBytes<TFile extends Pick<AssetInputFile, 'arrayBuffer'>>(
  entry: Uint8Array | TFile | undefined,
): Promise<Uint8Array | undefined> {
  if (entry === undefined) return undefined;
  if (entry instanceof Uint8Array) return entry;
  return new Uint8Array(await entry.arrayBuffer());
}
 
export function asLoadedFileEntryBytes(entry: unknown): Uint8Array | undefined {
  if (entry === undefined) return undefined;
  return entry instanceof Uint8Array ? entry : undefined;
}
 
export interface ReadFilesIntoEntryMapOptions {
  concurrency?: number;
  onRead?: (path: string, current: number, total: number) => void;
  deferAudio?: boolean;
  shouldDefer?: (path: string) => boolean;
  onReadError?: (path: string, error: unknown) => void;
}
 
export async function readFilesIntoEntryMap<TFile extends AssetInputFile>(
  files: ReadonlyArray<TFile>,
  options: ReadFilesIntoEntryMapOptions = {},
): Promise<Map<string, AssetFileEntry<TFile>>> {
  const concurrency = options.concurrency ?? 32;
  const deferAudio = options.deferAudio ?? true;
  const decideDefer = options.shouldDefer ?? (deferAudio ? isAudioAssetPath : neverDefer);
  const result = new Map<string, AssetFileEntry<TFile>>();
  let completed = 0;
  const total = files.length;
  await runWithConcurrency(files, concurrency, async (file) => {
    const path = normalizePath(file.webkitRelativePath || file.name);
    if (decideDefer(path)) {
      result.set(path, file);
    } else {
      try {
        const bytes = new Uint8Array(await file.arrayBuffer());
        result.set(path, bytes);
      } catch (error) {
        options.onReadError?.(path, error);
      }
    }
    completed += 1;
    options.onRead?.(path, completed, total);
  });
  return result;
}
 
export function isAudioAssetPath(path: string): boolean {
  const dot = path.lastIndexOf('.');
  Iif (dot < 0) return false;
  const slash = path.lastIndexOf('/');
  if (slash > dot) return false;
  return AUDIO_ASSET_EXTENSIONS.has(path.slice(dot).toLowerCase());
}
 
function getCaseInsensitivePathIndex<T>(files: ReadonlyMap<string, T>): ReadonlyMap<string, string> {
  const cacheKey = files as ReadonlyMap<string, unknown>;
  const cached = caseInsensitivePathIndexCache.get(cacheKey);
  if (cached) {
    return cached;
  }
  const index = new Map<string, string>();
  for (const key of files.keys()) {
    const lower = key.toLowerCase();
    if (!index.has(lower)) {
      index.set(lower, key);
    }
  }
  caseInsensitivePathIndexCache.set(cacheKey, index);
  return index;
}
 
function neverDefer(): boolean {
  return false;
}
 
const AUDIO_ASSET_EXTENSIONS = new Set(['.wav', '.ogg', '.mp3', '.opus', '.flac', '.oga']);
 
export function findLastIndexAtOrBefore<T>(
  items: ReadonlyArray<T>,
  target: number,
  resolveValue: (item: T) => number,
): number {
  let low = 0;
  let high = items.length;
  while (low < high) {
    const mid = (low + high) >>> 1;
    const value = resolveValue(items[mid]!);
    if (value <= target) {
      low = mid + 1;
    } else {
      high = mid;
    }
  }
  return low - 1;
}
 
export function findLastIndexBefore<T>(
  items: ReadonlyArray<T>,
  target: number,
  resolveValue: (item: T) => number,
): number {
  let low = 0;
  let high = items.length;
  while (low < high) {
    const mid = (low + high) >>> 1;
    const value = resolveValue(items[mid]!);
    if (value < target) {
      low = mid + 1;
    } else {
      high = mid;
    }
  }
  return low - 1;
}
 
export function findFirstIndexAtOrAfter<T>(
  items: ReadonlyArray<T>,
  target: number,
  resolveValue: (item: T) => number,
): number {
  let low = 0;
  let high = items.length;
  while (low < high) {
    const mid = (low + high) >>> 1;
    const value = resolveValue(items[mid]!);
    if (value < target) {
      low = mid + 1;
    } else {
      high = mid;
    }
  }
  return low;
}
 
export function findFirstIndexNumberAtOrAfter(items: ReadonlyArray<number>, target: number): number {
  let low = 0;
  let high = items.length;
  while (low < high) {
    const mid = (low + high) >>> 1;
    if (items[mid]! < target) {
      low = mid + 1;
    } else {
      high = mid;
    }
  }
  return low;
}
 
export function normalizeASCIIBase36Code(code: number): number {
  if (code >= 0x30 && code <= 0x39) {
    return code;
  }
  const uppercase = code & 0xdf;
  if (uppercase >= 0x41 && uppercase <= 0x5a) {
    return uppercase;
  }
  return -1;
}
 
/**
 * Base-62 counterpart of {@link normalizeASCIIBase36Code}: validates an ASCII char code as a member of `[0-9A-Za-z]`
 * and returns it unchanged. Returns `-1` for any other input.
 *
 * Unlike the base-36 variant, lowercase letters are NOT folded to uppercase — `#BASE 62` charts use lowercase as a
 * separate ID space (so `#WAV0a` and `#WAV0A` reference different sounds). Used for both indexed-header keys (`#WAVxx`,
 * `#BMPxx`, …) and object-stream tokens when the chart opted into base-62.
 */
export function normalizeASCIIBase62Code(code: number): number {
  if (code >= 0x30 && code <= 0x39) {
    return code;
  }
  if (code >= 0x41 && code <= 0x5a) {
    return code;
  }
  if (code >= 0x61 && code <= 0x7a) {
    return code;
  }
  return -1;
}
 
/**
 * bmson 1.0.0 spec MUST — "The implementation must protect from malicious paths. Absolute path: `C:\password.txt` or
 * `/etc/passwd`. Reference to parent directory: `../../../var/www/html/config.php`. Null characters (`\0`)."
 *
 * Pure-string predicate so CLI / TUI filesystem callers and the browser's case-insensitive file map can share one
 * canonical guard. Returns `true` for paths the implementation should refuse to resolve. Does NOT consult any
 * filesystem.
 *
 * - **Null byte** — many native APIs interpret `\0` as a C string terminator, so `safe.wav\0/etc/passwd` could resolve
 *   to the second half on a non-defensive backend.
 * - **POSIX absolute** — leading `/` (or `\`) escapes the chart bundle on Unix-style backends.
 * - **Windows absolute** — `C:\...` / `D:/...` drive-letter prefixes.
 * - **UNC / network share** — `\\server\share`, `//server/share`.
 * - **Parent traversal** — any path *segment* that is exactly `..` would walk out of the chart bundle. Per-segment
 *   matching (rather than substring) so a legitimate filename like `Lab..rinth.wav` still resolves.
 */
export function isMaliciousAssetPath(path: string): boolean {
  if (typeof path !== 'string' || path.length === 0) {
    return false;
  }
  if (path.includes('\0')) {
    return true;
  }
  if (path.startsWith('/') || path.startsWith('\\')) {
    return true;
  }
  if (/^[A-Za-z]:[\\/]/.test(path)) {
    return true;
  }
  Iif (path.startsWith('//') || path.startsWith('\\\\')) {
    return true;
  }
  for (const segment of path.split(/[/\\]/)) {
    if (segment === '..') {
      return true;
    }
  }
  return false;
}
 
/**
 * What makes a path need normalizing: a backslash, a leading or trailing or doubled slash, or a `.` / `..` segment.
 * Nearly every path of a dropped folder has none, and a library loads hundreds of thousands of them.
 */
const UNNORMALIZED_PATH = /\\|^\/|\/\/|\/$|(?:^|\/)\.\.?(?:\/|$)/;
 
export function normalizePath(path: string): string {
  if (!UNNORMALIZED_PATH.test(path)) return path;
  const segments = path.replaceAll('\\', '/').split('/');
  const normalizedSegments: string[] = [];
  for (const segment of segments) {
    if (!segment || segment === '.') {
      continue;
    }
    if (segment === '..') {
      normalizedSegments.pop();
      continue;
    }
    normalizedSegments.push(segment);
  }
  return normalizedSegments.join('/');
}
 
export function dirname(path: string): string {
  const normalizedPath = normalizePath(path);
  const slashIndex = normalizedPath.lastIndexOf('/');
  return slashIndex >= 0 ? normalizedPath.slice(0, slashIndex) : '';
}
 
export function basename(path: string): string {
  const normalizedPath = normalizePath(path);
  const slashIndex = normalizedPath.lastIndexOf('/');
  return slashIndex >= 0 ? normalizedPath.slice(slashIndex + 1) : normalizedPath;
}
 
export * from './abort.ts';
export * from './audio-transform.ts';