From 546e086c2e889abefed53f82c571f3ae3fb4af1d Mon Sep 17 00:00:00 2001 From: AleksandrHovhannisyan Date: Thu, 29 Aug 2024 15:04:04 -0500 Subject: [PATCH] Fix VTT EOF handling https://github.com/sindresorhus/file-type/issues/657 --- core.js | 38 ++++++++++++++++++++++++++------------ 1 file changed, 26 insertions(+), 12 deletions(-) diff --git a/core.js b/core.js index 3ce17372..bac11ce3 100644 --- a/core.js +++ b/core.js @@ -1139,18 +1139,32 @@ export class FileTypeParser { } } - if ( - this.checkString('WEBVTT') - && ( - // EOF - tokenizer.fileInfo.size === 6 - // One of LF/CRLF, tab, or space - || (['\n', '\r\n', '\t', ' '].some(whitespace => this.checkString(whitespace, {offset: 6})))) - ) { - return { - ext: 'vtt', - mime: 'text/vtt', - }; + if (this.checkString('WEBVTT')) { + await tokenizer.ignore(6); + let isValidWebVTT = false; + + // Try-catch to handle valid edge case of "WEBVTT" + try { + // The WebVTT standard says that the first line should be "WEBVTT" followed by a single ASCII whitespace character + const whitespaceToken = await tokenizer.readToken(new Token.StringType(1, 'ascii')); + // Must be one of LF/CRLF, tab, or space + isValidWebVTT = whitespaceToken === '\n' + || whitespaceToken === '\r\n' + || whitespaceToken === '\t' + || whitespaceToken === ' '; + } catch (error) { + // EOF reached, only contents must have been "WEBVTT" + if (error instanceof strtok3.EndOfStreamError) { + isValidWebVTT = true; + } + } + + if (isValidWebVTT) { + return { + ext: 'vtt', + mime: 'text/vtt', + }; + } } // -- 8-byte signatures --