All files / parser lsp.ts

96.33% Statements 105/109
89.74% Branches 70/78
100% Functions 13/13
96.26% Lines 103/107

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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446                                                                                                                                                                    84x                       329x 1x     328x                           164x 1x   163x             80x 70x   10x 8x   2x                   45x 45x       45x   45x   45x 45x     45x 6x 6x 6x 6x                 6x     39x 36x   118x           118x 118x   118x 118x       118x         118x       118x         118x                                             39x                               240x 240x 238x 238x 238x 238x       2x                           482x 482x   482x 89611x 5293x 5293x       482x 482x             60x     60x 4x     56x 56x       56x         56x                         78x 173x   78x 78x 78x   78x 134x   61x 20x 20x 14x       14x                           61x 66x   61x 61x 73x 28x 28x 26x           78x 41x 41x   32x   32x   32x                         78x                 84x   84x 84x 84x     84x 161x   84x       84x 6x       78x 78x 173x 32x 32x 30x           78x   78x                                             1x              
/**
 * LSP-aware parser module
 * Extends the base parser with position information for VS Code integration
 */
 
import type { Code, Root, RootContent, Yaml } from 'mdast';
import remarkFrontmatter from 'remark-frontmatter';
import remarkGfm from 'remark-gfm';
import remarkParse from 'remark-parse';
import { unified } from 'unified';
import { parseDocument } from 'yaml';
 
import {
  createParseError,
  createPosition,
  createRange,
  failure,
  success,
  type ParseError,
  type Position,
  type Range,
  type Result,
} from '../types/index.js';
import { findSectionByTag } from '../types/sections.js';
 
/**
 * Code block with position information
 */
export interface LocatedCodeBlock {
  readonly type: string; // e.g., 'experience', 'education', 'skills'
  readonly lang: string; // e.g., 'resume:experience'
  readonly content: string;
  readonly range: Range;
  readonly contentRange: Range; // Range of the YAML content inside the block
}
 
/**
 * Frontmatter field with position information
 */
export interface LocatedFrontmatterField {
  readonly key: string;
  readonly value: string | undefined;
  readonly range: Range;
  readonly keyRange: Range;
  readonly valueRange: Range | undefined;
}
 
/**
 * Frontmatter with position information
 */
export interface LocatedFrontmatter {
  readonly range: Range;
  readonly fields: readonly LocatedFrontmatterField[];
  readonly raw: string;
}
 
/**
 * Section with position information
 */
export interface LocatedSection {
  readonly id: string;
  readonly title: string;
  readonly range: Range;
  readonly titleRange: Range;
  readonly codeBlocks: readonly LocatedCodeBlock[];
}
 
/**
 * Parsed document with full position information for LSP
 */
export interface ParsedDocumentWithPositions {
  readonly frontmatter: LocatedFrontmatter | null;
  readonly sections: readonly LocatedSection[];
  readonly codeBlocks: readonly LocatedCodeBlock[];
  readonly rawContent: string;
}
 
/**
 * Create markdown processor
 */
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
function createProcessor() {
  return unified()
    .use(remarkParse)
    .use(remarkGfm)
    .use(remarkFrontmatter, ['yaml']);
}
 
/**
 * Convert mdast position to our Position type (0-based)
 */
function toPosition(
  point: { line: number; column: number } | undefined,
): Position {
  if (!point) {
    return createPosition(0, 0);
  }
  // mdast uses 1-based lines and columns, convert to 0-based
  return createPosition(point.line - 1, point.column - 1);
}
 
/**
 * Convert mdast position to our Range type
 */
function toRange(
  position:
    | {
        start: { line: number; column: number };
        end: { line: number; column: number };
      }
    | undefined,
): Range {
  if (!position) {
    return createRange(createPosition(0, 0), createPosition(0, 0));
  }
  return createRange(toPosition(position.start), toPosition(position.end));
}
 
/**
 * Extract text from mdast node
 */
function extractText(node: RootContent): string {
  if ('value' in node && typeof node.value === 'string') {
    return node.value;
  }
  if ('children' in node && Array.isArray(node.children)) {
    return (node.children as RootContent[]).map(extractText).join('');
  }
  return '';
}
 
/**
 * Parse frontmatter YAML with position information
 */
function parseFrontmatterWithPositions(
  yamlNode: Yaml,
  errors: ParseError[],
): LocatedFrontmatter | null {
  const yamlContent = yamlNode.value;
  const nodeRange = toRange(yamlNode.position);
 
  // The YAML content starts after the opening ---
  // We need to calculate the offset for field positions
  const yamlStartLine = nodeRange.start.line + 1; // Skip the --- line
 
  const fields: LocatedFrontmatterField[] = [];
 
  try {
    const doc = parseDocument(yamlContent, { keepSourceTokens: true });
 
    // Check for YAML parse errors
    if (doc.errors.length > 0) {
      for (const error of doc.errors) {
        const line = error.linePos?.[0]?.line ?? 1;
        const col = error.linePos?.[0]?.col ?? 1;
        errors.push(
          createParseError(
            `Invalid YAML frontmatter: ${error.message}`,
            yamlStartLine + line - 1,
            col,
            'frontmatter',
          ),
        );
      }
      return null;
    }
 
    if (doc.contents && 'items' in doc.contents) {
      for (const item of doc.contents.items) {
        // Check if item is a Pair (has key and value properties)
        Eif (
          'key' in item &&
          'value' in item &&
          item.key &&
          item.value !== undefined
        ) {
          const keyNode = item.key;
          const valueNode = item.value;
 
          const keyStr = String(keyNode);
          const valueStr = valueNode ? String(valueNode) : undefined;
 
          // Calculate positions relative to the document
          // yaml library uses 0-based offsets, we need to convert to line/column
          const keyRange = calculateYamlNodeRange(
            yamlContent,
            keyNode,
            yamlStartLine,
          );
          const valueRange = valueNode
            ? calculateYamlNodeRange(yamlContent, valueNode, yamlStartLine)
            : undefined;
 
          const fieldRange = createRange(
            keyRange.start,
            valueRange ? valueRange.end : keyRange.end,
          );
 
          fields.push({
            key: keyStr,
            value: valueStr,
            range: fieldRange,
            keyRange,
            valueRange,
          });
        }
      }
    }
  } catch (e) {
    // Handle unexpected errors (defensive code - YAML library normally doesn't throw)
    errors.push(
      createParseError(
        `Invalid YAML frontmatter: ${String(e)}`,
        yamlStartLine,
        1,
        'frontmatter',
      ),
    );
    return null;
  }
 
  return {
    range: nodeRange,
    fields,
    raw: yamlContent,
  };
}
 
/**
 * Calculate range for a YAML node within the document
 */
function calculateYamlNodeRange(
  yamlContent: string,
  node: unknown,
  baseLineOffset: number,
): Range {
  // Try to get range from node if available
  const nodeWithRange = node as { range?: [number, number, number?] };
  if (nodeWithRange.range) {
    const [startOffset, endOffset] = nodeWithRange.range;
    const startPos = offsetToPosition(yamlContent, startOffset, baseLineOffset);
    const endPos = offsetToPosition(yamlContent, endOffset, baseLineOffset);
    return createRange(startPos, endPos);
  }
 
  // Fallback: return a zero-width range at the base offset
  return createRange(
    createPosition(baseLineOffset, 0),
    createPosition(baseLineOffset, 0),
  );
}
 
/**
 * Convert byte offset to Position
 */
function offsetToPosition(
  content: string,
  offset: number,
  baseLineOffset: number,
): Position {
  let line = 0;
  let lastNewline = -1;
 
  for (let i = 0; i < offset && i < content.length; i++) {
    if (content[i] === '\n') {
      line++;
      lastNewline = i;
    }
  }
 
  const character = offset - lastNewline - 1;
  return createPosition(baseLineOffset + line, character);
}
 
/**
 * Parse code block with position information
 */
function parseCodeBlock(codeNode: Code): LocatedCodeBlock | null {
  const lang = codeNode.lang || '';
 
  // Only process resume: code blocks
  if (!lang.startsWith('resume:')) {
    return null;
  }
 
  const type = lang.replace('resume:', '');
  const range = toRange(codeNode.position);
 
  // Content range is inside the code fence
  // Start after the opening ``` line, end before the closing ```
  const contentRange = createRange(
    createPosition(range.start.line + 1, 0),
    createPosition(range.end.line - 1, 0),
  );
 
  return {
    type,
    lang,
    content: codeNode.value,
    range,
    contentRange,
  };
}
 
/**
 * Parse sections with position information
 */
function parseSectionsWithPositions(tree: Root): LocatedSection[] {
  const sections: LocatedSection[] = [];
  const contentNodes = tree.children.filter((node) => node.type !== 'yaml');
 
  let currentTitle: string | null = null;
  let currentTitleRange: Range | null = null;
  let currentCodeBlocks: LocatedCodeBlock[] = [];
 
  for (const node of contentNodes) {
    if (node.type === 'heading' && node.depth === 1) {
      // Save previous section
      if (currentTitle !== null && currentTitleRange !== null) {
        const sectionDef = findSectionByTag(currentTitle);
        if (sectionDef) {
          const endLine = node.position?.start.line
            ? node.position.start.line - 2
            : currentTitleRange.end.line;
 
          sections.push({
            id: sectionDef.id,
            title: currentTitle,
            range: createRange(
              currentTitleRange.start,
              createPosition(endLine, 0),
            ),
            titleRange: currentTitleRange,
            codeBlocks: currentCodeBlocks,
          });
        }
      }
 
      // Start new section
      currentTitle = node.children
        .map((c) => extractText(c as RootContent))
        .join('');
      currentTitleRange = toRange(node.position);
      currentCodeBlocks = [];
    } else if (currentTitle !== null && node.type === 'code') {
      const codeBlock = parseCodeBlock(node);
      if (codeBlock) {
        currentCodeBlocks.push(codeBlock);
      }
    }
  }
 
  // Don't forget last section
  if (currentTitle !== null && currentTitleRange !== null) {
    const sectionDef = findSectionByTag(currentTitle);
    if (sectionDef) {
      // Find the last line of content
      const lastNode = contentNodes[contentNodes.length - 1];
      const endLine =
        lastNode?.position?.end.line ?? currentTitleRange.end.line;
 
      sections.push({
        id: sectionDef.id,
        title: currentTitle,
        range: createRange(
          currentTitleRange.start,
          createPosition(endLine - 1, 0),
        ),
        titleRange: currentTitleRange,
        codeBlocks: currentCodeBlocks,
      });
    }
  }
 
  return sections;
}
 
/**
 * Parse markdown with full position information for LSP
 */
export function parseMarkdownWithPositions(
  markdown: string,
): Result<ParsedDocumentWithPositions, ParseError[]> {
  const errors: ParseError[] = [];
 
  try {
    const processor = createProcessor();
    const tree = processor.parse(markdown);
 
    // Find and parse frontmatter
    const yamlNode = tree.children.find(
      (node): node is Yaml => node.type === 'yaml',
    );
    const frontmatter = yamlNode
      ? parseFrontmatterWithPositions(yamlNode, errors)
      : null;
 
    if (errors.length > 0) {
      return failure(errors);
    }
 
    // Collect all code blocks
    const allCodeBlocks: LocatedCodeBlock[] = [];
    for (const node of tree.children) {
      if (node.type === 'code') {
        const codeBlock = parseCodeBlock(node);
        if (codeBlock) {
          allCodeBlocks.push(codeBlock);
        }
      }
    }
 
    // Parse sections
    const sections = parseSectionsWithPositions(tree);
 
    return success({
      frontmatter,
      sections,
      codeBlocks: allCodeBlocks,
      rawContent: markdown,
    });
  } catch (e) {
    // Handle unexpected errors (defensive code - remark parser normally doesn't throw)
    errors.push(
      createParseError(
        `Failed to parse markdown: ${String(e)}`,
        1,
        1,
        'markdown',
      ),
    );
    return failure(errors);
  }
}
 
export default parseMarkdownWithPositions;
 
// Export internal functions for testing
export const __test__ = {
  toPosition,
  toRange,
  extractText,
  calculateYamlNodeRange,
  offsetToPosition,
};