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 | 613x 613x 613x 613x 613x 613x 794448x 794448x 794448x 36248x 32607x 32607x 32607x 32607x 32607x 32607x 32607x 32607x 32607x 32607x 809x 32607x 32607x 32607x 32607x 32607x 32607x 3x 2x 25x 62x 9x 1x 8x 8x 3x 5x 5x 5x 1x 4x 2153017x 30898x 30898x 2122119x 259423x 1862696x 1862650x 1862650x 1862650x 1862650x 1862650x 1862647x 49x 13x 13x 12x 37x 37x 1x 36x 2x 2x 2x 1x 1x 34x 30x 30x 30x 30x 30x 27x 6x 21x 3x 4x 259423x 259412x 259412x 259412x 259411x 12x 3x 3x 3x 9x 9x 2x 7x 2x 2x 1x 1x 5x 3x 3x 3x 1x 2x 2x 8594992x 8594962x 8594962x 8594962x 8594962x 8594962x 8594962x 30x 447070x 38x 2x 36x 36x 1x 35x 34x 1x 1x 11x 11x 7x 7x 4x 3x 1x 1x 1x 6x 2x 2x 1x 5x 5x 5x 1357061x 1357061x 1357061x 1357061x 1357061x 3650739x 731724x 2919015x 129116x 104074x | import { cloneJSONFields, type JSONFields } from './bmson-extra-fields.ts';
export {
cloneJSONFields,
collectBmsonExtraFields,
type JSONValue,
type JSONFields,
type BmsonFieldScope,
} from './bmson-extra-fields.ts';
/** Opaque source annotations, excluded from playback and fingerprints. */
export interface BmsonExtraFields {
extraFields?: JSONFields;
}
import { normalizeASCIIBase36Code, normalizeASCIIBase62Code } from '@be-music/shared-utils/core';
import { cloneLRXExtensions, type LRXEventExtensions, type LRXExtensions } from './lrx.ts';
export { LRX_TICKS_PER_BEAT, type LRXBGACue, type LRXEventExtensions, type LRXExtensions } from './lrx.ts';
export const BMS_JSON_FORMAT = 'be-music-json/0.1.0' as const;
export type BeMusicSourceFormat = 'bms' | 'bmson' | 'lrx' | 'json';
export type BeMusicPlayLevel = number | string;
export interface BeMusicMetadata {
title?: string;
subtitle?: string;
artist?: string;
genre?: string;
comment?: string;
/** `#STAGEFILE`: full-size loading screen image. */
stageFile?: string;
/** bmson `info.title_image`: title artwork shown before play, distinct from the loading image. */
titleImage?: string;
/** `#BACKBMP`: select-screen banner / preview image (typically 256×256). */
backBMP?: string;
/** `#BANNER`: small banner image (typically 300×80). */
banner?: string;
playLevel?: BeMusicPlayLevel;
rank?: number;
total?: number;
difficulty?: number;
bpm: number;
extras: Record<string, string>;
}
export interface BMSResources {
wav: Record<string, string>;
/** Intrinsic per-slot linear gain, e.g. a composed NONSTOP stage's VOLWAV. Omitted slots use unity. */
wavGain?: Record<string, number>;
/**
* The format whose playback rules a WAV slot follows where it differs from the chart's `sourceFormat`, e.g. a BMS
* stage's slot in a NONSTOP chart stitched as bmson (BMS slots restart on retrigger). Omitted slots follow
* `sourceFormat`.
*/
wavSourceFormat?: Record<string, BeMusicSourceFormat>;
bmp: Record<string, string>;
/**
* The format whose drawing rules a BMP slot follows where it differs from the chart's `sourceFormat`, e.g. a BMS
* stage's image in a NONSTOP chart stitched as bmson (BMS keys out layer black). Omitted slots follow `sourceFormat`.
*/
bmpSourceFormat?: Record<string, BeMusicSourceFormat>;
bpm: Record<string, number>;
stop: Record<string, number>;
text: Record<string, string>;
}
export interface BeMusicMeasure {
index: number;
length: number;
}
export type BeMusicPosition = readonly [numerator: number, denominator: number];
export interface BmsonEventExtensions extends BmsonExtraFields {
/** Source-audio slice coordinates retained by a stitched NONSTOP chart, independent of FIT placement. */
sampleOffsetSeconds?: number;
sampleDurationSeconds?: number;
/** beatoraja extension: the source slice belongs to the LN ending on this lane and pulse. */
up?: boolean;
l?: number;
c?: boolean;
/**
* Per-note long-note type (beatoraja bmson extension `notes[].t`): `1` = LN, `2` = CN, `3` = HCN. Only meaningful
* on long notes (`l > 0`) and takes precedence over the chart-level `info.ln_type`.
*/
t?: number;
/**
* Per-mine gauge damage in 0..100, sourced from a bmson `mine_channels[].notes[].damage` entry (beatoraja
* extension). Only set on mine events emitted from `mine_channels`; absent on every other event. A bmson mine without
* it deals the default 4: its object value is the parser-assigned WAV slot, so the BMS-side rule (the object value
* read in base 36 is the damage) does not apply to it.
*/
damage?: number;
}
export interface BeMusicEvent {
measure: number;
channel: string;
position: BeMusicPosition;
value: string;
/** Relative BMS source line order for objects on normal note channels. */
bmsLineOrder?: number;
bmson?: BmsonEventExtensions;
/** LRX note values (sound parameters, long-note length, chain notes); only on events of an LRX chart. */
lrx?: LRXEventExtensions;
}
export interface BmsonInfoExtensions extends BmsonExtraFields {
title?: string;
subtitle?: string;
artist?: string;
genre?: string;
/**
* Contributor list per the bmson 1.0.0 spec — entries are authored as `"key:value"` strings (e.g. `"illust:foo"`,
* `"obj:bar"`). Stored verbatim; consumers that want the structured `{ role, name }` form can run each entry through
* {@link parseBmsonSubartist}.
*/
subartists?: string[];
chartName?: string;
level?: number;
initBPM?: number;
resolution?: number;
modeHint?: string;
judgeRank?: number;
/** A stitched mixed-format course can retain the last BMS stage's absolute TOTAL. */
totalUnit?: 'absolute' | 'percent';
total?: number;
/**
* Chart-level long-note type (beatoraja bmson extension `info.ln_type`): `1` = LN, `2` = CN, `3` = HCN. A per-note
* `t` overrides this; unspecified charts follow the player's default LN mode.
*/
lnType?: number;
backImage?: string;
eyecatchImage?: string;
titleImage?: string;
bannerImage?: string;
previewMusic?: string;
}
export interface BmsonBGAHeaderEntry extends BmsonExtraFields {
id: number;
name: string;
}
export interface BmsonBGAEvent extends BmsonExtraFields {
y: number;
/** Absent when the source omits it, as an `id_set`-only layer event may; beatoraja then reads Java's default 0. */
id?: number;
/** beatoraja layer-event alternatives, in authored order; overrides id for layer_events when present. */
idSet?: number[];
condition?: string;
interval?: number;
}
export interface BmsonBGASequenceFrame extends BmsonExtraFields {
/** Elapsed milliseconds from the sequence trigger, independent of pulse resolution. */
time: number;
/** Zero-based bga_header array index, as in beatoraja. Missing id (or -2147483648) ends the sequence. */
id?: number;
}
export interface BmsonBGASequence extends BmsonExtraFields {
id: number;
sequence: BmsonBGASequenceFrame[];
}
export interface BmsonBGAExtensions extends BmsonExtraFields {
sequences?: BmsonBGASequence[];
header: BmsonBGAHeaderEntry[];
events: BmsonBGAEvent[];
layerEvents: BmsonBGAEvent[];
poorEvents: BmsonBGAEvent[];
}
export interface BmsonBPMEventEntry extends BmsonExtraFields {
y: number;
bpm: number;
}
export interface BmsonStopEventEntry extends BmsonExtraFields {
y: number;
duration: number;
}
/**
* beatoraja extension — `scroll_events[]` shape. From pulse `y` on, the lane scrolls at `rate` times its normal speed
* (BMS `#SCROLLxx`), until the next scroll event.
*/
export interface BmsonScrollEventEntry extends BmsonExtraFields {
y: number;
rate: number;
}
export interface BmsonSoundNoteEntry extends BmsonExtraFields {
x?: number;
y: number;
l?: number;
c?: boolean;
/** beatoraja extension: attach this source slice to an LN end instead of creating a tap. */
up?: boolean;
/** beatoraja bmson extension — per-note long-note type (`1` = LN, `2` = CN, `3` = HCN) for notes with `l > 0`. */
t?: number;
}
export interface BmsonSoundChannelEntry extends BmsonExtraFields {
name: string;
notes: BmsonSoundNoteEntry[];
}
/**
* beatoraja extension — `key_channels[].notes[]` shape. `key_channels` hold hidden (invisible) notes: keysounds placed
* on a lane that are never judged, which the parser turns into BMS invisible objects (`3x` / `4x`). beatoraja reads
* only `x` and `y` from them.
*/
export interface BmsonKeyNoteEntry extends BmsonExtraFields {
x?: number;
y: number;
/** @deprecated Not read: hidden notes have no length. Kept so older IR producers still type-check. */
l?: number;
/** @deprecated Not read: hidden notes do not slice their sample. Kept so older IR producers still type-check. */
c?: boolean;
/**
* @deprecated Not read: `key_channels` are hidden notes, not mines. Mine damage lives on
* {@link BmsonMineNoteEntry.damage}.
*/
damage?: number;
}
export interface BmsonKeyChannelEntry extends BmsonExtraFields {
name: string;
notes: BmsonKeyNoteEntry[];
}
/**
* beatoraja extension — `mine_channels[].notes[]` shape. Each note is a mine on lane `x` at pulse `y`, with a gauge
* `damage` (0..100 percent). The channel `name` is the sample played when the mine explodes.
*/
export interface BmsonMineNoteEntry extends BmsonExtraFields {
x?: number;
y: number;
damage?: number;
}
export interface BmsonMineChannelEntry extends BmsonExtraFields {
name: string;
notes: BmsonMineNoteEntry[];
}
export interface BmsonExtensions extends BmsonExtraFields {
/** Opaque channel annotations keyed by the parser-assigned WAV slot. */
channelExtraFields?: Record<string, JSONFields>;
channelKinds?: Record<string, 'sound' | 'key' | 'mine'>;
/** Barline annotations keyed by normalized pulse. */
lineExtraFields?: Record<string, JSONFields>;
version?: string;
info: BmsonInfoExtensions;
bga: BmsonBGAExtensions;
/**
* `true` when the bmson source authored an explicit `lines: []` (intentionally barline-less, the bmson 1.0.0 spec's
* "100 % minimoo-G effect"). Distinct from "lines missing" (`undefined` / not present), which the spec treats as
* "assume 4/4 and generate a barline every 4 quarter notes".
*
* Only ever `true` for bmson charts; BMS / json sources leave the field undefined and the renderer falls back to its
* derive-from-events default.
*/
barlinesSuppressed?: boolean;
}
export type BMSControlFlowCommand =
| 'RANDOM'
| 'SETRANDOM'
| 'IF'
| 'ELSEIF'
| 'ELSE'
| 'ENDIF'
| 'ENDRANDOM'
| 'SWITCH'
| 'SETSWITCH'
| 'CASE'
| 'SKIP'
| 'DEF'
| 'ENDSW';
export interface BMSControlFlowDirectiveEntry {
kind: 'directive';
command: BMSControlFlowCommand;
value?: string;
}
export interface BMSControlFlowHeaderEntry {
kind: 'header';
command: string;
value: string;
/**
* Case-preserved command. Only set when the original source line had a case that differs from the uppercased
* `command` — most commonly because the chart opted into the `#BASE 62` extension and the captured directive carries
* a lowercase ID (e.g. `#WAV0a` inside a `#RANDOM` block). Replay paths use this to reconstruct the lowercase key; if
* absent, callers fall back to `command` (= upper-cased) for case-insensitive base-36 charts.
*/
commandRaw?: string;
/**
* `true` when a top-level line later in the file defines the same header. LR2 and beatoraja apply header lines in
* file order, so that later line wins even when this branch is taken, and resolving the control flow skips this
* entry. Never set on repeatable headers (`#STP`, `#WAVCMD`, `#LNOBJ`), which add up instead.
*/
overriddenByLaterHeader?: true;
}
export interface BMSControlFlowObjectEntry {
kind: 'object';
measure: number;
channel: string;
events: BeMusicEvent[];
measureLength?: number;
}
export type BMSControlFlowEntry = BMSControlFlowDirectiveEntry | BMSControlFlowHeaderEntry | BMSControlFlowObjectEntry;
export interface BMSObjectLineEntry {
measure: number;
channel: string;
events: BeMusicEvent[];
measureLength?: number;
}
export type BMSSourceLineEntry = BMSControlFlowEntry;
export interface BMSExtensions {
controlFlow: BMSControlFlowEntry[];
preview?: string;
lnType?: number;
lnMode?: number;
lnObjs?: string[];
volWAV?: number;
defExRank?: number;
exRank: Record<string, string>;
argb: Record<string, string>;
player?: number;
pathWAV?: string;
baseBPM?: number;
stp: string[];
/** Legacy last unconditional #OPTION declaration (last active declaration after resolving branches). */
option?: string;
/** Whole #OPTION declaration payloads in source order, without splitting vendor arguments. */
options?: string[];
/** The control-flow program includes every #OPTION, including unconditional declarations, in source order. */
optionHeadersInControlFlow?: true;
changeOption: Record<string, string>;
/**
* pomu `#SONGxx`: the obsolete name of `#TEXTxx` for channel `99`. Kept apart so it round-trips as written; the chart
* text timeline reads it only for indices `resources.text` leaves undefined.
*/
songText: Record<string, string>;
wavCmd?: string;
/**
* Every `#WAVCMD pp xx vv` line as the raw post-directive text (one entry per source line, in declaration order). The
* legacy `wavCmd` field above retains the FIRST value only for backward compatibility — `wavCmds` is the
* spec-faithful representation, since real-world charts emit one line per `(parameter, slot)` pair. Consumers should
* iterate `wavCmds` and parse via `@be-music/chart-model`'s `parseBmsWAVCmd` helper.
*/
wavCmds: string[];
exWAV: Record<string, string>;
/**
* Slots whose `#EXWAVxx` a later `#WAVxx` redefines (#1197): nanasigroove keeps one table for both, so the line later
* in the file wins. The `exWAV` declarations stay as authored; `@be-music/chart-model` skips these slots' EXWAV.
*/
exWAVOverridden?: string[];
exBMP: Record<string, string>;
bga: Record<string, string>;
scroll: Record<string, number>;
speed: Record<string, number>;
poorBGA?: string;
swBGA: Record<string, string>;
videoFile?: string;
midiFile?: string;
materials?: string;
divideProp?: string;
charset?: string;
/** Original first one/two filename bytes, in hex and keyed by WAV path; LR2 EXTRA groups sounds by these bytes. */
wavNameBytePrefixes?: Record<string, string>;
/**
* `#BASE` directive — the radix used for object IDs (`#WAVxx`, `#BMPxx`, `#BPMxx`, channel object tokens, …). Default
* is base 36 (case-insensitive `0-9A-Z`). The value `62` opts into the beatoraja-style base-62 extension where
* lowercase `a-z` is a separate ID space (so `#WAV0a` and `#WAV0A` reference different sounds). Only `36` and `62`
* are recognized; the field is omitted for the default base-36 case.
*/
base?: 62;
}
export interface BMSPreservation {
sourceLines: BMSSourceLineEntry[];
objectLines: BMSObjectLineEntry[];
}
export interface BmsonPreservation {
lines: number[];
bpmEvents: BmsonBPMEventEntry[];
stopEvents: BmsonStopEventEntry[];
/** The beatoraja extension `scroll_events`, as authored; left out when the chart has none. */
scrollEvents?: BmsonScrollEventEntry[];
soundChannels: BmsonSoundChannelEntry[];
}
export interface BeMusicPreservation {
bms: BMSPreservation;
bmson: BmsonPreservation;
}
/** A warning about input the chart reader or resolver recovered from. */
export interface ChartDiagnostic {
readonly code:
| 'legacy-bmson'
| 'unknown-mode-hint'
| 'stacked-note-length'
| 'missing-reference'
| 'unsupported-option'
| 'invalid-option'
| 'unsupported-lane-type'
| 'unsupported-channel';
readonly message: string;
readonly subject?: string;
readonly position:
| { readonly kind: 'field'; readonly path: string }
| {
readonly kind: 'object';
readonly measure: number;
readonly position: BeMusicPosition;
readonly channel: string;
};
}
export interface BeMusicJSON {
format: typeof BMS_JSON_FORMAT;
sourceFormat: BeMusicSourceFormat;
/** Warnings from reading the original input, when available. */
diagnostics?: readonly ChartDiagnostic[];
metadata: BeMusicMetadata;
resources: BMSResources;
measures: BeMusicMeasure[];
events: BeMusicEvent[];
bms: BMSExtensions;
bmson: BmsonExtensions;
/** The LRX values with no BMS counterpart; only on a chart read from LRX. */
lrx?: LRXExtensions;
preservation: BeMusicPreservation;
}
export const DEFAULT_BPM = 130;
const BASE36_UPPER_DIGITS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const BASE36_PAD_1_DIVISOR = 36;
const BASE36_PAD_2_DIVISOR = BASE36_PAD_1_DIVISOR * BASE36_PAD_1_DIVISOR;
const BASE36_PAD_2_TABLE = Array.from({ length: BASE36_PAD_2_DIVISOR }, (_value, index) => {
const high = Math.floor(index / BASE36_PAD_1_DIVISOR);
const low = index % BASE36_PAD_1_DIVISOR;
return `${BASE36_UPPER_DIGITS[high]}${BASE36_UPPER_DIGITS[low]}`;
});
export function createEmptyJSON(sourceFormat: BeMusicSourceFormat = 'bms'): BeMusicJSON {
return {
format: BMS_JSON_FORMAT,
sourceFormat,
metadata: {
bpm: DEFAULT_BPM,
extras: {},
},
resources: {
wav: {},
bmp: {},
bpm: {},
stop: {},
text: {},
},
measures: [],
events: [],
bms: {
controlFlow: [],
lnObjs: [],
exRank: {},
argb: {},
stp: [],
wavCmds: [],
changeOption: {},
songText: {},
exWAV: {},
exBMP: {},
bga: {},
scroll: {},
speed: {},
swBGA: {},
},
bmson: {
info: {},
bga: {
header: [],
events: [],
layerEvents: [],
poorEvents: [],
},
},
preservation: {
bms: {
sourceLines: [],
objectLines: [],
},
bmson: {
lines: [],
bpmEvents: [],
stopEvents: [],
soundChannels: [],
},
},
};
}
export function cloneJSON(json: BeMusicJSON): BeMusicJSON {
const measures = json.measures.map((measure) => ({ index: measure.index, length: measure.length }));
const events = json.events.map(cloneEvent);
const controlFlow = json.bms.controlFlow.map(cloneControlFlowEntry);
const bmsSourceLines = json.preservation.bms.sourceLines.map(cloneControlFlowEntry);
const objectLines = json.preservation.bms.objectLines.map(cloneBMSObjectLineEntry);
const lines = [...json.preservation.bmson.lines];
const bpmEvents = json.preservation.bmson.bpmEvents.map((event) => ({
y: event.y,
bpm: event.bpm,
...copyExtras(event),
}));
const stopEvents = json.preservation.bmson.stopEvents.map((event) => ({
y: event.y,
duration: event.duration,
...copyExtras(event),
}));
const scrollEvents = json.preservation.bmson.scrollEvents?.map((event) => ({
y: event.y,
rate: event.rate,
...copyExtras(event),
}));
const soundChannels = json.preservation.bmson.soundChannels.map((channel) => ({
name: channel.name,
...copyExtras(channel),
notes: channel.notes.map((note) => ({ ...note, ...copyExtras(note) })),
}));
const header = json.bmson.bga.header.map((entry) => ({ id: entry.id, name: entry.name, ...copyExtras(entry) }));
const cloneBGAEvent = (event: BmsonBGAEvent): BmsonBGAEvent => ({
...event,
...copyExtras(event),
...(event.idSet !== undefined ? { idSet: [...event.idSet] } : {}),
});
const bgaEvents = json.bmson.bga.events.map(cloneBGAEvent);
const layerEvents = json.bmson.bga.layerEvents.map(cloneBGAEvent);
const poorEvents = json.bmson.bga.poorEvents.map(cloneBGAEvent);
return {
format: json.format,
sourceFormat: json.sourceFormat,
...(json.diagnostics === undefined ? {} : { diagnostics: json.diagnostics }),
metadata: {
...json.metadata,
extras: { ...json.metadata.extras },
},
resources: {
wav: { ...json.resources.wav },
...(json.resources.wavGain !== undefined ? { wavGain: { ...json.resources.wavGain } } : {}),
...(json.resources.wavSourceFormat !== undefined
? { wavSourceFormat: { ...json.resources.wavSourceFormat } }
: {}),
bmp: { ...json.resources.bmp },
...(json.resources.bmpSourceFormat !== undefined
? { bmpSourceFormat: { ...json.resources.bmpSourceFormat } }
: {}),
bpm: { ...json.resources.bpm },
stop: { ...json.resources.stop },
text: { ...json.resources.text },
},
measures,
events,
bms: {
...json.bms,
controlFlow,
lnObjs: json.bms.lnObjs ? [...json.bms.lnObjs] : undefined,
exRank: { ...json.bms.exRank },
argb: { ...json.bms.argb },
stp: [...json.bms.stp],
wavCmds: [...json.bms.wavCmds],
...(json.bms.options !== undefined ? { options: [...json.bms.options] } : {}),
...(json.bms.wavNameBytePrefixes !== undefined
? { wavNameBytePrefixes: { ...json.bms.wavNameBytePrefixes } }
: {}),
changeOption: { ...json.bms.changeOption },
songText: { ...json.bms.songText },
exWAV: { ...json.bms.exWAV },
...(json.bms.exWAVOverridden !== undefined ? { exWAVOverridden: [...json.bms.exWAVOverridden] } : {}),
exBMP: { ...json.bms.exBMP },
bga: { ...json.bms.bga },
scroll: { ...json.bms.scroll },
speed: { ...json.bms.speed },
swBGA: { ...json.bms.swBGA },
},
bmson: {
...json.bmson,
...copyExtras(json.bmson),
...(json.bmson.channelKinds ? { channelKinds: { ...json.bmson.channelKinds } } : {}),
...(json.bmson.channelExtraFields
? {
channelExtraFields: Object.fromEntries(
Object.entries(json.bmson.channelExtraFields).map(([key, fields]) => [key, cloneJSONFields(fields)!]),
),
}
: {}),
...(json.bmson.lineExtraFields
? {
lineExtraFields: Object.fromEntries(
Object.entries(json.bmson.lineExtraFields).map(([key, fields]) => [key, cloneJSONFields(fields)!]),
),
}
: {}),
info: {
...json.bmson.info,
...copyExtras(json.bmson.info),
subartists: json.bmson.info.subartists ? [...json.bmson.info.subartists] : undefined,
},
bga: {
...copyExtras(json.bmson.bga),
...(json.bmson.bga.sequences !== undefined
? {
sequences: json.bmson.bga.sequences.map((entry) => ({
id: entry.id,
...copyExtras(entry),
sequence: entry.sequence.map((frame) => ({ ...frame, ...copyExtras(frame) })),
})),
}
: {}),
header,
events: bgaEvents,
layerEvents,
poorEvents,
},
},
...(json.lrx !== undefined ? { lrx: cloneLRXExtensions(json.lrx) } : {}),
preservation: {
bms: {
sourceLines: bmsSourceLines,
objectLines,
},
bmson: {
lines,
bpmEvents,
stopEvents,
...(scrollEvents ? { scrollEvents } : {}),
soundChannels,
},
},
};
}
/**
* Normalizes a 2-character BMS object ID for storage. With the default `base = 36`, lowercase `a-z` is folded to
* uppercase so `#WAV0a` and `#WAV0A` collapse to the same key. With `base = 62` (the beatoraja `#BASE 62` extension),
* case is preserved — they become distinct IDs.
*
* Always returns a 2-character string. Single-character / empty / malformed inputs are padded or truncated rather than
* raising because the parser already filters at the syntactic level; this is the post-syntactic normalizer.
*/
/**
* Structured form of a `bmson info.subartists[]` entry. The spec authors entries as `"role:name"` strings; consumers
* that want to group / filter contributors by role (illustrator, objet author, lyricist, …) split each entry through
* {@link parseBmsonSubartist} and read the structured pair instead of the raw string.
*/
export interface BmsonSubartistEntry {
/** The lower-cased role tag, or `undefined` if the entry is just a name. */
role?: string;
/** Contributor name with surrounding whitespace trimmed. */
name: string;
}
/**
* Splits a `subartists[]` entry on the first `:` per the bmson 1.0.0 convention. Whitespace around either half is
* trimmed, and the role half is lower-cased so a downstream lookup (e.g. `byRole.get('illust')`) is case-insensitive
* against common variants (`Illust:` / `ILLUST:` / `illust:`).
*
* Entries without a `:` (legacy free-form names) come back with `role` undefined and the whole string as `name`.
*/
export function parseBmsonSubartist(entry: string): BmsonSubartistEntry {
if (typeof entry !== 'string') {
return { name: '' };
}
const colon = entry.indexOf(':');
if (colon < 0) {
return { name: entry.trim() };
}
const role = entry.slice(0, colon).trim().toLowerCase();
const name = entry.slice(colon + 1).trim();
if (role.length === 0) {
return { name };
}
return { role, name };
}
export function normalizeObjectKey(value: string, base: 36 | 62 = 36, allowLongKeys = false): string {
// bmson has no two-character resource limit. BMS callers retain their original token normalization.
if (allowLongKeys && value.length > 2) {
const trimmed = value.trim();
Eif (trimmed.length > 2) return base === 62 ? trimmed : trimmed.toUpperCase();
}
if (base === 62) {
return normalizeObjectKeyBase62(value);
}
if (value.length === 2) {
const raw0 = value.charCodeAt(0);
const raw1 = value.charCodeAt(1);
const code0 = normalizeASCIIBase36Code(raw0);
const code1 = normalizeASCIIBase36Code(raw1);
if (code0 >= 0 && code1 >= 0) {
// Already normalized (the common case, called per event in every hot loop): no new string.
return code0 === raw0 && code1 === raw1 ? value : String.fromCharCode(code0, code1);
}
}
if (value.length === 1) {
const code = normalizeASCIIBase36Code(value.charCodeAt(0));
if (code >= 0) {
return String.fromCharCode(0x30, code);
}
}
const trimmed = value.trim();
if (trimmed.length === 0) {
return '00';
}
if (trimmed.length === 1) {
const sourceCode = trimmed.charCodeAt(0);
const code = normalizeASCIIBase36Code(sourceCode);
if (code >= 0) {
return code === sourceCode ? `0${trimmed}` : `0${String.fromCharCode(code)}`;
}
return `0${trimmed.toUpperCase()}`;
}
if (trimmed.length === 2) {
const sourceCode0 = trimmed.charCodeAt(0);
const sourceCode1 = trimmed.charCodeAt(1);
const code0 = normalizeASCIIBase36Code(sourceCode0);
const code1 = normalizeASCIIBase36Code(sourceCode1);
if (code0 >= 0 && code1 >= 0) {
if (code0 === sourceCode0 && code1 === sourceCode1) {
return trimmed;
}
return String.fromCharCode(code0, code1);
}
return trimmed.toUpperCase();
}
return trimmed.toUpperCase().slice(0, 2);
}
function normalizeObjectKeyBase62(value: string): string {
// Fast path: already 2 ASCII chars in `[0-9A-Za-z]`. Returned verbatim — no case folding in base-62 mode.
if (value.length === 2) {
const code0 = normalizeASCIIBase62Code(value.charCodeAt(0));
const code1 = normalizeASCIIBase62Code(value.charCodeAt(1));
if (code0 >= 0 && code1 >= 0) {
return value;
}
}
if (value.length === 1) {
const code = normalizeASCIIBase62Code(value.charCodeAt(0));
Eif (code >= 0) {
return `0${value}`;
}
}
const trimmed = value.trim();
if (trimmed.length === 0) {
return '00';
}
if (trimmed.length === 1) {
const code = normalizeASCIIBase62Code(trimmed.charCodeAt(0));
if (code >= 0) {
return `0${trimmed}`;
}
// Out of base-62 range — fall back to the base-36 normalizer so callers still get a sensible 2-char key.
return `0${trimmed.slice(0, 1).toUpperCase()}`;
}
if (trimmed.length === 2) {
const code0 = normalizeASCIIBase62Code(trimmed.charCodeAt(0));
const code1 = normalizeASCIIBase62Code(trimmed.charCodeAt(1));
if (code0 >= 0 && code1 >= 0) {
return trimmed;
}
// Mixed valid / invalid — uppercase as a deterministic fallback (matches the base-36 path's behavior).
return trimmed.toUpperCase();
}
return trimmed.slice(0, 2);
}
export function normalizeChannel(value: string): string {
if (value.length === 2) {
const raw0 = value.charCodeAt(0);
const raw1 = value.charCodeAt(1);
const code0 = normalizeASCIIBase36Code(raw0);
const code1 = normalizeASCIIBase36Code(raw1);
Eif (code0 >= 0 && code1 >= 0) {
// Already normalized (the common case, called per event in every hot loop): no new string.
return code0 === raw0 && code1 === raw1 ? value : String.fromCharCode(code0, code1);
}
}
return normalizeObjectKey(value);
}
/**
* Returns the radix the chart's object IDs should be interpreted under. `36` is the default (case-folded `0-9A-Z`);
* `62` is the beatoraja `#BASE 62` extension (case-sensitive `0-9A-Za-z`).
*
* Use this everywhere an `event.value` / `#WAVxx`-style key is about to be looked up against `json.resources.wav`,
* `json.resources.bpm`, etc. — passing the result through `normalizeObjectKey(value, base)` so the lookup honors the
* chart's authored case-sensitivity.
*
* Accepts a partial (`Pick<...>`) chart so callers that only have a `bms` slice (e.g. preservation walks) can use the
* same helper without rebuilding the full JSON.
*/
export function resolveBMSBase(json: { bms?: { base?: 36 | 62 } } | undefined): 36 | 62 {
return json?.bms?.base === 62 ? 62 : 36;
}
export function intToBase36(value: number, pad = 2): string {
if (!Number.isFinite(value) || value < 0) {
return '0'.repeat(pad);
}
const normalized = Math.floor(value);
if (pad === 1) {
return BASE36_UPPER_DIGITS[normalized % BASE36_PAD_1_DIVISOR] ?? '0';
}
if (pad === 2) {
return BASE36_PAD_2_TABLE[normalized % BASE36_PAD_2_DIVISOR] ?? '00';
}
const encoded = normalized.toString(36).toUpperCase();
return encoded.padStart(pad, '0').slice(-pad);
}
export function ensureMeasure(json: BeMusicJSON, index: number): BeMusicMeasure {
const measureCount = json.measures.length;
if (measureCount > 0) {
const lastMeasure = json.measures[measureCount - 1]!;
if (lastMeasure.index === index) {
return lastMeasure;
}
if (lastMeasure.index < index) {
const created: BeMusicMeasure = {
index,
length: 1,
};
json.measures.push(created);
return created;
}
}
for (let measureIndex = 0; measureIndex < json.measures.length; measureIndex += 1) {
const measure = json.measures[measureIndex]!;
if (measure.index === index) {
return measure;
}
}
const created: BeMusicMeasure = {
index,
length: 1,
};
json.measures.push(created);
return created;
}
function cloneEvent(event: BeMusicEvent): BeMusicEvent {
// Optional fields are assigned, not spread, so clones share the hidden classes of parsed events; extra shapes slow
// every event comparison. The key order matches the declaration's.
const cloned: BeMusicEvent = {
measure: event.measure,
channel: event.channel,
position: [event.position[0], event.position[1]],
value: event.value,
};
if (event.bmsLineOrder !== undefined) cloned.bmsLineOrder = event.bmsLineOrder;
cloned.bmson = event.bmson ? { ...event.bmson, ...copyExtras(event.bmson) } : undefined;
if (event.lrx !== undefined) cloned.lrx = { ...event.lrx };
return cloned;
}
function cloneControlFlowEntry(entry: BMSControlFlowEntry): BMSControlFlowEntry {
if (entry.kind === 'object') {
return {
...entry,
events: entry.events.map(cloneEvent),
};
}
return { ...entry };
}
function cloneBMSObjectLineEntry(entry: BMSObjectLineEntry): BMSObjectLineEntry {
return {
...entry,
events: entry.events.map(cloneEvent),
};
}
function copyExtras(node: BmsonExtraFields): BmsonExtraFields {
return node.extraFields ? { extraFields: cloneJSONFields(node.extraFields) } : {};
}
|