|
| 1 | +/** |
| 2 | + * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | + * |
| 4 | + * This source code is licensed under the MIT license found in the |
| 5 | + * LICENSE file in the root directory of this source tree. |
| 6 | + */ |
| 7 | + |
| 8 | +const INLINE_HIGHLIGHT_REGEX = /(\[\[.*\]\])/; |
| 9 | + |
| 10 | +function validateInlineHighlights(meta, code) { |
| 11 | + const match = INLINE_HIGHLIGHT_REGEX.exec(meta); |
| 12 | + if (!match) { |
| 13 | + return []; |
| 14 | + } |
| 15 | + |
| 16 | + let highlights; |
| 17 | + try { |
| 18 | + highlights = JSON.parse(match[1]); |
| 19 | + } catch (error) { |
| 20 | + return ['Code highlight metadata must be valid JSON']; |
| 21 | + } |
| 22 | + |
| 23 | + if (!Array.isArray(highlights)) { |
| 24 | + return ['Code highlight metadata must be an array']; |
| 25 | + } |
| 26 | + |
| 27 | + const lines = code.split('\n'); |
| 28 | + const errors = []; |
| 29 | + |
| 30 | + for (const highlight of highlights) { |
| 31 | + if (!Array.isArray(highlight) || highlight.length < 3) { |
| 32 | + errors.push('Each code highlight must specify a step, line, and text'); |
| 33 | + continue; |
| 34 | + } |
| 35 | + |
| 36 | + const [, lineNo, text, fromIndex] = highlight; |
| 37 | + if (!Number.isInteger(lineNo) || lineNo < 1 || lineNo > lines.length) { |
| 38 | + errors.push(`Code highlight line ${lineNo} is outside this code block`); |
| 39 | + continue; |
| 40 | + } |
| 41 | + if (typeof text !== 'string') { |
| 42 | + errors.push(`Code highlight text on line ${lineNo} must be a string`); |
| 43 | + continue; |
| 44 | + } |
| 45 | + |
| 46 | + const line = lines[lineNo - 1]; |
| 47 | + let index = line.indexOf(text); |
| 48 | + const lastIndex = line.lastIndexOf(text); |
| 49 | + if (index !== lastIndex) { |
| 50 | + if (fromIndex === undefined) { |
| 51 | + errors.push( |
| 52 | + `Found '${text}' twice on highlighted line ${lineNo}; specify fromIndex` |
| 53 | + ); |
| 54 | + continue; |
| 55 | + } |
| 56 | + index = line.indexOf(text, fromIndex); |
| 57 | + } |
| 58 | + if (index === -1) { |
| 59 | + errors.push(`Could not find '${text}' on highlighted line ${lineNo}`); |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + return errors; |
| 64 | +} |
| 65 | + |
| 66 | +module.exports = {validateInlineHighlights}; |
0 commit comments