All files / player-engine/src/replay format.ts

95.43% Statements 439/460
95.13% Branches 450/473
96.29% Functions 26/27
95% Lines 380/400

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 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256                                                                                                                                                      330x         330x     330x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           451x               9x   9x           9x   9x     9x                 738x 738x 282x 282x   2x     736x 736x 3x   733x 2x   731x 731x 1x     730x 730x 730x   730x 8x 1x 743x 535x 4986x 2x     535x           1x 532x 738x   738x                           730x 730x 1x 729x 1x   728x 728x             728x 726x 726x 726x   726x 726x     4698x   726x 726x 1x       699x 139x 139x 139x 139x 136x   696x                                               730x                             9022x   694x 694x 15x 694x       727x 265x     265x 265x 265x               727x 34x     34x 42x 42x 42x 42x             1x       41x               330x     4698x 4698x 4698x 1x   4697x           4697x 88x 5x 83x   4691x 4691x 4691x 330x     330x   4691x 4691x 4691x 59x               16x     43x   4675x         4675x 169x 3x 166x   4672x       694x 1x   693x 5653x 5653x 5653x 1x   5652x 5861x 1x   5651x             5651x 421x 2x   419x   5647x 214x 2x   212x   5645x 209x 1x   208x   5644x         170x 169x 337x 337x 337x 337x 336x 1x   335x           335x 168x     168x   335x           6x 6x 6x 12x 10x 6x 2x   4x       684x 684x     684x 684x 5x       679x 1x   678x           678x 660x 215x 215x 215x 215x 215x 215x   660x 660x 4x       4x   660x 660x 660x 362x     362x   660x 206x   652x 652x 652x 652x 652x 652x 14x 6x 8x   646x 8x 1x 7x   645x 32x         5x     27x   640x 628x 14x 14x 11x   625x 1x 1x   625x 625x 1x 1x   625x 170x 170x   622x 3x 2x   621x 29x 1x   28x   620x                     620x 26x             1x 25x   619x 14x 14x 11x   616x 11x 11x 9x   614x 12x   12x 12x 23x 23x 23x 23x 2x 20x 20x     611x       2x 609x 2x 607x       3x 604x 10x 1x 9x   603x 6x 601x 16x 1x     15x   600x 10x       597x 11x 11x 7x   593x 7x 7x 5x   591x 5x 1x 4x   590x 4x 1x 3x   589x 24x                         2x     22x   587x 19x 19x 19x     17x         19x 17x   585x 17x 17x 15x   583x 1746x 29x 27x   581x 1161x 579x 575x 18x 17x   574x 1144x 29x 29x 21x   566x 8x       563x 6x 6x 3x   560x 12x 12x   556x 8x 1x 7x   555x 7x 552x 28x 28x 16x   540x 12x       540x 20x     1x       19x   539x 1614x 11x 8x     536x 536x 536x 82x 82x 82x 328x 328x     82x   536x     330x 330x 330x     347x 1x   346x 346x 293x 1x   292x   345x 173x 1x   172x   344x 259x 259x                 335x 335x                               330x     6x 6x 6x 13x 13x 12x   6x 1x 4x 12x 4x                         6x 1x 2x    
import type { ChartOptionProgram, ChartPlayOptionProgram, PlayerChartPlayOptions } from '@be-music/chart-model';
import { parseChartOptionProgram, parseChartPlayOptionProgram } from './chart-options.ts';
import {
  clampCustomJudgeRate,
  DEFAULT_BEATORAJA_CUSTOM_JUDGE,
  type BeatorajaCustomJudge,
} from '../ruleset/custom-judge.ts';
import type { EffectiveBattleMode } from '../core/battle-mode.ts';
import { getPlayModeLayouts, type ChartPlayVariant } from '@be-music/chart-model';
import type { LR2ExtraLevel } from '../core/lr2-extra-lanes.ts';
import type { ScrollTimelinePoint } from '@be-music/chart-model';
import { isSoftLanding, type ScrollModifier } from '../core/scroll-modifier.ts';
import type { LongNoteModifier } from '../core/long-note-modifier.ts';
import type { MineModifier } from '../core/mine-modifier.ts';
import {
  parseReplayOptionState,
  parseReplayOptionChanges,
  type ReplayOptionState,
  type ReplayOptionChange,
} from './options.ts';
import type { LongNoteMode, RandomDraw } from '@be-music/chart-model';
import { isScratchSpin, type ScratchSpin } from '../core/scratch-spin.ts';
import {
  GAUGE_TYPES,
  isGaugePick,
  type GaugePick,
  type GaugeAutoShift,
  type GaugeShiftBottom,
} from '../ruleset/gauge-type.ts';
import type { CourseGaugeSet, CourseJudgeConstraint, RulesetCourseKind } from '../ruleset/course.ts';
import { isRulesetId, RULESET_IDS, type RulesetId } from '../ruleset/definitions.ts';
import {
  parseReplayTempoChanges,
  parseReplayViewChanges,
  parseReplayViewState,
  type ReplayTempoChange,
  type ReplayViewChange,
  type ReplayViewState,
} from './view.ts';
import {
  parseGaugeValues,
  expectFiniteNumber,
  expectNonNegativeInteger,
  expectRecord,
  expectString,
  optionalFiniteNumber,
  optionalString,
  parseRandomDraws,
  parseRecorder,
  parseResults,
  ReplayParseError,
} from './parse.ts';
import {
  parseReplayAnalogScratch,
  parseReplayInputSources,
  type ReplayAnalogScratch,
  type ReplayInputSource,
} from './input-sources.ts';
 
export { ReplayParseError } from './parse.ts';
export type { ReplayAnalogScratch, ReplayInputSource } from './input-sources.ts';
export { parseReplayAnalogScratch, parseReplayInputSources } from './input-sources.ts';
 
/**
 * Be-Music replay ("replay") format.
 *
 * A replay is an INPUT REPLAY, not a result log: the canonical payload is the resolved chart that actually
 * scrolled past the player (post `#RANDOM`, post lane-shuffle / DP-flip), the raw key press / release stream, and
 * the play settings. Judgments, EX-SCORE, combo, and gauge values are deliberately NOT part of the canonical data —
 * they are re-derived by ruleset simulators (`simulate.ts`), so a later fix to a ruleset re-scores every past play
 * without re-recording anything. `results` is a regenerable cache, never the source of truth.
 *
 * Times are integer microseconds relative to chart zero (the same t=0 the engine's note `seconds` axis uses).
 * Events that share a timestamp are ordered by `seq` — sort key is always `(timeUs, seq)`.
 */
export const BE_MUSIC_REPLAY_FORMAT = 'be-music-replay';
/**
 * The replay format's revision. `0` while the format is still being defined: it may change incompatibly without the
 * number moving. The first stable revision will be `1`.
 */
export const BE_MUSIC_REPLAY_VERSION = 0;
 
/** Recommended file suffix for serialized replays (JSON payload). */
export const REPLAY_FILE_SUFFIX = '.bmplay.json';
 
export type ReplayNoteType = 'normal' | 'long' | 'mine' | 'invisible' | 'freezone';
 
export interface ReplayNote {
  /** Stable note id — index into the chart's note array at record time. */
  id: number;
  /** Normalized playable channel AFTER every lane transform (`11`..`19` / `21`..`29`), i.e. the lane the player saw. */
  channel: string;
  /** Original lane when rearranged; omitted when it is the same as channel or in older replays. */
  sourceChannel?: string;
  /** A generated long-note head; source identity and endpoint reconstruct the modifier without rerolling. */
  generatedLongNote?: true;
  type: ReplayNoteType;
  timeUs: number;
  /** Long-note / freezone tail. Present only when `type` is `'long'` or `'freezone'`. */
  endTimeUs?: number;
  /** `#LNMODE`-resolved mode for `type: 'long'` notes (1: LN / 2: CN / 3: HCN). */
  lnMode?: LongNoteMode;
  /** Gauge damage percentage for `type: 'mine'` notes (base-36 value / bmson `damage`, already resolved). */
  damage?: number;
  /** Generated mines carry no explosion sample. Valid only for mine notes. */
  silent?: boolean;
  /**
   * A note plugout judges but leaves out of its note count: an LRX chain note at the start of its lane. Only the
   * `plugout` ruleset reads it.
   */
  uncounted?: true;
}
 
export type ReplayInputAction = 'down' | 'up';
 
export interface ReplayInputEvent {
  /** Monotonic sequence number — tie-breaker for events that share `timeUs`. */
  seq: number;
  timeUs: number;
  action: ReplayInputAction;
  /**
   * Playable channels the physical input resolved to under the play session's lane bindings (auto-scratch lanes
   * already filtered out). One press can cover several channels (e.g. a token bound to multiple lanes); simulators
   * search all of them for a judgable note, mirroring the live engine.
   */
  channels: string[];
  /**
   * The physical input the event came from: an `id` in {@link ReplayPlay.inputSources}. Authoritative: the judge and
   * the simulators key a scratch hold by it (beatoraja's back-spin scratch and scratch LN rules), and lane holds and
   * ANY KEY routes by it.
   */
  source: number;
  /**
   * The physical input the player pressed or let go: a keyboard's `KeyboardEvent.code` (`'KeyZ'`, `'ShiftLeft'`), or
   * `'touch'` for a touch lane. Diagnostic only; absent when the host named none (a terminal, an inferred release).
   */
  code?: string;
  /**
   * The way a scratch press turned the turntable (`'cw'` / `'ccw'`): the direction a controller reported, or the
   * keyboard's odd-even key. Display only (the turntable's animation in a replay); judging reads {@link source}. Only
   * on a `down`; absent when the press reported no spin.
   */
  spin?: ScratchSpin;
  /**
   * An `up` the engine inferred: the input reported no key releases (a terminal without the kitty keyboard protocol),
   * so this is the instant the engine took the key as let go — when its repeats stopped for longer than the hold
   * grace. Diagnostic only: replays and simulators read it as any release.
   */
  inferred?: true;
}
 
/**
 * A press or release of a control button that is not a lane: START / SELECT (`'1P-start'`, `'2P-select'`, as the host
 * names them), on the chart clock of `inputs`. Diagnostic only: what the button did shows in `viewChanges` and the
 * rest, and simulators don't read it.
 */
export interface ReplayControlInputEvent {
  /** Monotonic sequence number, shared with nothing else — the order of control inputs at one `timeUs`. */
  seq: number;
  timeUs: number;
  action: ReplayInputAction;
  /** The logical button. */
  button: string;
  /** The physical input (`ReplayInputEvent.code`). */
  code?: string;
}
 
export interface ReplayJudgeRank {
  /**
   * Initial judgerank on the internal LR2 percent axis (VERY HARD = 25 / HARD = 50 / NORMAL = 75 / EASY = 100),
   * resolved through `resolveJudgeRankPercent` at record time. LR2 judges a BMS chart with a positive
   * {@link sourceExRank} (`#DEFEXRANK`) by that value instead, scaling the `#RANK 2` windows (#1190).
   */
  percent: number;
  /** Raw `#RANK` (`metadata.rank`) when the chart specified one. */
  sourceRank?: number;
  /** Raw `#DEFEXRANK` (BMS) / `info.judge_rank` (bmson) when specified (`100 = NORMAL` unit). */
  sourceExRank?: number;
  /** Dynamic `#EXRANKxx` changes (channel `A0`), in chart order. Values share the `100 = NORMAL` unit. */
  timeline?: Array<{ timeUs: number; exRankValue: number }>;
  /**
   * A stitched LR2 NONSTOP play's later stages taking over the judge rank with their `#RANK`, in time order: from
   * `timeUs` on, the windows a chart opening with `rank` gets (`'chart'`) or LR2's NONSTOP rank table
   * (`'lr2-nonstop'`). Absent in logs recorded before it existed, which played with the first stage's rank throughout.
   */
  stageRanks?: Array<{
    timeUs: number;
    rank: number;
    table: 'chart' | 'lr2-nonstop' | 'bmson' | 'bms-exrank' | 'bms-exrank-change';
  }>;
}
 
export interface ReplayChart {
  /** Recorded effective display operations; never reinterprets unsupported source declarations. */
  chartOptions?: ChartOptionProgram;
  /**
   * The chart-authored gameplay options the play ran with (#844): the forced lane arrangement and ADDMINE (whose
   * result `notes` already holds) and the judge modifiers a re-simulation applies. Absent when the chart forced none.
   */
  chartPlayOptions?: ChartPlayOptionProgram;
  /** Original header BPM, kept separately from the effective tempo map. */
  headerBPM?: number;
  /** Resolved chart BPM extrema, used for source option classification. */
  bpmRange?: { min: number; max: number };
  title?: string;
  subtitle?: string;
  artist?: string;
  genre?: string;
  /** `#PLAYLEVEL` / bmson `info.level` as the chart wrote it (a number for most charts, text for some). */
  playLevel?: string;
  /** `#DIFFICULTY`: 1 BEGINNER, 2 NORMAL, 3 HYPER, 4 ANOTHER, 5 INSANE. */
  difficulty?: number;
  /** Lowercase-hex SHA-256 of the source chart FILE bytes — the primary key for matching a log back to its chart. */
  sha256?: string;
  /** Lowercase-hex MD5 of the source chart FILE bytes — how LR2 and LR2IR name a chart. */
  md5?: string;
  /**
   * Chart fingerprint (`bmfp0:…`, docs/fingerprint-spec.md) of the source chart, every `#RANDOM` / `#SWITCH` branch
   * included — identifies the chart regardless of file bytes, keysounds, BGA, metadata or which branches this play
   * rolled, so plays of one chart share it. Equal to {@link playFingerprint} for a chart without control flow. Omitted
   * when the recorder did not have the source chart (a host resolved `#RANDOM` itself without passing it).
   */
  chartFingerprint?: string;
  /**
   * Play fingerprint (`bmfp0:…`) of the chart after this play's `#RANDOM` / `#SWITCH` outcomes — identifies what
   * the player played. Lane options (MIRROR / RANDOM / FLIP) are part of neither fingerprint; they live in `play`.
   */
  playFingerprint?: string;
  /** The chart's source format. An LRX chart reads its rank and TOTAL as a BMS chart does. */
  sourceFormat: 'bms' | 'bmson' | 'lrx';
  /** Explicit TOTAL units for mixed-format NONSTOP charts; otherwise derived from sourceFormat. */
  totalUnit?: 'absolute' | 'percent';
  /** Engine lane display mode (`'7keys'` / `'14keys'` / ... — `resolveLaneDisplayMode` output). */
  laneMode: string;
  /**
   * Raw `#TOTAL` / bmson `info.total` as the chart wrote it — not the effective TOTAL, which each ruleset resolves on
   * replay (bmson `total` is a percentage of the ruleset's default). Omitted when the chart did not specify one.
   */
  total?: number;
  /** Chart-level long-note mode (1: LN / 2: CN / 3: HCN) after `#LNMODE` / `info.ln_type` resolution. */
  lnMode: LongNoteMode;
  judgeRank: ReplayJudgeRank;
  /** Number of scorable notes (TOTAL / EX-SCORE denominator — mines / invisibles / freezones excluded). */
  noteCount: number;
  /**
   * LR2 negative-BPM reversal in chart µs (#134). Judging and realtime audio froze here during the recorded run,
   * so re-simulations must apply the same cutoff. Absent when the chart has no negative `#BPMxx`.
   */
  reversalTimeUs?: number;
  /** Observed play tick at which the negative BPM fired. Older recordings mirror at reversalTimeUs. */
  reversalActivationUs?: number;
  notes: ReplayNote[];
}
 
export interface ReplayPlay {
  /**
   * The physical inputs the play used (#605), numbered by `id`; every input event names one (`ReplayInputEvent.source`).
   * Coarse device classes and normalised labels, plus a source's `deviceName` (a browser's `Gamepad.id`) only when the
   * player opted in to recording it (`ReplayRecordingOptions.includeDeviceNames`, off by default). Never a serial.
   */
  inputSources: ReplayInputSource[];
  /** How the host turned an analog turntable axis into presses and releases, when one was played. */
  analogScratch?: ReplayAnalogScratch;
  /** Absent retains beatoraja-compatible bmson zero-total recovery. */
  bmsonTotalMode?: import('../ruleset/bmson-total.ts').BmsonTotalMode;
  /** Selected source options at the start; typed effective play/chart fields remain authoritative for judging. */
  options?: ReplayOptionState;
  /** Every later selected-option change, on the same chart clock as inputs and view changes. */
  optionChanges?: ReplayOptionChange[];
  mode: 'manual' | 'auto';
  autoScratch: boolean;
  /** Effective manual assist per side; older replays fall back to autoScratch for both. */
  judgeAlgorithm?: 'combo' | 'duration' | 'lowest';
  /** LR2's mania option GAMBOL, LEVEL 1 or 2: the play's fixed judge windows under LR2 rules. Absent while it was off. */
  lr2Gambol?: 1 | 2;
  /** beatoraja CUSTOM JUDGE rates in percent; absent while the option was off. */
  customJudge?: BeatorajaCustomJudge;
  longNoteModifier?: LongNoteModifier;
  longNoteRate?: number;
  sevenToNinePattern?: import('../core/seven-to-nine.ts').SevenToNinePattern;
  sevenToNineType?: import('../core/seven-to-nine.ts').SevenToNineType;
  sevenToNineThresholdBPM?: number;
  sevenToNineApplied?: boolean;
  battleMode?: EffectiveBattleMode;
  battleSourceVariant?: ChartPlayVariant;
  battleTempo?: number;
  battleAssist1P?: boolean;
  battleAssist2P?: boolean;
  battleChangedObjectCount?: number;
  battleDroppedObjectCount?: number;
  /** LR2 D-BATTLE: scratch objects stayed playable (LR2's hidden `randSC` command, buttons 12 + 13 at decide). */
  dBattleScratch?: boolean;
  lr2ExtraMode?: boolean;
  lr2ExtraLevel?: LR2ExtraLevel;
  /** LR2's mania chart generators as the play applied them; absent when none was on. */
  lr2Mania?: ReplayLR2Mania;
  lr2ExtraEffectiveLevel?: LR2ExtraLevel;
  lr2ExtraConvertedObjectCount?: number;
  lr2ExtraTempo?: number;
  extraNoteDepth?: number;
  extraNoteScratch?: boolean;
  /** Actual source conversions, including overwritten additions; independent of record policy. */
  extraNoteChangeCount?: number;
  longNoteModifierChangeCount?: number;
  mineModifier?: MineModifier;
  scrollModifier?: ScrollModifier;
  scrollSection?: number;
  scrollRate?: number;
  scrollModifierTimeline?: ScrollTimelinePoint[];
  /** Effective chart change, not an assist-policy decision (source ADD does not set an assist flag). */
  scrollModifierChanged?: boolean;
  mineModifierChangeCount?: number;
  autoScratch1P?: boolean;
  autoScratch2P?: boolean;
  /**
   * ANY KEY (That-Which-Must-Not-Be-Named PC, #751): each press took the nearest unjudged note in reach on any lane.
   * `inputs` keep the keys' own lanes, and replays and simulators route them again. Absent = off.
   */
  anyKey?: boolean;
  /**
   * Gauge the player selected for the session (declared by the host; LR2-family gauge id). A bare value is the played
   * ruleset's own gauge, read under a re-judging ruleset as that ruleset's own. A qualified one (`lr2:HARD`) keeps its
   * source's gauge, auto-shift ladder and course gauges under every ruleset (ADR 0019, #1171).
   */
  gauge: GaugePick;
  /** The 2P player's gauge of a two-player play (`battleMode: 'TWO-PLAYER'`); `results.secondPlayer` is its result. */
  gauge2P?: GaugePick;
  /**
   * Lane-arrangement option per side, when the host applied one (`'OFF'` / `'MIRROR'` / `'RANDOM'` / `'lr2:S-RANDOM'` /
   * ...). A bare colliding name (`'S-RANDOM'`, `'CONVERGE'`) is the played ruleset's own (ADR 0019). Older replays may hold
   * `'lr2:RANDOM'` and the like, which read as `'RANDOM'` (`canonicalOptionValue`).
   */
  randomLane?: { p1?: string; p2?: string };
  /**
   * The nanasigroove CRAZY gameplay options the player chose that the play ran with (#1243): those of
   * `chart.chartPlayOptions` the chart's own `#OPTION` does not set (`playerChartPlayOptionsOf`). Absent when the player
   * added none. A player's NOTES COPY / DBLCOPY keeps no record (`classifyReplayAssists`).
   */
  playerChartPlayOptions?: PlayerChartPlayOptions;
  dpFlip?: boolean;
  /** Debug BAD-window override (`PlayerOptions.judgeWindowMs`) — simulations of such plays are non-standard. */
  judgeWindowOverrideMs?: number;
  /** Judgment-window ruleset the live engine ran (`PlayerOptions.judgeRuleset`). Absent = `'lr2'` (the default). */
  judgeRuleset?: RulesetId;
  /**
   * The play's `#RANDOM` / `#SETRANDOM` / `#SWITCH` / `#SETSWITCH` outcomes (`RandomDraws` from `@be-music/chart-model`): one
   * entry per such line of the chart, in file order. With the chart file, `resolveBMSControlFlowWithDraws(json,
   * randomDraws)` rebuilds the chart that was played (so a verifier can recompute `chart.playFingerprint`), and a
   * replay passes them back as `PlayerOptions.randomDraws`. Absent for charts without control flow.
   */
  randomDraws?: RandomDraw[];
  /** True when the play ended early (ESC). The input stream stops at the abort point. */
  aborted?: boolean;
  /**
   * Chart time (µs) the judge had settled through when the play was aborted: everything due before it was judged,
   * nothing from it on. Re-simulations stop there instead of missing the rest of the chart. Absent on older logs.
   */
  abortedAtUs?: number;
  /** ESC ended a frozen LR2 stage and applied its outstanding-note gauge rule. */
  exitedReversal?: boolean;
  /** The reversing event itself completed the stage at chart.reversalActivationUs. */
  completedAtReversal?: boolean;
  /**
   * True when the play ended the moment its survival gauge emptied (`PlayerOptions.endOnFailure`): nothing after the
   * judgment that emptied it counts. Absent on older logs, which kept judging to the end.
   */
  endOnFailure?: boolean;
  gaugeAutoShift?: GaugeAutoShift;
  bottomShiftableGauge?: GaugeShiftBottom;
  /** Set when the play was one stage of a course: what the stage's rules and starting state were. */
  course?: ReplayCourseStage;
  /**
   * The play tempo (`PlayerOptions.speed`): the chart, its audio and the play clock ran `tempo` times as fast (0.5 to
   * 1.5 in the web player). Judgments and input times stay in chart time, so a re-simulation is unaffected; a replay
   * plays back at the same tempo. Absent = 1, and on a log re-recorded from a replay (`replayInputs`), whose speed only
   * sets how fast it is re-driven. A play at another tempo is a practice play and is not ranked. This is the tempo at
   * the start; {@link tempoChanges} lists the changes during the play.
   */
  tempo?: number;
  /** Tempo changes during the play, in chart-time order (the web player lets the tempo change mid-play). */
  tempoChanges?: ReplayTempoChange[];
  /** What the player saw at the start: hi-speed, hi-speed fix, lane covers and lift. Judgments do not depend on it. */
  view?: ReplayViewState;
  /** Changes to {@link view} during the play, in chart-time order. */
  viewChanges?: ReplayViewChange[];
  /** The control buttons (START / SELECT) pressed and let go during the play, in chart-time order. */
  controlInputs?: ReplayControlInputEvent[];
  /** Lossless bag for host-specific settings that don't affect simulation (hi-speed, skin, ...). */
  native?: Record<string, string | number | boolean | null>;
}
 
/** The course context a stage was played in. A stage log replays on its own with it. */
export interface ReplayCourseStage {
  kind: RulesetCourseKind;
  /** The course's `gauge_*` constraint (beatoraja's class-gauge set), when it named one. */
  gaugeSet?: CourseGaugeSet;
  /** The course's `no_good` / `no_great` constraint. */
  judge?: CourseJudgeConstraint;
  /** The state the previous stage left. Absent for the first stage, which starts on a full gauge and no combo. */
  carryIn?: ReplayCourseCarry;
  /**
   * A stage cut out of a NONSTOP play: the FIT time-stretch it was played at (its notes keep the stretched times; 1
   * without FIT). Display only; the log replays as recorded.
   */
  rate?: number;
}
 
/** The state carried from one course stage into the next. */
export interface ReplayCourseCarry {
  /** Every course gauge of the ruleset's ladder (raw values), carried independently under gauge auto-shift. */
  gauges?: Record<string, number>;
  /** Gauge value in percent. */
  gauge: number;
  /** The course-wide combo running into the stage. */
  combo: number;
  /** The course-wide max combo so far. */
  maxCombo: number;
}
 
export interface ReplayJudgmentCounts {
  pgreat: number;
  great: number;
  good: number;
  bad: number;
  poor: number;
  /** LR2-style empty POOR count — never part of the judgment counters above. */
  emptyPoor: number;
}
 
export interface ReplayGaugeResult {
  /** Raw values for every parallel gauge; course stages carry these into the next stage. */
  values?: Record<string, number>;
  /** Gauge id in its source's line-up (`'GROOVE'`, `'HARD'`, `'NORMAL'`, `'EX-HARD'`, ...). */
  type: string;
  /**
   * The source whose gauge {@link type} names, when the play ran another source's gauge than the judging ruleset's own
   * (`play.gauge: 'lr2:HARD'` under beatoraja judging, #1171). Absent: the judging ruleset's own.
   */
  source?: RulesetId;
  /** Final gauge value in percent. */
  final: number;
  cleared: boolean;
  /** True when a survival gauge bottomed out mid-play (the simulator keeps judging to the end regardless). */
  failedMidPlay?: boolean;
}
 
export interface ReplayRulesetResult {
  /** Ruleset identifier + revision (e.g. `'lr2/0'`, `'beatoraja/0'`, `'____/0'`, `'be-music/native'`). */
  ruleset: string;
  judge: ReplayJudgmentCounts;
  fast: number;
  slow: number;
  exScore: number;
  /**
   * The ruleset's judgment-note count (EX-SCORE denominator ÷ 2). Differs per ruleset: charge-note styles
   * (beatoraja CN/HCN, That-Which-Must-Not-Be-Named CN) count a long note's head and tail as two judgments, LN styles as one.
   */
  noteCount: number;
  /** Final combo eligibility when empty POOR can break combo; absent in legacy/count-only results. */
  fullCombo?: boolean;
  maxCombo: number;
  /** LR2 mine hits included in judge.poor, excluded from the judged-note count. */
  minePoor?: number;
  /** 200000-max money score where the ruleset defines one. */
  score?: number;
  /** That-Which-Must-Not-Be-Named DJ LEVEL label (`'AAA'`..`'F'`) where the ruleset defines one. */
  djLevel?: string;
  gauge: ReplayGaugeResult;
  /** For a course stage: the course-wide combo and max combo the stage left, which the next stage carries in. */
  course?: { combo: number; maxCombo: number };
}
 
/**
 * Software that recorded the play — self-reported, so it identifies builds for compatibility and bug triage, never
 * for trust. Every field is optional: a log from a host that declared nothing still carries the engine version.
 */
export interface ReplayRecorderInfo {
  /** Recording application id (`'be-music-web'`, `'be-music-tui'`, ...). */
  name?: string;
  /** Recording application version. */
  version?: string;
  /** Build identifier of the application, e.g. the source commit. */
  build?: string;
  /** `@be-music/player-engine` version whose engine ran the play — filled by the recorder, not the host. */
  engine?: string;
  /** Coarse platform label (`'web'`, `'node'`, ...). Never a full user-agent string. */
  platform?: string;
}
 
export interface BeMusicReplay {
  format: typeof BE_MUSIC_REPLAY_FORMAT;
  version: typeof BE_MUSIC_REPLAY_VERSION;
  /** ISO 8601 timestamp of the recording, when the recorder had a clock available. */
  createdAt?: string;
  /** Software that recorded the play. Absent in logs written before the field existed. */
  recorder?: ReplayRecorderInfo;
  clock: { unit: 'us'; origin: 'chart-zero' };
  chart: ReplayChart;
  inputs: ReplayInputEvent[];
  play: ReplayPlay;
  /** Regenerable result cache keyed by ruleset id. Never authoritative — delete freely. */
  results?: Record<string, ReplayRulesetResult>;
}
 
export function serializeReplay(replay: BeMusicReplay): string {
  return JSON.stringify(replay);
}
 
/**
 * Suggested download / save filename for a replay: `<title>-<timestamp>.bmplay.json` with
 * filesystem-hostile characters stripped. `when` defaults to the replay's own `createdAt`.
 */
export function resolveReplayFilename(replay: BeMusicReplay, when?: Date): string {
  const stemSource = replay.chart.title ?? 'play';
  const stem =
    stemSource
      .normalize('NFKC')
      .replace(/[\\/:*?"<>|]+/g, ' ')
      .replace(/\s+/g, ' ')
      .trim()
      .slice(0, 60) || 'play';
  const timestampSource = when ?? (replay.createdAt !== undefined ? new Date(replay.createdAt) : undefined);
  const timestamp =
    timestampSource !== undefined && Number.isFinite(timestampSource.getTime())
      ? timestampSource.toISOString().replace(/[:.]/g, '-')
      : 'unknown-time';
  return `${stem}-${timestamp}${REPLAY_FILE_SUFFIX}`;
}
 
/**
 * Parses (and defensively validates) a serialized replay. Accepts either the JSON text or an already-parsed
 * value. Throws {@link ReplayParseError} with a field-path message on structural problems; unknown extra fields
 * are preserved-by-ignoring so future minor additions stay readable.
 */
export function parseReplay(source: unknown): BeMusicReplay {
  let value: unknown = source;
  if (typeof source === 'string') {
    try {
      value = JSON.parse(source);
    } catch (error) {
      throw new ReplayParseError(`invalid JSON: ${(error as Error).message}`);
    }
  }
  const root = expectRecord(value, 'replay');
  if (root.format !== BE_MUSIC_REPLAY_FORMAT) {
    throw new ReplayParseError(`format: expected '${BE_MUSIC_REPLAY_FORMAT}', got ${JSON.stringify(root.format)}`);
  }
  if (root.version !== BE_MUSIC_REPLAY_VERSION) {
    throw new ReplayParseError(`version: unsupported version ${JSON.stringify(root.version)}`);
  }
  const clock = expectRecord(root.clock, 'clock');
  if (clock.unit !== 'us' || clock.origin !== 'chart-zero') {
    throw new ReplayParseError(`clock: expected { unit: 'us', origin: 'chart-zero' }`);
  }
 
  const chart = parseChart(expectRecord(root.chart, 'chart'));
  const inputs = parseInputs(root.inputs);
  const play = parsePlay(expectRecord(root.play, 'play'));
  // The player's selections are part of the program the play ran with.
  for (const [key, value] of Object.entries(play.playerChartPlayOptions ?? {}))
    if (chart.chartPlayOptions?.options[key as keyof PlayerChartPlayOptions] !== value)
      throw new ReplayParseError(`play.playerChartPlayOptions.${key}: not in chart.chartPlayOptions`);
  const sourceIds = new Set(play.inputSources.map((source) => source.id));
  inputs.forEach((input, index) => {
    if (!sourceIds.has(input.source)) {
      throw new ReplayParseError(`inputs[${index}].source: no input source ${input.source} in play.inputSources`);
    }
  });
  if (
    play.bmsonTotalMode === 'spec' &&
    chart.total !== undefined &&
    chart.total < 0 &&
    (chart.totalUnit ?? (chart.sourceFormat === 'bmson' ? 'percent' : 'absolute')) === 'percent'
  )
    throw new ReplayParseError('chart.total: bmson spec mode requires a normalized non-negative percentage.');
  const results = root.results === undefined ? undefined : parseResults(expectRecord(root.results, 'results'));
  const recorder = root.recorder === undefined ? undefined : parseRecorder(expectRecord(root.recorder, 'recorder'));
 
  return {
    format: BE_MUSIC_REPLAY_FORMAT,
    version: BE_MUSIC_REPLAY_VERSION,
    createdAt: optionalString(root.createdAt, 'createdAt'),
    ...(recorder !== undefined ? { recorder } : {}),
    clock: { unit: 'us', origin: 'chart-zero' },
    chart,
    inputs,
    play,
    ...(results !== undefined ? { results } : {}),
  };
}
 
function parseChart(chart: Record<string, unknown>): ReplayChart {
  const sourceFormat = chart.sourceFormat;
  if (chart.totalUnit !== undefined && chart.totalUnit !== 'absolute' && chart.totalUnit !== 'percent')
    throw new ReplayParseError('chart.totalUnit: expected absolute or percent');
  if (sourceFormat !== 'bms' && sourceFormat !== 'bmson' && sourceFormat !== 'lrx') {
    throw new ReplayParseError(`chart.sourceFormat: expected 'bms' | 'bmson' | 'lrx'`);
  }
  const judgeRankRaw = expectRecord(chart.judgeRank, 'chart.judgeRank');
  const judgeRank: ReplayJudgeRank = {
    percent: expectFiniteNumber(judgeRankRaw.percent, 'chart.judgeRank.percent'),
    sourceRank: optionalFiniteNumber(judgeRankRaw.sourceRank, 'chart.judgeRank.sourceRank'),
    sourceExRank: optionalFiniteNumber(judgeRankRaw.sourceExRank, 'chart.judgeRank.sourceExRank'),
    timeline: parseJudgeRankTimeline(judgeRankRaw.timeline),
    stageRanks: parseStageRanks(judgeRankRaw.stageRanks),
  };
  if (judgeRank.sourceRank === undefined) delete judgeRank.sourceRank;
  if (judgeRank.sourceExRank === undefined) delete judgeRank.sourceExRank;
  if (judgeRank.timeline === undefined) delete judgeRank.timeline;
  if (judgeRank.stageRanks === undefined) delete judgeRank.stageRanks;
 
  const notesRaw = chart.notes;
  Iif (!Array.isArray(notesRaw)) {
    throw new ReplayParseError('chart.notes: expected an array');
  }
  const notes = notesRaw.map((note, index) => parseNote(note, index));
 
  const lnMode = chart.lnMode;
  if (lnMode !== 1 && lnMode !== 2 && lnMode !== 3) {
    throw new ReplayParseError('chart.lnMode: expected 1 | 2 | 3');
  }
 
  let bpmRange: ReplayChart['bpmRange'];
  if (chart.bpmRange !== undefined) {
    const range = expectRecord(chart.bpmRange, 'chart.bpmRange');
    const min = expectFiniteNumber(range.min, 'chart.bpmRange.min');
    const max = expectFiniteNumber(range.max, 'chart.bpmRange.max');
    if (min > max) throw new ReplayParseError('chart.bpmRange: min must not exceed max');
    bpmRange = { min, max };
  }
  const parsed: ReplayChart = {
    ...(bpmRange !== undefined ? { bpmRange } : {}),
    ...(chart.headerBPM !== undefined ? { headerBPM: expectFiniteNumber(chart.headerBPM, 'chart.headerBPM') } : {}),
    title: optionalString(chart.title, 'chart.title'),
    subtitle: optionalString(chart.subtitle, 'chart.subtitle'),
    artist: optionalString(chart.artist, 'chart.artist'),
    genre: optionalString(chart.genre, 'chart.genre'),
    playLevel: optionalString(chart.playLevel, 'chart.playLevel'),
    difficulty: optionalFiniteNumber(chart.difficulty, 'chart.difficulty'),
    sha256: optionalString(chart.sha256, 'chart.sha256'),
    md5: optionalString(chart.md5, 'chart.md5'),
    chartFingerprint: optionalString(chart.chartFingerprint, 'chart.chartFingerprint'),
    playFingerprint: optionalString(chart.playFingerprint, 'chart.playFingerprint'),
    sourceFormat,
    laneMode: expectString(chart.laneMode, 'chart.laneMode'),
    total: optionalFiniteNumber(chart.total, 'chart.total'),
    ...(chart.totalUnit !== undefined ? { totalUnit: chart.totalUnit as 'absolute' | 'percent' } : {}),
    lnMode,
    judgeRank,
    noteCount: expectFiniteNumber(chart.noteCount, 'chart.noteCount'),
    reversalActivationUs: optionalFiniteNumber(chart.reversalActivationUs, 'chart.reversalActivationUs'),
    reversalTimeUs: optionalFiniteNumber(chart.reversalTimeUs, 'chart.reversalTimeUs'),
    notes,
  };
  for (const key of [
    'title',
    'subtitle',
    'artist',
    'genre',
    'playLevel',
    'difficulty',
    'sha256',
    'md5',
    'chartFingerprint',
    'playFingerprint',
    'total',
    'reversalActivationUs',
    'reversalTimeUs',
  ] as const) {
    if (parsed[key] === undefined) delete parsed[key];
  }
  if (chart.chartOptions !== undefined) parsed.chartOptions = parseChartOptionProgram(chart.chartOptions);
  if (chart.chartPlayOptions !== undefined)
    parsed.chartPlayOptions = parseChartPlayOptionProgram(chart.chartPlayOptions);
  return parsed;
}
 
function parseJudgeRankTimeline(value: unknown): ReplayJudgeRank['timeline'] {
  if (value === undefined) return undefined;
  Iif (!Array.isArray(value)) {
    throw new ReplayParseError('chart.judgeRank.timeline: expected an array');
  }
  return value.map((entry, index) => {
    const record = expectRecord(entry, `chart.judgeRank.timeline[${index}]`);
    return {
      timeUs: expectFiniteNumber(record.timeUs, `chart.judgeRank.timeline[${index}].timeUs`),
      exRankValue: expectFiniteNumber(record.exRankValue, `chart.judgeRank.timeline[${index}].exRankValue`),
    };
  });
}
 
function parseStageRanks(value: unknown): ReplayJudgeRank['stageRanks'] {
  if (value === undefined) return undefined;
  Iif (!Array.isArray(value)) {
    throw new ReplayParseError('chart.judgeRank.stageRanks: expected an array');
  }
  return value.map((entry, index) => {
    const path = `chart.judgeRank.stageRanks[${index}]`;
    const record = expectRecord(entry, path);
    const table = record.table;
    if (
      table !== 'chart' &&
      table !== 'lr2-nonstop' &&
      table !== 'bmson' &&
      table !== 'bms-exrank' &&
      table !== 'bms-exrank-change'
    ) {
      throw new ReplayParseError(
        `${path}.table: expected 'chart', 'lr2-nonstop', 'bmson', 'bms-exrank' or 'bms-exrank-change'`,
      );
    }
    return {
      timeUs: expectFiniteNumber(record.timeUs, `${path}.timeUs`),
      rank: expectFiniteNumber(record.rank, `${path}.rank`),
      table,
    };
  });
}
 
const REPLAY_NOTE_TYPES: ReadonlySet<string> = new Set(['normal', 'long', 'mine', 'invisible', 'freezone']);
 
function parseNote(value: unknown, index: number): ReplayNote {
  const record = expectRecord(value, `chart.notes[${index}]`);
  const type = record.type;
  if (typeof type !== 'string' || !REPLAY_NOTE_TYPES.has(type)) {
    throw new ReplayParseError(`chart.notes[${index}].type: expected one of ${[...REPLAY_NOTE_TYPES].join(' | ')}`);
  }
  const note: ReplayNote = {
    id: expectFiniteNumber(record.id, `chart.notes[${index}].id`),
    channel: expectString(record.channel, `chart.notes[${index}].channel`),
    type: type as ReplayNoteType,
    timeUs: expectFiniteNumber(record.timeUs, `chart.notes[${index}].timeUs`),
  };
  if (record.sourceChannel !== undefined) {
    if (typeof record.sourceChannel !== 'string' || !/^[12][0-9A-Z]$/.test(record.sourceChannel))
      throw new ReplayParseError(`chart.notes[${index}].sourceChannel: expected a normalized playable lane`);
    note.sourceChannel = record.sourceChannel;
  }
  const endTimeUs = optionalFiniteNumber(record.endTimeUs, `chart.notes[${index}].endTimeUs`);
  if (endTimeUs !== undefined) note.endTimeUs = endTimeUs;
  if (record.lnMode !== undefined) {
    Iif (record.lnMode !== 1 && record.lnMode !== 2 && record.lnMode !== 3) {
      throw new ReplayParseError(`chart.notes[${index}].lnMode: expected 1 | 2 | 3`);
    }
    note.lnMode = record.lnMode;
  }
  const damage = optionalFiniteNumber(record.damage, `chart.notes[${index}].damage`);
  if (damage !== undefined) note.damage = damage;
  if (record.generatedLongNote !== undefined) {
    if (
      record.generatedLongNote !== true ||
      type !== 'long' ||
      note.lnMode === undefined ||
      !Number.isSafeInteger(note.timeUs) ||
      !Number.isSafeInteger(note.endTimeUs) ||
      !(note.endTimeUs! > note.timeUs)
    )
      throw new ReplayParseError(
        `chart.notes[${index}].generatedLongNote: expected a timed long note with a resolved mode`,
      );
    note.generatedLongNote = true;
  }
  Iif (record.uncounted !== undefined) {
    if (record.uncounted !== true || (type !== 'normal' && type !== 'long'))
      throw new ReplayParseError(`chart.notes[${index}].uncounted: expected true on a judged note`);
    note.uncounted = true;
  }
  if (record.silent !== undefined) {
    if (type !== 'mine' || typeof record.silent !== 'boolean')
      throw new ReplayParseError(`chart.notes[${index}].silent: expected a mine boolean`);
    note.silent = record.silent;
  }
  return note;
}
 
function parseInputs(value: unknown): ReplayInputEvent[] {
  if (!Array.isArray(value)) {
    throw new ReplayParseError('inputs: expected an array');
  }
  return value.map((entry, index) => {
    const record = expectRecord(entry, `inputs[${index}]`);
    const action = record.action;
    if (action !== 'down' && action !== 'up') {
      throw new ReplayParseError(`inputs[${index}].action: expected 'down' | 'up'`);
    }
    const channelsRaw = record.channels;
    if (!Array.isArray(channelsRaw) || channelsRaw.some((channel) => typeof channel !== 'string')) {
      throw new ReplayParseError(`inputs[${index}].channels: expected string[]`);
    }
    const event: ReplayInputEvent = {
      seq: expectFiniteNumber(record.seq, `inputs[${index}].seq`),
      timeUs: expectFiniteNumber(record.timeUs, `inputs[${index}].timeUs`),
      action,
      channels: channelsRaw as string[],
      source: expectNonNegativeInteger(record.source, `inputs[${index}].source`),
    };
    if (record.code !== undefined) {
      if (typeof record.code !== 'string' || record.code.length === 0) {
        throw new ReplayParseError(`inputs[${index}].code: expected a non-empty string`);
      }
      event.code = record.code;
    }
    if (record.spin !== undefined) {
      if (!isScratchSpin(record.spin) || action !== 'down') {
        throw new ReplayParseError(`inputs[${index}].spin: expected 'cw' | 'ccw' on a 'down'`);
      }
      event.spin = record.spin;
    }
    if (record.inferred !== undefined) {
      if (record.inferred !== true || action !== 'up') {
        throw new ReplayParseError(`inputs[${index}].inferred: expected true on an 'up'`);
      }
      event.inferred = true;
    }
    return event;
  });
}
 
function parseControlInputs(value: unknown): ReplayControlInputEvent[] {
  if (!Array.isArray(value)) throw new ReplayParseError('play.controlInputs: expected an array');
  return value.map((entry, index) => {
    const path = `play.controlInputs[${index}]`;
    const record = expectRecord(entry, path);
    const action = record.action;
    if (action !== 'down' && action !== 'up') throw new ReplayParseError(`${path}.action: expected 'down' | 'up'`);
    if (typeof record.button !== 'string' || record.button.length === 0) {
      throw new ReplayParseError(`${path}.button: expected a non-empty string`);
    }
    const event: ReplayControlInputEvent = {
      seq: expectFiniteNumber(record.seq, `${path}.seq`),
      timeUs: expectFiniteNumber(record.timeUs, `${path}.timeUs`),
      action,
      button: record.button,
    };
    if (record.code !== undefined) {
      Iif (typeof record.code !== 'string' || record.code.length === 0) {
        throw new ReplayParseError(`${path}.code: expected a non-empty string`);
      }
      event.code = record.code;
    }
    return event;
  });
}
 
/** The player's nanasigroove selections: GOOD2BAD / GREAT2BAD, HELLJUDGE and a NOTES conversion, as a player chooses them. */
function parsePlayerChartPlayOptions(raw: unknown): PlayerChartPlayOptions {
  const options = expectRecord(raw, 'play.playerChartPlayOptions');
  const parsed: PlayerChartPlayOptions = {};
  for (const [key, value] of Object.entries(options)) {
    if (key === 'judge' && (value === 'GOOD2BAD' || value === 'GREAT2BAD')) parsed.judge = value;
    else if (key === 'hellJudge' && value === true) parsed.hellJudge = true;
    else if (key === 'notes' && (value === 'DOUBLE' || value === 'COPY' || value === 'DBLCOPY')) parsed.notes = value;
    else throw new ReplayParseError(`play.playerChartPlayOptions.${key}: unsupported value`);
  }
  return parsed;
}
 
function parsePlay(play: Record<string, unknown>): ReplayPlay {
  const mode = play.mode;
  Iif (mode !== 'manual' && mode !== 'auto') {
    throw new ReplayParseError(`play.mode: expected 'manual' | 'auto'`);
  }
  const gauge = play.gauge;
  if (!isGaugePick(gauge)) {
    throw new ReplayParseError(
      `play.gauge: expected one of ${GAUGE_TYPES.join(' | ')}, optionally qualified with its source (lr2:HARD)`,
    );
  }
  if (play.inputSources === undefined) {
    throw new ReplayParseError('play.inputSources: required (replays recorded before input sources are not read)');
  }
  const parsed: ReplayPlay = {
    inputSources: parseReplayInputSources(play.inputSources),
    mode,
    autoScratch: play.autoScratch === true,
    gauge,
  };
  if (play.analogScratch !== undefined) parsed.analogScratch = parseReplayAnalogScratch(play.analogScratch);
  if (play.randomLane !== undefined) {
    const randomLane = expectRecord(play.randomLane, 'play.randomLane');
    parsed.randomLane = {};
    const p1 = optionalString(randomLane.p1, 'play.randomLane.p1');
    const p2 = optionalString(randomLane.p2, 'play.randomLane.p2');
    Eif (p1 !== undefined) parsed.randomLane.p1 = p1;
    if (p2 !== undefined) parsed.randomLane.p2 = p2;
  }
  if (play.dpFlip !== undefined) parsed.dpFlip = play.dpFlip === true;
  if (play.gauge2P !== undefined) {
    Iif (!isGaugePick(play.gauge2P))
      throw new ReplayParseError(
        `play.gauge2P: expected one of ${GAUGE_TYPES.join(' | ')}, optionally qualified with its source (lr2:HARD)`,
      );
    parsed.gauge2P = play.gauge2P;
  }
  const judgeWindowOverrideMs = optionalFiniteNumber(play.judgeWindowOverrideMs, 'play.judgeWindowOverrideMs');
  if (judgeWindowOverrideMs !== undefined) parsed.judgeWindowOverrideMs = judgeWindowOverrideMs;
  if (play.judgeRuleset !== undefined) {
    Iif (!isRulesetId(play.judgeRuleset)) {
      throw new ReplayParseError(`play.judgeRuleset: expected ${RULESET_IDS.map((id) => `'${id}'`).join(' | ')}`);
    }
    parsed.judgeRuleset = play.judgeRuleset;
  }
  if (play.randomDraws !== undefined) {
    parsed.randomDraws = parseRandomDraws(play.randomDraws, 'play.randomDraws');
  }
  if (play.aborted !== undefined) parsed.aborted = play.aborted === true;
  if (play.completedAtReversal === true) parsed.completedAtReversal = true;
  if (play.exitedReversal === true) parsed.exitedReversal = true;
  if (play.abortedAtUs !== undefined) parsed.abortedAtUs = expectFiniteNumber(play.abortedAtUs, 'play.abortedAtUs');
  if (play.endOnFailure !== undefined) parsed.endOnFailure = play.endOnFailure === true;
  if (play.bmsonTotalMode !== undefined) {
    if (play.bmsonTotalMode !== 'beatoraja' && play.bmsonTotalMode !== 'spec')
      throw new ReplayParseError('play.bmsonTotalMode: expected beatoraja or spec');
    parsed.bmsonTotalMode = play.bmsonTotalMode;
  }
  if (play.bottomShiftableGauge !== undefined) {
    if (!['ASSIST-EASY', 'EASY', 'GROOVE'].includes(play.bottomShiftableGauge as string))
      throw new ReplayParseError('play.bottomShiftableGauge: expected ASSIST-EASY, EASY or GROOVE');
    parsed.bottomShiftableGauge = play.bottomShiftableGauge as GaugeShiftBottom;
  }
  if (play.gaugeAutoShift !== undefined) {
    if (
      !['NONE', 'CONTINUE', 'SURVIVAL_TO_GROOVE', 'BEST_CLEAR', 'SELECT_TO_UNDER'].includes(
        play.gaugeAutoShift as string,
      )
    )
      throw new ReplayParseError(
        'play.gaugeAutoShift: expected NONE, CONTINUE, SURVIVAL_TO_GROOVE, BEST_CLEAR or SELECT_TO_UNDER',
      );
    parsed.gaugeAutoShift = play.gaugeAutoShift as GaugeAutoShift;
  }
  if (play.course !== undefined) parsed.course = parseCourseStage(expectRecord(play.course, 'play.course'));
  if (play.tempo !== undefined) {
    const tempo = expectFiniteNumber(play.tempo, 'play.tempo');
    if (!(tempo > 0)) throw new ReplayParseError('play.tempo: expected a positive number');
    if (tempo !== 1) parsed.tempo = tempo;
  }
  if (play.tempoChanges !== undefined) {
    const changes = parseReplayTempoChanges(play.tempoChanges, 'play.tempoChanges');
    Eif (changes.length > 0) parsed.tempoChanges = changes;
  }
  if (play.view !== undefined) parsed.view = parseReplayViewState(expectRecord(play.view, 'play.view'), 'play.view');
  if (play.viewChanges !== undefined) {
    const changes = parseReplayViewChanges(play.viewChanges, 'play.viewChanges');
    Eif (changes.length > 0) parsed.viewChanges = changes;
  }
  if (play.controlInputs !== undefined) {
    const inputs = parseControlInputs(play.controlInputs);
    if (inputs.length > 0) parsed.controlInputs = inputs;
  }
  if (play.lr2Gambol !== undefined) {
    if (play.lr2Gambol !== 1 && play.lr2Gambol !== 2) throw new ReplayParseError('play.lr2Gambol: expected 1 or 2');
    parsed.lr2Gambol = play.lr2Gambol;
  }
  if (play.judgeAlgorithm !== undefined) {
    if (!['combo', 'duration', 'lowest'].includes(play.judgeAlgorithm as string)) {
      throw new ReplayParseError('play.judgeAlgorithm: expected combo, duration or lowest');
    }
    parsed.judgeAlgorithm = play.judgeAlgorithm as 'combo' | 'duration' | 'lowest';
  }
  Iif (play.customJudge !== undefined) {
    const raw = expectRecord(play.customJudge, 'play.customJudge');
    const judge = {} as BeatorajaCustomJudge;
    for (const field of Object.keys(DEFAULT_BEATORAJA_CUSTOM_JUDGE) as Array<keyof BeatorajaCustomJudge>) {
      const value = expectNonNegativeInteger(raw[field], `play.customJudge.${field}`);
      if (value !== clampCustomJudgeRate(field, value))
        throw new ReplayParseError(`play.customJudge.${field}: outside the source range`);
      judge[field] = value;
    }
    parsed.customJudge = judge;
  }
  if (play.scrollModifier !== undefined) {
    if (
      play.scrollModifier !== 'OFF' &&
      play.scrollModifier !== 'REMOVE' &&
      play.scrollModifier !== 'ADD' &&
      play.scrollModifier !== 'SOFTLANDING-1' &&
      play.scrollModifier !== 'SOFTLANDING-2'
    )
      throw new ReplayParseError('play.scrollModifier: expected OFF, REMOVE, ADD, SOFTLANDING-1 or SOFTLANDING-2');
    parsed.scrollModifier = play.scrollModifier;
  }
  if (play.scrollSection !== undefined) {
    const section = expectNonNegativeInteger(play.scrollSection, 'play.scrollSection');
    if (section < 1 || section > 1024) throw new ReplayParseError('play.scrollSection: expected 1..1024');
    parsed.scrollSection = section;
  }
  if (play.scrollRate !== undefined) {
    const rate = expectFiniteNumber(play.scrollRate, 'play.scrollRate');
    if (rate < 0 || rate > 1) throw new ReplayParseError('play.scrollRate: expected 0..1');
    parsed.scrollRate = rate;
  }
  if (play.scrollModifierTimeline !== undefined) {
    Iif (!Array.isArray(play.scrollModifierTimeline))
      throw new ReplayParseError('play.scrollModifierTimeline: expected array');
    let previous = -Infinity;
    parsed.scrollModifierTimeline = play.scrollModifierTimeline.map((value, index) => {
      const point = expectRecord(value, `play.scrollModifierTimeline[${index}]`);
      const beat = expectFiniteNumber(point.beat, 'scroll timeline beat');
      const speed = expectFiniteNumber(point.speed, 'scroll timeline speed');
      if (beat < 0 || beat < previous)
        throw new ReplayParseError('play.scrollModifierTimeline: expected ordered nonnegative beats');
      previous = beat;
      return { beat, speed };
    });
  }
  if (
    parsed.scrollModifier === 'ADD' &&
    (parsed.scrollSection === undefined || parsed.scrollRate === undefined || !parsed.scrollModifierTimeline?.length)
  )
    throw new ReplayParseError('play.scrollModifier: ADD requires section, rate and an effective timeline');
  if (isSoftLanding(parsed.scrollModifier) && !parsed.scrollModifierTimeline?.length)
    throw new ReplayParseError('play.scrollModifier: SOFTLANDING requires an effective timeline');
  if (
    (parsed.scrollModifier === 'ADD' || isSoftLanding(parsed.scrollModifier)) &&
    parsed.scrollModifierTimeline?.[0]?.beat !== 0
  )
    throw new ReplayParseError('play.scrollModifierTimeline: expected initial beat zero');
  if (play.scrollModifierChanged !== undefined) {
    if (typeof play.scrollModifierChanged !== 'boolean')
      throw new ReplayParseError('play.scrollModifierChanged: expected boolean');
    parsed.scrollModifierChanged = play.scrollModifierChanged;
  }
  if (play.playerChartPlayOptions !== undefined)
    parsed.playerChartPlayOptions = parsePlayerChartPlayOptions(play.playerChartPlayOptions);
  if (play.mineModifier !== undefined) {
    if (!['OFF', 'REMOVE', 'ADD_RANDOM', 'ADD_NEAR', 'ADD_BLANK', 'NANASI_ADD'].includes(play.mineModifier as string))
      throw new ReplayParseError(
        'play.mineModifier: expected OFF, REMOVE, ADD_RANDOM, ADD_NEAR, ADD_BLANK or NANASI_ADD',
      );
    parsed.mineModifier = play.mineModifier as MineModifier;
  }
  if (play.mineModifierChangeCount !== undefined)
    parsed.mineModifierChangeCount = expectNonNegativeInteger(
      play.mineModifierChangeCount,
      'play.mineModifierChangeCount',
    );
  if (play.sevenToNinePattern !== undefined) {
    const value = expectNonNegativeInteger(play.sevenToNinePattern, 'play.sevenToNinePattern');
    if (value > 6) throw new ReplayParseError('play.sevenToNinePattern: expected 0..6');
    parsed.sevenToNinePattern = value as import('../core/seven-to-nine.ts').SevenToNinePattern;
  }
  if (play.sevenToNineType !== undefined) {
    const value = expectNonNegativeInteger(play.sevenToNineType, 'play.sevenToNineType');
    if (value > 2) throw new ReplayParseError('play.sevenToNineType: expected 0..2');
    parsed.sevenToNineType = value as import('../core/seven-to-nine.ts').SevenToNineType;
  }
  if (play.sevenToNineThresholdBPM !== undefined) {
    if (typeof play.sevenToNineThresholdBPM !== 'number' || !Number.isFinite(play.sevenToNineThresholdBPM))
      throw new ReplayParseError('play.sevenToNineThresholdBPM: expected finite number');
    parsed.sevenToNineThresholdBPM = play.sevenToNineThresholdBPM;
  }
  if (play.sevenToNineApplied !== undefined) {
    if (typeof play.sevenToNineApplied !== 'boolean')
      throw new ReplayParseError('play.sevenToNineApplied: expected boolean');
    parsed.sevenToNineApplied = play.sevenToNineApplied;
  }
  if (play.battleMode !== undefined) {
    if (
      ![
        'OFF',
        'COUPLE',
        'SP-TO-DP',
        'D-BATTLE',
        'BATTLE',
        'beatoraja:BATTLE',
        '____:BATTLE',
        'BATTLE-AS',
        'TWO-PLAYER',
      ].includes(play.battleMode as string)
    )
      throw new ReplayParseError(
        'play.battleMode: expected OFF, COUPLE, SP-TO-DP, D-BATTLE, BATTLE (bare, beatoraja: or ____:), BATTLE-AS or TWO-PLAYER',
      );
    parsed.battleMode = play.battleMode as EffectiveBattleMode;
  }
  if (play.battleSourceVariant !== undefined) {
    let knownVariant = false;
    try {
      knownVariant =
        typeof play.battleSourceVariant === 'string' &&
        getPlayModeLayouts(play.battleSourceVariant as ChartPlayVariant).some(
          (layout) => layout.variant === play.battleSourceVariant,
        );
    } catch {
      // Numeric generic variants outside the supported domain are malformed replay input.
    }
    if (!knownVariant) throw new ReplayParseError('play.battleSourceVariant: unknown play variant');
    parsed.battleSourceVariant = play.battleSourceVariant as ChartPlayVariant;
  }
  if (play.battleTempo !== undefined) {
    const tempo = expectFiniteNumber(play.battleTempo, 'play.battleTempo');
    if (tempo <= 0) throw new ReplayParseError('play.battleTempo: expected positive tempo');
    parsed.battleTempo = tempo;
  }
  for (const field of ['battleAssist1P', 'battleAssist2P', 'dBattleScratch'] as const) {
    if (play[field] === undefined) continue;
    if (typeof play[field] !== 'boolean') throw new ReplayParseError(`play.${field}: expected boolean`);
    parsed[field] = play[field] as boolean;
  }
  for (const field of ['battleChangedObjectCount', 'battleDroppedObjectCount'] as const)
    if (play[field] !== undefined) parsed[field] = expectNonNegativeInteger(play[field], `play.${field}`);
  if (play.lr2Mania !== undefined) parsed.lr2Mania = parseLR2Mania(play.lr2Mania);
  if (play.lr2ExtraMode !== undefined) {
    if (typeof play.lr2ExtraMode !== 'boolean') throw new ReplayParseError('play.lr2ExtraMode: expected boolean');
    parsed.lr2ExtraMode = play.lr2ExtraMode;
  }
  for (const field of ['lr2ExtraLevel', 'lr2ExtraEffectiveLevel'] as const) {
    if (play[field] === undefined) continue;
    const value = expectNonNegativeInteger(play[field], `play.${field}`);
    if (value > 2) throw new ReplayParseError(`play.${field}: expected 0, 1 or 2`);
    parsed[field] = value as LR2ExtraLevel;
  }
  if (play.lr2ExtraConvertedObjectCount !== undefined)
    parsed.lr2ExtraConvertedObjectCount = expectNonNegativeInteger(
      play.lr2ExtraConvertedObjectCount,
      'play.lr2ExtraConvertedObjectCount',
    );
  if (play.lr2ExtraTempo !== undefined) {
    const tempo = expectFiniteNumber(play.lr2ExtraTempo, 'play.lr2ExtraTempo');
    if (tempo <= 0) throw new ReplayParseError('play.lr2ExtraTempo: expected positive tempo');
    parsed.lr2ExtraTempo = tempo;
  }
  if (play.extraNoteDepth !== undefined) {
    parsed.extraNoteDepth = expectNonNegativeInteger(play.extraNoteDepth, 'play.extraNoteDepth');
    if (parsed.extraNoteDepth > 100) throw new ReplayParseError('play.extraNoteDepth: expected 0..100');
  }
  if (play.extraNoteScratch !== undefined) {
    if (typeof play.extraNoteScratch !== 'boolean')
      throw new ReplayParseError('play.extraNoteScratch: expected boolean');
    parsed.extraNoteScratch = play.extraNoteScratch;
  }
  if (play.extraNoteChangeCount !== undefined)
    parsed.extraNoteChangeCount = expectNonNegativeInteger(play.extraNoteChangeCount, 'play.extraNoteChangeCount');
  if (play.longNoteRate !== undefined) {
    const rate = expectFiniteNumber(play.longNoteRate, 'play.longNoteRate');
    if (rate < 0 || rate > 1) throw new ReplayParseError('play.longNoteRate: expected 0..1');
    parsed.longNoteRate = rate;
  }
  if (play.longNoteModifierChangeCount !== undefined)
    parsed.longNoteModifierChangeCount = expectNonNegativeInteger(
      play.longNoteModifierChangeCount,
      'play.longNoteModifierChangeCount',
    );
  if (play.longNoteModifier !== undefined) {
    if (
      !['OFF', 'LEGACY', 'REMOVE', 'ADD_LN', 'ADD_CN', 'ADD_HCN', 'ADD_ALL'].includes(play.longNoteModifier as string)
    ) {
      throw new ReplayParseError(
        'play.longNoteModifier must be OFF, LEGACY, REMOVE, ADD_LN, ADD_CN, ADD_HCN or ADD_ALL',
      );
    }
    parsed.longNoteModifier = play.longNoteModifier as LongNoteModifier;
  }
  for (const key of ['autoScratch1P', 'autoScratch2P', 'anyKey'] as const) {
    if (play[key] !== undefined) {
      if (typeof play[key] !== 'boolean') throw new ReplayParseError(`play.${key}: expected a boolean`);
      parsed[key] = play[key];
    }
  }
  if (play.options !== undefined) parsed.options = parseReplayOptionState(play.options);
  if (play.optionChanges !== undefined) parsed.optionChanges = parseReplayOptionChanges(play.optionChanges);
  if (play.native !== undefined) {
    const native = expectRecord(play.native, 'play.native');
    const copied: Record<string, string | number | boolean | null> = {};
    for (const [key, raw] of Object.entries(native)) {
      Eif (raw === null || typeof raw === 'string' || typeof raw === 'number' || typeof raw === 'boolean') {
        copied[key] = raw;
      }
    }
    parsed.native = copied;
  }
  return parsed;
}
 
const COURSE_KINDS: ReadonlySet<string> = new Set(['grade', 'expert', 'nonstop']);
const COURSE_GAUGE_SETS: ReadonlySet<string> = new Set(['lr2', '5k', '7k', '9k', '24k']);
const COURSE_JUDGE_CONSTRAINTS: ReadonlySet<string> = new Set(['no-good', 'no-great']);
 
function parseCourseStage(course: Record<string, unknown>): ReplayCourseStage {
  if (typeof course.kind !== 'string' || !COURSE_KINDS.has(course.kind)) {
    throw new ReplayParseError(`play.course.kind: expected 'grade' | 'expert' | 'nonstop'`);
  }
  const parsed: ReplayCourseStage = { kind: course.kind as RulesetCourseKind };
  if (course.gaugeSet !== undefined) {
    if (typeof course.gaugeSet !== 'string' || !COURSE_GAUGE_SETS.has(course.gaugeSet)) {
      throw new ReplayParseError(`play.course.gaugeSet: expected 'lr2' | '5k' | '7k' | '9k' | '24k'`);
    }
    parsed.gaugeSet = course.gaugeSet as CourseGaugeSet;
  }
  if (course.judge !== undefined) {
    if (typeof course.judge !== 'string' || !COURSE_JUDGE_CONSTRAINTS.has(course.judge)) {
      throw new ReplayParseError(`play.course.judge: expected 'no-good' | 'no-great'`);
    }
    parsed.judge = course.judge as CourseJudgeConstraint;
  }
  if (course.carryIn !== undefined) {
    const carry = expectRecord(course.carryIn, 'play.course.carryIn');
    parsed.carryIn = {
      ...(carry.gauges !== undefined
        ? { gauges: parseGaugeValues(carry.gauges, 'play.course.carryIn.gauges', true) }
        : {}),
      gauge: expectFiniteNumber(carry.gauge, 'play.course.carryIn.gauge'),
      combo: expectNonNegativeInteger(carry.combo, 'play.course.carryIn.combo'),
      maxCombo: expectNonNegativeInteger(carry.maxCombo, 'play.course.carryIn.maxCombo'),
    };
  }
  if (course.rate !== undefined) parsed.rate = expectFiniteNumber(course.rate, 'play.course.rate');
  return parsed;
}
 
/**
 * LR2's mania chart generators as a play applied them: each rate (0 is off, else 10–100), the seed every draw came
 * from, and what each generator changed. The rates and the seed rebuild the chart; the counts check that they did.
 */
export interface ReplayLR2Mania {
  addNotes: number;
  loudness: number;
  addLongNotes: number;
  addMines: number;
  seed: string;
  changes: { addNotes: number; loudness: number; addLongNotes: number; addMines: number };
}
 
const LR2_MANIA_FIELDS = ['addNotes', 'loudness', 'addLongNotes', 'addMines'] as const;
 
function parseLR2Mania(value: unknown): ReplayLR2Mania {
  const record = expectRecord(value, 'play.lr2Mania');
  const changes = expectRecord(record.changes, 'play.lr2Mania.changes');
  const rate = (field: (typeof LR2_MANIA_FIELDS)[number]): number => {
    const parsed = expectNonNegativeInteger(record[field], `play.lr2Mania.${field}`);
    if (parsed > 100) throw new ReplayParseError(`play.lr2Mania.${field}: expected 0..100`);
    return parsed;
  };
  if (typeof record.seed !== 'string' || !/^\d{1,19}$/.test(record.seed))
    throw new ReplayParseError('play.lr2Mania.seed: expected a non-negative integer string');
  const count = (field: (typeof LR2_MANIA_FIELDS)[number]): number =>
    expectNonNegativeInteger(changes[field], `play.lr2Mania.changes.${field}`);
  const parsed: ReplayLR2Mania = {
    addNotes: rate('addNotes'),
    loudness: rate('loudness'),
    addLongNotes: rate('addLongNotes'),
    addMines: rate('addMines'),
    seed: record.seed,
    changes: {
      addNotes: count('addNotes'),
      loudness: count('loudness'),
      addLongNotes: count('addLongNotes'),
      addMines: count('addMines'),
    },
  };
  if (LR2_MANIA_FIELDS.every((field) => parsed[field] === 0))
    throw new ReplayParseError('play.lr2Mania: expected at least one generator on');
  return parsed;
}