import { ATTRIBUTES_TO_SANITIZE, CAPTURE_LETTER_AFTER_HYPHEN, CR_NEWLINE_R, FENCE_DELIMITER_R, FORMFEED_R, HTML_CUSTOM_ATTR_R, INTERPOLATION_R, TAB_R, TABLE_CENTER_ALIGN, TABLE_LEFT_ALIGN, TABLE_RIGHT_ALIGN, TABLE_TRIM_PIPES, UNESCAPE_R, } from './constants'; import type { NestedParser, ParserResult, ParseState, Rule } from './types'; // ============================================================================ // STRING UTILITIES // ============================================================================ /** * Trim trailing whitespace from a string. */ export const trimEnd = (str: string): string => { let end = str.length; while (end > 0 && str.charCodeAt(end - 1) <= 32) end--; return end === str.length ? str : str.slice(0, end); }; /** * Check if string starts with prefix. */ export const startsWith = (str: string, prefix: string): boolean => { return str.startsWith(prefix); }; /** * Remove symmetrical leading and trailing quotes. */ export const unquote = (str: string): string => { const first = str[0]; if ( (first === '"' || first === "'") && str.length >= 2 && str[str.length - 1] === first ) { return str.slice(1, -1); } return str; }; /** * Unescape backslash-escaped characters. */ export const unescapeString = (rawString: T): T => (rawString && rawString.indexOf('\\') !== -1 ? rawString.replace(UNESCAPE_R, '$1') : rawString) as T; /** * Join class names, filtering out falsy values. */ export const cx = (...args: any[]): string => args.filter(Boolean).join(' '); /** * Get a nested property from an object using dot notation. */ export const get = (src: any, path: string, fb?: any): any => { // The overwhelming majority of paths are a single segment (a tag name), and // splitting those allocated two arrays per lookup. if (path.indexOf('.') === -1) return src?.[path] ?? fb; let ptr = src; const frags = path.split('.'); while (frags.length) { ptr = ptr[frags[0]!]; if (ptr === undefined) break; else frags.shift(); } return ptr ?? fb; }; // ============================================================================ // SLUGIFY // ============================================================================ /** * Convert a string to a URL-safe slug. * Based on https://stackoverflow.com/a/18123682/1141611 */ const SLUGIFY_REPLACEMENTS: [pattern: RegExp, replacement: string][] = [ [/[ÀÁÂÃÄÅàáâãä忯]/g, 'a'], [/[çÇ]/g, 'c'], [/[ðÐ]/g, 'd'], [/[ÈÉÊËéèêë]/g, 'e'], [/[ÏïÎîÍíÌì]/g, 'i'], [/[Ññ]/g, 'n'], [/[øØœŒÕõÔôÓóÒò]/g, 'o'], [/[ÜüÛûÚúÙù]/g, 'u'], [/[ŸÿÝý]/g, 'y'], ]; const NON_ASCII_R = /[\u0080-\uffff]/; const SLUGIFY_STRIP_R = /[^\p{L}\p{N}\p{M} -]/gu; const SLUGIFY_SPACE_R = / /g; export const slugify = (str: string): string => { let result = str; // Every transliteration matches non-ASCII only, so an ASCII heading — the // overwhelmingly common case — skips nine full passes over the string. if (NON_ASCII_R.test(result)) { for (let i = 0; i < SLUGIFY_REPLACEMENTS.length; i++) { const [pattern, replacement] = SLUGIFY_REPLACEMENTS[i]!; result = result.replace(pattern, replacement); } } result = result.replace(SLUGIFY_STRIP_R, '').replace(SLUGIFY_SPACE_R, '-'); return result.toLowerCase(); }; // ============================================================================ // SANITIZER // ============================================================================ const SANITIZE_R = /(javascript|vbscript|data(?!:image)):/i; const SANITIZE_STRIP_R = /[^A-Za-z0-9/:]/g; /** * Sanitize URLs to prevent XSS attacks. * Returns null if the URL is unsafe. */ export const sanitizer = (input: string): string | null => { // `SANITIZE_R` only ever matches on a colon, and decoding can introduce one // solely through a percent escape — so a value with neither is safe as-is, // and skipping the decode avoids the bulk of the work on ordinary links. if (input.indexOf(':') === -1 && input.indexOf('%') === -1) return input; try { const decoded = decodeURIComponent(input).replace(SANITIZE_STRIP_R, ''); if (SANITIZE_R.test(decoded)) { console.warn( 'Input contains an unsafe JavaScript/VBScript/data expression, it will not be rendered.', decoded ); return null; } } catch (_e) { console.warn( 'Input could not be decoded due to malformed syntax or characters, it will not be rendered.', input ); // decodeURIComponent sometimes throws a URIError return null; } return input; }; // ============================================================================ // WHITESPACE NORMALIZATION // ============================================================================ /** * Normalize whitespace in source string. */ export const normalizeWhitespace = (source: string): string => { // Three `indexOf` probes beat one character-class regex here by a wide margin: // each is a native memchr over the source, and none of them normally match. // Each probe guards its own replacement too, so a source carrying only tabs — // the usual case — never rewrites for the other two, and every replacement is // a constant string instead of a callback the engine has to re-enter. let normalized = source; if (normalized.indexOf('\t') !== -1) { normalized = normalized.replace(TAB_R, ' '); } if (normalized.indexOf('\r') !== -1) { normalized = normalized.replace(CR_NEWLINE_R, '\n'); } if (normalized.indexOf('\f') !== -1) { normalized = normalized.replace(FORMFEED_R, ''); } return normalized; }; /** * Safely remove a uniform leading indentation from lines, but do NOT touch * the content inside fenced code blocks (``` or ~~~). * * Inside a fenced block the structural indentation is irrelevant: what matters * is the indentation of the opening fence itself, which is the only amount * CommonMark strips from the code lines. A block nested in an indented HTML * element but written with its fence at column 0 therefore keeps its code * verbatim, instead of losing the first level of indentation. */ export const trimLeadingWhitespaceOutsideFences = ( text: string, whitespace: string ): string => { if (!whitespace) return text; const lines = text.split('\n'); /** Indentation and marker of the fence currently open, if any. */ let openFence: { indentation: string; marker: string } | null = null; const removePrefix = (line: string, prefix: string): string => prefix && line.startsWith(prefix) ? line.slice(prefix.length) : line; // Outside fences, strip the base structural indentation from every line. // Lines that don't start with the whitespace prefix are left as-is. const result = lines .map((line) => { const fenceMatch = line.match(FENCE_DELIMITER_R); if (!openFence) { if (fenceMatch) openFence = { indentation: fenceMatch[1]!, marker: fenceMatch[2]! }; return removePrefix(line, whitespace); } const isClosingFence = fenceMatch?.[2]?.startsWith(openFence.marker); const { indentation } = openFence; if (isClosingFence) openFence = null; return removePrefix(line, indentation); }) .join('\n'); return result; }; /** * Normalize HTML attribute key to JSX prop name. */ export const normalizeAttributeKey = (key: string): string => { const hyphenIndex = key.indexOf('-'); if (hyphenIndex !== -1 && key.match(HTML_CUSTOM_ATTR_R) === null) { key = key.replace(CAPTURE_LETTER_AFTER_HYPHEN, (_, letter) => { return letter.toUpperCase(); }); } return key; }; type StyleTuple = [key: string, value: string]; /** * Parse a CSS style string into an array of [key, value] tuples. */ export const parseStyleAttribute = (styleString: string): StyleTuple[] => { const styles: StyleTuple[] = []; let buffer = ''; let inUrl = false; let inQuotes = false; let quoteChar: '"' | "'" | '' = ''; if (!styleString) return styles; for (let i = 0; i < styleString.length; i++) { const char = styleString[i]; if ((char === '"' || char === "'") && !inUrl) { if (!inQuotes) { inQuotes = true; quoteChar = char; } else if (char === quoteChar) { inQuotes = false; quoteChar = ''; } } if (char === '(' && buffer.endsWith('url')) { inUrl = true; } else if (char === ')' && inUrl) { inUrl = false; } if (char === ';' && !inQuotes && !inUrl) { const declaration = buffer.trim(); if (declaration) { const colonIndex = declaration.indexOf(':'); if (colonIndex > 0) { const key = declaration.slice(0, colonIndex).trim(); const value = declaration.slice(colonIndex + 1).trim(); styles.push([key, value]); } } buffer = ''; } else { buffer += char; } } const declaration = buffer.trim(); if (declaration) { const colonIndex = declaration.indexOf(':'); if (colonIndex > 0) { const key = declaration.slice(0, colonIndex).trim(); const value = declaration.slice(colonIndex + 1).trim(); styles.push([key, value]); } } return styles; }; /** * Convert an attribute value to a Node prop value. */ export const attributeValueToNodePropValue = ( tag: string, key: string, value: string, sanitizeUrlFn: ( value: string, tag: string, attribute: string ) => string | null ): any => { if (key === 'style') { return parseStyleAttribute(value).reduce( (styles, [styleKey, styleValue]) => { const camelCasedKey = styleKey.replace(/(-[a-z])/g, (substr) => substr[1]!.toUpperCase() ); (styles as Record)[camelCasedKey] = sanitizeUrlFn( styleValue, tag, styleKey ); return styles; }, {} as Record ); } else if (ATTRIBUTES_TO_SANITIZE.indexOf(key) !== -1) { return sanitizeUrlFn(unescapeString(value), tag, key); } else if (value.match(INTERPOLATION_R)) { value = unescapeString(value.slice(1, value.length - 1)); } if (value === 'true') { return true; } else if (value === 'false') { return false; } return value; }; // ============================================================================ // TABLE PARSING // ============================================================================ /** * Parse table alignment from a separator row. */ export const parseTableAlignCapture = ( alignCapture: string ): 'left' | 'right' | 'center' => { // All three patterns need a colon, and the right-align one backtracks across // the whole cell before failing — so reject colon-free cells up front. if (alignCapture.indexOf(':') === -1) return 'left'; if (TABLE_RIGHT_ALIGN.test(alignCapture)) { return 'right'; } else if (TABLE_CENTER_ALIGN.test(alignCapture)) { return 'center'; } else if (TABLE_LEFT_ALIGN.test(alignCapture)) { return 'left'; } return 'left'; }; /** * Parse table alignment row. */ export const parseTableAlign = ( source: string ): ('left' | 'right' | 'center')[] => { const alignText = source.replace(TABLE_TRIM_PIPES, '').split('|'); return alignText.map(parseTableAlignCapture); }; /** * Parse a single table row. */ export const parseTableRow = ( source: string, parse: NestedParser, state: ParseState, tableOutput: boolean ): ParserResult[][] => { const prevInTable = state.inTable; state.inTable = true; let rStart = 0; let rEnd = source.length; while (rStart < rEnd) { const c = source.charCodeAt(rStart); if (c === 32 || c === 9) rStart++; else break; } while (rEnd > rStart) { const c = source.charCodeAt(rEnd - 1); if (c === 32 || c === 9) rEnd--; else break; } // Trim leading pipe if present if (rStart < rEnd && source.charCodeAt(rStart) === 124 /* | */) { rStart++; } // Trim trailing pipe if present (and not escaped) if ( rEnd > rStart && source.charCodeAt(rEnd - 1) === 124 /* | */ && (rEnd - 2 < rStart || source.charCodeAt(rEnd - 2) !== 92) /* \ */ ) { rEnd--; } if (!tableOutput) { const cell = parse(source.slice(rStart, rEnd), state); state.inTable = prevInTable; return [cell]; } const cells: ParserResult[][] = []; const len = source.length; let cellStart = rStart; let i = rStart; /** * Parse one cell, dropping the padding an aligned table pads it with. * * GFM strips a cell's surrounding whitespace, so trimming is both the correct * output and the cheap one: the padding of a column-aligned table is a large * share of its bytes, and every space handed to `parse` costs a rule dispatch, * a capture and a lookbehind update. `trim` is a native scan, and walking the * padding back from the delimiter in JavaScript instead costs half as much * again as the whole row scan. */ const parseCell = (from: number, to: number): ParserResult[] => { const cell = source.slice(from, to).trim(); return cell === '' ? [] : parse(cell, state); }; // Cursors on the only three characters that can end a run of ordinary cell // text. Each moves forward only, so the row is swept three times in total by // `indexOf` — cheaper than re-entering the regex engine once per character // found, which is what an anchored run scanner costs on a wide row. let pipeAt = -1; let escapeAt = -1; let backtickAt = -1; while (i < rEnd) { if (pipeAt < i) { const at = source.indexOf('|', i); pipeAt = at === -1 ? len : at; } if (escapeAt < i) { const at = source.indexOf('\\', i); escapeAt = at === -1 ? len : at; } if (backtickAt < i) { const at = source.indexOf('`', i); backtickAt = at === -1 ? len : at; } i = Math.min(pipeAt, escapeAt, backtickAt); if (i >= rEnd) break; // Escape: \| if (i === escapeAt) { i += i + 1 < rEnd ? 2 : 1; continue; } // Code span: `...` if (i === backtickAt) { let backticks = 0; while (i < rEnd && source.charCodeAt(i) === 96) { backticks++; i++; } let found = false; while (i < rEnd && !found) { let closeBackticks = 0; while (i < rEnd && source.charCodeAt(i) === 96) { closeBackticks++; i++; } if (closeBackticks === backticks) { found = true; } else if (closeBackticks === 0) { i++; } } continue; } // Cell delimiter: | cells.push(parseCell(cellStart, i)); i++; cellStart = i; } cells.push(parseCell(cellStart, rEnd)); state.inTable = prevInTable; return cells; }; /** * Parse table cells (multiple rows). */ export const parseTableCells = ( source: string, parse: NestedParser, state: ParseState ): ParserResult[][][] => { if (!source) return []; const result: ParserResult[][][] = []; let start = 0; const len = source.length; while (start < len) { let nextNewline = source.indexOf('\n', start); if (nextNewline === -1) nextNewline = len; const rowText = source.slice(start, nextNewline); start = nextNewline + 1; // Check if row has non-whitespace content let hasContent = false; for (let j = 0; j < rowText.length; j++) { const c = rowText.charCodeAt(j); if (c !== 32 && c !== 9 && c !== 13) { hasContent = true; break; } } if (!hasContent) continue; result.push(parseTableRow(rowText, parse, state, true)); } return result; }; // ============================================================================ // PARSING HELPERS // ============================================================================ /** * Check if a rule qualifies for the current source and state. */ export const qualifies = ( source: string, state: ParseState, qualify: NonNullable['_qualify']> ): boolean => { if (Array.isArray(qualify)) { for (let i = 0; i < qualify.length; i++) { if (startsWith(source, qualify[i]!)) return true; } return false; } return (qualify as (source: string, state: ParseState) => boolean)( source, state ); }; /** * Marks a matcher function as eligible for being run inside an inline context. */ export const allowInline = any>( fn: T ): T & { inline: 1 } => { (fn as any).inline = 1; return fn as T & { inline: 1 }; }; /** * Creates a match function for an inline scoped element from a regex. */ export const inlineRegex = (regex: RegExp) => allowInline((source: string, state: ParseState): RegExpMatchArray | null => { if (state.inline) { return regex.exec(source); } else { return null; } }); /** * Creates a match function for inline elements except links. */ export const simpleInlineRegex = (regex: RegExp) => allowInline((source: string, state: ParseState): RegExpMatchArray | null => { if (state.inline || state.simple) { return regex.exec(source); } else { return null; } }); /** * Creates a match function for a block scoped element from a regex. */ export const blockRegex = (regex: RegExp) => (source: string, state: ParseState): RegExpMatchArray | null => { if (state.inline || state.simple) { return null; } else { return regex.exec(source); } }; /** * Creates a match function from a regex, ignoring block/inline scope. */ export const anyScopeRegex = ( fn: RegExp | ((source: string, state: ParseState) => RegExpMatchArray | null) ) => allowInline((source: string, state: ParseState): RegExpMatchArray | null => { if (typeof fn === 'function') { return fn(source, state); } return fn.exec(source); }); /** * Parse inline content (including links). */ export const parseInline = ( parse: NestedParser, children: string, state: ParseState ): ParserResult[] => { const isCurrentlyInline = state.inline ?? false; const isCurrentlySimple = state.simple ?? false; state.inline = true; state.simple = true; const result = parse(children, state); state.inline = isCurrentlyInline; state.simple = isCurrentlySimple; return result; }; /** * Parse simple inline content (no links). */ export const parseSimpleInline = ( parse: NestedParser, children: string, state: ParseState ): ParserResult[] => { const isCurrentlyInline = state.inline ?? false; const isCurrentlySimple = state.simple ?? false; state.inline = false; state.simple = true; const result = parse(children, state); state.inline = isCurrentlyInline; state.simple = isCurrentlySimple; return result; }; /** * Parse block content. */ export const parseBlock = ( parse: NestedParser, children: string, state: ParseState = {} ): ParserResult[] => { const isCurrentlyInline = state.inline || false; state.inline = false; const normalizedChildren = trimEnd(children); const needsTerminator = /\n\n$/.test(normalizedChildren) === false; const blockInput = needsTerminator ? normalizedChildren.endsWith('\n') ? `${normalizedChildren}\n` : `${normalizedChildren}\n\n` : normalizedChildren; const result = parse(blockInput, state); state.inline = isCurrentlyInline; return result; }; /** * Helper to parse capture group 2 as inline content. */ export const parseCaptureInline = ( capture: RegExpMatchArray, parse: NestedParser, state: ParseState ): { children: ParserResult[] } => { return { children: parseInline(parse, capture[2] ?? '', state), }; }; /** * Helper that captures nothing (empty object). */ export const captureNothing = (): Record => ({}); /** * Helper that renders nothing (null). */ export const renderNothing = (): null => null; /** * Check if any regex in a list matches the input. */ /** * A block-syntax probe: either a regex to test, or a predicate for the rules * whose regex was replaced by a linear scanner. */ export type BlockSyntaxProbe = RegExp | ((input: string) => boolean); export const some = (probes: BlockSyntaxProbe[], input: string): boolean => { for (let i = 0; i < probes.length; i++) { const probe = probes[i]!; if (typeof probe === 'function' ? probe(input) : probe.test(input)) { return true; } } return false; };