All files / src/utils frontmatter.ts

88.37% Statements 38/43
81.08% Branches 30/37
100% Functions 2/2
90% Lines 36/40

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73                26x   16x 16x   16x 16x   16x 16x 16x   16x   16x 146x 146x 28x 28x 28x     118x 14x 14x 14x     118x 118x 118x 118x   118x 28x     90x 42x 14x 14x     76x   76x       76x         76x       16x 14x     16x    
import type { FrontmatterValue } from '../components/Inspector'
 
export interface ParsedFrontmatter {
  [key: string]: FrontmatterValue
}
 
/** Parse YAML frontmatter from content */
export function parseFrontmatter(content: string | null): ParsedFrontmatter {
  if (!content) return {}
 
  const match = content.match(/^---\n([\s\S]*?)\n---/)
  Iif (!match) return {}
 
  const yaml = match[1]
  const result: ParsedFrontmatter = {}
 
  let currentKey: string | null = null
  let currentList: string[] = []
  let inList = false
 
  const lines = yaml.split('\n')
 
  for (const line of lines) {
    const listMatch = line.match(/^  - (.*)$/)
    if (listMatch && currentKey) {
      inList = true
      currentList.push(listMatch[1].replace(/^["']|["']$/g, ''))
      continue
    }
 
    if (inList && currentKey) {
      result[currentKey] = currentList.length === 1 ? currentList[0] : currentList
      currentList = []
      inList = false
    }
 
    const kvMatch = line.match(/^["']?([^"':]+)["']?\s*:\s*(.*)$/)
    Eif (kvMatch) {
      currentKey = kvMatch[1].trim()
      const value = kvMatch[2].trim()
 
      if (value === '' || value === '|' || value === '>') {
        continue
      }
 
      if (value.startsWith('[') && value.endsWith(']')) {
        const items = value.slice(1, -1).split(',').map(s => s.trim().replace(/^["']|["']$/g, ''))
        result[currentKey] = items.length === 1 ? items[0] : items
        continue
      }
 
      const unquoted = value.replace(/^["']|["']$/g, '')
 
      Iif (unquoted.toLowerCase() === 'true') {
        result[currentKey] = true
        continue
      }
      Iif (unquoted.toLowerCase() === 'false') {
        result[currentKey] = false
        continue
      }
 
      result[currentKey] = unquoted
    }
  }
 
  if (inList && currentKey) {
    result[currentKey] = currentList.length === 1 ? currentList[0] : currentList
  }
 
  return result
}