All files / src/pipeline/preprocessing escape-processor.js

18.75% Statements 3/16
0% Branches 0/12
0% Functions 0/3
18.75% Lines 3/16

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                    1x   1x                                                                                                     1x            
/**
 * Escape handler for substitution tags in Spec-Up
 * Provides mechanism to display literal [[tag]] syntax without processing
 * 
 * Implements a three-phase approach:
 * 1. Pre-processing: Convert escaped sequences to temporary placeholders
 * 2. Tag Processing: Existing substitution logic runs normally (placeholders ignored)
 * 3. Post-processing: Restore escaped sequences as literals
 */
 
const { escaping } = require('../../utils/regex-patterns.js');
 
const ESCAPED_PLACEHOLDER = '__SPEC_UP_ESCAPED_TAG__';
 
/**
 * Pre-processes text to handle escaped substitution tags
 * @param {string} text - Input text with potential escaped tags
 * @returns {string} Text with escaped tags replaced by placeholders
 */
function preProcessEscapes(text) {
  if (!text || typeof text !== 'string') {
    return text;
  }
  
  // Handle double backslash first: \\[[ → \__PLACEHOLDER__
  let processed = text.replace(/\\\\(\[\[)/g, `\\${ESCAPED_PLACEHOLDER}`);
  
  // Handle single backslash: \[[ → __PLACEHOLDER__
  processed = processed.replace(/\\(\[\[)/g, ESCAPED_PLACEHOLDER);
  
  return processed;
}
 
/**
 * Post-processes text to restore escaped tags as literals
 * @param {string} text - Text after substitution processing
 * @returns {string} Text with placeholders restored to literal tags
 */
function postProcessEscapes(text) {
  if (!text || typeof text !== 'string') {
    return text;
  }
  
  // Restore placeholders to literal [[
  return text.replace(escaping.placeholderRegex, '[[');
}
 
/**
 * Main processing function that wraps existing substitution logic
 * @param {string} content - Raw markdown content
 * @param {Function} processSubstitutions - Existing substitution processor
 * @returns {string} Processed content with escape handling
 */
function processWithEscapes(content, processSubstitutions) {
  if (!content || typeof content !== 'string') {
    return content;
  }
  
  const preProcessed = preProcessEscapes(content);
  const substituted = processSubstitutions(preProcessed);
  return postProcessEscapes(substituted);
}
 
module.exports = {
  preProcessEscapes,
  postProcessEscapes,
  processWithEscapes,
  ESCAPED_PLACEHOLDER
};