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

90.97% Statements 242/266
84.29% Branches 220/261
97.5% Functions 39/40
93.16% Lines 218/234

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                                                                                                294x 294x                                                                                                                                                                                         274x 274x   274x     274x 274x                 274x 274x 274x                                                   14x 14x 14x   14x 14x                       167x 166x 166x   166x 112x   166x                             188x 188x 188x 188x 188x 188x 188x 2184x 364x 364x 364x 364x 364x               416x 188x 188x 188x                     105x   188x       364x     2x           188x 188x                                   188x 188x 188x 188x               342x                   157x 153x         49x                             166x 24x 48x   24x   142x 142x   142x 142x 330x     298x 298x 330x 142x   156x           298x 298x 298x 298x   142x 337x   142x                                   35x 35x   35x                 35x                           70x                           35x 35x 35x 35x         2x 2x                               93x       200x   93x 93x 93x 15x 15x 15x 11x 22x   11x   11x 11x 11x   15x   170x 78x 138x 138x   90x 28x 28x 54x   28x 28x               28x   78x       73x                 4x           4x   4x     4x     294x   294x 3234x       15x 15x 1x 15x     15x                   15x       16x 16x     16x 16x 1x   15x 15x 15x 15x                           15x 15x               75x 75x 16x 16x   1x     74x 74x 1x       73x     73x 73x 1x   106x     72x     72x         42x 42x             72x 4x 3x   71x 1x   70x 158x 158x 158x 142x 142x   1x       16x     16x 16x 16x 16x 16x 15x 15x 15x   70x           70x 70x 68x 65x 65x 28x   65x     294x     17x     17x     17x 1x     16x 16x         16x     16x 31x 31x 31x         31x 16x   31x 15x   30x   16x 16x     86x   1x   14x                     28x 28x 28x 28x   28x 28x 28x 28x 28x 28x                                           28x 28x 28x   28x    
import { gaugePickType, splitGaugePick, type GaugePick } from '../ruleset/gauge-type.ts';
import { resolve____RankLabel } from '../ruleset/score.ts';
import type { RulesetChartFacts } from '../ruleset/facts.ts';
import { resolveRuleset, type RulesetId } from '../ruleset/index.ts';
import {
  CLEAR_LAMPS,
  resolveCourseClearLamp,
  resolveMissCount,
  type ClearLamp,
  type CourseClearLampFacts,
} from '../ruleset/clear-lamp.ts';
import {
  courseGoesOnAfterGivingUp,
  isCourseStageFailed,
  resolveCourseGauge,
  resolveCourseGaugeId,
  type RulesetCourseKind,
} from '../ruleset/course.ts';
import {
  BE_MUSIC_REPLAY_VERSION,
  parseReplay,
  type BeMusicReplay,
  type ReplayCourseStage,
  type ReplayJudgmentCounts,
  type ReplayRecorderInfo,
  type ReplayRulesetResult,
} from './format.ts';
import {
  expectFiniteNumber,
  expectRecord,
  expectString,
  optionalString,
  parseRandomDraws,
  parseRecorder,
  parseResults,
  ReplayParseError,
} from './parse.ts';
import { courseStageRulesetOptions, resolveRulesetConfig } from './rulesets.ts';
import { simulateReplay, type SimulateReplayOptions } from './simulate.ts';
import type { ReplayNonstopRun } from './nonstop.ts';
import { LR2_NONSTOP_CONNECTIONS } from '../course/lr2crs.ts';
 
/**
 * A course replay: one file for a whole course run, holding each stage's own replay in order. Every stage log is
 * complete on its own (its `play.course` carries the course kind, constraints and the state carried in), so a stage
 * can be extracted and replayed or re-simulated as a single-chart log. Stages the run never reached (after a failed
 * stage) are listed with their chart facts only, so the course result can still count their notes.
 */
export const BE_MUSIC_COURSE_REPLAY_FORMAT = 'be-music-course-replay';
export const COURSE_REPLAY_FILE_SUFFIX = '.bmcourse.json';
 
export interface BeMusicCourseReplay {
  format: typeof BE_MUSIC_COURSE_REPLAY_FORMAT;
  /** Shares the replay revision: course logs change together with the stage logs they hold. */
  version: number;
  createdAt?: string;
  recorder?: ReplayRecorderInfo;
  course: ReplayCourseInfo;
  /** One entry per course stage, in order. For a NONSTOP run, the reached stages cut out of {@link nonstop}. */
  stages: ReplayCourseStageEntry[];
  /** A NONSTOP run: the stitched play that was judged. The course result comes from it. */
  nonstop?: ReplayNonstopRun;
  /** Regenerable cache: the course result per ruleset id, plus `native` (the engine's own). */
  results?: Record<string, ReplayCourseResult>;
}
 
/** What the course was: enough to identify it and to compute its trophy. */
export interface ReplayCourseInfo {
  name: string;
  kind: RulesetCourseKind;
  /** The course's constraints, by their table-header names (`grade_mirror`, `gauge_lr2`, ...). */
  constraints: string[];
  trophies: Array<{ name: string; missRate: number; scoreRate: number }>;
  /**
   * `false` for a course whose runs must not be ranked: beatoraja's `release: false`, which also marks a drawn random
   * course. Absent = released.
   */
  release?: false;
}
 
export type ReplayCourseStageEntry =
  | { played: true; replay: BeMusicReplay }
  | {
      played: false;
      /** The stage chart's file hashes, when known. */
      sha256?: string;
      md5?: string;
      /**
       * The stage chart's Be-Music chart fingerprint (`bmfp0:…`), as a played stage's `chart.chartFingerprint` would
       * be: it keys the course on the Leaderboard (`computeCourseReplayFingerprint`). Absent in logs from before it was
       * recorded.
       */
      chartFingerprint?: string;
      /** The facts a ruleset needs to count the stage's notes. */
      facts: RulesetChartFacts;
    };
 
/** The lamps a course run earns: every `ClearLamp` but NO PLAY, ASSIST EASY and LIGHT ASSIST EASY (no course gauge is an assist
 * gauge, and an assisted run keeps no course record). */
export type CourseClearLamp = Exclude<ClearLamp, 'NO_PLAY' | 'ASSIST_EASY' | 'LIGHT_ASSIST_EASY'>;
 
export interface ReplayCourseResult {
  ruleset: string;
  /** Judgments summed over the stages played. */
  judge: ReplayJudgmentCounts;
  fast: number;
  slow: number;
  exScore: number;
  /** Judgment notes over every stage of the course, reached or not. */
  noteCount: number;
  /** BP: BADs, POORs and empty POORs, plus every note the run never judged (failed or unreached stages). */
  missCount: number;
  /** The course-wide max combo. */
  maxCombo: number;
  /** Mine POORs included in judge.poor, not consumed judgment notes. */
  minePoor?: number;
  /** Final combo eligibility for modes that break combo on empty POOR. */
  fullCombo?: boolean;
 
  djLevel: string;
  /** The gauge the course ended on. */
  /** The last stage's gauge; `source` as in a play's result, when it is another source's than the ruleset's own. */
  gauge: { type: string; source?: RulesetId; final: number; cleared: boolean };
  /** The number of stages the run reached. */
  stagesPlayed: number;
  lamp: CourseClearLamp;
  /** The best trophy the run earned, by name. */
  trophy?: string;
  /** Each played stage's own result, in order. */
  stages: ReplayRulesetResult[];
}
 
/**
 * The lamp of a course run, by the course clear-lamp rule (`resolveCourseClearLamp`): FAILED when a stage ended with its
 * gauge empty or a stage was never reached; FULL COMBO, PERFECT or MAX when the course max combo covers every note;
 * otherwise the gauge's lamp, LR2's by the player's gauge `pick` and beatoraja's by the class gauge.
 */
export function resolveCourseLamp(
  ruleset: string,
  result: Pick<ReplayCourseResult, 'judge' | 'noteCount' | 'maxCombo' | 'gauge' | 'fullCombo'>,
  pick: GaugePick,
): CourseClearLamp {
  const id = ruleset.split('/')[0]!;
  const fullCombo = result.fullCombo !== false && result.noteCount > 0 && result.maxCombo >= result.noteCount;
  // The HP rule is the course gauge's own: LR2's course gauges keep it under another ruleset's judging (#1171).
  const lr2Gauge = (result.gauge.source ?? id) === 'lr2';
  // CheckCourseClear: HP >= 2 may advance; at course end, HP == 2 clears only through the full-combo branch.
  const cleared =
    result.gauge.cleared && (!lr2Gauge || (result.gauge.final >= 2 && (fullCombo || result.gauge.final > 2)));
  const facts: CourseClearLampFacts = {
    ruleset: id,
    cleared,
    gauge: result.gauge.type,
    gaugeType: gaugePickType(pick),
    noteCount: result.noteCount,
    maxCombo: result.maxCombo,
    judge: result.judge,
  };
  if (result.gauge.source !== undefined) facts.gaugeSource = result.gauge.source;
  if (result.fullCombo !== undefined) facts.fullCombo = result.fullCombo;
  return resolveCourseClearLamp(facts) as CourseClearLamp;
}
 
/** The gauge a course stage starts on (see {@link resolveCourseStageStartGauge}). */
export interface CourseStageStartGauge {
  /** The ruleset's course gauge id (`GRADE`, `COURSE-EASY`, `CLASS`, …), as the engine reports it. */
  type: string;
  /** The value the stage starts from: the gauge carried in, or the gauge's start (100) on the first stage. */
  initial: number;
  max: number;
  /** The clear border (0: a course gauge clears unless it empties). */
  border: number;
  survival: boolean;
}
 
/**
 * The gauge a course stage starts on, before the engine has run a frame: its course gauge id and the value carried in
 * from the previous stage. A host shows it during the stage's READY phase and seeds the result graph with it, so
 * neither starts on the single-chart gauge. The judging values, which depend on the chart, are left out.
 */
export function resolveCourseStageStartGauge(
  rulesetId: RulesetId,
  course: ReplayCourseStage,
  selectedGauge: GaugePick,
): CourseStageStartGauge {
  // A qualified pick starts on its own source's course gauge (#1171). A bare pick, the common case, needs no split.
  const parts = selectedGauge.includes(':') ? splitGaugePick(selectedGauge) : undefined;
  const source = parts?.source ?? rulesetId;
  const gaugeId = resolveCourseGaugeId(source, course.kind, parts?.type ?? selectedGauge);
  // The lane mode and the HARD damage multiplier only pick the judging values, which this leaves out.
  const spec = resolveCourseGauge(source, gaugeId, courseStageRulesetOptions(course), '7', 1);
  return { type: spec.id, initial: spec.initial, max: spec.max, border: spec.border, survival: spec.survival };
}
 
/**
 * The trophy a course result earns (beatoraja `GradeBar.getTrophy`): the last trophy whose `missRate` is at least the
 * BP rate (`missCount × 100 / notes`) and whose `scoreRate` is at most the score rate (`exScore × 100 / (2 × notes)`).
 * Trophies are listed easiest first, so the last one that qualifies is the best.
 */
export function resolveCourseTrophy(
  trophies: ReplayCourseInfo['trophies'],
  result: Pick<ReplayCourseResult, 'missCount' | 'exScore' | 'noteCount'>,
): string | undefined {
  if (result.noteCount <= 0) return undefined;
  const missRate = (result.missCount * 100) / result.noteCount;
  const scoreRate = (result.exScore * 100) / (2 * result.noteCount);
  let earned: string | undefined;
  for (const trophy of trophies) {
    if (trophy.missRate >= missRate && trophy.scoreRate <= scoreRate) earned = trophy.name;
  }
  return earned;
}
 
/**
 * Sums a course run from its stage results: judgments, fast / slow and EX-SCORE over the stages played; notes over every
 * stage (`stageNoteCounts`, reached or not); BP with every note the run never judged; the course max combo and the gauge
 * from the last stage played. The run is cleared when every stage was reached and the last one cleared.
 */
export function aggregateCourseResult(
  ruleset: string,
  course: ReplayCourseInfo,
  stageResults: readonly ReplayRulesetResult[],
  stageNoteCounts: readonly number[],
  pick: GaugePick,
): ReplayCourseResult {
  const judge: ReplayJudgmentCounts = { pgreat: 0, great: 0, good: 0, bad: 0, poor: 0, emptyPoor: 0 };
  let fast = 0;
  let slow = 0;
  let exScore = 0;
  let judged = 0;
  let minePoor = 0;
  for (const stage of stageResults) {
    for (const key of Object.keys(judge) as Array<keyof ReplayJudgmentCounts>) judge[key] += stage.judge[key];
    fast += stage.fast;
    slow += stage.slow;
    exScore += stage.exScore;
    minePoor += stage.minePoor ?? 0;
    judged +=
      stage.judge.pgreat +
      stage.judge.great +
      stage.judge.good +
      stage.judge.bad +
      stage.judge.poor -
      (stage.minePoor ?? 0);
  }
  const noteCount = stageNoteCounts.reduce((sum, count) => sum + count, 0);
  const last = stageResults.at(-1);
  const reachedAll = stageResults.length === stageNoteCounts.length;
  const gauge: ReplayCourseResult['gauge'] = {
    type: last?.gauge.type ?? '',
    ...(last?.gauge.source !== undefined ? { source: last.gauge.source } : {}),
    final: last?.gauge.final ?? 0,
    cleared:
      reachedAll &&
      last !== undefined &&
      last.gauge.cleared &&
      (ruleset.split('/')[0] !== 'lr2' || judged === noteCount) &&
      // LR2's course gauges go on past a stage given up (`courseGoesOnAfterGivingUp`), which leaves the course FAILED
      // under any judge ruleset; a stage that did not clear is only ever that one, since a failed stage ends the run.
      ((last.gauge.source ?? ruleset.split('/')[0]) !== 'lr2' || stageResults.every((stage) => stage.gauge.cleared)),
  };
  const partial = {
    judge,
    noteCount,
    maxCombo: last?.course?.maxCombo ?? last?.maxCombo ?? 0,
    ...(stageResults.some((stage) => stage.fullCombo !== undefined)
      ? {
          fullCombo:
            stageResults.every((stage) => stage.fullCombo !== false) &&
            (last?.course?.combo ?? last?.maxCombo ?? 0) === noteCount,
        }
      : {}),
    gauge,
  };
  const missCount = resolveMissCount(judge, noteCount - judged);
  const result: ReplayCourseResult = {
    ruleset,
    judge,
    fast,
    slow,
    exScore,
    noteCount,
    missCount,
    maxCombo: partial.maxCombo,
    ...(minePoor > 0 ? { minePoor } : {}),
    ...(partial.fullCombo !== undefined ? { fullCombo: partial.fullCombo } : {}),
 
    djLevel: resolve____RankLabel(exScore, noteCount),
    gauge,
    stagesPlayed: stageResults.length,
    lamp: resolveCourseLamp(ruleset.split('/')[0]!, partial, pick),
    stages: [...stageResults],
  };
  gauge.cleared = result.lamp !== 'FAILED';
  const trophy = gauge.cleared ? resolveCourseTrophy(course.trophies, result) : undefined;
  if (trophy !== undefined) result.trophy = trophy;
  return result;
}
 
/**
 * A stage the player gave up (ESC, `play.aborted`) did not clear, whatever its gauge stood at, and the course it is in
 * is a failed run, as LR2 records it.
 */
function givenUpResult(stageLog: BeMusicReplay, result: ReplayRulesetResult): ReplayRulesetResult {
  return stageLog.play.aborted === true && result.gauge.cleared
    ? { ...result, gauge: { ...result.gauge, cleared: false } }
    : result;
}
 
/**
 * Whether the run ends after a stage: one that ended with its survival gauge empty ends the course, and so does one the
 * player gave up unless the course gauge's rule goes on (`courseGoesOnAfterGivingUp`).
 */
function stageEndsRun(result: ReplayRulesetResult, givenUp: boolean): boolean {
  if (givenUp) return !courseGoesOnAfterGivingUp(result.ruleset, result);
  return isCourseStageFailed(result.ruleset, result.gauge);
}
 
/** The judgment notes one stage counts under a ruleset, from a stage log or from an unreached stage's facts. */
function stageNoteCount(entry: ReplayCourseStageEntry, rulesetId: RulesetId): number {
  return entry.played
    ? resolveRulesetConfig(entry.replay, rulesetId).noteCount
    : resolveRuleset(entry.facts, rulesetId).noteCount;
}
 
/**
 * Re-simulates a whole course under one ruleset. Each stage after the first starts from the state the SIMULATED
 * previous stage left (its gauge value and course combo replace the recorded carry-in), so the result never trusts the
 * recording; the course stops at the first stage whose gauge emptied, or that was given up where this ruleset's course
 * gauge does not go on, as the live run did.
 */
export function simulateCourseReplay(
  courseLog: BeMusicCourseReplay,
  options: Omit<SimulateReplayOptions, 'course'>,
): ReplayCourseResult {
  if (courseLog.nonstop !== undefined) {
    const stageResults = courseLog.stages.flatMap((entry) =>
      entry.played ? [simulateReplay(entry.replay, options)] : [],
    );
    return nonstopCourseResult(courseLog, simulateReplay(courseLog.nonstop.replay, options), stageResults);
  }
  const stageResults: ReplayRulesetResult[] = [];
  let pick: GaugePick = 'GROOVE';
  let previous: ReplayRulesetResult | undefined;
  let previousGivenUp = false;
  for (const entry of courseLog.stages) {
    if (!entry.played || (previous !== undefined && stageEndsRun(previous, previousGivenUp))) break;
    // Only the stage's course carry-in changes, and `simulateReplay` never writes to the log it reads: copy the path
    // down to `play.course` and share the rest (the inputs and chart are most of a log).
    pick = entry.replay.play.gauge;
    const course = { ...(entry.replay.play.course ?? { kind: courseLog.course.kind }) };
    if (previous === undefined) {
      delete course.carryIn;
    } else {
      course.carryIn = {
        gauge: previous.gauge.final,
        combo: previous.course?.combo ?? 0,
        maxCombo: previous.course?.maxCombo ?? previous.maxCombo,
      };
    }
    const stageLog: BeMusicReplay = { ...entry.replay, play: { ...entry.replay.play, course } };
    previous = givenUpResult(stageLog, simulateReplay(stageLog, options));
    previousGivenUp = stageLog.play.aborted === true;
    stageResults.push(previous);
  }
  const stageNoteCounts = courseLog.stages.map((entry, index) =>
    index < stageResults.length ? stageResults[index]!.noteCount : stageNoteCount(entry, options.ruleset),
  );
  return aggregateCourseResult(
    stageResults[0]?.ruleset ?? options.ruleset,
    courseLog.course,
    stageResults,
    stageNoteCounts,
    pick,
  );
}
 
/**
 * A NONSTOP course result: the stitched play's own judgments, gauge and max combo (it was one play), BP with every note
 * it never judged, and the cut-out stages' results listed alongside.
 */
function nonstopCourseResult(
  courseLog: BeMusicCourseReplay,
  run: ReplayRulesetResult,
  stageResults: readonly ReplayRulesetResult[],
): ReplayCourseResult {
  const { judge, noteCount } = run;
  const judged = judge.pgreat + judge.great + judge.good + judge.bad + judge.poor - (run.minePoor ?? 0);
  // A NONSTOP play given up with ESC is a failed run.
  const gauge: ReplayCourseResult['gauge'] = {
    type: run.gauge.type,
    ...(run.gauge.source !== undefined ? { source: run.gauge.source } : {}),
    final: run.gauge.final,
    cleared:
      run.gauge.cleared &&
      courseLog.nonstop?.replay.play.aborted !== true &&
      (run.ruleset.split('/')[0] !== 'lr2' || judged === noteCount),
  };
  const result: ReplayCourseResult = {
    ruleset: run.ruleset,
    judge: { ...judge },
    fast: run.fast,
    slow: run.slow,
    exScore: run.exScore,
    noteCount,
    missCount: resolveMissCount(judge, noteCount - judged),
    maxCombo: run.maxCombo,
    ...(run.minePoor !== undefined ? { minePoor: run.minePoor } : {}),
    ...(run.fullCombo !== undefined ? { fullCombo: run.fullCombo } : {}),
 
    djLevel: resolve____RankLabel(run.exScore, noteCount),
    gauge,
    stagesPlayed: courseLog.stages.filter((entry) => entry.played).length,
    lamp: resolveCourseLamp(
      run.ruleset.split('/')[0]!,
      {
        judge,
        noteCount,
        maxCombo: run.maxCombo,
        gauge,
        ...(run.fullCombo !== undefined ? { fullCombo: run.fullCombo } : {}),
      },
      courseLog.nonstop!.replay.play.gauge,
    ),
    stages: [...stageResults],
  };
  gauge.cleared = result.lamp !== 'FAILED';
  const trophy = gauge.cleared ? resolveCourseTrophy(courseLog.course.trophies, result) : undefined;
  Iif (trophy !== undefined) result.trophy = trophy;
  return result;
}
 
/** A course stage's own replay, ready to replay or re-simulate as a single-chart log. `undefined` for an unreached stage. */
export function extractCourseStage(courseLog: BeMusicCourseReplay, index: number): BeMusicReplay | undefined {
  const entry = courseLog.stages[index];
  return entry?.played === true ? structuredClone(entry.replay) : undefined;
}
 
/**
 * Assembles a course replay from the stages a host played (their own replays, in order) and the facts of the
 * stages it never reached. The native course result is aggregated from the stage logs' native results and lamped under
 * the judge ruleset the stages were played on.
 */
export function createCourseReplay(options: {
  course: ReplayCourseInfo;
  stages: readonly ReplayCourseStageEntry[];
  recorder?: ReplayRecorderInfo;
  createdAt?: string;
  /** A NONSTOP run's stitched play; `stages` then hold its cut-out stages (`splitNonstopReplay`). */
  nonstop?: ReplayNonstopRun;
}): BeMusicCourseReplay {
  const log: BeMusicCourseReplay = {
    format: BE_MUSIC_COURSE_REPLAY_FORMAT,
    version: BE_MUSIC_REPLAY_VERSION,
    course: structuredClone(options.course),
    stages: options.stages.map((entry) => structuredClone(entry)),
  };
  if (options.createdAt !== undefined) log.createdAt = options.createdAt;
  if (options.recorder !== undefined) log.recorder = { ...options.recorder };
  if (options.nonstop !== undefined) {
    log.nonstop = structuredClone(options.nonstop);
    const native = options.nonstop.replay.results?.native;
    if (native !== undefined) {
      const stageNative = options.stages.flatMap((entry) =>
        entry.played && entry.replay.results?.native !== undefined ? [entry.replay.results.native] : [],
      );
      const result = nonstopCourseResult(log, native, stageNative);
      // The engine judged the run under its judge ruleset: lamp it by that ruleset's lamps, as a re-simulation does.
      const judgeRuleset = options.nonstop.replay.play.judgeRuleset ?? 'lr2';
      const lamp = resolveCourseLamp(judgeRuleset, result, options.nonstop.replay.play.gauge);
      log.results = { native: { ...result, lamp } };
    }
    return log;
  }
  const played = options.stages.filter((entry) => entry.played);
  const native = played.map((entry) => {
    const result = entry.replay.results?.native;
    return result !== undefined ? givenUpResult(entry.replay, result) : undefined;
  });
  if (played.length > 0 && native.every((result) => result !== undefined)) {
    const ruleset = played[0]!.replay.play.judgeRuleset ?? 'lr2';
    const noteCounts = options.stages.map((entry, index) =>
      index < native.length ? native[index]!.noteCount : stageNoteCount(entry, ruleset),
    );
    const pick = played.at(-1)!.replay.play.gauge;
    const result = aggregateCourseResult(
      native[0]!.ruleset,
      options.course,
      native as ReplayRulesetResult[],
      noteCounts,
      pick,
    );
    // The engine judged the run under its judge ruleset: lamp it by that ruleset's lamps, as a re-simulation does.
    log.results = { native: { ...result, lamp: resolveCourseLamp(ruleset, result, pick) } };
  }
  return log;
}
 
export function serializeCourseReplay(courseLog: BeMusicCourseReplay): string {
  return JSON.stringify(courseLog);
}
 
/**
 * Suggested filename for a course replay: `<course name>-<timestamp>.bmcourse.json`, with filesystem-hostile
 * characters stripped. `when` defaults to the log's own `createdAt`.
 */
export function resolveCourseReplayFilename(courseLog: BeMusicCourseReplay, when?: Date): string {
  const stem =
    courseLog.course.name
      .normalize('NFKC')
      .replace(/[\\/:*?"<>|]+/g, ' ')
      .replace(/\s+/g, ' ')
      .trim()
      .slice(0, 60) || 'course';
  const source = when ?? (courseLog.createdAt !== undefined ? new Date(courseLog.createdAt) : undefined);
  const timestamp =
    source !== undefined && Number.isFinite(source.getTime())
      ? source.toISOString().replace(/[:.]/g, '-')
      : 'unknown-time';
  return `${stem}-${timestamp}${COURSE_REPLAY_FILE_SUFFIX}`;
}
 
const COURSE_KINDS: ReadonlySet<string> = new Set(['grade', 'expert', 'nonstop']);
/** The lamps a course run can earn ({@link CourseClearLamp}). */
const COURSE_LAMPS: ReadonlySet<string> = new Set(
  CLEAR_LAMPS.filter((lamp) => lamp !== 'NO_PLAY' && lamp !== 'ASSIST_EASY' && lamp !== 'LIGHT_ASSIST_EASY'),
);
 
function parseJudgeRankFacts(judgeRank: Record<string, unknown>, path: string): RulesetChartFacts['judgeRank'] {
  const parsed: RulesetChartFacts['judgeRank'] = { percent: expectFiniteNumber(judgeRank.percent, `${path}.percent`) };
  if (judgeRank.sourceRank !== undefined)
    parsed.sourceRank = expectFiniteNumber(judgeRank.sourceRank, `${path}.sourceRank`);
  Iif (judgeRank.sourceExRank !== undefined) {
    parsed.sourceExRank = expectFiniteNumber(judgeRank.sourceExRank, `${path}.sourceExRank`);
  }
  Iif (judgeRank.timeline !== undefined) {
    if (!Array.isArray(judgeRank.timeline)) throw new ReplayParseError(`${path}.timeline: expected an array`);
    parsed.timeline = judgeRank.timeline.map((raw, index) => {
      const change = expectRecord(raw, `${path}.timeline[${index}]`);
      return {
        timeUs: expectFiniteNumber(change.timeUs, `${path}.timeline[${index}].timeUs`),
        exRankValue: expectFiniteNumber(change.exRankValue, `${path}.timeline[${index}].exRankValue`),
      };
    });
  }
  return parsed;
}
 
function parseFacts(value: unknown, path: string): RulesetChartFacts {
  const facts = expectRecord(value, path);
  Iif (facts.sourceFormat !== 'bms' && facts.sourceFormat !== 'bmson' && facts.sourceFormat !== 'lrx') {
    throw new ReplayParseError(`${path}.sourceFormat: expected 'bms' | 'bmson' | 'lrx'`);
  }
  const lnMode = facts.lnMode;
  if (lnMode !== 1 && lnMode !== 2 && lnMode !== 3) {
    throw new ReplayParseError(`${path}.lnMode: expected 1 | 2 | 3`);
  }
  const judgeRank = expectRecord(facts.judgeRank, `${path}.judgeRank`);
  const notes = expectRecord(facts.notes, `${path}.notes`);
  const long = expectRecord(notes.long, `${path}.notes.long`);
  const parsed: RulesetChartFacts = {
    sourceFormat: facts.sourceFormat,
    laneMode: expectString(facts.laneMode, `${path}.laneMode`),
    lnMode,
    judgeRank: parseJudgeRankFacts(judgeRank, `${path}.judgeRank`),
    notes: {
      normal: expectFiniteNumber(notes.normal, `${path}.notes.normal`),
      long: {
        1: expectFiniteNumber(long[1], `${path}.notes.long.1`),
        2: expectFiniteNumber(long[2], `${path}.notes.long.2`),
        3: expectFiniteNumber(long[3], `${path}.notes.long.3`),
      },
    },
  };
  Iif (facts.total !== undefined) parsed.total = expectFiniteNumber(facts.total, `${path}.total`);
  return parsed;
}
 
/**
 * Parses (and validates) a course replay, JSON text or an already-parsed value. Each played stage goes through
 * `parseReplay`; errors name the stage (`stages[1].replay: ...`).
 */
export function parseCourseReplay(source: unknown): BeMusicCourseReplay {
  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, 'course replay');
  if (root.format !== BE_MUSIC_COURSE_REPLAY_FORMAT) {
    throw new ReplayParseError(
      `format: expected '${BE_MUSIC_COURSE_REPLAY_FORMAT}', got ${JSON.stringify(root.format)}`,
    );
  }
  Iif (root.version !== BE_MUSIC_REPLAY_VERSION) {
    throw new ReplayParseError(`version: unsupported version ${JSON.stringify(root.version)}`);
  }
  const course = expectRecord(root.course, 'course');
  if (typeof course.kind !== 'string' || !COURSE_KINDS.has(course.kind)) {
    throw new ReplayParseError(`course.kind: expected 'grade' | 'expert' | 'nonstop'`);
  }
  Iif (!Array.isArray(course.constraints) || !course.constraints.every((name) => typeof name === 'string')) {
    throw new ReplayParseError('course.constraints: expected an array of strings');
  }
  Iif (!Array.isArray(course.trophies)) {
    throw new ReplayParseError('course.trophies: expected an array');
  }
  const info: ReplayCourseInfo = {
    name: expectString(course.name, 'course.name'),
    kind: course.kind as RulesetCourseKind,
    constraints: [...(course.constraints as string[])],
    trophies: course.trophies.map((raw, index) => {
      const trophy = expectRecord(raw, `course.trophies[${index}]`);
      return {
        name: expectString(trophy.name, `course.trophies[${index}].name`),
        missRate: expectFiniteNumber(trophy.missRate, `course.trophies[${index}].missRate`),
        scoreRate: expectFiniteNumber(trophy.scoreRate, `course.trophies[${index}].scoreRate`),
      };
    }),
  };
  if (course.release !== undefined) {
    if (typeof course.release !== 'boolean') throw new ReplayParseError('course.release: expected a boolean');
    if (!course.release) info.release = false;
  }
  if (!Array.isArray(root.stages) || root.stages.length === 0) {
    throw new ReplayParseError('stages: expected a non-empty array');
  }
  const stages = root.stages.map((raw, index): ReplayCourseStageEntry => {
    const path = `stages[${index}]`;
    const entry = expectRecord(raw, path);
    if (entry.played === true) {
      try {
        return { played: true, replay: parseReplay(entry.replay) };
      } catch (error) {
        Eif (error instanceof ReplayParseError) throw new ReplayParseError(`${path}.replay: ${error.message}`);
        throw error;
      }
    }
    Iif (entry.played !== false) {
      throw new ReplayParseError(`${path}.played: expected a boolean`);
    }
    const unreached: ReplayCourseStageEntry = { played: false, facts: parseFacts(entry.facts, `${path}.facts`) };
    const sha256 = optionalString(entry.sha256, `${path}.sha256`);
    const md5 = optionalString(entry.md5, `${path}.md5`);
    const chartFingerprint = optionalString(entry.chartFingerprint, `${path}.chartFingerprint`);
    Iif (sha256 !== undefined) unreached.sha256 = sha256;
    if (md5 !== undefined) unreached.md5 = md5;
    if (chartFingerprint !== undefined) unreached.chartFingerprint = chartFingerprint;
    return unreached;
  });
  const parsed: BeMusicCourseReplay = {
    format: BE_MUSIC_COURSE_REPLAY_FORMAT,
    version: BE_MUSIC_REPLAY_VERSION,
    course: info,
    stages,
  };
  const createdAt = optionalString(root.createdAt, 'createdAt');
  if (createdAt !== undefined) parsed.createdAt = createdAt;
  if (root.nonstop !== undefined) parsed.nonstop = parseNonstopRun(expectRecord(root.nonstop, 'nonstop'));
  Iif (root.recorder !== undefined) parsed.recorder = parseRecorder(expectRecord(root.recorder, 'recorder'));
  if (root.results !== undefined) {
    parsed.results = parseCourseResults(expectRecord(root.results, 'results'));
  }
  return parsed;
}
 
const NONSTOP_CONNECTIONS: ReadonlySet<string> = new Set(LR2_NONSTOP_CONNECTIONS);
 
function parseNonstopRun(run: Record<string, unknown>): ReplayNonstopRun {
  Iif (!Array.isArray(run.connections) || !run.connections.every((value) => NONSTOP_CONNECTIONS.has(value as string))) {
    throw new ReplayParseError('nonstop.connections: expected an array of NONSTOP connections');
  }
  Iif (run.placement !== 'intended' && run.placement !== 'lr2') {
    throw new ReplayParseError(`nonstop.placement: expected 'intended' | 'lr2'`);
  }
  if (run.stitch !== undefined && !(Number.isInteger(run.stitch) && (run.stitch as number) >= 1)) {
    throw new ReplayParseError('nonstop.stitch: expected a positive integer');
  }
  let replay: BeMusicReplay;
  try {
    replay = parseReplay(run.replay);
  } catch (error) {
    if (error instanceof ReplayParseError) throw new ReplayParseError(`nonstop.replay: ${error.message}`);
    throw error;
  }
  Iif (!Array.isArray(run.stages) || run.stages.length === 0) {
    throw new ReplayParseError('nonstop.stages: expected a non-empty array');
  }
  const stages = run.stages.map((raw, index) => {
    const path = `nonstop.stages[${index}]`;
    const stage = expectRecord(raw, path);
    const parsed: ReplayNonstopRun['stages'][number] = {
      offsetUs: expectFiniteNumber(stage.offsetUs, `${path}.offsetUs`),
      windowStartUs: expectFiniteNumber(stage.windowStartUs, `${path}.windowStartUs`),
      rate: expectFiniteNumber(stage.rate, `${path}.rate`),
    };
    if (stage.windowEndUs !== undefined) {
      parsed.windowEndUs = expectFiniteNumber(stage.windowEndUs, `${path}.windowEndUs`);
    }
    if (stage.randomDraws !== undefined) {
      parsed.randomDraws = parseRandomDraws(stage.randomDraws, `${path}.randomDraws`);
    }
    return parsed;
  });
  const noteStages = run.noteStages;
  if (
    !Array.isArray(noteStages) ||
    noteStages.length !== replay.chart.notes.length ||
    !noteStages.every((stage) => Number.isInteger(stage) && stage >= 0 && stage < stages.length)
  ) {
    throw new ReplayParseError('nonstop.noteStages: expected a stage index per note of nonstop.replay');
  }
  return {
    connections: [...(run.connections as ReplayNonstopRun['connections'])],
    placement: run.placement,
    ...(run.stitch !== undefined ? { stitch: run.stitch as number } : {}),
    replay,
    stages,
    noteStages: [...(noteStages as number[])],
  };
}
 
function parseCourseResults(results: Record<string, unknown>): Record<string, ReplayCourseResult> {
  const parsed: Record<string, ReplayCourseResult> = {};
  for (const [key, raw] of Object.entries(results)) {
    const path = `results.${key}`;
    const record = expectRecord(raw, path);
    // The per-ruleset fields share the stage result shape; the stage list is parsed like a results map.
    const [base] = Object.values(parseResults({ [key]: record }));
    const lamp = expectString(record.lamp, `${path}.lamp`);
    Iif (!COURSE_LAMPS.has(lamp)) throw new ReplayParseError(`${path}.lamp: unknown lamp ${JSON.stringify(lamp)}`);
    Iif (!Array.isArray(record.stages)) throw new ReplayParseError(`${path}.stages: expected an array`);
    const stageMap = Object.fromEntries(record.stages.map((stage, index) => [String(index), stage]));
    const result: ReplayCourseResult = {
      ruleset: base!.ruleset,
      judge: base!.judge,
      fast: base!.fast,
      slow: base!.slow,
      exScore: base!.exScore,
      noteCount: base!.noteCount,
      missCount: expectFiniteNumber(record.missCount, `${path}.missCount`),
      maxCombo: base!.maxCombo,
      ...(base!.minePoor !== undefined ? { minePoor: base!.minePoor } : {}),
      djLevel: expectString(record.djLevel, `${path}.djLevel`),
      gauge: {
        type: base!.gauge.type,
        ...(base!.gauge.source !== undefined ? { source: base!.gauge.source } : {}),
        final: base!.gauge.final,
        cleared: base!.gauge.cleared,
      },
      stagesPlayed: expectFiniteNumber(record.stagesPlayed, `${path}.stagesPlayed`),
      lamp: lamp as CourseClearLamp,
      stages: Object.values(parseResults(stageMap, `${path}.stages`)),
      ...(base!.fullCombo !== undefined ? { fullCombo: base!.fullCombo } : {}),
    };
    const trophy = optionalString(record.trophy, `${path}.trophy`);
    if (trophy !== undefined) result.trophy = trophy;
    parsed[key] = result;
  }
  return parsed;
}