All files / chart-writer/src bmson.ts

96.68% Statements 408/422
92.32% Branches 421/456
100% Functions 49/49
97.22% Lines 385/396

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                                                                              201x 2x 199x 199x 199x 201x   201x     201x 22x   177x 177x 177x         177x 177x 16056x 16056x 11714x   4342x 16056x   177x   177x 177x   177x           177x 177x 177x 177x 177x     177x     177x 177x     177x 177x 177x 177x 16056x 16056x 16056x 20x 18x 20x     16036x 16036x 16036x 40x 40x 40x 40x     40x 40x 40x         40x           40x   40x   15996x 86x 86x 86x 86x 86x         86x 86x   86x   15910x     4272x 18x   4254x 4254x 4272x 4272x 4272x   4272x           4272x 4272x 1x 4253x     4272x       4272x         4272x                 4272x     15891x 2x 2x 2x   2x   15889x 3882x 3882x 3876x 6x   4x   3882x   12007x   3875x 3875x 3869x         6x 6x   3875x   8132x   3879x 3879x 3879x         176x 22x 22x 22x 22x 3x   176x                           201x 33x   176x 31x   176x 176x 36x   176x           176x               159x           115x       44x 133x   10x     34x   79x   1x     33x 33x 1x   32x       33x       33x 33x   33x 31x 6x   33x 8x   33x 6x   33x 33x 1x   33x 32x   33x 33x 8x   33x       33x 33x   33x 14x   33x 5x   33x 11x   33x 10x   33x 4x   33x 2x   33x 5x   33x 33x   33x 5x   33x 4x   33x 8x   33x 4x   33x 3x   33x 2x   33x     33x 2x   33x 2x   33x 33x         33x       32x 32x       9x               7x               3x                     44x     60x                                 199x 35x   164x 86x       673x 673x         509x       176x 81x   95x                 176x 176x 176x                       176x 176x 1x   176x     176x 176x 29x     176x 176x 34x   176x 176x 82x 94x         3x           176x 6x   176x 6x   176x 6x   176x 6x   176x       176x                           24x                     176x 176x 5x   171x 171x 77x   94x 94x 8x   86x 21x   65x                       176x 176x 5x   171x 171x 77x   94x                         176x 7x 7x 176x 1x       7x 1x       7x 1x       7x 1x       7x 1x             176x 4x   172x 172x                                             209x 209x 64x           209x 209x 209x 209x   209x 209x 209x 8x 8x 8x 8x 8x 8x 8x 8x     209x               165x     44x         33x     87x                             176x 175x   3x       176x 174x 23x       151x         23x 10x 21x       23x 23x 1x   23x       151x 151x 151x 15826x 1091x     151x 151x 151x 4x 4x   4x   151x   151x 151x 151x 1244x 1244x 1244x 1244x     151x               182x 182x 1464x   182x             627x 627x 145x                 627x                     177x 48x   129x 129x 130x 130x 129x 128x 136x 125x     3x                           177x 177x 177x 177x 336x 336x 320x   16x     177x 177x 177x         82x 82x 82x             8877x       4519x 180x         4475x 4433x       24x 24x                           177x 177x 177x 177x 177x 10x 9x     177x 10x   177x             40x 6x             176x 176x 22x   154x 176x 176x    
import { resolveLandmineDamage } from '@be-music/chart-model';
import { collectBmsonExtraFields, type JSONFields } from '@be-music/chart-source';
import { resolveChartLongNoteMode } from '@be-music/chart-model';
import {
  createBeatResolver,
  isLandmineChannel,
  isSampleTriggerChannel,
  mapBMSLongNoteChannelToPlayable,
  parseBPMFrom03Token,
  resolveBMSLongNotes,
  resolveChartPlayVariant,
  BMSON_MODE_HINT_LAYOUTS,
  getPlayModeLayouts,
  resolveBmsonModeHintLayout,
  resolveLNOBJLongNotes,
  sortEvents,
} from '@be-music/chart-model';
import { parseBmson } from '@be-music/chart-parser/core';
import {
  normalizeChannel,
  normalizeObjectKey,
  resolveBMSBase,
  type BmsonBPMEventEntry,
  type BmsonBGAEvent,
  type BmsonBGASequence,
  type BmsonScrollEventEntry,
  type BmsonSoundChannelEntry,
  type BmsonStopEventEntry,
  type BeMusicEvent,
  type BeMusicJSON,
} from '@be-music/chart-source';
import { normalizeSortedUniqueNonNegativeIntegers } from '@be-music/shared-utils/core';
import { areBmsonChartsEquivalent } from './equivalence.ts';
import { convertBmsBGAToBmson, type ChartExportDiagnosticHandler } from './bga-export.ts';
import type { BmsonStringifyOptions } from './options.ts';
import { intrinsicWAVGains } from './wav-gain.ts';
import { DEFAULT_BMSON_RESOLUTION, resolveExactBmsonResolution } from './bmson-output-resolution.ts';
 
export function stringifyBmson(json: BeMusicJSON, options: BmsonStringifyOptions = {}): string {
  if (intrinsicWAVGains(json).length)
    throw new RangeError('Intrinsic WAV gain cannot be represented by bmson; export Be-Music JSON.');
  const resolution = resolveBmsonResolutionForOutput(json, options);
  const sourceResolution = resolveBmsonSourceResolution(json);
  const indent = options.indent ?? 2;
  const skipValidation = options.skipPreservationValidation === true;
  const preservedDocument =
    options.resolution === undefined
      ? resolvePreservedBmsonDocumentForOutput(json, resolution, skipValidation)
      : undefined;
  if (preservedDocument) {
    return `${JSON.stringify(preservedDocument, null, indent)}\n`;
  }
  const sortedEvents = sortEvents(json.events);
  const beatResolver = createBeatResolver(json);
  const bmsLongNotes = resolveBMSLongNotesForBmsonOutput(json);
 
  // Lanes get bmson `x` numbers from every playable channel in use, plus the lanes mines and invisible objects sit on (a
  // mine on `D3` or a hidden note on `33` sits on lane `13`), so they keep their lane even where no playable note
  // shares it.
  const playableChannelSet = new Set<string>();
  for (const event of sortedEvents) {
    const channel = normalizeChannel(event.channel);
    if (channel === '01' || !isSampleTriggerChannel(channel)) {
      continue;
    }
    const lane = laneExtensionChannelToPlayableChannel(channel) ?? mapBMSLongNoteChannelToPlayable(channel) ?? channel;
    playableChannelSet.add(lane);
  }
  const playableChannels = [...playableChannelSet].sort();
 
  const modeHint = resolveBmsonModeHintForOutput(json, playableChannels);
  const xMap = createBmsonXMap(playableChannels, modeHint, json.bmson.info.modeHint !== undefined);
 
  const soundChannels = new Map<
    string,
    { name: string; notes: Array<{ x: number; y: number; l: number; c: boolean; t?: number; up?: boolean }> }
  >();
  // beatoraja's lane extensions, grouped by sample like `sound_channels`: `key_channels` hold hidden notes (BMS
  // invisible objects) and `mine_channels` hold mines, each keeping its `damage`.
  const keyChannels = new Map<string, { name: string; notes: Array<{ x: number; y: number }> }>();
  const mineChannels = new Map<string, { name: string; notes: Array<{ x: number; y: number; damage?: number }> }>();
  const bpmEvents: Array<{ y: number; bpm: number }> = [];
  const stopEvents: Array<{ y: number; duration: number }> = [];
  const scrollEvents: Array<{ y: number; rate: number }> = [];
  // Honor `#BASE 62` so a chart whose `event.value` is a case-sensitive lowercase ID resolves to the right sample /
  // BPM / STOP slot when re-emitted as bmson.
  const idBase = resolveBMSBase(json);
 
  // BMS objects bmson has no field for, counted for `onDiagnostic`.
  let speedObjects = 0;
  let exRankObjects = 0;
  // BMS BPM and STOP objects the player plays as LR2 does but bmson cannot hold (`collectTempoChanges`,
  // `collectStopChanges`): a negative or undefined `#BPMxx`, and a STOP without a positive `#STOPxx`.
  let reversingBPMObjects = 0;
  let unsetStopObjects = 0;
  const playsBMSTimingRules = json.sourceFormat === 'bms';
  for (const event of sortedEvents) {
    const channel = normalizeChannel(event.channel);
    const isSampleChannel = isSampleTriggerChannel(channel);
    if (!isSampleChannel && channel !== '03' && channel !== '08' && channel !== '09' && channel !== 'SC') {
      if (channel === 'SP') speedObjects += 1;
      else if (channel === 'A0') exRankObjects += 1;
      continue;
    }
 
    const beat = beatResolver.eventToBeat(event);
    const y = Math.round(beat * resolution);
    if (isSampleChannel && isLandmineChannel(channel)) {
      const lane = landmineChannelToPlayableChannel(channel);
      const x = lane ? xMap.get(lane) : undefined;
      Eif (x !== undefined) {
        const damage = resolveMineDamageForBmsonOutput(json, event, idBase);
        // A BMS mine's value is its damage, not a WAV slot: every BMS mine explodes with `#WAV00`, so they share one
        // channel named after it (no sample when the chart has none). bmson-sourced mines keep their WAV slot.
        const key = json.sourceFormat === 'bmson' ? normalizeObjectKey(event.value, idBase, true) : BMS_MINE_SAMPLE_KEY;
        const name = json.resources.wav[key] ?? (json.sourceFormat === 'bmson' ? key : '');
        const slot = mineChannels.get(key) ?? {
          ...collectBmsonExtraFields(json.bmson.channelExtraFields?.[key], 'channel'),
          name,
          notes: [],
        };
        slot.notes.push({
          ...collectBmsonExtraFields(event.bmson?.extraFields, 'mineNote'),
          x,
          y,
          ...(damage !== undefined ? { damage } : {}),
        });
        mineChannels.set(key, slot);
      }
      continue;
    }
    if (isSampleChannel && isInvisibleChannel(channel)) {
      const lane = invisibleChannelToPlayableChannel(channel);
      const x = lane ? xMap.get(lane) : undefined;
      Eif (x !== undefined) {
        const key = normalizeObjectKey(event.value, idBase, json.sourceFormat === 'bmson');
        const slot = keyChannels.get(key) ?? {
          ...collectBmsonExtraFields(json.bmson.channelExtraFields?.[key], 'channel'),
          name: json.resources.wav[key] ?? key,
          notes: [],
        };
        slot.notes.push({ ...collectBmsonExtraFields(event.bmson?.extraFields, 'keyNote'), x, y });
        keyChannels.set(key, slot);
      }
      continue;
    }
    if (isSampleChannel) {
      // The end of a BMS long note (`#LNOBJ` end object, `5x` / `6x` end or continuation) is part of the note that
      // starts it, which carries the length as `l`.
      if (bmsLongNotes.endEvents.has(event)) {
        continue;
      }
      const key = normalizeObjectKey(event.value, idBase, json.sourceFormat === 'bmson');
      const fileName = json.resources.wav[key] ?? key;
      const lane = mapBMSLongNoteChannelToPlayable(channel) ?? channel;
      const x = channel === '01' ? 0 : (xMap.get(lane) ?? 0);
      const sourceLength = event.bmson?.l;
      const longNoteEndBeat =
        bmsLongNotes.startToEndBeat.get(event) ??
        (typeof sourceLength === 'number' && Number.isFinite(sourceLength) && sourceLength > 0
          ? beat + sourceLength / sourceResolution
          : undefined);
      // Round both absolute endpoints, just as the separate `up` event is rounded. Scaling l alone can put the
      // tail one pulse away from its release keysound when the requested ratio is not an integer.
      const length = longNoteEndBeat === undefined ? 0 : Math.max(0, Math.round(longNoteEndBeat * resolution) - y);
      if (longNoteEndBeat !== undefined && longNoteEndBeat > beat && length === 0)
        throw new RangeError('The long note collapses at the output pulse grid; choose a higher resolution.');
      const continuation = event.bmson?.c === true;
      // beatoraja bmson extension — per-note long-note type rides along only on actual long notes.
      const longNoteType =
        length > 0 && (event.bmson?.t === 1 || event.bmson?.t === 2 || event.bmson?.t === 3)
          ? event.bmson.t
          : undefined;
 
      const slot = soundChannels.get(key) ?? {
        ...collectBmsonExtraFields(json.bmson.channelExtraFields?.[key], 'channel'),
        name: fileName,
        notes: [],
      };
      slot.notes.push({
        ...collectBmsonExtraFields(event.bmson?.extraFields, 'note'),
        x,
        y,
        l: length,
        c: continuation,
        ...(longNoteType !== undefined ? { t: longNoteType } : {}),
        ...(typeof event.bmson?.up === 'boolean' ? { up: event.bmson.up } : {}),
      });
      soundChannels.set(key, slot);
    }
 
    if (channel === '03') {
      const bpm = parseBPMFrom03Token(event.value);
      Eif (bpm > 0) {
        bpmEvents.push({ ...collectBmsonExtraFields(event.bmson?.extraFields, 'bpm'), y, bpm });
      }
      continue;
    }
    if (channel === '08') {
      const bpm = json.resources.bpm[normalizeObjectKey(event.value, idBase, json.sourceFormat === 'bmson')];
      if (typeof bpm === 'number' && bpm > 0) {
        bpmEvents.push({ ...collectBmsonExtraFields(event.bmson?.extraFields, 'bpm'), y, bpm });
      } else if (playsBMSTimingRules && (bpm === undefined || (Number.isFinite(bpm) && bpm < 0))) {
        // A zero `#BPMxx` is ignored in play as well, so only these change the chart.
        reversingBPMObjects += 1;
      }
      continue;
    }
    if (channel === '09') {
      // `#STOPxx` counts 1/192 of a 4/4 measure (48 per beat); bmson `duration` counts pulses at `resolution`.
      const stopUnits = json.resources.stop[normalizeObjectKey(event.value, idBase, json.sourceFormat === 'bmson')];
      if (typeof stopUnits === 'number' && stopUnits > 0) {
        stopEvents.push({
          ...collectBmsonExtraFields(event.bmson?.extraFields, 'stop'),
          y,
          duration: Math.round((stopUnits * resolution) / 48),
        });
      } else Eif (playsBMSTimingRules) {
        unsetStopObjects += 1;
      }
      continue;
    }
    if (channel === 'SC') {
      // beatoraja's `scroll_events` extension carries `#SCROLLxx` rates as they are.
      const rate = json.bms.scroll[normalizeObjectKey(event.value, idBase, json.sourceFormat === 'bmson')];
      Eif (typeof rate === 'number' && Number.isFinite(rate)) {
        scrollEvents.push({ ...collectBmsonExtraFields(event.bmson?.extraFields, 'scroll'), y, rate });
      }
    }
  }
 
  for (const [key, fields] of Object.entries(json.bmson.channelExtraFields ?? {})) {
    Iif (!Object.hasOwn(json.resources.wav, key)) continue;
    const kind = json.bmson.channelKinds?.[key] ?? 'sound';
    const channels = kind === 'mine' ? mineChannels : kind === 'key' ? keyChannels : soundChannels;
    if (!soundChannels.has(key) && !keyChannels.has(key) && !mineChannels.has(key))
      channels.set(key, { ...collectBmsonExtraFields(fields, 'channel'), name: json.resources.wav[key]!, notes: [] });
  }
  const bmson: Record<string, unknown> = {
    ...collectBmsonExtraFields(json.bmson.extraFields, 'root'),
    version: resolveBmsonVersionForOutput(json),
    info: createBmsonInfoForOutput(json, resolution, modeHint, options.onDiagnostic),
    lines: mapBmsonLineValues(
      resolveBmsonLinesForOutput(json, resolution),
      json.bmson.lineExtraFields,
      resolution / sourceResolution,
    ),
    bpm_events: bpmEvents,
    stop_events: stopEvents,
    ...(scrollEvents.length > 0 ? { scroll_events: scrollEvents } : {}),
    sound_channels: [...soundChannels.values()],
  };
  if (keyChannels.size > 0) {
    bmson.key_channels = [...keyChannels.values()];
  }
  if (mineChannels.size > 0) {
    bmson.mine_channels = [...mineChannels.values()];
  }
  const bga = createBmsonBGAForOutput(json, resolution, options.onDiagnostic);
  if (bga) {
    bmson.bga = bga;
  }
  reportBMSOnlyDirectives(
    json,
    { speedObjects, exRankObjects, reversingBPMObjects, unsetStopObjects },
    options.onDiagnostic,
  );
 
  return `${JSON.stringify(bmson, null, indent)}\n`;
}
 
function resolvePreservedBmsonDocumentForOutput(
  json: BeMusicJSON,
  resolution: number,
  skipValidation: boolean,
): Record<string, unknown> | undefined {
  if (
    json.preservation.bmson.soundChannels.length === 0 &&
    json.preservation.bmson.bpmEvents.length === 0 &&
    json.preservation.bmson.stopEvents.length === 0 &&
    (json.preservation.bmson.scrollEvents?.length ?? 0) === 0
  ) {
    return undefined;
  }
  // The preserved arrays hold no `key_channels` / `mine_channels`, so a chart with hidden notes or mines always takes
  // the canonical path; otherwise a trusted (unvalidated) re-output would silently drop them.
  if (
    json.events.some((event) => laneExtensionChannelToPlayableChannel(normalizeChannel(event.channel)) !== undefined)
  ) {
    return undefined;
  }
  // Likewise SCROLL objects without a preserved `scroll_events` list (added after parsing, or from an older IR).
  if (
    (json.preservation.bmson.scrollEvents?.length ?? 0) === 0 &&
    json.events.some((event) => normalizeChannel(event.channel) === 'SC')
  ) {
    return undefined;
  }
 
  const document = createPreservedBmsonDocumentForOutput(json, resolution);
  if (skipValidation) {
    return document;
  }
  return doPreservedBmsonDocumentMatchChart(json, document) ? document : undefined;
}
 
function createPreservedBmsonDocumentForOutput(json: BeMusicJSON, resolution: number): Record<string, unknown> {
  const document: Record<string, unknown> = {
    ...collectBmsonExtraFields(json.bmson.extraFields, 'root'),
    info: createPreservedBmsonInfoForOutput(json, resolution),
  };
  Eif (typeof json.bmson.version === 'string' && json.bmson.version.length > 0) {
    document.version = json.bmson.version;
  }
  if (json.bmson.barlinesSuppressed === true) document.lines = [];
  else if (json.preservation.bmson.lines.length > 0) {
    document.lines = mapBmsonLineValues(json.preservation.bmson.lines, json.bmson.lineExtraFields);
  }
  if (json.preservation.bmson.bpmEvents.length > 0) {
    document.bpm_events = json.preservation.bmson.bpmEvents.map(mapBmsonBPMEventForOutput);
  }
  if (json.preservation.bmson.stopEvents.length > 0) {
    document.stop_events = json.preservation.bmson.stopEvents.map(mapBmsonStopEventForOutput);
  }
  const scrollEvents = json.preservation.bmson.scrollEvents ?? [];
  if (scrollEvents.length > 0) {
    document.scroll_events = scrollEvents.map(mapBmsonScrollEventForOutput);
  }
  if (json.preservation.bmson.soundChannels.length > 0) {
    document.sound_channels = json.preservation.bmson.soundChannels.map(mapBmsonSoundChannelForOutput);
  }
  const bga = createBmsonBGAForOutput(json, resolution);
  if (bga) {
    document.bga = bga;
  }
  return document;
}
 
function createPreservedBmsonInfoForOutput(json: BeMusicJSON, resolution: number): Record<string, unknown> {
  const info = json.bmson.info;
  const output: Record<string, unknown> = { ...collectBmsonExtraFields(info.extraFields, 'info') };
 
  if (typeof info.title === 'string') {
    output.title = info.title;
  }
  if (typeof info.subtitle === 'string') {
    output.subtitle = info.subtitle;
  }
  if (typeof info.artist === 'string') {
    output.artist = info.artist;
  }
  if (typeof info.genre === 'string') {
    output.genre = info.genre;
  }
  if (Array.isArray(info.subartists)) {
    output.subartists = info.subartists.filter((item) => typeof item === 'string');
  }
  if (typeof info.chartName === 'string') {
    output.chart_name = info.chartName;
  }
  if (typeof info.level === 'number') {
    output.level = info.level;
  }
  Eif (typeof info.initBPM === 'number') {
    output.init_bpm = info.initBPM;
  }
  if (typeof info.modeHint === 'string') {
    output.mode_hint = info.modeHint;
  }
  if (typeof info.judgeRank === 'number') {
    output.judge_rank = info.judgeRank;
  }
  if (info.lnType === 1 || info.lnType === 2 || info.lnType === 3) {
    output.ln_type = info.lnType;
  }
  if (typeof info.total === 'number') {
    output.total = info.total;
  }
  if (typeof info.backImage === 'string') {
    output.back_image = info.backImage;
  }
  if (typeof info.eyecatchImage === 'string') {
    output.eyecatch_image = info.eyecatchImage;
  }
  Iif (typeof info.titleImage === 'string') {
    output.title_image = info.titleImage;
  }
  if (typeof info.bannerImage === 'string') {
    output.banner_image = info.bannerImage;
  }
  if (typeof info.previewMusic === 'string') {
    output.preview_music = info.previewMusic;
  }
  if (typeof info.resolution === 'number') {
    output.resolution = info.resolution;
  } else E{
    output.resolution = resolution;
  }
 
  return output;
}
 
function doPreservedBmsonDocumentMatchChart(json: BeMusicJSON, document: Record<string, unknown>): boolean {
  const reparsed = parseBmson(JSON.stringify(document));
  return areBmsonChartsEquivalent(json, reparsed);
}
 
function mapBmsonBPMEventForOutput(event: BmsonBPMEventEntry): { y: number; bpm: number } {
  return {
    ...collectBmsonExtraFields(event.extraFields, 'bpm'),
    y: Math.max(0, Math.floor(event.y)),
    bpm: event.bpm,
  };
}
 
function mapBmsonStopEventForOutput(event: BmsonStopEventEntry): { y: number; duration: number } {
  return {
    ...collectBmsonExtraFields(event.extraFields, 'stop'),
    y: Math.max(0, Math.floor(event.y)),
    duration: event.duration,
  };
}
 
function mapBmsonScrollEventForOutput(event: BmsonScrollEventEntry): { y: number; rate: number } {
  return {
    ...collectBmsonExtraFields(event.extraFields, 'scroll'),
    y: Math.max(0, Math.floor(event.y)),
    rate: event.rate,
  };
}
 
function mapBmsonSoundChannelForOutput(channel: BmsonSoundChannelEntry): {
  name: string;
  notes: Array<{ x?: number; y: number; l?: number; c?: boolean; t?: number; up?: boolean }>;
} {
  return {
    ...collectBmsonExtraFields(channel.extraFields, 'channel'),
    name: channel.name,
    notes: channel.notes.map((note) => ({
      ...collectBmsonExtraFields(note.extraFields, 'note'),
      ...(typeof note.x === 'number' ? { x: Math.floor(note.x) } : {}),
      y: Math.max(0, Math.floor(note.y)),
      ...(typeof note.l === 'number' ? { l: Math.max(0, Math.floor(note.l)) } : {}),
      ...(typeof note.c === 'boolean' ? { c: note.c } : {}),
      ...(typeof note.up === 'boolean' ? { up: note.up } : {}),
      ...(note.t !== undefined ? { t: note.t } : {}),
    })),
  };
}
 
/**
 * The output pulses per beat: the caller's `resolution`, else a bmson source's own, else for a BMS chart the least
 * multiple of 240 that keeps every position exact (`resolveExactBmsonResolution`).
 */
function resolveBmsonResolutionForOutput(json: BeMusicJSON, options: BmsonStringifyOptions): number {
  if (typeof options.resolution === 'number' && Number.isFinite(options.resolution) && options.resolution >= 1) {
    return Math.floor(options.resolution);
  }
  if (hasBmsonSourceResolution(json) || json.sourceFormat === 'bmson') return resolveBmsonSourceResolution(json);
  return resolveExactBmsonResolution(json);
}
 
function hasBmsonSourceResolution(json: BeMusicJSON): boolean {
  const irResolution = json.bmson.info.resolution;
  return typeof irResolution === 'number' && Number.isFinite(irResolution) && irResolution >= 1;
}
 
/** The pulses per beat native bmson data in the IR is written at: its `info.resolution`, 240 when absent. */
function resolveBmsonSourceResolution(json: BeMusicJSON): number {
  return hasBmsonSourceResolution(json) ? Math.floor(json.bmson.info.resolution as number) : DEFAULT_BMSON_RESOLUTION;
}
 
function resolveBmsonVersionForOutput(json: BeMusicJSON): string {
  if (typeof json.bmson.version === 'string' && json.bmson.version.length > 0) {
    return json.bmson.version;
  }
  return '1.0.0';
}
 
function createBmsonInfoForOutput(
  json: BeMusicJSON,
  resolution: number,
  modeHint: string,
  report?: ChartExportDiagnosticHandler,
): Record<string, unknown> {
  const info = json.bmson.info;
  const metadataPlayLevel = resolveBmsonCompatiblePlayLevel(json.metadata.playLevel);
  const output: Record<string, unknown> = {
    ...collectBmsonExtraFields(info.extraFields, 'info'),
    title: info.title ?? json.metadata.title ?? '',
    subtitle: info.subtitle ?? json.metadata.subtitle ?? '',
    artist: info.artist ?? json.metadata.artist ?? '',
    genre: info.genre ?? json.metadata.genre ?? '',
    level: typeof info.level === 'number' ? info.level : (metadataPlayLevel ?? 0),
    init_bpm: typeof info.initBPM === 'number' ? info.initBPM : json.metadata.bpm,
    mode_hint: modeHint,
    resolution,
  };
 
  const subartists = normalizeBmsonSubartistsForOutput(info.subartists);
  if (subartists !== undefined) {
    output.subartists = subartists;
  }
  Iif (typeof info.chartName === 'string') {
    output.chart_name = info.chartName;
  }
  const lnType = resolveBmsonLNTypeForOutput(json);
  if (lnType !== undefined) {
    output.ln_type = lnType;
  }
 
  const judgeRank = resolveBmsonJudgeRankForOutput(json);
  if (judgeRank !== undefined) {
    output.judge_rank = judgeRank;
  }
  const total = resolveBmsonTotalForOutput(json);
  if (total !== undefined) {
    output.total = total;
  } else if (
    typeof json.metadata.total === 'number' &&
    Number.isFinite(json.metadata.total) &&
    json.metadata.total > 0
  ) {
    report?.({
      code: 'total',
      message: `#TOTAL ${json.metadata.total} is an absolute gauge TOTAL, which bmson total (a percentage of the player's default) cannot express; no total is written and the player's default applies.`,
    });
  }
 
  if (typeof info.backImage === 'string') {
    output.back_image = info.backImage;
  }
  if (typeof info.eyecatchImage === 'string') {
    output.eyecatch_image = info.eyecatchImage;
  }
  if (typeof info.titleImage === 'string') {
    output.title_image = info.titleImage;
  }
  if (typeof info.bannerImage === 'string') {
    output.banner_image = info.bannerImage;
  }
  Iif (typeof info.previewMusic === 'string') {
    output.preview_music = info.previewMusic;
  }
 
  return output;
}
 
/**
 * BMS `#RANK 0..4` (VERY HARD / HARD / NORMAL / EASY / VERY EASY) expressed on bmson's `judge_rank` axis, which is
 * `#DEFEXRANK`'s unit (100 = NORMAL). Each entry is the `#DEFEXRANK` value that judges like that rank: LR2 places
 * `#RANK 0..3` at 25 / 50 / 75 / 100 % and beatoraja at judgerank 25 / 50 / 75 / 100, both with NORMAL at 75, so both
 * give 100/3, 200/3, 100 and 400/3. They disagree only on VERY EASY — LR2 plays it as NORMAL, beatoraja (bmson's native
 * player) at judgerank 125 — and beatoraja's value (500/3) is used. Values are rounded to whole percents, which moves
 * LR2's windows by at most 0.4 ms. beatoraja itself reads a bmson `judge_rank` as the judgerank directly instead of
 * scaling it like `#DEFEXRANK` (× 75 / 100), so under it any bmson — including one converted from `#DEFEXRANK` or one
 * leaving `judge_rank` at its default — judges 4/3 wider than the same value in a BMS. No value on this axis can undo
 * that without breaking NORMAL = 100 for every other reader, so the mapping stays on the `#DEFEXRANK` axis.
 */
const BMS_RANK_TO_BMSON_JUDGE_RANK = [33, 67, 100, 133, 167] as const;
 
/**
 * bmson `info.judge_rank` shares `#DEFEXRANK`'s unit (100 = NORMAL), while BMS `#RANK` — `metadata.rank` on any
 * non-bmson chart — is a 0..4 rank index, so writing it verbatim turned `#RANK 2` into a 2 % window. Resolution order:
 * `bmson.info.judge_rank` as authored; for a bmson source, `metadata.rank` (the parser mirrors `judge_rank` there);
 * otherwise a positive `#DEFEXRANK` verbatim, then an integer `#RANK 0..4` through
 * {@link BMS_RANK_TO_BMSON_JUDGE_RANK}. beatoraja judges any other `#RANK` (out of range or fractional) as NORMAL, so
 * the field is left out and the bmson default (100 = NORMAL) applies.
 */
function resolveBmsonJudgeRankForOutput(json: BeMusicJSON): number | undefined {
  const authored = json.bmson.info.judgeRank;
  if (typeof authored === 'number' && Number.isFinite(authored)) {
    return authored;
  }
  const rank = json.metadata.rank;
  if (json.sourceFormat === 'bmson') {
    return typeof rank === 'number' && Number.isFinite(rank) ? rank : undefined;
  }
  const defExRank = json.bms.defExRank;
  if (typeof defExRank === 'number' && Number.isFinite(defExRank) && defExRank > 0) {
    return defExRank;
  }
  if (typeof rank === 'number' && Number.isInteger(rank) && rank >= 0 && rank < BMS_RANK_TO_BMSON_JUDGE_RANK.length) {
    return BMS_RANK_TO_BMSON_JUDGE_RANK[rank];
  }
  return undefined;
}
 
/**
 * bmson `info.total` is a percentage of the player's default TOTAL (beatoraja scales it by the note-count-based
 * default), while BMS `#TOTAL` — and `metadata.total` on any non-bmson chart — is the absolute gauge TOTAL. Writing the
 * absolute value would make e.g. `#TOTAL 300` mean 300% of the default, and there is no exact conversion here: the
 * default depends on the ruleset and on how it counts long notes. So only a value already in bmson terms is written —
 * `bmson.info.total`, or `metadata.total` of a bmson source (the parser mirrors `info.total` there) — and a BMS / JSON
 * chart's absolute TOTAL is left out, letting the bmson default (100%) apply.
 */
function resolveBmsonTotalForOutput(json: BeMusicJSON): number | undefined {
  const authored = json.bmson.info.total;
  if (typeof authored === 'number' && Number.isFinite(authored)) {
    return authored;
  }
  const total = json.metadata.total;
  if (json.sourceFormat === 'bmson' && typeof total === 'number' && Number.isFinite(total)) {
    return total;
  }
  return undefined;
}
 
/**
 * Reports the BMS directives bmson has no field for, which the output leaves out: `#STP` stops, `#EXRANKxx` changes,
 * negative or undefined `#BPMxx` (LR2's reverse scroll) and STOPs without a positive `#STOPxx` (all four change
 * judging), and `SPEED` changes (the scroll).
 */
function reportBMSOnlyDirectives(
  json: BeMusicJSON,
  counts: { speedObjects: number; exRankObjects: number; reversingBPMObjects: number; unsetStopObjects: number },
  report: ChartExportDiagnosticHandler | undefined,
): void {
  if (report === undefined) return;
  const { speedObjects, exRankObjects, reversingBPMObjects, unsetStopObjects } = counts;
  const stops = (json.bms.stp ?? []).filter((stp) => typeof stp === 'string' && stp.length > 0).length;
  if (stops > 0)
    report({
      code: 'stp',
      message: `${stops} #STP stop(s) are left out: bmson has no field for them, so every later note comes earlier.`,
    });
  if (exRankObjects > 0)
    report({
      code: 'exrank',
      message: `${exRankObjects} #EXRANK change(s) (channel A0) are left out: bmson has no field for them, so the judgment rank stays at judge_rank.`,
    });
  if (reversingBPMObjects > 0)
    report({
      code: 'bpm',
      message: `${reversingBPMObjects} BPM change(s) to a negative or undefined #BPM (channel 08) are left out: bmson has no reverse scroll, so the chart keeps its previous BPM and never reverses.`,
    });
  if (unsetStopObjects > 0)
    report({
      code: 'stop',
      message: `${unsetStopObjects} STOP(s) without a positive #STOP (channel 09) are left out: bmson has no negative stop, so the notes after each stay where they are instead of coming 1/192 of a measure earlier.`,
    });
  if (speedObjects > 0)
    report({
      code: 'speed',
      message: `${speedObjects} SPEED change(s) (channel SP) are left out: bmson has no field for them, so the scroll speed does not change.`,
    });
}
 
function resolveBmsonCompatiblePlayLevel(value: BeMusicJSON['metadata']['playLevel']): number | undefined {
  if (typeof value === 'number' && Number.isFinite(value)) {
    return value;
  }
  Eif (typeof value !== 'string') {
    return undefined;
  }
  const trimmed = value.trim();
  if (!/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/.test(trimmed)) {
    return undefined;
  }
  const parsed = Number.parseFloat(trimmed);
  return Number.isFinite(parsed) ? parsed : undefined;
}
 
function createBmsonBGAForOutput(
  json: BeMusicJSON,
  resolution: number,
  report?: ChartExportDiagnosticHandler,
):
  | {
      bga_header: Array<{ id: number; name: string }>;
      bga_sequence?: BmsonBGASequence[];
      bga_events: Array<{ y: number; id?: number; id_set?: number[]; condition?: string; interval?: number }>;
      layer_events: Array<{ y: number; id?: number; id_set?: number[]; condition?: string; interval?: number }>;
      poor_events: Array<{ y: number; id?: number; id_set?: number[]; condition?: string; interval?: number }>;
    }
  | undefined {
  const header: Array<{ id: number; name: string }> = [];
  for (const entry of json.bmson.bga.header ?? []) {
    header.push({
      ...collectBmsonExtraFields(entry.extraFields, 'bgaHeader'),
      id: Math.max(0, Math.floor(entry.id)),
      name: entry.name,
    });
  }
  const scale = resolution / resolveBmsonSourceResolution(json);
  const events = normalizeBmsonBGAEventEntries(json.bmson.bga.events ?? [], scale);
  const layerEvents = normalizeBmsonBGAEventEntries(json.bmson.bga.layerEvents ?? [], scale);
  const poorEvents = normalizeBmsonBGAEventEntries(json.bmson.bga.poorEvents ?? [], scale);
  // Ordinary BMS BGA (image resources and 04 / 07 / 06 cues) joins after the native lists, on ids of its own (#839).
  const nativeIds = [...header.map((entry) => entry.id), ...(json.bmson.bga.sequences ?? []).map((entry) => entry.id)];
  const fromBMS = convertBmsBGAToBmson(json, resolution, Math.max(0, ...nativeIds) + 1, report);
  if (fromBMS) {
    header.push(...fromBMS.header);
    const byPulse = (left: { y: number }, right: { y: number }) => left.y - right.y;
    events.push(...fromBMS.events);
    layerEvents.push(...fromBMS.layerEvents);
    poorEvents.push(...fromBMS.poorEvents);
    events.sort(byPulse);
    layerEvents.sort(byPulse);
    poorEvents.sort(byPulse);
  }
 
  if (
    header.length === 0 &&
    events.length === 0 &&
    layerEvents.length === 0 &&
    poorEvents.length === 0 &&
    json.bmson.bga.sequences === undefined &&
    !json.bmson.bga.extraFields
  ) {
    return undefined;
  }
 
  return {
    ...collectBmsonExtraFields(json.bmson.bga.extraFields, 'bga'),
    bga_header: header,
    ...(json.bmson.bga.sequences !== undefined
      ? {
          bga_sequence: json.bmson.bga.sequences.map((entry) => ({
            ...collectBmsonExtraFields(entry.extraFields, 'bgaSequence'),
            id: entry.id,
            sequence: entry.sequence.map((frame) => ({
              ...collectBmsonExtraFields(frame.extraFields, 'bgaFrame'),
              time: frame.time,
              ...(frame.id !== undefined ? { id: frame.id } : {}),
            })),
          })),
        }
      : {}),
    bga_events: events,
    layer_events: layerEvents,
    poor_events: poorEvents,
  };
}
 
function normalizeBmsonSubartistsForOutput(value: string[] | undefined): string[] | undefined {
  if (!Array.isArray(value)) {
    return undefined;
  }
  return value.filter((item) => typeof item === 'string');
}
 
function resolveBmsonLinesForOutput(json: BeMusicJSON, resolution: number): number[] {
  if (json.bmson.barlinesSuppressed === true) return [];
  if (json.preservation.bmson.lines.length > 0) {
    return normalizeBmsonLines(
      rescaleBmsonLines(json.preservation.bmson.lines, resolveBmsonSourceResolution(json), resolution),
    );
  }
  return createDefaultBmsonLines(json, resolution);
}
 
/** Preserved barlines use the normalized source resolution (240 when absent), just like notes and BGA cues. */
function rescaleBmsonLines(lines: number[], sourceResolution: number, resolution: number): number[] {
  if (sourceResolution === resolution) return lines;
  const scale = resolution / sourceResolution;
  return lines.map((y) => Math.round(y * scale));
}
 
function normalizeBmsonLines(lines: number[]): number[] {
  const sorted = normalizeSortedUniqueNonNegativeIntegers(lines);
  if (sorted.length === 0 || sorted[0] !== 0) {
    sorted.unshift(0);
  }
  return sorted;
}
 
function createDefaultBmsonLines(json: BeMusicJSON, resolution: number): number[] {
  const ticksPerMeasure = Math.max(1, Math.floor(resolution * 4));
  let lastEventMeasure = 0;
  for (const event of json.events) {
    if (event.measure > lastEventMeasure) {
      lastEventMeasure = event.measure;
    }
  }
  let lastMeasureLength = 0;
  const lengths = new Map<number, number>();
  for (const measure of json.measures) {
    Eif (measure.index > lastMeasureLength) {
      lastMeasureLength = measure.index;
    }
    lengths.set(measure.index, measure.length);
  }
  const measureCount = Math.max(1, Math.max(lastEventMeasure, lastMeasureLength) + 1);
 
  const lines = [0];
  let cursor = 0;
  for (let measure = 0; measure < measureCount; measure += 1) {
    const length = lengths.get(measure) ?? 1;
    const ticks = Math.max(1, Math.round(length * ticksPerMeasure));
    cursor += ticks;
    lines.push(cursor);
  }
 
  return lines;
}
 
function mapBmsonLineValues(
  lines: ReadonlyArray<number>,
  extras?: Record<string, JSONFields>,
  scale = 1,
): Array<{ y: number }> {
  const mapped: Array<{ y: number }> = [];
  for (const y of lines) {
    mapped.push({ ...collectBmsonExtraFields(extras?.[String(Math.round(y / scale))], 'line'), y });
  }
  return mapped;
}
 
function normalizeBmsonBGAEventEntries(
  entries: ReadonlyArray<BmsonBGAEvent>,
  scale: number,
): Array<{ y: number; id?: number; id_set?: number[]; condition?: string; interval?: number }> {
  const normalized: Array<{ y: number; id?: number; id_set?: number[]; condition?: string; interval?: number }> = [];
  for (const entry of entries) {
    normalized.push({
      ...collectBmsonExtraFields(entry.extraFields, 'bgaEvent'),
      y: Math.max(0, Math.round(entry.y * scale)),
      ...(entry.id !== undefined ? { id: Math.max(0, Math.floor(entry.id)) } : {}),
      ...(entry.idSet !== undefined ? { id_set: [...entry.idSet] } : {}),
      ...(entry.condition !== undefined ? { condition: entry.condition } : {}),
      ...(entry.interval !== undefined ? { interval: entry.interval } : {}),
    });
  }
  return normalized;
}
 
/**
 * The `mode_hint` a bmson rendering of `json` declares: the chart's own hint when it has one, else the hint of the chart's
 * play-mode layout (from the play-mode table in `@be-music/chart-model`) — always for the 24 / 48 KEY keyboard layouts, whose
 * wheel and extended lanes only have a home there, and for the other layouts when every lane in use has a place in the
 * hint's table — else the spec's `generic-<lanes>keys`, a layout ordered left to right. (A made-up `beat-<lanes>k` would be
 * an unknown hint, which beatoraja, Qwilight, Bemuse and the Be-Music parser read as `beat-7k`.)
 */
function resolveBmsonModeHintForOutput(json: BeMusicJSON, playableChannels: readonly string[]): string {
  if (json.bmson.info.modeHint !== undefined) {
    return json.bmson.info.modeHint;
  }
  const variant = resolveChartPlayVariant({ events: json.events, bms: json.bms, bmson: json.bmson });
  for (const layout of getPlayModeLayouts(variant)) {
    const hint = layout.bmsonModeHint;
    if (hint === undefined) continue;
    if (variant === '24' || variant === '48') return hint;
    const lanes = BMSON_MODE_HINT_LAYOUTS[hint].xByChannel;
    if (playableChannels.every((channel) => lanes.has(channel))) {
      return hint;
    }
  }
  return `generic-${Math.max(1, playableChannels.length)}keys`;
}
 
/**
 * Lane channel → bmson `x`. A hint with a lane table in the play-mode table (`@be-music/chart-model`) gives each lane the
 * fixed `x` the parser reads back from it — the keyboard layouts x = side * 26 + lane, the That-Which-Must-Not-Be-Named / Pop'n hints their
 * spec table — so a sparse chart keeps its keys; lanes outside the table follow after its last `x`. Unknown hints
 * number the lanes in use from 1.
 */
function createBmsonXMap(
  playableChannels: readonly string[],
  modeHint: string,
  authoredHint: boolean,
): Map<string, number> {
  const xMap = new Map<string, number>();
  const table = !authoredHint && modeHint.startsWith('generic-') ? undefined : resolveBmsonModeHintLayout(modeHint);
  const unmapped: string[] = [];
  for (const channel of playableChannels) {
    const x = table?.xByChannel.get(channel.toUpperCase());
    if (x !== undefined) {
      xMap.set(channel, x);
    } else {
      unmapped.push(channel);
    }
  }
  const firstUnmappedX = (table?.width ?? 0) + 1;
  unmapped.forEach((channel, index) => xMap.set(channel, firstUnmappedX + index));
  return xMap;
}
 
/** The playable lane a landmine channel sits on (`D3` → `13`, `E5` → `25`), or `undefined` for anything else. */
function landmineChannelToPlayableChannel(channel: string): string | undefined {
  Iif (channel.length !== 2) return undefined;
  const side = channel[0]!.toUpperCase();
  Eif (side === 'D') return `1${channel[1]}`;
  if (side === 'E') return `2${channel[1]}`;
  return undefined;
}
 
/** `3x` / `4x` — BMS invisible objects, written as bmson `key_channels` (beatoraja's hidden notes). */
function isInvisibleChannel(channel: string): boolean {
  return channel.length === 2 && (channel[0] === '3' || channel[0] === '4');
}
 
function invisibleChannelToPlayableChannel(channel: string): string | undefined {
  if (!isInvisibleChannel(channel)) return undefined;
  return `${channel[0] === '3' ? '1' : '2'}${channel[1]}`;
}
 
/** The playable lane (`1x` / `2x`) a mine or invisible object sits on, or `undefined` for any other channel. */
function laneExtensionChannelToPlayableChannel(channel: string): string | undefined {
  if (isLandmineChannel(channel)) return landmineChannelToPlayableChannel(channel);
  return invisibleChannelToPlayableChannel(channel);
}
 
/** BMS mines explode with `#WAV00`; their object value is the damage. */
export const BMS_MINE_SAMPLE_KEY = '00';
export const BMSON_LONG_NOTE_TYPES: ReadonlySet<number> = new Set([1, 2, 3]);
 
interface BMSLongNotesForBmsonOutput {
  /** Start event → beat of its end. */
  startToEndBeat: Map<BeMusicEvent, number>;
  /** End objects and `#LNTYPE 2` continuations, which belong to the note that starts them. */
  endEvents: Set<BeMusicEvent>;
}
 
/**
 * The long notes of a BMS chart as Be-Music plays them — `#LNOBJ` pairs and `5x` / `6x` long notes (`#LNTYPE 1` /
 * `2`, inferred like the web player when `#LNTYPE` is missing) — so bmson can write each as one note with `l`.
 */
function resolveBMSLongNotesForBmsonOutput(json: BeMusicJSON): BMSLongNotesForBmsonOutput {
  const lnobj = resolveLNOBJLongNotes(json);
  const startToEndBeat = new Map(lnobj.startToEndBeat);
  const endEvents = new Set(lnobj.endEvents);
  const legacy = resolveBMSLongNotes(json);
  for (const note of legacy.notes) {
    if (note.endBeat !== undefined) {
      startToEndBeat.set(note.event, note.endBeat);
    }
  }
  for (const event of legacy.suppressedTriggerEvents) {
    endEvents.add(event);
  }
  return { startToEndBeat, endEvents };
}
 
/**
 * Preserve explicit damage and materialize the BMS fallback when converting to bmson.
 */
function resolveMineDamageForBmsonOutput(json: BeMusicJSON, event: BeMusicEvent, idBase: 36 | 62): number | undefined {
  if (json.sourceFormat === 'bmson') return event.bmson?.damage;
  return resolveLandmineDamage(event, idBase, json.sourceFormat);
}
 
/**
 * bmson `info.ln_type`: the authored `bmson.info.lnType`, else the effective BMS mode (`#LNMODE` or HDX LONGMODE) — both use 1 = LN, 2 = CN, 3 = HCN.
 */
function resolveBmsonLNTypeForOutput(json: BeMusicJSON): number | undefined {
  const authored = json.bmson.info.lnType;
  if (typeof authored === 'number' && BMSON_LONG_NOTE_TYPES.has(authored)) {
    return authored;
  }
  const effective = json.sourceFormat === 'bms' ? resolveChartLongNoteMode(json) : undefined;
  const lnMode = effective === 2 || effective === 3 ? effective : json.bms.lnMode;
  return typeof lnMode === 'number' && BMSON_LONG_NOTE_TYPES.has(lnMode) ? lnMode : undefined;
}