All files / player-browser/src/collection collection.ts

92.41% Statements 390/422
82.02% Branches 178/217
93.97% Functions 78/83
93.73% Lines 344/367

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 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075                                                                        88x 88x 88x   88x   88x   88x                                               52x           52x                   1x 1x 1x                               27x 26x 27x 27x           2x   24x 24x 24x 23x   77x 24x       27x         24x       24x 24x   4x       5x               27x             1x 1x 1x               1x 1x                         5x               12x 12x 12x 2x 2x   12x                     12x 12x 12x       12x 12x 13x   12x 12x 12x             6x 6x 6x 6x 6x   6x                 88x                                     27x 27x 16x 16x     16x 1x   16x   11x 11x 11x 11x 22x   22x 22x 22x                 22x 22x 11x             11x       14x 14x                                         12x 16x 12x 16x   12x 12x 16x   12x                                         12x 16x                                                                     47x                                                     108x 28x 28x 29x 29x 22x 22x               54x 54x 54x 54x 54x 54x       54x 54x     54x 54x 54x 128x 4x   124x 124x               54x 54x 47x 124x   124x     47x 124x     54x 54x 54x 4x 4x 4x       4x 1x       1x   3x 3x 3x               54x 54x 54x   54x   54x 47x               54x       54x 50x 50x 127x   50x 50x   54x 54x 54x 49x   54x 109x 54x 54x   54x         107x   107x                                     107x         107x 107x 107x   107x 107x   54x 107x 107x       54x 125x 54x 54x 54x 109x 109x 8x   54x 4x 4x 4x   8x   4x 4x 8x 8x 2x 2x   6x 6x     56x     4x 1x 1x   54x       102x 102x 102x   102x         16x 16x       101x 102x   1x 1x           101x   101x       53x 108x 108x 54x 48x     53x                     102x 102x 102x     101x 102x       19x           3x         3x 3x 3x 3x 3x     3x   3x                 5x 5x 5x 4x 4x             88x     47x 47x                 299x                                   1x 2x 2x                       120x 120x                   2x 2x                   204x 204x                                   401x 401x 401x                             415x           415x 1421x 1063x 1063x 864x 864x   199x 199x 82x     333x                                         57x 57x 57x 14x 49x 49x                               22x 21x 22x 2x   20x 20x 20x 20x 170x 170x 170x 170x 170x           680x 295x 295x 295x 680x 35x 35x         20x 26x 130x 130x 130x     20x                     49x 54x       177x 177x 31x 31x   171x 171x     5x       307x 72x 72x       72x 72x 72x 307x 1x   71x       80x 80x   80x 80x 80x 400x                                                 26x                       38x 38x         38x   38x   50x 50x 56x 56x 211x 211x 211x 211x 211x 211x       1x               88x     38x 38x 38x     38x 18x 18x 162x   20x 20x   120x       228x                 76x       3x 3x 3x       124x       128x 128x    
import { runBrowserTask, getBrowserWorkerCount } from '../compute/index.ts';
import { unzipTask } from '../compute/tasks.ts';
import { yieldToTask } from '../compute/yield.ts';
import { seedLibraryChartPlayVariant, type ChartSourceKind, type LibraryChart } from '@be-music/player-scene-model';
import {
  basename,
  dirname,
  findCaseInsensitiveMapPath,
  normalizePath,
  readFilesIntoEntryMap,
  runWithConcurrency,
} from '@be-music/shared-utils/core';
import type { BrowserAssetEntry, BrowserAssetSource, BrowserChartCollection, LoadProgressCallback } from './types.ts';
import { createEagerDropPathPredicate, isChartFilePath } from '../browser/drop.ts';
import { restoreDeferredChartFields, restorePackedCollectionChart } from './compact-chart.ts';
import {
  type BrowserDroppedFile,
  DeferredDroppedFile,
  materializeDroppedFiles,
  withRelativePath,
} from './dropped-file.ts';
import { isMaliciousAssetPath, loadAssetBytes } from './file-lookup.ts';
import { logger } from '../logger.ts';
import {
  parseChartThroughCache,
  readParsedCharts,
  type ChartCacheKeyBook,
  type ParsedChartCache,
} from './parsed-chart-cache.ts';
import { hasChartSiblings, loadChartSiblings } from './chart-siblings.ts';
import { chartFileHashesOfCacheKey, seedChartFileHashes } from './chart-hash.ts';
import type { ParseChartTaskResult } from '../compute/tasks.ts';
 
export { loadAssetBytes, loadAssetFile, asLoadedBytes } from './file-lookup.ts';
export { type BrowserDroppedFile, DeferredDroppedFile, materializeDroppedFiles } from './dropped-file.ts';
 
const log = logger('drop');
const MAX_ZIP_ARCHIVE_BYTES = 512 * 1024 * 1024;
const MAX_ZIP_UNCOMPRESSED_BYTES = 1024 * 1024 * 1024;
/** Charts being read, hashed, looked up and parsed at once. */
const PARSE_READ_CONCURRENCY = 32;
/** Charts parsed between two yields to the page. */
const PARSE_YIELD_INTERVAL = 32;
/** Charts read from the parsed-chart cache per lookup: the page gets to paint between two batches. */
const KNOWN_CHART_BATCH = 512;
 
/**
 * Optional progress hook for the dropped-folder loaders. When supplied, the loader fires the callback as it walks
 * through the `enumerating` / `reading` / `parsing` phases. UIs can use this to render a determinate progress bar so a
 * multi-thousand-file drop doesn't look like a frozen page.
 */
export interface LoadProgressOptions {
  onProgress?: LoadProgressCallback;
  /** Parsed charts kept across loads, by the SHA-256 of each chart file; charts found there are not parsed again. */
  parsedChartCache?: ParsedChartCache;
  /**
   * The cache keys of the chart files the host has seen before: a chart whose key it knows comes from
   * {@link parsedChartCache} without its file being opened, read or hashed. Used for loose files only (a folder), and
   * never for an LRX chart, whose key also depends on the files beside it.
   */
  chartKeys?: ChartCacheKeyBook;
  /** Skip opening chart files whose parsed results are missing during a cache-only library restore. */
  onChartCacheMiss?: (path: string) => void;
  /** Cancels background collection reads before publishing a new library. */
  signal?: AbortSignal;
}
 
export class BrowserChartCollectionStore {
  public collection: BrowserChartCollection = { sources: [], charts: [], errors: [] };
  /**
   * Monotonic counter that prefixes every appended drop's source ids so subsequent drops don't collide with the
   * previous one's `files:0` / `bundle:0` ids. The counter is incremented every time a drop produces at least one new
   * source.
   */
  private dropSeq = 0;
 
  /**
   * Replace the store's collection with the chart pack parsed from `files`. Used for the explicit "load these and ONLY
   * these" entry point — the file-input picker, the initial drop before any songs have been added, etc.
   */
  public async loadFromFiles(
    files: Iterable<BrowserDroppedFile>,
    options: LoadProgressOptions = {},
  ): Promise<BrowserChartCollection> {
    this.collection = await loadChartCollectionFromFiles(files, options);
    this.dropSeq = 0;
    return this.collection;
  }
 
  /**
   * Append the chart pack parsed from `files` onto the existing collection. This is the "drop another folder onto an
   * already-loaded collection" entry point — the user's previous songs stay, and the new drop's sources / songs are
   * merged in.
   *
   * Source ids and song ids are re-prefixed with a per-drop tag (`drop1-files:0`, `drop2-bundle:0`, …) so the new
   * entries don't collide with previously-loaded ones (each `loadSong*` call internally numbers sources from `0`, so
   * without a prefix a second drop would overwrite the first's lookup keys).
   */
  public async appendFromFiles(
    files: Iterable<BrowserDroppedFile>,
    options: LoadProgressOptions & { replaceSourceIds?: readonly string[] } = {},
  ): Promise<BrowserChartCollection> {
    const incoming = await loadChartCollectionFromFiles(files, options);
    options.signal?.throwIfAborted();
    const replaced = new Set(options.replaceSourceIds);
    if (
      incoming.sources.length === 0 &&
      incoming.charts.length === 0 &&
      incoming.errors.length === 0 &&
      !replaced.size
    ) {
      return this.collection;
    }
    this.dropSeq += 1;
    const prefix = `drop${this.dropSeq}-`;
    const sourceIds = new Map(
      incoming.sources.map(({ id }, index) => [id, options.replaceSourceIds?.[index] ?? prefix + id]),
    );
    const remapId = (id: string) => sourceIds.get(id) ?? prefix + id;
    const remappedSources: BrowserAssetSource[] = incoming.sources.map((source) => ({
      ...source,
      id: remapId(source.id),
    }));
    const remappedCharts: LibraryChart[] = incoming.charts.map((chart) => ({
      ...chart,
      sourceId: remapId(chart.sourceId),
      id: `${remapId(chart.sourceId)}:${chart.chartPath}`,
    }));
    const remappedErrors = incoming.errors.map((error) => ({
      ...error,
      sourceId: remapId(error.sourceId),
    }));
    const current = this.collection;
    this.collection = {
      sources: [
        ...(replaced.size > 0 ? current.sources.filter(({ id }) => !replaced.has(id)) : current.sources),
        ...remappedSources,
      ],
      charts: [
        ...(replaced.size > 0 ? current.charts.filter(({ sourceId }) => !replaced.has(sourceId)) : current.charts),
        ...remappedCharts,
      ],
      errors: [
        ...(replaced.size > 0 ? current.errors.filter(({ sourceId }) => !replaced.has(sourceId)) : current.errors),
        ...remappedErrors,
      ],
    };
    return this.collection;
  }
 
  public async loadFromDrop(
    dataTransfer: DataTransfer,
    options: LoadProgressOptions = {},
  ): Promise<BrowserChartCollection> {
    this.collection = await loadChartCollectionFromDrop(dataTransfer, options);
    this.dropSeq = 0;
    return this.collection;
  }
}
 
export async function loadChartCollectionFromDrop(
  dataTransfer: DataTransfer,
  options: LoadProgressOptions = {},
): Promise<BrowserChartCollection> {
  const files = await collectFilesFromDataTransfer(dataTransfer, options.onProgress);
  return loadChartCollectionFromFiles(files, options);
}
 
/**
 * Lists a drop's files. Files the host needs straight away (theme candidates outside chart directories, replays,
 * archives) come back as opened `File`s; song-bundle files come back as {@link DeferredDroppedFile} handles that open
 * on first read. Pass theme-side files through {@link materializeDroppedFiles} before handing them to an API that
 * needs real `File`s.
 */
export async function readDroppedFiles(
  dataTransfer: DataTransfer,
  options: LoadProgressOptions = {},
): Promise<BrowserDroppedFile[]> {
  return collectFilesFromDataTransfer(dataTransfer, options.onProgress);
}
 
/**
 * The top-level entries of a drop (its files and folders, `webkitGetAsEntry`), which can be walked again later with
 * {@link readDropEntries} to read what the folders hold then. Empty where the browser gives no entries.
 */
export function dropEntries(dataTransfer: DataTransfer): FileSystemEntry[] {
  const entries: FileSystemEntry[] = [];
  const items = dataTransfer.items;
  for (let index = 0; index < (items?.length ?? 0); index += 1) {
    const entry = items[index]?.webkitGetAsEntry?.();
    Eif (entry) entries.push(entry);
  }
  return entries;
}
 
/**
 * Lists the files under a drop's entries, walking its folders as they are now: a drop walked again after the player
 * changed its folders on disk reads the new and changed files (the folder reload). Like {@link readDroppedFiles}.
 */
export async function readDropEntries(
  entries: readonly FileSystemEntry[],
  options: LoadProgressOptions = {},
): Promise<BrowserDroppedFile[]> {
  const { signal } = options;
  signal?.throwIfAborted();
  const listed: ListedDropEntry[] = [];
  // Total is unknown while we're still walking the FileSystem tree (the FileSystemEntry API doesn't expose a
  // directory's file count up-front), so we report `total: -1` and let the host UI show an indeterminate
  // "Collecting…" indicator.
  options.onProgress?.({ phase: 'enumerating', current: 0, total: -1 });
  for (const entry of entries) {
    await listDropEntries(entry, '', listed, options.onProgress, signal);
  }
  const files = await openListedDropEntries(listed, signal);
  options.onProgress?.({ phase: 'enumerating', current: files.length, total: files.length });
  return files;
}
 
async function collectFilesFromDataTransfer(
  dataTransfer: DataTransfer,
  onProgress?: LoadProgressCallback,
): Promise<BrowserDroppedFile[]> {
  const entries = dropEntries(dataTransfer);
  Iif (entries.length > 0) return readDropEntries(entries, onProgress !== undefined ? { onProgress } : {});
  const fallback = dataTransfer.files ? [...dataTransfer.files] : [];
  Eif (fallback.length > 0) {
    onProgress?.({ phase: 'enumerating', current: fallback.length, total: fallback.length });
  }
  return fallback;
}
 
/**
 * Cap on how many `entry.file()` / sub-directory `readEntries` calls can be in flight at once during the
 * FileSystemEntry walk. Chrome's FileSystem API silently rejects (or drops) some calls when the in-flight set grows
 * large, manifesting as a mid-load abort on multi-thousand-file drops. 16 is enough to keep disk I/O saturated without
 * bumping that limit.
 */
const ENTRY_WALK_CONCURRENCY = 16;
 
interface ListedDropEntry {
  entry: FileSystemFileEntry;
  path: string;
}
 
/**
 * Lists every file entry under `entry` without opening any of them. Listing is cheap (one `readEntries` per batch of a
 * directory); opening is not — `FileSystemFileEntry.file()` is a serialised browser round trip per file — so the
 * walk defers that choice to {@link openListedDropEntries}, which only opens the files needed right away.
 */
async function listDropEntries(
  entry: FileSystemEntry,
  prefix: string,
  listed: ListedDropEntry[],
  onProgress?: LoadProgressCallback,
  signal?: AbortSignal,
): Promise<void> {
  signal?.throwIfAborted();
  if (entry.isFile) {
    const path = `${prefix}${entry.name}`;
    listed.push({ entry: entry as FileSystemFileEntry, path });
    // Throttle the per-file progress emit: a 4000-file walk doesn't need 4000 React-style updates. Keep one in every 32
    // entries plus the very first, which is enough for a visibly-moving counter without thrashing the host UI.
    if (onProgress && (listed.length & 0x1f) === 1) {
      onProgress({ phase: 'enumerating', current: listed.length, total: -1, label: path });
    }
    return;
  }
  Eif (entry.isDirectory) {
    const reader = (entry as FileSystemDirectoryEntry).createReader();
    const nextPrefix = `${prefix}${entry.name}/`;
    while (true) {
      signal?.throwIfAborted();
      let batch: FileSystemEntry[];
      try {
        batch = await new Promise<FileSystemEntry[]>((resolve, reject) => {
          reader.readEntries(resolve, reject);
        });
      } catch (error) {
        signal?.throwIfAborted();
        // A directory readEntries failure aborts iteration on THIS directory — the parent walk continues with what we
        // already collected. Logged because this is unusual (file-system errors are uncommon in dropped folders).
        log.warn(`skipped (readEntries failed): ${nextPrefix}`, error);
        return;
      }
      signal?.throwIfAborted();
      if (batch.length === 0) {
        return;
      }
      // Walk children with a bounded-concurrency pool. The unbounded `Promise.all(batch.map(...))` from before fanned
      // out into the recursive walks too, piling up hundreds of pending FileSystemEntry handles for deep trees.
      // Chrome's FileSystem API has an internal in-flight cap that, when exceeded, silently rejects later calls —
      // observable on the user side as a partial / interrupted load. Bounding the walk here keeps disk I/O saturated
      // without tripping that cap. Children are wrapped in `.catch` so one bad sub-tree doesn't reject the whole pool.
      await runWithConcurrency(
        batch,
        ENTRY_WALK_CONCURRENCY,
        async (child) => {
          try {
            await listDropEntries(child, nextPrefix, listed, onProgress, signal);
          } catch (error) {
            signal?.throwIfAborted();
            log.warn(`skipped (child walk failed): ${nextPrefix}${child.name}`, error);
          }
        },
        signal === undefined ? {} : { signal },
      );
    }
  }
}
 
/**
 * Opens the listed entries the host needs immediately (see {@link createEagerDropPathPredicate}) and wraps the rest as
 * {@link DeferredDroppedFile} handles. On a large BMS pack the song audio / BGA make up nearly every file, so this
 * skips almost all of the per-file `file()` round trips that used to dominate the drop.
 */
async function openListedDropEntries(
  listed: readonly ListedDropEntry[],
  signal?: AbortSignal,
): Promise<BrowserDroppedFile[]> {
  signal?.throwIfAborted();
  const isEager = createEagerDropPathPredicate(listed.map((item) => normalizePath(item.path)));
  const files: Array<BrowserDroppedFile | undefined> = listed.map((item) =>
    isEager(normalizePath(item.path)) ? undefined : new DeferredDroppedFile(item.entry, item.path),
  );
  const eagerIndices: number[] = [];
  for (let index = 0; index < files.length; index += 1) {
    Iif (files[index] === undefined) eagerIndices.push(index);
  }
  await runWithConcurrency(
    eagerIndices,
    ENTRY_WALK_CONCURRENCY,
    async (index) => {
      const { entry, path } = listed[index]!;
      try {
        const file = await new Promise<File>((resolve, reject) => {
          entry.file(resolve, reject);
        });
        signal?.throwIfAborted();
        files[index] = withRelativePath(file, path);
      } catch (error) {
        signal?.throwIfAborted();
        // A single file failing to materialize (permission denied, stale entry, network drive disconnect, …) shouldn't
        // kill the entire drop. Log and skip — the resulting collection simply omits that file, matching what real LR2
        // does when an asset is missing.
        log.warn(`skipped (entry.file failed): ${path}`, error);
      }
    },
    signal === undefined ? {} : { signal },
  );
  signal?.throwIfAborted();
  return files.filter((file): file is BrowserDroppedFile => file !== undefined);
}
 
/**
 * Reads `files` into a `Map<path, bytes>` using a worker-pool pattern so up to `concurrency` reads are in-flight at
 * once. Replaces the textbook `for ... await arrayBuffer()` serial loop, which on a 4000-file drop spent the bulk of
 * its time idling on disk between reads.
 *
 * Every call passes `path = normalizePath(webkitRelativePath || name)`, matching the rest of the loader so a downstream
 * lookup (`source.files.get(path)`) doesn't need to negotiate separator-style differences. Progress is reported once
 * per worker step but throttled to every ~32 reads in callers via {@link createThrottledProgress} so the UI updates
 * don't dwarf the actual read work.
 */
export async function readFilesIntoBytesMap(
  files: ReadonlyArray<BrowserDroppedFile>,
  options: {
    concurrency?: number;
    onRead?: (path: string, current: number, total: number) => void;
    /**
     * When `true` (default), audio files (`.wav` / `.ogg` / `.mp3` / `.opus` / `.flac` / `.oga`) are stored as the
     * original `File` reference instead of being slurped into a `Uint8Array`. The gameplay scene reads the bytes on
     * demand via {@link loadAssetBytes}. Ignored when {@link shouldDefer} is supplied — that callback is the source of
     * truth.
     */
    deferAudio?: boolean;
    /**
     * Per-file decision callback. Returning `true` keeps the file as a lazy `File` reference; `false` reads the bytes
     * eagerly. Overrides {@link deferAudio} when supplied. Used by the song-collection loader to defer EVERY
     * song-bundle file (charts plus assets) so a multi-thousand-file pack doesn't sit gigabytes-resident in the heap
     * while the user is just browsing the bar list — the chart parser then pulls each chart's bytes through
     * `loadAssetBytes` on demand and lets them be GC'd as soon as parsing finishes.
     */
    shouldDefer?: (path: string) => boolean;
  } = {},
): Promise<Map<string, BrowserAssetEntry>> {
  return readFilesIntoEntryMap(files, {
    concurrency: options.concurrency,
    onRead: options.onRead,
    deferAudio: options.deferAudio,
    shouldDefer: options.shouldDefer,
    onReadError: (path, error) => {
      // A single file failing to read shouldn't kill the entire drop. The map simply omits that path; the caller's
      // chart parser / asset resolver will treat it as missing, which matches what happens for genuinely-missing
      // files.
      log.warn(`skipped (arrayBuffer failed): ${path}`, error);
    },
  });
}
 
/**
 * Returns a progress-emit wrapper that fires at most once per `intervalMs` (default 32ms ≈ two display frames). Callers
 * always emit through this when they're producing progress events from a hot loop — the host UI only needs ~30 updates
 * a second to look smooth, but `loadFromFiles` was firing 4000+ `onProgress` callbacks per drop, which dominated the
 * load time on weaker machines.
 *
 * The trailing-edge call inside the wrapper isn't synchronously scheduled (no setTimeout) — callers should make a final
 * unthrottled call themselves at the end of their loop so the 100 % tick always lands.
 */
function createThrottledProgress(
  onProgress: LoadProgressCallback | undefined,
  intervalMs = 32,
): LoadProgressCallback | undefined {
  if (!onProgress) return undefined;
  let lastEmit = 0;
  return (event) => {
    const now = performance.now();
    if (now - lastEmit < intervalMs) return;
    lastEmit = now;
    onProgress(event);
  };
}
 
export async function loadChartCollectionFromFiles(
  files: Iterable<BrowserDroppedFile>,
  options: LoadProgressOptions = {},
): Promise<BrowserChartCollection> {
  const { onProgress, signal } = options;
  signal?.throwIfAborted();
  const sources: BrowserAssetSource[] = [];
  const looseFiles = new Map<string, BrowserAssetEntry>();
  const looseLabels = new Set<string>();
  const errors: BrowserChartCollection['errors'] = [];
 
  // Materialize the iterable so we can report "X / N" totals up front. The callers always pass an array today, so this
  // is a no-op spread; it just lets the typing accept any iterable.
  const fileList = [...files];
  onProgress?.({ phase: 'reading', current: 0, total: fileList.length });
  // Split ZIPs out before the parallel-read pool so we can keep each archive's expansion tied to its own source label.
  // Everything else lands in the shared `looseFiles` map.
  const zipFiles: BrowserDroppedFile[] = [];
  const looseEntries: BrowserDroppedFile[] = [];
  for (const file of fileList) {
    if (extensionOf(file.name) === '.zip' && !file.webkitRelativePath) {
      zipFiles.push(file);
    } else {
      looseEntries.push(file);
      looseLabels.add(firstPathSegment(normalizePath(file.webkitRelativePath || file.name)) || file.name);
    }
  }
  // Defer EVERY song-bundle file. Charts get read on demand by the parse loop below (each chart's bytes are released as
  // soon as the parser produces its `BeMusicJSON`), and asset files (BGA images, audio, video, banner, …) stay as lazy
  // `File` references until gameplay-mount actually needs them. This keeps the at-rest heap to "parsed chart metadata
  // only" for the song bundle — the dropped pack itself sits on disk until the user picks a song. The throttled
  // progress wrapper keeps the 4000-emit storm from dominating the read time.
  const throttledProgress = createThrottledProgress(onProgress);
  if (looseEntries.length > 0) {
    const looseMap = await readFilesIntoBytesMap(looseEntries, {
      shouldDefer: () => true,
      onRead: (path, current, total) => {
        throttledProgress?.({ phase: 'reading', current, total, label: path });
      },
    });
    for (const [path, bytes] of looseMap) {
      looseFiles.set(path, bytes);
    }
  }
  const zipSources: Array<BrowserAssetSource | undefined> = Array.from({ length: zipFiles.length });
  const zipErrors: BrowserChartCollection['errors'][] = Array.from({ length: zipFiles.length }, () => []);
  await runWithConcurrency(zipFiles, getBrowserWorkerCount(), async (dropped, index) => {
    const sourceId = `zip:${dropped.name}`;
    const [file] = await materializeDroppedFiles([dropped]);
    Iif (!file) {
      zipErrors[index]!.push({ sourceId, message: 'failed to open ZIP archive' });
      return;
    }
    if (file.size > MAX_ZIP_ARCHIVE_BYTES) {
      zipErrors[index]!.push({
        sourceId,
        message: `ZIP archive is too large (${formatBytes(file.size)}; limit ${formatBytes(MAX_ZIP_ARCHIVE_BYTES)})`,
      });
      return;
    }
    try {
      const bytes = new Uint8Array(await file.arrayBuffer());
      zipSources[index] = await createZipSource(file.name, bytes);
    } catch (error) {
      zipErrors[index]!.push({
        sourceId,
        message: error instanceof Error ? error.message : 'failed to read ZIP archive',
      });
    }
  });
  sources.push(...zipSources.filter((source): source is BrowserAssetSource => source !== undefined));
  errors.push(...zipErrors.flat());
  signal?.throwIfAborted();
  // Final 100 % emit for the read phase — the throttled wrapper may have suppressed the last one.
  onProgress?.({ phase: 'reading', current: fileList.length, total: fileList.length });
 
  if (looseFiles.size > 0) {
    sources.push({
      id: `files:${sources.length}`,
      kind: inferSourceKind(looseFiles),
      label: looseLabels.size === 1 ? [...looseLabels][0]! : 'Dropped files',
      files: looseFiles,
    });
  }
 
  const charts: LibraryChart[] = [];
  // Build the chart-path lists in one pass per source so we don't sort + filter the full path table twice (once for the
  // count, once for the parse loop). Sort the chart paths only — the non-chart paths don't need ordering since they're
  // just asset lookups.
  const chartPathsBySource = sources.map((source) => {
    const paths: string[] = [];
    for (const path of source.files.keys()) {
      if (isChartFilePath(path)) paths.push(path);
    }
    paths.sort(JAPANESE_COLLATOR.compare);
    return paths;
  });
  const chartCount = chartPathsBySource.reduce((acc, list) => acc + list.length, 0);
  let parsedSoFar = 0;
  if (chartCount > 0) {
    onProgress?.({ phase: 'parsing', current: 0, total: chartCount });
  }
  const throttledParseProgress = createThrottledProgress(onProgress);
  const items = sources.flatMap((source, index) => chartPathsBySource[index]!.map((path) => ({ source, path })));
  const loadedCharts: Array<LibraryChart | undefined> = Array.from({ length: items.length });
  const parseErrors: Array<BrowserChartCollection['errors'][number] | undefined> = Array.from({ length: items.length });
  /** Lists a parsed chart: the library entry kept for as long as the chart is in the collection. */
  const listChart = (
    index: number,
    { chart, scored, packed, strings, deferred, md5 }: ParseChartTaskResult,
    key: string | undefined,
  ): void => {
    const { source, path } = items[index]!;
    // The scored notes and the play variant they were read under, without timing every note: the list shows a count.
    const libraryChart: LibraryChart = {
      id: `${source.id}:${path}`,
      sourceId: source.id,
      sourceLabel: source.label,
      sourceKind: source.kind,
      chartPath: path,
      directoryLabel: dirname(path) || source.label,
      fileLabel: basename(path),
      title: chart.metadata.title || basenameWithoutExtension(path),
      subtitle: chart.metadata.subtitle,
      artist: chart.metadata.artist,
      genre: chart.metadata.genre,
      playLevel: chart.metadata.playLevel,
      bpm: chart.metadata.bpm,
      // The notes the engine scores: FREE ZONE tails are judged by nobody, and mines / invisible objects are not
      // notes at all. A long note counts once.
      totalNotes: scored.notes,
      chart,
    };
    loadedCharts[index] = libraryChart;
    // Every parsed chart stays resident for as long as the song is in the collection, so trim it before keeping
    // it. Keep the play variant first, while the events are still plain objects: select screens filter the whole
    // list by it, and a cached answer spares them from unpacking every chart's events. Counting the notes already
    // worked it out (`resolveChartPlayVariant` over the same chart and path).
    seedLibraryChartPlayVariant(libraryChart, scored.playVariant);
    restorePackedCollectionChart(chart, packed, strings);
    restoreDeferredChartFields(chart, deferred);
    // The file's hashes are in hand: its cache key starts with its SHA-256, and its MD5 came with the parse.
    const hashes = chartFileHashesOfCacheKey(key, md5);
    if (hashes !== undefined) seedChartFileHashes(chart, hashes);
  };
  const reportParsed = (path: string): void => {
    parsedSoFar += 1;
    throttledParseProgress?.({ phase: 'parsing', current: parsedSoFar, total: chartCount, label: path });
  };
  // A chart file the host knows unchanged is not read: its parse comes from the cache under the key the host kept,
  // a batch of charts per lookup. Whatever the cache no longer has is parsed with the rest below.
  const chartKeysOf = ({ source, path }: (typeof items)[number]): ChartCacheKeyBook | undefined =>
    source.kind === 'zip' || hasChartSiblings(path) ? undefined : options.chartKeys;
  const unread: number[] = [];
  const known: Array<{ index: number; key: string }> = [];
  for (const [index, item] of items.entries()) {
    const key = options.parsedChartCache !== undefined ? chartKeysOf(item)?.known(item.path) : undefined;
    if (key === undefined) unread.push(index);
    else known.push({ index, key });
  }
  for (let start = 0; start < known.length; start += KNOWN_CHART_BATCH) {
    signal?.throwIfAborted();
    const batch = known.slice(start, start + KNOWN_CHART_BATCH);
    const cached = await readParsedCharts(
      options.parsedChartCache,
      batch.map(({ key }) => key),
    );
    signal?.throwIfAborted();
    for (const [offset, { index, key }] of batch.entries()) {
      const result = cached[offset];
      if (result === undefined) {
        unread.push(index);
        continue;
      }
      listChart(index, result, key);
      reportParsed(items[index]!.path);
    }
  }
  unread.sort((left, right) => left - right);
  // More charts in flight than there are workers: a chart spends most of its time waiting on its file, its hash and
  // the cache, and the pool queues the parses it has no worker for, so files are read while charts are parsed.
  if (options.onChartCacheMiss !== undefined) {
    for (const index of unread) options.onChartCacheMiss(items[index]!.path);
    unread.length = 0;
  }
  await runWithConcurrency(
    unread,
    signal === undefined ? PARSE_READ_CONCURRENCY : 1,
    async (index) => {
      const { source, path } = items[index]!;
      try {
        const chartKeys = chartKeysOf(items[index]!);
        let key: string | undefined;
        const result = await parseChartFile(
          source,
          path,
          options.parsedChartCache,
          (hashed) => {
            key = hashed;
            chartKeys?.learned(path, hashed);
          },
          signal,
        );
        signal?.throwIfAborted();
        listChart(index, result, key);
      } catch (error) {
        signal?.throwIfAborted();
        parseErrors[index] = {
          sourceId: source.id,
          path,
          message: error instanceof Error ? error.message : 'failed to parse chart',
        };
      }
      reportParsed(path);
      // Keep cooperative progress yielding for hosts using the local fallback; workers already run outside the UI thread.
      if (parsedSoFar % PARSE_YIELD_INTERVAL === 0) await yieldToTask();
    },
    signal === undefined ? {} : { signal },
  );
  signal?.throwIfAborted();
  charts.push(...loadedCharts.filter((chart): chart is LibraryChart => chart !== undefined));
  errors.push(...parseErrors.filter((error): error is BrowserChartCollection['errors'][number] => error !== undefined));
  if (chartCount > 0) {
    onProgress?.({ phase: 'parsing', current: chartCount, total: chartCount });
  }
 
  return { sources, charts, errors };
}
 
/** Reads and parses the chart file at `path` (through `cache`); `onKey` receives the cache key it worked out. */
async function parseChartFile(
  source: BrowserAssetSource,
  path: string,
  cache: ParsedChartCache | undefined,
  onKey: (key: string) => void,
  signal?: AbortSignal,
): Promise<ParseChartTaskResult> {
  const chartBytes = await loadAssetBytes(source.files.get(path));
  signal?.throwIfAborted();
  Iif (!chartBytes) {
    throw new Error(`chart bytes missing for ${path}`);
  }
  const siblings = hasChartSiblings(path) ? await loadChartSiblings(source.files, path, chartBytes) : undefined;
  return parseChartThroughCache({ path, bytes: chartBytes, ...(siblings ? { siblings } : {}) }, cache, onKey, signal);
}
 
export function describeChartCollection(collection: BrowserChartCollection): string {
  return `${collection.charts.length} charts loaded${
    collection.errors.length > 0 ? `, ${collection.errors.length} errors` : ''
  }`;
}
 
async function createZipSource(name: string, bytes: Uint8Array): Promise<BrowserAssetSource> {
  const input = {
    bytes,
    limit: MAX_ZIP_UNCOMPRESSED_BYTES,
    limitMessage: `ZIP archive expands beyond ${formatBytes(MAX_ZIP_UNCOMPRESSED_BYTES)}; use a smaller archive or drop an extracted folder`,
  };
  const entries = await runBrowserTask('unzip', input, () => unzipTask(input));
  const files = new Map<string, Uint8Array>();
  for (const [path, entryBytes] of Object.entries(entries)) {
    const normalizedPath = normalizePath(path);
    Iif (!normalizedPath || normalizedPath.endsWith('/')) {
      continue;
    }
    files.set(normalizedPath, entryBytes);
  }
  return {
    id: `zip:${name}`,
    kind: 'zip',
    label: name,
    files,
  };
}
 
function formatBytes(bytes: number): string {
  Iif (!Number.isFinite(bytes) || bytes < 0) return 'unknown size';
  const mib = bytes / (1024 * 1024);
  if (mib < 1024) return `${mib.toFixed(mib >= 10 ? 0 : 1)} MiB`;
  const gib = mib / 1024;
  return `${gib.toFixed(gib >= 10 ? 0 : 1)} GiB`;
}
 
/**
 * `localeCompare(…, 'ja')` as one collator: the same order, without setting up a collator for each of the thousands of
 * comparisons a large drop's path sort makes.
 */
const JAPANESE_COLLATOR = new Intl.Collator('ja');
 
function inferSourceKind(files: ReadonlyMap<string, BrowserAssetEntry>): ChartSourceKind {
  for (const path of files.keys()) {
    Eif (path.includes('/')) return 'directory';
  }
  return 'files';
}
 
export function resolveChartSource(
  collection: BrowserChartCollection,
  chartEntry: LibraryChart,
): BrowserAssetSource | undefined {
  return collection.sources.find((source) => source.id === chartEntry.sourceId);
}
 
/**
 * Resolves a chart-relative asset path (BMP, WAV, banner, …) to its decoded byte array within a song asset source.
 * Mirrors the BMS convention of looking next to the chart file first, then falling back to the source's root and the
 * basename, then — as LR2 does — the same one folder up from the chart. Used by both gameplay (BGA/audio) and select (banner / preview) loaders.
 *
 * Lookup is **case-insensitive** at every candidate step: real-world BMS archives routinely mix `KICK.WAV` / `kick.WAV`
 * / `Kick.wav`, and demanding the chart's casing match the file's would scuttle a large fraction of legitimate drops on
 * case-sensitive filesystems (and in `webkitRelativePath` directory drops). The `findCaseInsensitiveMapPath` helper
 * builds a lazy lower-key index the first time it's called per source and caches it via WeakMap.
 */
export function resolveChartAsset(
  source: BrowserAssetSource,
  chartPath: string,
  assetPath: string,
): BrowserAssetEntry | undefined {
  for (const folderChartPath of chartLookupFolders(chartPath)) {
    const entry = resolveChartAssetInFolder(source, folderChartPath, assetPath);
    if (entry) return entry;
  }
  return undefined;
}
 
/**
 * Where a chart's assets are looked for, as chart paths: the chart itself, then — as LR2 does — a stand-in one folder
 * up, so a 差分 (alternate difficulty) chart shipped in a sub-folder finds the keysounds and BGA beside its parent.
 * A chart directly under the dropped folder has no extra entry: its parent is the top, which the lookup always tries.
 * Every extension is tried in the chart's own folder before the parent's (see {@link resolveChartAudioAsset}).
 */
function chartLookupFolders(chartPath: string): string[] {
  const parent = dirname(dirname(chartPath));
  return parent === '' ? [chartPath] : [chartPath, `${parent}/${basename(chartPath)}`];
}
 
/** {@link resolveChartAsset} in one folder: next to `chartPath`, then the top of the source. */
function resolveChartAssetInFolder(
  source: BrowserAssetSource,
  chartPath: string,
  assetPath: string,
  excludedEntries?: ReadonlySet<BrowserAssetEntry>,
): BrowserAssetEntry | undefined {
  const key = resolveChartAssetKeyInFolder(source, chartPath, assetPath, excludedEntries);
  return key === undefined ? undefined : source.files.get(key);
}
 
/** {@link resolveChartAssetInFolder}, naming the key in `source.files` it found the file under. */
function resolveChartAssetKeyInFolder(
  source: BrowserAssetSource,
  chartPath: string,
  assetPath: string,
  excludedEntries?: ReadonlySet<BrowserAssetEntry>,
): string | undefined {
  const parts = chartAssetPathParts(assetPath);
  return parts === undefined
    ? undefined
    : resolveChartAssetPartsKey(source, dirname(chartPath), parts, excludedEntries);
}
 
/** An asset path as the folder lookup reads it: normalized, and its file name alone. */
interface ChartAssetPathParts {
  readonly normalized: string;
  readonly baseName: string;
}
 
/**
 * `assetPath` split for {@link resolveChartAssetPartsKey}, or `undefined` for a malicious path. bmson 1.0.0 spec MUST:
 * reject malicious paths at the chart-asset entry point. `findCaseInsensitiveMapPath` also vets each candidate as
 * defense-in-depth, but short-circuiting here means we don't even synthesize the joined `${base}/${assetPath}`
 * candidate for a path the chart never had any business referencing.
 */
function chartAssetPathParts(assetPath: string): ChartAssetPathParts | undefined {
  Iif (isMaliciousAssetPath(assetPath)) return undefined;
  const normalized = normalizePath(assetPath);
  return { normalized, baseName: basename(normalized) };
}
 
/**
 * The key an asset is found under from the chart folder `base`: the path joined to the folder, the path from the top of
 * the source, the file name in the folder, then the file name at the top. `missed` holds paths already looked up and
 * missed in the same resolution; they are not looked up again, and this lookup's misses join them.
 */
function resolveChartAssetPartsKey(
  source: BrowserAssetSource,
  base: string,
  { normalized, baseName }: ChartAssetPathParts,
  excludedEntries?: ReadonlySet<BrowserAssetEntry>,
  missed?: Set<string>,
): string | undefined {
  const candidates = [
    normalizePath(`${base}/${normalized}`),
    normalized,
    normalizePath(`${base}/${baseName}`),
    baseName,
  ];
  for (const candidate of candidates) {
    if (missed?.has(candidate)) continue;
    const key = findCaseInsensitiveMapPath(source.files, candidate, { rejectCandidate: isMaliciousAssetPath });
    if (key === undefined) {
      missed?.add(candidate);
      continue;
    }
    const entry = source.files.get(key);
    if (entry !== undefined && !excludedEntries?.has(entry)) {
      return key;
    }
  }
  return undefined;
}
 
export interface ResolveChartAudioAssetOptions {
  /**
   * BMS spec — `#PATH_WAV <prefix>` declares a directory the chart's WAVs live under. The resolver tries each codec
   * fallback prefixed with this string before falling through to the bare path, so a chart authored as `wav/` + bare
   * `kick.wav` references resolves the file as `wav/kick.wav`.
   */
  pathPrefix?: string;
  /** Assets already rejected by the decoder; lookup continues through codec and folder fallbacks. */
  excludedEntries?: ReadonlySet<BrowserAssetEntry>;
}
 
/** Try the authored name, then alternate audio extensions, in the chart folder before its parent. */
export function resolveChartAudioAsset(
  source: BrowserAssetSource,
  chartPath: string,
  assetPath: string,
  options: ResolveChartAudioAssetOptions = {},
): BrowserAssetEntry | undefined {
  Iif (isMaliciousAssetPath(assetPath)) return undefined;
  const compositeCandidates = source.audioFallbacks?.get(normalizePath(assetPath));
  if (compositeCandidates !== undefined)
    return compositeCandidates.find((entry) => !options.excludedEntries?.has(entry));
  const key = resolveChartAudioKey(source, chartPath, assetPath, options);
  return key === undefined ? undefined : source.files.get(key);
}
 
/**
 * Every file {@link resolveChartAudioAsset} can play for `assetPath`, best first: the one it returns, then each one it
 * would fall back to once the ones before it fail to decode (`excludedEntries`), found in one pass over the folder and
 * codec fallbacks. Each comes with the key in `source.files` it is stored under (`key`), so a host that re-files the
 * assets (a stitched NONSTOP chart's composite source) needs no reverse lookup over the source's files; a composite
 * source's own fallbacks (`audioFallbacks`) have none.
 */
export function resolveChartAudioAssetCandidates(
  source: BrowserAssetSource,
  chartPath: string,
  assetPath: string,
  options: Pick<ResolveChartAudioAssetOptions, 'pathPrefix'> = {},
): Array<{ entry: BrowserAssetEntry; key: string | undefined }> {
  if (isMaliciousAssetPath(assetPath)) return [];
  const compositeCandidates = source.audioFallbacks?.get(normalizePath(assetPath));
  if (compositeCandidates !== undefined) {
    return [...new Set(compositeCandidates)].map((entry) => ({ entry, key: undefined }));
  }
  const found: Array<{ entry: BrowserAssetEntry; key: string | undefined }> = [];
  const seen = new Set<BrowserAssetEntry>();
  const tried = new Set<string>();
  const collect = (folderChartPath: string, path: string): void => {
    Iif (isMaliciousAssetPath(path)) return;
    const base = dirname(folderChartPath);
    const normalized = normalizePath(path);
    const baseName = basename(normalized);
    for (const candidate of [
      normalizePath(`${base}/${normalized}`),
      normalized,
      normalizePath(`${base}/${baseName}`),
      baseName,
    ]) {
      if (tried.has(candidate)) continue;
      tried.add(candidate);
      const key = findCaseInsensitiveMapPath(source.files, candidate, { rejectCandidate: isMaliciousAssetPath });
      const entry = key === undefined ? undefined : source.files.get(key);
      if (entry === undefined || seen.has(entry)) continue;
      seen.add(entry);
      found.push({ entry, key });
    }
  };
  // The order of resolveChartAudioKey: every codec in the chart's folder before any in its parent, each with the
  // `#PATH_WAV` prefix before the bare name.
  for (const folderChartPath of chartLookupFolders(chartPath)) {
    for (const candidate of audioFallbackPaths(assetPath.replaceAll('\\', '/'))) {
      const prefixed = joinPathWAVPrefix(options.pathPrefix, candidate);
      if (prefixed !== undefined) collect(folderChartPath, prefixed);
      collect(folderChartPath, candidate);
    }
  }
  return found;
}
 
/** The key of {@link resolveChartAudioAsset}'s file in `source.files`, from its folder and codec fallbacks. */
function resolveChartAudioKey(
  source: BrowserAssetSource,
  chartPath: string,
  assetPath: string,
  options: ResolveChartAudioAssetOptions,
): string | undefined {
  // Every codec in the chart's folder before any in its parent, as LR2 does.
  for (const folderChartPath of chartLookupFolders(chartPath)) {
    for (const candidate of audioFallbackPaths(assetPath.replaceAll('\\', '/'))) {
      // Try the `#PATH_WAV` prefixed form first when supplied; fall through to the bare name if the prefix-joined path
      // doesn't resolve. Charts that don't author `#PATH_WAV` pass `pathPrefix: undefined` and behave exactly as
      // before.
      const prefixed = joinPathWAVPrefix(options.pathPrefix, candidate);
      if (prefixed !== undefined) {
        const key = resolveChartAssetKeyInFolder(source, folderChartPath, prefixed, options.excludedEntries);
        if (key !== undefined) return key;
      }
      const key = resolveChartAssetKeyInFolder(source, folderChartPath, candidate, options.excludedEntries);
      if (key !== undefined) return key;
    }
  }
  return undefined;
}
 
function joinPathWAVPrefix(prefix: string | undefined, samplePath: string): string | undefined {
  if (typeof prefix !== 'string') return undefined;
  const trimmedPrefix = prefix.trim();
  Iif (trimmedPrefix.length === 0) return undefined;
  // Skip when the chart already includes the prefix in the sample path — common when `#WAV01` already references
  // `wav/kick.wav` AND `#PATH_WAV wav/` is also set. The bare-path candidate (returned without the second prefix
  // application) already resolves correctly.
  const normalizedPrefix = trimmedPrefix.replaceAll('\\', '/');
  const normalizedSample = samplePath.replaceAll('\\', '/');
  const prefixWithSep = normalizedPrefix.endsWith('/') ? normalizedPrefix : `${normalizedPrefix}/`;
  if (normalizedSample.startsWith(prefixWithSep)) {
    return undefined;
  }
  return `${prefixWithSep}${samplePath}`;
}
 
function audioFallbackPaths(path: string): string[] {
  const lastSlash = path.lastIndexOf('/');
  const dotIndex = path.lastIndexOf('.');
  // bmson permits extensionless names, which get the same fallback list.
  const base = dotIndex > lastSlash ? path.slice(0, dotIndex) : path;
  const alternatives = [`${base}.opus`, `${base}.ogg`, `${base}.mp3`, `${base}.wav`, `${base}.m4a`];
  const authored = path.toLowerCase();
  return [path, ...alternatives.filter((candidate) => candidate.toLowerCase() !== authored)];
}
 
/**
 * Image-asset variant of {@link resolveChartAsset} that walks the common BMS image-format extensions before giving up.
 * BMS charts historically declare `#BMPxx test.bmp`, but archives ship the actual graphic as `.png` / `.jpg` / `.gif`
 * more often than as a real Windows bitmap. Mirrors {@link resolveChartAudioAsset}'s codec-walking behavior:
 *
 * - 1. the path the chart names, as LR2 tries it before any other extension (OpenLR2 `LR2f.cpp` L14607-L14673). A
 *   same-stem file is not guaranteed to hold the same picture, so it never replaces a file that is there (#1192).
 * - 2. when that file is missing, the same name as `.webp`, `.png`, `.jpg`, `.jpeg`, `.gif`, `.bmp`, without repeating
 *   the named extension. The order is a Be-Music policy: LR2 tries `.png`, `.jpg`, `.bmp` and beatoraja `.jpg`,
 *   `.jpeg`, `.gif`, `.bmp`, `.png`, `.tga`; `.webp` is first so a pack re-encoded to save space resolves.
 *
 * The bytes are decoded by content, not by the declared extension, so a `#BMPxx foo.bmp` resolved to `foo.webp` decodes
 * as WebP.
 *
 * Case is handled by `resolveChartAsset` itself (case-insensitive lookup), so this list doesn't need explicit
 * upper-case duplicates.
 */
export function resolveChartImageAsset(
  source: BrowserAssetSource,
  chartPath: string,
  assetPath: string,
): BrowserAssetEntry | undefined {
  return resolveChartBGAAsset(source, chartPath, assetPath)?.entry;
}
 
/**
 * {@link resolveChartImageAsset}, also naming the file it found (`path`, relative like `assetPath`): a video declared
 * as `_bga.mpg` may resolve to `_bga.mp4`, and the video loader should treat the bytes as what they are.
 */
export function resolveChartBGAAsset(
  source: BrowserAssetSource,
  chartPath: string,
  assetPath: string,
): { entry: BrowserAssetEntry; path: string; key: string } | undefined {
  const primary = imageFallbackPaths(assetPath);
  const stills = isVideoExtensionPath(assetPath)
    ? stillImageFallbackPaths(assetPath.slice(0, assetPath.lastIndexOf('.')))
    : [];
  // Each candidate is split once and each folder named once; a path missed once stays missed, since the bare forms
  // recur across folders.
  const missed = new Set<string>();
  // Exhaust the video candidates across both folders before trying still images.
  for (const paths of [primary, stills]) {
    // Split lazily: a hit in the chart's own folder usually comes on the first candidate or two.
    const split: (ChartAssetPathParts | null | undefined)[] = [];
    for (const folderChartPath of chartLookupFolders(chartPath)) {
      const base = dirname(folderChartPath);
      for (let index = 0; index < paths.length; index += 1) {
        const candidate = paths[index]!;
        const candidateParts = (split[index] ??= chartAssetPathParts(candidate) ?? null);
        Iif (candidateParts === null) continue;
        const key = resolveChartAssetPartsKey(source, base, candidateParts, undefined, missed);
        const entry = key === undefined ? undefined : source.files.get(key);
        if (key !== undefined && entry !== undefined) return { entry, path: candidate, key };
      }
    }
  }
  return undefined;
}
 
/**
 * The video extensions tried, in order, when a chart's declared video BGA isn't there under its own name: packs often
 * re-encode `_bga.mpg` / `_bga.wmv` to `_bga.mp4` without touching the chart (beatoraja looks for the other
 * extensions too). Browser-native containers come first, so the re-encode wins over a legacy original left beside it.
 */
const VIDEO_FALLBACK_EXTENSIONS = ['mp4', 'webm', 'm4v', 'mov', 'mpg', 'mpeg', 'wmv', 'avi', 'mkv'] as const;
 
function imageFallbackPaths(path: string): string[] {
  const lastSlash = path.lastIndexOf('/');
  const dotIndex = path.lastIndexOf('.');
  Iif (dotIndex < 0 || dotIndex < lastSlash) {
    return [path];
  }
  if (isVideoExtensionPath(path)) {
    const videoBase = path.slice(0, dotIndex);
    const declared = path.slice(dotIndex + 1).toLowerCase();
    return [path, ...VIDEO_FALLBACK_EXTENSIONS.filter((ext) => ext !== declared).map((ext) => `${videoBase}.${ext}`)];
  }
  const base = path.slice(0, dotIndex);
  const authored = path.toLowerCase();
  // The file the chart names first, as LR2 looks images up: a same-stem file is not guaranteed to be the same picture.
  return [path, ...stillImageFallbackPaths(base).filter((candidate) => candidate.toLowerCase() !== authored)];
}
 
function stillImageFallbackPaths(base: string): string[] {
  return ['webp', 'png', 'jpg', 'jpeg', 'gif', 'bmp'].map((extension) => `${base}.${extension}`);
}
 
/**
 * Local copy of `isVideoExtension` from `chart/bga-timeline.ts`. Pulled inline rather than imported so
 * `collection.ts` (the data-layer entry point) doesn't take a dependency on the play's BGA helpers; the patterns are
 * tiny and trivially kept in sync.
 */
function isVideoExtensionPath(path: string): boolean {
  return /\.(mpg|mpeg|mp4|m4v|avi|mov|wmv|webm|mkv)$/iu.test(path);
}
 
function basenameWithoutExtension(path: string): string {
  const name = basename(path);
  const dotIndex = name.lastIndexOf('.');
  return dotIndex >= 0 ? name.slice(0, dotIndex) : name;
}
 
function firstPathSegment(path: string): string {
  return normalizePath(path).split('/')[0] ?? '';
}
 
function extensionOf(path: string): string {
  const dotIndex = path.lastIndexOf('.');
  return dotIndex >= 0 ? path.slice(dotIndex).toLowerCase() : '';
}