import { TokenType, type Token, type ParserOptions, type ParseResult, type RootNode, type TagNode, type TextNode, type ASTNode, type ParseError } from './types'; import { TagRegistry } from './tag-registry'; const DEFAULT_OPTIONS: ParserOptions = { mode: 'lenient', maxNestingDepth: 50 }; export class MiniMessageParser { private registry: TagRegistry; private options: ParserOptions; constructor(options: Partial = {}) { this.registry = new TagRegistry(); this.options = { ...DEFAULT_OPTIONS, ...options }; } parse(input: string): ParseResult { const errors: ParseError[] = []; try { const tokens = this.tokenize(input); const ast = this.buildAST(tokens, errors); return { ast, errors, success: errors.every((e) => e.severity !== 'error') }; } catch (error) { errors.push({ message: error instanceof Error ? error.message : 'Unknown parsing error', position: 0, severity: 'error' }); return { ast: { type: 'root', children: [], start: 0, end: input.length }, errors, success: false }; } } private tokenize(input: string): Token[] { const tokens: Token[] = []; let pos = 0; let textBuffer = ''; let textStart = 0; const flushText = () => { if (textBuffer.length > 0) { tokens.push({ type: TokenType.TEXT, value: textBuffer, position: textStart }); textBuffer = ''; } }; while (pos < input.length) { const char = input[pos]; if (char === '\\' && pos + 1 < input.length) { const nextChar = input[pos + 1]; if (nextChar === '<' || nextChar === '>' || nextChar === '\\') { if (textBuffer.length === 0) textStart = pos; textBuffer += nextChar; pos += 2; continue; } } if (char === '<') { flushText(); const tagResult = this.parseTag(input, pos); if (tagResult) { tokens.push(tagResult.token); pos = tagResult.newPos; continue; } else { if (textBuffer.length === 0) textStart = pos; textBuffer += char; pos++; } } else { if (textBuffer.length === 0) textStart = pos; textBuffer += char; pos++; } } flushText(); tokens.push({ type: TokenType.EOF, value: '', position: pos }); return tokens; } private parseTag( input: string, startPos: number ): { token: Token; newPos: number } | null { let pos = startPos + 1; if (pos < input.length && input[pos] === '/') { pos++; const closeResult = this.parseTagName(input, pos); if (!closeResult) return null; pos = closeResult.newPos; while (pos < input.length && (input[pos] === ' ' || input[pos] === '\t')) pos++; if (pos >= input.length || input[pos] !== '>') return null; return { token: { type: TokenType.TAG_CLOSE, value: closeResult.name, position: startPos }, newPos: pos + 1 }; } const isNegation = pos < input.length && input[pos] === '!'; if (isNegation) pos++; const nameResult = this.parseTagName(input, pos); if (!nameResult) return null; let tagName = nameResult.name; pos = nameResult.newPos; while (pos < input.length && (input[pos] === ' ' || input[pos] === '\t')) pos++; if (pos + 1 < input.length && input[pos] === '/' && input[pos + 1] === '>') { return { token: { type: TokenType.TAG_SELF_CLOSE, value: tagName, position: startPos, args: [] }, newPos: pos + 2 }; } let args: string[] = []; if (pos < input.length && input[pos] === ':') { pos++; const argsResult = this.parseArguments(input, pos); if (argsResult) { args = argsResult.args; pos = argsResult.newPos; } } while (pos < input.length && (input[pos] === ' ' || input[pos] === '\t')) pos++; if (pos >= input.length || input[pos] !== '>') return null; if (isNegation && args.length === 0) { args = ['false']; } return { token: { type: TokenType.TAG_OPEN, value: tagName, position: startPos, args }, newPos: pos + 1 }; } private parseTagName(input: string, startPos: number): { name: string; newPos: number } | null { let pos = startPos; let name = ''; while ( pos < input.length && /[a-zA-Z0-9_#]/.test(input[pos]) ) { name += input[pos]; pos++; } if (name.length === 0) return null; return { name, newPos: pos }; } private parseArguments( input: string, startPos: number ): { args: string[]; newPos: number } | null { const args: string[] = []; let pos = startPos; let currentArg = ''; let inQuotes = false; let quoteChar = ''; while (pos < input.length) { const char = input[pos]; if (!inQuotes && char === '>') { if (currentArg.length > 0) { args.push(currentArg); } break; } if ((char === '"' || char === "'") && (pos === startPos || input[pos - 1] !== '\\')) { if (!inQuotes) { inQuotes = true; quoteChar = char; pos++; continue; } else if (char === quoteChar) { inQuotes = false; quoteChar = ''; pos++; continue; } } if (!inQuotes && char === ':') { args.push(currentArg); currentArg = ''; pos++; continue; } if (inQuotes && char === '\\' && pos + 1 < input.length) { const nextChar = input[pos + 1]; if (nextChar === quoteChar || nextChar === '\\') { currentArg += nextChar; pos += 2; continue; } } currentArg += char; pos++; } return { args, newPos: pos }; } private buildAST(tokens: Token[], errors: ParseError[]): RootNode { const root: RootNode = { type: 'root', children: [], start: 0, end: tokens[tokens.length - 1]?.position || 0 }; const stack: TagNode[] = []; let currentParent: RootNode | TagNode = root; let depth = 0; for (let i = 0; i < tokens.length; i++) { const token = tokens[i]; if (token.type === TokenType.TEXT) { const textNode: TextNode = { type: 'text', content: token.value, start: token.position, end: token.position + token.value.length }; currentParent.children.push(textNode); } else if (token.type === TokenType.TAG_OPEN) { depth++; if (depth > this.options.maxNestingDepth!) { errors.push({ message: `Maximum nesting depth exceeded (${this.options.maxNestingDepth})`, position: token.position, severity: 'error' }); continue; } const tagDef = this.registry.get(token.value); if (!tagDef) { if (this.options.mode === 'strict') { errors.push({ message: `Unknown tag: ${token.value}`, position: token.position, severity: 'error' }); continue; } else { const textNode: TextNode = { type: 'text', content: `<${token.value}${token.args?.length ? ':' + token.args.join(':') : ''}>`, start: token.position, end: token.position }; currentParent.children.push(textNode); depth--; continue; } } const argsString = token.args?.join(':') || ''; const tagArgs = tagDef.parseArgs(argsString); const tagNode: TagNode = { type: 'tag', tagName: tagDef.name, args: tagArgs, children: [], selfClosing: false, start: token.position, end: token.position }; currentParent.children.push(tagNode); if (tagDef.canHaveChildren) { stack.push(tagNode); currentParent = tagNode; } else { depth--; } } else if (token.type === TokenType.TAG_CLOSE) { depth--; const matchIndex = this.findMatchingTag(stack, token.value); if (matchIndex === -1) { if (this.options.mode === 'strict') { errors.push({ message: `Unmatched closing tag: `, position: token.position, severity: 'error' }); } continue; } if (matchIndex < stack.length - 1 && this.options.mode === 'strict') { errors.push({ message: `Tag closed out of order: `, position: token.position, severity: 'error' }); } const closedTags = stack.splice(matchIndex); for (const tag of closedTags) { tag.end = token.position; } currentParent = stack.length > 0 ? stack[stack.length - 1] : root; } else if (token.type === TokenType.TAG_SELF_CLOSE) { const tagDef = this.registry.get(token.value); if (!tagDef) { if (this.options.mode === 'strict') { errors.push({ message: `Unknown tag: ${token.value}`, position: token.position, severity: 'error' }); } continue; } const argsString = token.args?.join(':') || ''; const tagArgs = tagDef.parseArgs(argsString); const tagNode: TagNode = { type: 'tag', tagName: tagDef.name, args: tagArgs, children: [], selfClosing: true, start: token.position, end: token.position }; currentParent.children.push(tagNode); } } if (stack.length > 0) { if (this.options.mode === 'strict') { for (const tag of stack) { errors.push({ message: `Unclosed tag: <${tag.tagName}>`, position: tag.start, severity: 'error' }); } } else { const lastPos = tokens[tokens.length - 1].position; for (const tag of stack) { tag.end = lastPos; } } } return root; } private findMatchingTag(stack: TagNode[], tagName: string): number { for (let i = stack.length - 1; i >= 0; i--) { if (stack[i].tagName.toLowerCase() === tagName.toLowerCase()) { return i; } } return -1; } }