import { WrapVariable } from './WrapVariable' ; export class VariableWrapper { private static start = /(^|[^{])({{{?)/ . source ; private static end = /(}}}?)([^}]|$)/ . source ; private static space = /(?:[\s]*)/ . source ; private static createVariableMatcher ( ) { const { source : variableRoot } = /(\$?)(\w+)/ ; const { source : variableChild } = /(\.[\w\d\[\]\.]+)?/ ; const { source : variable } = RegExp ( `${ VariableWrapper . space }(?!else)(${ variableRoot }${ variableChild })${ VariableWrapper . space }` ) ; return RegExp ( `${ VariableWrapper . start }${ variable }${ VariableWrapper . end }` , 'g' ) ; } private static createWrappedHelperMatcher ( wrappedHelpers ) { const wrappedHelperStr = wrappedHelpers . join ( '|' ) ; const wrappedHelper = `(()(${ wrappedHelperStr })\\s([^}]+))` ; const { source : variable } = RegExp ( `${ VariableWrapper . space }${ wrappedHelper }${ VariableWrapper . space }` ) ; return RegExp ( `${ VariableWrapper . start }${ variable }${ VariableWrapper . end }` , 'g' ) ; } private variableMatch : RegExp = VariableWrapper . createVariableMatcher ( ) ; private wrappedHelperMatch : RegExp ; private wrapVariable : WrapVariable ; public constructor ( wrappedHelpers , wrapVariable ) { this . wrapVariable = wrapVariable ; this . wrappedHelperMatch = VariableWrapper . createWrappedHelperMatcher ( wrappedHelpers ) ; } public wrap ( template ) { const processVariable = this . processVariable . bind ( this ) ; const newTemplate = template . replace ( this . variableMatch , processVariable ) ; return newTemplate . replace ( this . wrappedHelperMatch , processVariable ) ; } private processVariable ( ... p ) { let className = 'data' ; if ( p [ 4 ] === '$' ) { className = p [ 5 ] ; } const variable = p [ 2 ] + p [ 3 ] + p [ 7 ] ; return this . wrapVariable ( p [ 1 ] , className , variable , p [ 8 ] ) ; } }