UNPKG

@echecs/pgn

Version:

PGN is a parser that is part of the ECHECS project, designed to interpret the PGN (Portable Game Notation) specification.

39 lines 1.26 kB
import nearley from 'nearley'; import grammar from './grammar.cjs'; // It's a CJS module and cannot compile with that // eslint-disable-next-line import-x/no-named-as-default-member const { Grammar, Parser } = nearley; function _(input) { // @ts-expect-error Mismatching types const parser = new Parser(Grammar.fromCompiled(grammar)); try { parser.feed(input); if (parser.results.length > 1) { throw new Error(`@echecs/parser: Ambiguous syntax. Found ${parser.results.length} results`); } return parser.results[0]; } catch { return []; } } /** * Parse a PGN string into an array of games * * @param input */ export default function parse(input) { /** * Syntax does not allow empty lines at the beginning or end of the PGN string. */ const cleaned = input.replace(/^\s+|\s+$/g, ''); /** * Split the PGN because nearly/moo has a problem with big files. Beyond the * buffer size, the lexer will not work properly because is not feed with entire * tokens. */ const games = cleaned.split(/(?<=1-0|0-1|1\/2-1\/2|\*(?!"))(\s+)\n/g); // Parse each game independently return games.map(_).flat(); } //# sourceMappingURL=index.js.map