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 | 442x 442x 32084x 32084x 32084x 32084x 32084x 32084x 32084x 35x 32084x 32084x 2018512x 2018512x 7524x 2010988x 2010988x 2018512x 444833x 444833x 444833x 444833x 444833x 444833x 444826x 444826x 444826x 444826x 444833x 246929x 246929x 246929x 159537x 87392x 45187x 61407x 61407x 45187x 99509x 444826x 325509x 119317x 119317x 192x 119317x 173424x 173424x 173424x 444826x 1566155x 1566155x 1566155x 1566155x 1566155x 1566155x 3x 3x 3x 3x 3x 1566152x 1261901x 1261901x 1261901x 1261901x 1261901x 304251x 304251x 220041x 220041x 220041x 220041x 220041x 186473x 186473x 72820x 113653x 220041x 84210x 24x 24x 24x 20x 20x 16x 16x 84210x 2018512x 31963x 31963x 31963x 84210x 32084x 1409733x 10454x 10454x 985118x 10454x 32084x 127x 32084x 32084x 32084x 655x 655x 136x 62x 74x 1514x 286x 286x 245x 1269x 1514x 84x 1185x 93x 93x 1092x 1092x 1092x 1092x 1092x 1092x 43x 43x 1049x 198x 29535x 26060x 444833x 444833x 444833x 444833x 444833x 444833x 444833x 444833x 444833x 444833x 444833x 444833x 444833x 444833x 444833x 444833x 444833x 1566155x 1566155x 1566155x 1566155x 1566155x 6055373x 1566155x 1566155x 1566155x 1566155x 955893x 1566155x 1566155x 3757343x 8577420x 7011265x 5838956x 1172309x 1566152x 32084x 32084x 32084x 18991186x 18991186x 17004758x 17004758x 1986428x 1986428x 61x 1986428x 1986428x 32084x 32084x 32084x 39x 32084x | import {
BMS_JSON_FORMAT,
type BMSControlFlowCommand,
type BMSControlFlowHeaderEntry,
type BMSSourceLineEntry,
type BeMusicJSON,
createEmptyJSON,
} from '@be-music/chart-source';
import { compareEvents, drawRandomOutcomes, type RandomDraws } from '@be-music/chart-model';
import { normalizeASCIIBase36Code } from '@be-music/shared-utils/core';
import { buildBMSObjectLineEntry, upsertMeasureLength } from './event-utils.ts';
import type { BmsonDocument } from './bmson.ts';
import {
resolveControlFlow,
resolveControlFlowAliasDirective,
type ControlFlowCaptureFrameType,
updateControlFlowCaptureStack,
} from './control-flow.ts';
import { pushHeaderLine, resolveHeaderCommandAlias, resolveHeaderDefinitionKey } from './bms-headers.ts';
import { parseJSONDocument } from './bms-json-document.ts';
import { parseBmsonDocument } from './bmson-document.ts';
/**
* Pre-scans for the BMS `#BASE` directive (the beatoraja base-62 extension switch). Default base is 36; only `#BASE 62`
* or `#BASE 36` are recognized. We do a one-pass forward scan and stop at the first object data line, mirroring real
* implementations that require `#BASE` to come before any objects.
*/
// A whole `#BASE 36` / `#BASE 62` line, with the leading / separating whitespace `parseBMS` trims (never a line break).
const BASE_DIRECTIVE_REGEX = /^[^\S\r\n]*#BASE[^\S\r\n]+(36|62)\b/gim;
const CONTROL_FLOW_COMMANDS: ReadonlySet<BMSControlFlowCommand> = new Set([
'RANDOM',
'SETRANDOM',
'IF',
'ELSEIF',
'ELSE',
'ENDIF',
'ENDRANDOM',
'SWITCH',
'SETSWITCH',
'CASE',
'SKIP',
'DEF',
'ENDSW',
]);
type MeasureLengthEntry = BeMusicJSON['measures'][number];
export function parseBMS(input: string): BeMusicJSON {
const json = createEmptyJSON('bms');
const controlFlowCaptureStack: ControlFlowCaptureFrameType[] = [];
// Branch header lines by the header they define, until a later top-level line of the same header overrides them.
const capturedHeadersByKey = new Map<string, BMSControlFlowHeaderEntry[]>();
const measureByIndex = new Map<number, MeasureLengthEntry>();
let hasValidMainBPMHeader = false;
// Resolve the chart's object-ID radix BEFORE main parsing so that every `#WAVxx` / `#BMPxx` key + every
// channel-stream token gets normalized under the right rule. Default is base 36 (case-fold lowercase to uppercase).
// `#BASE 62` opts into the beatoraja extension where lowercase `a-z` is a separate ID space.
const base = detectBMSBase(input);
if (base === 62) {
json.bms.base = 62;
}
// The first object line of each normal-channel measure, with the events it made (its preserved entry's and, outside
// control flow, their copies in `json.events`), so a duplicate line can stamp both with their line orders.
const firstNormalObjectLines = new Map<
number,
{ order: number; events: BeMusicJSON['events'] | undefined; copyStart: number | undefined }
>();
forEachLine(input, (rawLine) => {
const line = rawLine.trim();
if (!line.startsWith('#')) {
return;
}
const second = line.charCodeAt(1);
const startsWithMeasure = second >= 0x30 && second <= 0x39;
if (startsWithMeasure) {
const bmsLineOrder = json.preservation.bms.sourceLines.length;
const parsedLine = parseObjectDataLine(line);
Iif (!parsedLine) {
return;
}
const { measure, channel, data } = parsedLine;
const objectLine = buildBMSObjectLineEntry(measure, channel, data, base);
if (!objectLine) return;
const entry = { kind: 'object' as const, ...objectLine };
json.preservation.bms.sourceLines.push(entry);
const captured = controlFlowCaptureStack.length > 0;
const copyStart = captured ? undefined : json.events.length;
if (channel[0] === '1' || channel[0] === '2') {
const key = measure * 256 + (channel[0] === '2' ? 128 : 0) + channel.charCodeAt(1);
const first = firstNormalObjectLines.get(key);
if (first === undefined) {
firstNormalObjectLines.set(key, { order: bmsLineOrder, events: entry.events, copyStart });
} else {
if (first.events !== undefined) {
for (let index = 0; index < first.events.length; index += 1) {
first.events[index]!.bmsLineOrder = first.order;
if (first.copyStart !== undefined) json.events[first.copyStart + index]!.bmsLineOrder = first.order;
}
first.events = undefined;
}
for (const event of entry.events) event.bmsLineOrder = bmsLineOrder;
}
}
if (captured) {
json.bms.controlFlow.push(entry);
} else {
json.preservation.bms.objectLines.push(objectLine);
if (objectLine.measureLength !== undefined) {
upsertMeasureLength(json, measure, objectLine.measureLength, measureByIndex);
}
for (const event of entry.events) {
const copy: BeMusicJSON['events'][number] = {
measure,
channel,
position: [event.position[0], event.position[1]],
value: event.value,
};
if (event.bmsLineOrder !== undefined) copy.bmsLineOrder = event.bmsLineOrder;
json.events.push(copy);
}
}
return;
}
const headerLine = parseHeaderDirectiveLine(line);
Iif (!headerLine) {
return;
}
const { value } = headerLine;
// `#EXBPMxx` is stored as `#BPMxx`, so round-tripped output is normalized like the control-flow spellings below.
const { command, commandRaw } = resolveHeaderCommandAlias(headerLine.command, headerLine.commandRaw);
// Spelling variants (`#END IF` / `#END` / `#ELSE IF n`) normalize onto the canonical control-flow commands —
// captured entries store the canonical form, so round-tripped output is normalized too.
const aliasedDirective = resolveControlFlowAliasDirective(command, value);
if (aliasedDirective) {
const directiveEntry: BMSSourceLineEntry = {
kind: 'directive',
command: aliasedDirective.command,
value: aliasedDirective.value,
};
json.bms.controlFlow.push(directiveEntry);
json.preservation.bms.sourceLines.push(directiveEntry);
updateControlFlowCaptureStack(controlFlowCaptureStack, aliasedDirective.command);
return;
}
if (isControlFlowCommand(command)) {
const directiveEntry: BMSSourceLineEntry = {
kind: 'directive',
command,
value: value.length > 0 ? value : undefined,
};
json.bms.controlFlow.push(directiveEntry);
json.preservation.bms.sourceLines.push(directiveEntry);
updateControlFlowCaptureStack(controlFlowCaptureStack, command);
return;
}
// Stash the case-preserved command on captured entries when it differs from the uppercased canonical form. Only
// base-62 charts (`#BASE 62`) put lowercase letters in indexed-header keys (e.g. `#WAV0a`), so most charts skip
// this entirely and the JSON stays compact.
const commandCaseDiffers = command !== commandRaw;
if (controlFlowCaptureStack.length > 0) {
const definitionKey = resolveHeaderDefinitionKey(command, commandRaw, base);
const headerEntry: BMSControlFlowHeaderEntry = {
kind: 'header',
command,
value,
...(commandCaseDiffers ? { commandRaw } : {}),
};
json.bms.controlFlow.push(headerEntry);
json.preservation.bms.sourceLines.push(headerEntry);
if (definitionKey !== undefined) {
const captured = capturedHeadersByKey.get(definitionKey);
if (captured) {
captured.push(headerEntry);
} else {
capturedHeadersByKey.set(definitionKey, [headerEntry]);
}
}
return;
}
// LR2 and beatoraja apply header lines in file order: a top-level line overrides the same header in any branch
// above it, taken or not.
if (capturedHeadersByKey.size > 0 && value.length > 0) {
const definitionKey = resolveHeaderDefinitionKey(command, commandRaw, base);
// A non-positive STOP cannot replace a positive definition in a selected branch.
const replacesDefinition = !/^STOP[0-9A-Z]{2}$/u.test(command) || Number.parseInt(value, 10) > 0;
if (definitionKey !== undefined && replacesDefinition) {
const captured = capturedHeadersByKey.get(definitionKey);
if (captured !== undefined) {
for (const entry of captured) entry.overriddenByLaterHeader = true;
capturedHeadersByKey.delete(definitionKey);
}
}
}
json.preservation.bms.sourceLines.push({
kind: 'header',
command,
value,
...(commandCaseDiffers ? { commandRaw } : {}),
});
if (command === 'BPM') {
const parsedMainBPM = Number.parseFloat(value);
Eif (Number.isFinite(parsedMainBPM) && parsedMainBPM !== 0) {
hasValidMainBPMHeader = true;
}
}
pushHeaderLine(json, command, commandRaw, value, base);
});
if (
json.bms.controlFlow.length > 0 &&
json.preservation.bms.sourceLines.some((entry) => entry.kind === 'header' && entry.command === 'OPTION')
) {
// Unlike replacing headers, OPTION families combine. Keep unconditional declarations interleaved with
// branch declarations so their source order remains available after choosing a RANDOM/SWITCH outcome.
const captured = new Set(json.bms.controlFlow);
json.bms.controlFlow = json.preservation.bms.sourceLines.filter(
(entry) => captured.has(entry) || (entry.kind === 'header' && entry.command === 'OPTION'),
);
json.bms.optionHeadersInControlFlow = true;
}
if (!hasValidMainBPMHeader) {
// BMS compatibility: if #BPM is not declared, treat 130 as the default base BPM.
json.metadata.bpm = 130;
}
json.measures.sort((left, right) => left.index - right.index);
// Every event above was built normalized (channel and object ids folded, positions in range), so sorting is enough.
json.events.sort(compareEvents);
return json;
}
export function parseBmson(input: string): BeMusicJSON {
const document = JSON.parse(input) as BmsonDocument;
return parseBmsonDocument(document);
}
function parseStructuredChartObject(parsed: Record<string, unknown>): BeMusicJSON {
if (parsed.format === BMS_JSON_FORMAT) {
return parseJSONDocument(parsed as Partial<BeMusicJSON>);
}
return parseBmsonDocument(parsed as BmsonDocument);
}
export function parseChart(input: string, formatHint?: string): BeMusicJSON {
if (formatHint === undefined) {
const firstCode = input.charCodeAt(0);
if (firstCode === 0x23) {
return parseBMS(input);
}
}
const hint = formatHint?.toLowerCase();
if (hint === 'bmson') {
return parseBmson(input);
}
if (hint === 'json') {
const parsed = JSON.parse(input.trim()) as Record<string, unknown>;
return parseStructuredChartObject(parsed);
}
let startIndex = 0;
while (startIndex < input.length) {
const code = input.charCodeAt(startIndex);
Eif (code !== 0x20 && code !== 0x09 && code !== 0x0a && code !== 0x0d) {
break;
}
startIndex += 1;
}
if (input.charCodeAt(startIndex) === 0x7b) {
const parsed = JSON.parse(input.slice(startIndex)) as Record<string, unknown>;
return parseStructuredChartObject(parsed);
}
return parseBMS(input);
}
export interface ResolveBMSControlFlowOptions {
/** Random source for the draws, in `[0, 1)`. Defaults to `Math.random`. */
random?: () => number;
}
/**
* Resolves `#RANDOM` / `#SETRANDOM` / `#SWITCH` control flow with freshly drawn outcomes: shorthand for
* `resolveBMSControlFlowWithDraws(input, drawRandomOutcomes(input, random))`. A host that needs to know which branches
* it played (the replay, the RANDOM summary, a second scene showing the same chart) draws once with
* `drawRandomOutcomes` (`@be-music/chart-model`) and resolves with {@link resolveBMSControlFlowWithDraws} instead.
*/
export function resolveBMSControlFlow(input: BeMusicJSON, options: ResolveBMSControlFlowOptions = {}): BeMusicJSON {
return resolveBMSControlFlowWithDraws(input, drawRandomOutcomes(input, options.random ?? Math.random));
}
/**
* Resolves `#RANDOM` / `#SETRANDOM` / `#SWITCH` control flow with explicit outcomes — the draws made once for a play
* with `drawRandomOutcomes`, or the ones a replay recorded. The same chart and draws always give the same result.
*
* @throws RangeError when `draws` was not drawn for `input`'s control flow.
*/
export function resolveBMSControlFlowWithDraws(input: BeMusicJSON, draws: RandomDraws): BeMusicJSON {
return resolveControlFlow(input, draws, {
applyHeader: (json, command, commandRaw, value) => {
// Replay path: prefer the case-preserved `commandRaw` when available so a `#WAV0a` captured inside a `#RANDOM` /
// `#IF` block on a `#BASE 62` chart still registers under the lowercase key. Falls back to the uppercased
// `command` for the common base-36 case-insensitive path.
pushHeaderLine(json, command, commandRaw ?? command, value, json.bms.base === 62 ? 62 : 36);
},
});
}
export { decodeBMSText, decodeUTF8Text, type DecodedBMSText } from './bms-text-decode.ts';
export { canonicalizeBMSCharset, extractDeclaredBMSCharset } from './bms-charset.ts';
interface ParsedObjectDataLine {
measure: number;
channel: string;
data: string;
}
function parseObjectDataLine(line: string): ParsedObjectDataLine | undefined {
Iif (line.length < 8 || line.charCodeAt(0) !== 0x23) {
return undefined;
}
const digit0 = line.charCodeAt(1);
const digit1 = line.charCodeAt(2);
const digit2 = line.charCodeAt(3);
Iif (digit0 < 0x30 || digit0 > 0x39 || digit1 < 0x30 || digit1 > 0x39 || digit2 < 0x30 || digit2 > 0x39) {
return undefined;
}
const channel0 = normalizeASCIIBase36Code(line.charCodeAt(4));
const channel1 = normalizeASCIIBase36Code(line.charCodeAt(5));
Iif (channel0 < 0 || channel1 < 0) {
return undefined;
}
let cursor = 6;
while (cursor < line.length && isASCIIWhitespace(line.charCodeAt(cursor))) {
cursor += 1;
}
Iif (cursor >= line.length || line.charCodeAt(cursor) !== 0x3a) {
return undefined;
}
cursor += 1;
while (cursor < line.length && isASCIIWhitespace(line.charCodeAt(cursor))) {
cursor += 1;
}
Iif (cursor >= line.length) {
return undefined;
}
const data = line.slice(cursor).trim();
Iif (data.length === 0) {
return undefined;
}
return {
measure: (digit0 - 0x30) * 100 + (digit1 - 0x30) * 10 + (digit2 - 0x30),
channel: String.fromCharCode(channel0, channel1),
data,
};
}
interface ParsedHeaderDirectiveLine {
/** Uppercased command — used for keyword matching (case-insensitive). */
command: string;
/**
* Case-preserved command. For base-62 indexed-header keys, the trailing 2 characters of `commandRaw` hold the
* lowercase-aware ID — uppercasing here would collapse `#WAV0a` and `#WAV0A` back into the same slot.
*/
commandRaw: string;
value: string;
}
function parseHeaderDirectiveLine(line: string): ParsedHeaderDirectiveLine | undefined {
Iif (line.length < 2 || line.charCodeAt(0) !== 0x23) {
return undefined;
}
const commandStart = line.charCodeAt(1);
Iif (!isASCIILetter(commandStart)) {
return undefined;
}
let cursor = 2;
while (cursor < line.length && isHeaderCommandChar(line.charCodeAt(cursor))) {
cursor += 1;
}
Iif (cursor < line.length && !isASCIIWhitespace(line.charCodeAt(cursor))) {
return undefined;
}
const commandRaw = line.slice(1, cursor);
const command = commandRaw.toUpperCase();
while (cursor < line.length && isASCIIWhitespace(line.charCodeAt(cursor))) {
cursor += 1;
}
const value = cursor < line.length ? line.slice(cursor).trim() : '';
return { command, commandRaw, value };
}
function isASCIIWhitespace(code: number): boolean {
return code === 0x20 || code === 0x09 || code === 0x0b || code === 0x0c;
}
function isASCIILetter(code: number): boolean {
return (code >= 0x41 && code <= 0x5a) || (code >= 0x61 && code <= 0x7a);
}
function isHeaderCommandChar(code: number): boolean {
if (isASCIILetter(code)) {
return true;
}
return (code >= 0x30 && code <= 0x39) || code === 0x5f;
}
function isControlFlowCommand(command: string): command is BMSControlFlowCommand {
return CONTROL_FLOW_COMMANDS.has(command as BMSControlFlowCommand);
}
function forEachLine(input: string, visitor: (line: string) => void): void {
let lineStart = 0;
let index = 0;
while (index < input.length) {
const code = input.charCodeAt(index);
if (code !== 0x0a && code !== 0x0d) {
index += 1;
continue;
}
visitor(input.slice(lineStart, index));
if (code === 0x0d && index + 1 < input.length && input.charCodeAt(index + 1) === 0x0a) {
index += 1;
}
lineStart = index + 1;
index += 1;
}
visitor(input.slice(lineStart, input.length));
}
/**
* Pre-scans the BMS source for the `#BASE` directive (the beatoraja base-62 extension switch). Returns 62 when the last
* `#BASE 36` / `#BASE 62` line in the file is `#BASE 62`, otherwise 36.
*
* Like beatoraja's BMSDecoder, the scan covers the whole file before anything is decoded, so the directive's position
* does not matter (it may follow object data) and control-flow blocks are not evaluated. Other values are ignored.
*/
function detectBMSBase(input: string): 36 | 62 {
let resolved: 36 | 62 = 36;
// A failed exec resets the global regexp for the next chart.
for (let match = BASE_DIRECTIVE_REGEX.exec(input); match !== null; match = BASE_DIRECTIVE_REGEX.exec(input)) {
resolved = match[1] === '62' ? 62 : 36;
}
return resolved;
}
|